-
Notifications
You must be signed in to change notification settings - Fork 20
/
beatsaber-cli-fast
executable file
·332 lines (268 loc) · 7.9 KB
/
beatsaber-cli-fast
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
#!/usr/bin/env python3
#==============================================================================
# Functionality
#==============================================================================
import pdb
import sys
import os
import re
# utility funcs, classes, etc go here.
def asserting(cond):
if not cond:
pdb.set_trace()
assert(cond)
def has_stdin():
return not sys.stdin.isatty()
def reg(pat, flags=0):
return re.compile(pat, re.VERBOSE | flags)
#==============================================================================
# Cmdline
#==============================================================================
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter,
description="""
TODO
""")
parser.add_argument('-v', '--verbose',
action="store_true",
help="verbose output" )
args = None
#==============================================================================
# Main
#==============================================================================
import json
from collections import namedtuple
from ansi_styles import ansiStyles as styles
class Renderer:
def __init__(self):
self.cmds = []
self(ansiEscapes.clearScreen)
self(ansiEscapes.cursorHide)
def __call__(self, msg):
self.cmds.append(msg)
def to(self, x, y):
self(ansiEscapes.cursorTo(x, y))
def flush(self):
print(''.join(self.cmds), end='', flush=True)
self.cmds.clear()
def viewport(self, w, h):
for line in range(h):
self(ansiEscapes.cursorTo(w, line) + ansiEscapes.eraseStartLine)
self(ansiEscapes.cursorTo(0, 0))
class Note(namedtuple('Note', 'index time lineIndex lineLayer type cutDirection'.split())):
@property
def insignia(self):
return "↑↓←→↖↗↙↘∎"[self.cutDirection]
@property
def upwards(self):
return "1↓←→11↙↘∎"[self.cutDirection] == "1"
@property
def downwards(self):
return "↑1←→↖↗11∎"[self.cutDirection] == "1"
def color(self, opacity=1.0):
if self.type == 0:
return (1.0, 0, 0, opacity)
elif self.type == 1:
return (0, 0, 1.0, opacity)
else:
return (96/255, 100/255, 105/255, opacity)
@property
def w(self):
return 3
@property
def h(self):
return 1
def secs(self, bpm):
return self.time / bpm * 60
@property
def x(self):
return self.lineIndex
@property
def y(self):
return 2 - self.lineLayer
class BeatsaberMap:
def __init__(self, info='info.dat'):
if isinstance(info, str):
with open(info) as f:
info = json.load(f)
self.info = info
@property
def bpm(self):
return self.info['_beatsPerMinute']
def parse(self, file):
if isinstance(file, str):
with open(file) as f:
file = json.load(f)
notes = file['_notes']
#notes = [list(sorted(x.items())) for x in notes]
#notes = [[y[1] for y in x] for x in notes]
notes = [Note(index=i, **{k.lstrip('_'): v for k, v in x.items()}) for i, x in enumerate(notes)]
#return Track([(n.type, n.c, n.time / self.bpm * 60000, n.x, n.y) for n in notes])
return Song(self.bpm, notes)
from ansi_escapes import ansiEscapes
import subprocess
import vlc
def dovlc(cmd):
cmd = cmd.replace('\n', '\n ')
return subprocess.check_output(['osascript', '-e', f"""
tell application "VLC"
{cmd}
end tell
""".strip()])
def lerp(a, b, t):
return (b - a) * t + a
def lerprgb(a, b, t):
return tuple([lerp(x, y, t) for x, y in zip(a, b)])
def wherebetween(lo, hi, t):
return (t - lo) / (hi - lo)
def clamp(lo, hi, t):
if t < lo:
return lo
if t > hi:
return hi
return t
def blend(src, dst=(0.0, 0.0, 0.0, 1.0)):
sr, sg, sb, sa = src
dr, dg, db, da = dst
sr *= sa
sg *= sa
sb *= sa
dr *= (1 - sa)
dg *= (1 - sa)
db *= (1 - sa)
dr += sr * sa
dg += sg * sa
db += sb * sa
return (
clamp(0, 255, int(255*dr)),
clamp(0, 255, int(255*dg)),
clamp(0, 255, int(255*db))
)
from glob import glob
class Song:
def __init__(self, bpm, notes):
self.bpm = bpm
self.tracks = tuple(list(Track(bpm, tuple(note for note in notes if note.type == i)) for i in range(4)))
self.v = (10, 3) # viewport offset
size = os.get_terminal_size()
self.v = (
size.columns // 2 - 3*2,
size.lines // 2 - 2)
def play(self):
pos = (0, 0)
self.player = vlc.MediaPlayer(list(glob('*.egg'))[0])
self.player.play()
try:
start = time.time()
r = Renderer()
r.flush()
last = self.last_note()
totalsecs = last.secs(self.bpm)
elapsed = 0
while self.player.is_playing() or elapsed < 5:
#time.sleep(0.005)
elapsed = (time.time() - start)
notes = self.gather_notes(elapsed)
self.render_notes(r, notes, elapsed)
# if elapsed >= totalsecs + 3:
# break
finally:
self.player.stop()
def last_note(self):
won = None
for kind, track in enumerate(self.tracks):
for note in track.notes:
if not won or note.time > won.time:
won = note
return won
def gather_notes(self, elapsed):
notes = []
for kind, track in enumerate(self.tracks):
notes.extend(track.at(elapsed))
return notes
def render_note(self, r, note, elapsed):
til = note.secs(self.bpm) - elapsed
if -0.05 <= til <= 0.5:
r.to(0+note.w*note.x+self.v[0], 1+note.h*note.y+self.v[1])
c = note.insignia
if til < 0:
t = clamp(0.0, 1.0, wherebetween(0, -0.05, til))
else:
t = clamp(0.0, 1.0, wherebetween(0, 0.5, til))
# opacity = lerp(1.5, 0.5, 1 - (1 - t)**8) # good
opacity = lerp(1.5, 0.5, 1 - (1 - t)**8) # good
# opacity = 1.0
rgb = note.color(opacity=opacity)
bgColor = blend(rgb)
fgColor = blend((1.0,1.0,1.0,opacity), rgb)
#fgColor = blend((1.0,1.0,1.0,opacity), (0.5,0.0,-0.5,1.0))
bg, bge = styles.bgColor.ansi16m(*bgColor), styles.bgColor.close
fg, fge = styles.color.ansi16m(*fgColor), styles.color.close
e = '\033[0m'
if til > 0:
m = '\033[1m'
m += '\033[3m' # italics
if note.upwards:
m += '\033[4m'
r(f'{bg}{fg} {m}{c}{e}{bg} {fge}{bge}')
else:
if not note.downwards and not note.upwards:
m = '\033[9m'
else:
m = '\033[0m'
# m += '\033[3m' # italics
r(f'{m}{fg} {c} {fge}{e}')
def render_notes(self, r, notes, elapsed):
r.viewport(16 + self.v[0], 8 + self.v[1])
r(f'{int(elapsed/60.0):02d}m{int(elapsed%60.0):02d}s')
for note in sorted(notes, key=lambda x: -x.time):
self.render_note(r, note, elapsed)
r.flush()
import time
class Track:
def __init__(self, bpm, notes):
self.bpm = bpm
self.notes = notes
# def before(self, now):
# return tuple(n for n in self.notes if n.secs(self.bpm) <= now)
def at(self, now):
r = []
for i, note in enumerate(self.notes):
t = note.secs(self.bpm)
if abs(now - t) < 2.0:
r.append(note)
return r
def run():
if args.verbose:
print(args)
files = [os.path.realpath(file) for file in args.args]
while True:
# shuffle?
for file in files:
try:
os.chdir(os.path.dirname(file) or '.')
file = os.path.basename(file)
bs = BeatsaberMap()
song = bs.parse(file)
song.play()
except KeyboardInterrupt:
time.sleep(1.0)
def main():
try:
global args
if not args:
args, leftovers = parser.parse_known_args()
args.args = leftovers
return run()
except IOError:
# http://stackoverflow.com/questions/15793886/how-to-avoid-a-broken-pipe-error-when-printing-a-large-amount-of-formatted-data
try:
sys.stdout.close()
except IOError:
pass
try:
sys.stderr.close()
except IOError:
pass
if __name__ == "__main__":
main()