-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathchart.ts
More file actions
468 lines (448 loc) · 13.8 KB
/
chart.ts
File metadata and controls
468 lines (448 loc) · 13.8 KB
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
/*
v8現在、譜面データを表す形式は以下の通り
Chart〜 は複数レベルを含むデータ、 Level〜 は単一レベルのデータ
chartFormat/ 内の定義
(Min, Edit, Play は型名にそれぞれバージョン番号がつき、legacy/ 以下にバージョンごとに定義が置かれる)
* ChartBrief: /share 内や /api/brief などで情報表示に使われる
* Edit -> Brief: createBrief(chart)
* EntryCompressed -> Brief: entryToBrief(chart)
* ChartMin: ローカル保存に使われる、情報量を失わない最小サイズの形式
* 旧バージョンからの変換: convertTo14Min(chart)
* Edit -> Min: convertToMin14(chart)
* ChartEdit: 譜面の編集時と、 /api/chartFile の送受信に使われる
* 旧バージョンからの変換: convertTo14(chart)
* Min -> Edit: (await luaExec(level.lua.join("\n"))).levelFreezed
* Entry -> Edit: entryToChart(chart)
* LevelPlay: /api/playFile で使われる、プレイ時の譜面データ
* Edit -> Play: convertToPlay9(chart, lvIndex)
* ChartSeqData, Note: プレイ中の譜面データ (過去 /api/seqFile でも使われていた)
* Play -> SeqData: loadChart9(level)
route/ 内の定義
* ChartEntry, ChartLevelCore: データベースにアクセスする際の中間形式
* Edit -> Entry: chartToEntry(chart)
* EntryCompressed -> Entry: unzipEntry(entry)
* ChartEntryCompressed: データベース内の形式
* Entry -> EntryCompressed: zipEntry(entry)
*/
import * as v from "valibot";
import { difficulty } from "./difficulty.js";
import { luaAddBpmChange } from "./lua/bpm.js";
import { luaAddBeatChange } from "./lua/signature.js";
import { luaAddSpeedChange } from "./lua/speed.js";
import { stepZero, stepSimplify } from "./step.js";
import { defaultCopyBufferObj, NoteCommand } from "./command.js";
import {
Chart13Edit,
ChartEditSchema13,
ChartUntil13Min,
Level13Freeze,
} from "./legacy/chart13.js";
import {
Chart14Edit,
Chart14Min,
ChartEditSchema14,
ChartMinSchema14,
ChartUntil14,
ChartUntil14Min,
convertTo14Min,
convertToMin14,
} from "./legacy/chart14.js";
import { LevelForLuaEditLatest } from "./lua/edit.js";
import {
BPMChange,
BPMChangeWithLua,
SpeedChange,
SpeedChangeWithLua,
updateBpmTimeSec,
} from "./bpm.js";
import { Signature, SignatureWithLua } from "./signature.js";
import { Level11Freeze } from "./legacy/chart11.js";
import { Chart5, Level5 } from "./legacy/chart5.js";
import { Level9Freeze } from "./legacy/chart9.js";
import { Level8Freeze } from "./legacy/chart8.js";
import { Level7 } from "./legacy/chart7.js";
import { Level6 } from "./legacy/chart6.js";
import { Level4 } from "./legacy/chart4.js";
import {
Chart15,
ChartSchema15,
ChartUntil15,
convertTo15,
convertToPlay15,
Level15Freeze,
Level15Meta,
Level15Play,
} from "./legacy/chart15.js";
import { docRefs, Reference, Schema } from "./docSchema.js";
import { maxLv, minLv } from "./apiConfig.js";
export const YoutubeIdSchema = () =>
v.pipe(
v.string(),
v.regex(/^[a-zA-Z0-9_-]{11}$/, "YouTube video id must be 11 characters")
);
export const HashSchema = () => v.pipe(v.string(), v.regex(/^[a-f0-9]{64}$/));
export const EmptyObj = <
T extends v.BaseSchema<unknown, unknown, v.BaseIssue<unknown>>,
>() =>
v.pipe(
v.strictObject({}),
v.transform(() => [] as v.InferOutput<T>[]),
v.description(
"accept empty object instead of empty array for Lua compatibility"
)
);
export const ArrayOrEmptyObj = <
T extends v.BaseSchema<unknown, unknown, v.BaseIssue<unknown>>,
>(
schema: T
) => v.union([v.array(schema), EmptyObj<T>()]);
export function ArrayOrEmptyObjDoc(doc: Schema | Reference): Schema {
return {
anyOf: [ArrayDoc(doc), docRefs("EmptyObj")],
};
}
export function ArrayDoc(doc: Schema | Reference): Schema {
return {
type: "array",
items: doc,
};
}
// luaコードの実行結果をパースする際nilがundefinedになるので、それも受け付けるようにしている
export const LuaLineSchema = () =>
v.pipe(
v.optional(
v.nullable(v.pipe(v.number(), v.integer(), v.minValue(0))),
null
),
v.description(
"A line number corresponding to the Lua code, or null if not editable. " +
"The first line is 0."
)
);
export const CidSchema = () =>
v.pipe(v.string(), v.regex(/^[0-9]{6}$/, "cid must be 6 digits"));
export const levelTypes = ["Single", "Double", "Maniac"];
export const levelTypesConst = ["Single", "Double", "Maniac"] as const;
export const DifficultySchema = () =>
v.pipe(v.number(), v.integer(), v.minValue(minLv), v.maxValue(maxLv));
export const ChartBriefSchema = () =>
v.object({
ytId: YoutubeIdSchema(),
title: v.string(),
composer: v.string(),
chartCreator: v.string(),
updatedAt: v.pipe(v.number(), v.description("value from Date.getTime()")),
published: v.boolean(),
locale: v.pipe(
v.string(),
v.description(
"Locale where this chart was created, e.g. 'jp', 'en', " +
"though this field is currently not used for anything."
)
),
levels: v.array(
v.object({
name: v.string(),
hash: HashSchema(),
type: v.picklist(levelTypesConst),
difficulty: DifficultySchema(),
noteCount: v.pipe(v.number(), v.integer(), v.minValue(0)),
bpmMin: v.pipe(v.number(), v.gtValue(0)),
bpmMax: v.pipe(v.number(), v.gtValue(0)),
length: v.pipe(
v.number(),
v.minValue(0),
v.description("The length of chart in seconds")
),
// どこかのタイミングでmigrationをミスったか、unlisted:nullのデータがDBに存在している
unlisted: v.nullable(v.boolean()),
})
),
});
export type ChartBrief = v.InferOutput<ReturnType<typeof ChartBriefSchema>>;
export function emptyBrief(): ChartBrief {
return {
ytId: "",
title: "",
composer: "",
chartCreator: "",
updatedAt: 0,
published: false,
locale: "",
levels: [],
};
}
export const currentChartVer = 15;
export const lastIncompatibleVer = 6;
export type ChartEdit = Chart15;
export type LevelPlay = Level15Play;
export type LevelMin = Level15Meta;
export type LevelFreeze = Level15Freeze;
export const convertToMin = convertToMin14;
export const convertToPlay = convertToPlay15;
export async function convertToLatest(chart: ChartUntil15): Promise<ChartEdit> {
if (chart.ver !== 15) chart = await convertTo15(chart as ChartUntil14);
return chart;
}
export async function validateChart(chart: ChartUntil15): Promise<ChartEdit> {
if (chart.falling !== "nikochan") throw "not a falling nikochan data";
chart = await convertToLatest(chart);
chart satisfies Chart15;
chart = v.parse(ChartSchema15(), chart);
return { ...chart, ver: 15 };
}
export function validateChartWithoutConvert(chart: ChartUntil15): ChartUntil15 {
if (chart.falling !== "nikochan") throw "not a falling nikochan data";
switch (chart.ver) {
case 15:
chart satisfies Chart15;
return v.parse(ChartSchema15(), chart);
case 14:
chart satisfies Chart14Edit;
return v.parse(ChartEditSchema14(), chart);
case 13:
chart satisfies Chart13Edit;
return v.parse(ChartEditSchema13(), chart);
default:
throw `chart version too old: ${chart.ver}`;
}
}
export async function validateChartMin(
chart: ChartUntil14Min
): Promise<Chart14Min> {
if (chart.falling !== "nikochan") throw "not a falling nikochan data";
if (chart.ver !== 14) chart = await convertTo14Min(chart as ChartUntil13Min);
chart satisfies Chart14Min;
chart = v.parse(ChartMinSchema14(), chart);
return { ...chart, ver: 14 };
}
export async function hash(text: string) {
const msgUint8 = new TextEncoder().encode(text); // (utf-8 の) Uint8Array にエンコードする
const hashBuffer = await crypto.subtle.digest("SHA-256", msgUint8); // メッセージをハッシュする
const hashArray = Array.from(new Uint8Array(hashBuffer)); // バッファーをバイト列に変換する
const hashHex = hashArray
.map((b) => b.toString(16).padStart(2, "0"))
.join(""); // バイト列を 16 進文字列に変換する
return hashHex;
}
/**
* Calculates hash of a level using object-hash library.
* This ensures consistent hashing regardless of property order.
* Normalizes all Step types to ensure fractions are in simplest form.
* @param level Level13Edit to hash
* @returns Promise<string> SHA-256 hash in hex format
*/
export async function hashLevel(
level:
| Level15Freeze
| Level13Freeze
| Level11Freeze
| Level9Freeze
| Level8Freeze
| Level7
| Level6
| Level5
| Level4
): Promise<string> {
// Normalize all Step types by simplifying fractions
const normalizedNotes = level.notes.map(
(note) =>
({
step: stepSimplify({ ...note.step }),
big: note.big,
hitX: note.hitX,
hitVX: note.hitVX,
hitVY: note.hitVY,
fall: "fall" in note ? note.fall : false,
}) satisfies NoteCommand
);
const normalizedBpmChanges = level.bpmChanges.map(
(bpm) =>
({
step: stepSimplify({ ...bpm.step }),
bpm: bpm.bpm,
}) satisfies BPMChange
);
const normalizedSpeedChanges = level.speedChanges.map(
(speed) =>
({
step: stepSimplify({ ...speed.step }),
bpm: speed.bpm,
interp: "interp" in speed ? speed.interp : false,
}) satisfies SpeedChange
);
const normalizedSignature =
"signature" in level
? level.signature.map(
(sig) =>
({
step: stepSimplify({ ...sig.step }),
offset: stepSimplify({ ...sig.offset }),
bars: sig.bars,
}) satisfies Signature
)
: undefined;
return await hash(
JSON.stringify([
normalizedNotes,
normalizedBpmChanges,
normalizedSpeedChanges,
normalizedSignature,
])
);
}
export function numEvents(chart: Chart14Edit | ChartEdit): number {
return chart.levelsFreeze
.map(
(l) =>
l.notes.length +
l.rest.length +
l.bpmChanges.length +
l.speedChanges.length +
l.signature.length
)
.reduce((a, b) => a + b);
}
export function emptyChart(locale: string): ChartEdit {
const { min, freeze, lua } = emptyLevel();
let chart: ChartEdit = {
falling: "nikochan",
ver: currentChartVer,
levelsMeta: [min],
lua: [lua],
levelsFreeze: [freeze],
offset: 0,
ytId: "",
title: "",
composer: "",
chartCreator: "",
changePasswd: null,
published: false,
locale,
copyBuffer: defaultCopyBufferObj(),
zoom: 0,
};
return chart;
}
// prevLevelからbpmとspeedだけはコピー
export function emptyLevel(
prevBPM?: BPMChangeWithLua[],
prevSpeed?: SpeedChangeWithLua[],
prevSignature?: SignatureWithLua[]
) {
let levelMin: LevelMin = {
name: "",
type: levelTypesConst[0],
unlisted: false,
ytBegin: 0,
ytEnd: "note",
ytEndSec: 0,
snapDivider: 4,
};
let level: LevelForLuaEditLatest = {
notes: [],
rest: [],
bpmChanges: [],
speedChanges: [],
signature: [],
lua: [],
};
if (prevBPM && prevSpeed && prevSignature) {
for (const change of prevBPM) {
level = luaAddBpmChange(level, change)!;
}
for (const change of prevSpeed) {
level = luaAddSpeedChange(level, change)!;
}
for (const s of prevSignature) {
level = luaAddBeatChange(level, s)!;
}
} else {
level = luaAddBpmChange(level, {
bpm: 120,
step: stepZero(),
timeSec: 0,
})!;
level = luaAddSpeedChange(level, {
bpm: 120,
step: stepZero(),
timeSec: 0,
interp: false,
})!;
level = luaAddBeatChange(level, {
step: stepZero(),
offset: stepZero(),
barNum: 0,
bars: [[4, 4, 4, 4]],
})!;
}
return {
min: levelMin,
freeze: {
notes: level.notes,
rest: level.rest,
bpmChanges: level.bpmChanges,
speedChanges: level.speedChanges,
signature: level.signature,
} satisfies LevelFreeze,
lua: level.lua,
};
}
export async function createBrief(
// API用に過去2バージョンサポート
// seedでChart5を使う
chart: Chart5 | Chart14Edit | Chart15,
updatedAt: number
): Promise<ChartBrief> {
let levelHashes: string[] = [];
try {
levelHashes = await Promise.all(
"levels" in chart
? chart.levels.map((level) => hashLevel(level))
: chart.levelsFreeze.map((level) => hashLevel(level))
);
} catch (e) {
console.error(e);
}
const levelsMin =
"levels" in chart
? chart.levels
: "levelsMin" in chart
? chart.levelsMin
: chart.levelsMeta;
const levelsFreeze = "levels" in chart ? chart.levels : chart.levelsFreeze;
const levelBrief = levelsMin.map(
(level, i) =>
({
name: level.name,
type: level.type as "Single" | "Double" | "Maniac",
unlisted: !!level.unlisted,
hash: levelHashes.at(i) ?? "",
noteCount: levelsFreeze[i].notes.length,
difficulty: difficulty(
{
...levelsFreeze[i],
bpmChanges: updateBpmTimeSec(levelsFreeze[i].bpmChanges).bpm,
},
level.type
),
bpmMin: levelsFreeze[i].bpmChanges
.map((b) => b.bpm)
.reduce((a, b) => Math.min(a, b)),
bpmMax: levelsFreeze[i].bpmChanges
.map((b) => b.bpm)
.reduce((a, b) => Math.max(a, b)),
length: "ytBegin" in level ? level.ytEndSec - level.ytBegin : 0,
}) satisfies ChartBrief["levels"][number]
);
return {
ytId: chart.ytId,
title: chart.title,
composer: chart.composer,
chartCreator: chart.chartCreator,
levels: levelBrief,
updatedAt: updatedAt,
published: "published" in chart ? chart.published : false,
locale: "locale" in chart ? chart.locale : "ja",
};
}