Repository navigation
Expand file tree
/
Copy pathmain_glfw.py
More file actions
277 lines (226 loc) · 9.25 KB
/
Copy pathmain_glfw.py
File metadata and controls
277 lines (226 loc) · 9.25 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
import resources
import math
import os
import os.path
import sys
import time
if sys.platform.startswith("linux") and not os.environ.get("PYOPENGL_PLATFORM"):
# glfw 创建的是 GLX 上下文;PyOpenGL 在本机默认选 EGL 会导致 context 跟踪失效
os.environ["PYOPENGL_PLATFORM"] = "glx"
import glfw
import live2d
from live2d.utils import log
from live2d.utils.lipsync import WavHandler
import OpenGL.GL as GL
live2d.enableLog(True)
live2d.setLogLevel(live2d.LogLevels.LV_INFO)
LOAD_FROM_JSON = False
LIVE2D_VERSION = 2
if LIVE2D_VERSION == 2:
from live2d import StandardParamsV2 as StandardParams
else:
from live2d import StandardParamsV3 as StandardParams
def load_from_generated_json():
from live2d.utils.model_json import Motion, ModelJson
m = ModelJson(version=3)
m.model = "Haru.moc3"
m.textures = [
"Haru.2048/texture_00.png",
"Haru.2048/texture_01.png",
]
m.physics = "Haru.physics3.json"
m.pose = "Haru.pose3.json"
m.display_info = "Haru.cdi3.json"
m.user_data = "Haru.userdata3.json"
for i in range(1, 3):
m.add_expression(f"F{i:02d}", f"expressions/F{i:02d}.exp3.json")
m.add_motion("Idle", Motion("motions/haru_g_idle.motion3.json", 0.5, 0.5))
m.add_motion(
"TapBody",
Motion(
"motions/haru_g_m26.motion3.json",
0.5,
0.5,
sound="sounds/haru_talk_13.wav",
),
)
m.add_group("Parameter", "EyeBlink", ["ParamEyeLOpen", "ParamEyeROpen"])
m.add_group("Parameter", "LipSync", ["ParamMouthOpenY"])
m.add_hit_area("HitArea", "Head")
m.add_hit_area("HitArea2", "Body")
model = live2d.Model()
# 内存生成的 json 先落成临时文件再按路径加载(json 内相对路径以其所在目录解析)
json_path = os.path.join(resources.RESOURCES_DIRECTORY, "v3/Haru", "_generated.model3.json")
with open(json_path, "w", encoding="utf-8") as f:
f.write(m.to_string())
model.LoadModelJson(json_path, create_renderer=False)
os.remove(json_path)
return model
def main():
display = (500, 600)
windowWidth, windowHeight = display
frameWidth, frameHeight = (0, 0)
if not glfw.init():
raise RuntimeError("glfw.init failed")
window = glfw.create_window(*display, "glfw", None, None)
if not window:
glfw.terminate()
return
glfw.make_context_current(window)
live2d.init()
live2d.glInit()
model = None
if LOAD_FROM_JSON:
model = load_from_generated_json()
elif LIVE2D_VERSION == 3:
model = live2d.Model()
model.LoadModelJson(os.path.join(resources.RESOURCES_DIRECTORY, "v3/llny/llny.model3.json"))
# model.LoadModelJson(os.path.join(resources.RESOURCES_DIRECTORY, "v3/Haru/Haru.model3.json"), create_renderer=False)
# model.LoadModelJson(os.path.join(resources.RESOURCES_DIRECTORY, "v3/绫地宁宁/nn.model3.json"), create_renderer=False)
# model.LoadModelJson(os.path.join(resources.RESOURCES_DIRECTORY, "v3/akane/InariTalk_PSDtool2.model3.json"), create_renderer=False)
elif LIVE2D_VERSION == 2:
model = live2d.Model()
# model.LoadModelJson(os.path.join(resources.RESOURCES_DIRECTORY, "v2/托尔/model0.json"),
model.LoadModelJson(os.path.join(resources.RESOURCES_DIRECTORY, "v2/kasumi2/kasumi2.model.json"),
# model.LoadModelJson(os.path.join(resources.RESOURCES_DIRECTORY, "v2/haru/haru.model.json"),
# model.LoadModelJson(os.path.join(resources.RESOURCES_DIRECTORY, "v2/hibiki/hibiki.model.json"),
# model.LoadModelJson(os.path.join(resources.RESOURCES_DIRECTORY, "v2/shizuku/shizuku.model.json"),
create_renderer=False) # Load model without creating renderer
model.CreateRenderer()
model.Resize(*display)
# Disable auto effects
model.SetAutoBlink(True)
model.SetAutoBreath(True)
wavHandler = WavHandler()
lipSyncN = 3
audioPlayed = False
def on_start_motion_callback(group, no):
log.LOGI("start motion: [%s_%d]" % (group, no))
def on_finish_motion_callback(group, no):
log.LOGI("motion finished")
# Print all parameters
print(f"Parameter Count: {model.GetParamCount()}")
paramIds = model.GetParamIds()
# for i in range(model.GetParamCount()):
# log.LOGD(paramIds[i], 0, model.GetParamValueByIndex(i), model.GetParamMaxByIndex(i),
# model.GetParamMinByIndex(i), model.GetParamDefaultByIndex(i))
# Print part IDs
partIds = model.GetPartIds()
print(f"Part Count: {len(partIds)}")
print("Part IDs:", partIds)
print("Canvas size:", model.GetCanvasSize())
print("Canvas size in pixels:", model.GetCanvasSizePixel())
print("Pixels per unit:", model.GetPixelsPerUnit())
# ---- Keyboard / drag state ----
dx, dy = 0.0, 0.0
scale = 1.0
currentTopClickedPartId = None
def getHitFeedback(x, y):
nonlocal currentTopClickedPartId
t = time.time()
hitPartIds = model.HitPart(x, y, False)
print(f"hit part cost: {(time.time() - t) * 1000:.4f}ms")
print(f"hit parts: {hitPartIds}")
if currentTopClickedPartId is not None:
pidx = partIds.index(currentTopClickedPartId)
model.SetPartOpacity(pidx, 1)
model.SetPartMultiplyColor(pidx, 1.0, 1.0, 1.0, 1.0)
print("Part Multiply Color:", model.GetPartMultiplyColor(pidx))
if len(hitPartIds) > 0:
return hitPartIds[0]
def on_key(window, key, scancode, action, mods):
nonlocal dx, dy, scale
if action != glfw.PRESS:
return
if key == glfw.KEY_LEFT:
dx -= 0.1
elif key == glfw.KEY_RIGHT:
dx += 0.1
elif key == glfw.KEY_UP:
dy += 0.1
elif key == glfw.KEY_DOWN:
dy -= 0.1
elif key == glfw.KEY_I:
scale += 0.1
elif key == glfw.KEY_U:
scale -= 0.1
elif key == glfw.KEY_R:
model.StopAllMotions()
model.ResetPose()
model.ResetAllParameters()
elif key == glfw.KEY_E:
model.ResetExpression()
glfw.set_key_callback(window, on_key)
def on_mouse_button(window, button, action, mods):
nonlocal currentTopClickedPartId
if button == glfw.MOUSE_BUTTON_LEFT and action == glfw.PRESS:
x, y = glfw.get_cursor_pos(window)
currentTopClickedPartId = getHitFeedback(x, y)
expname = model.SetRandomExpression()
print(f"random expression: {expname}")
model.StartRandomMotion(priority=3, onFinish=on_finish_motion_callback)
glfw.set_mouse_button_callback(window, on_mouse_button)
def on_cursor_pos(window, x, y):
nonlocal currentTopClickedPartId, frameWidth, frameHeight, windowWidth, windowHeight
px, py = x * frameWidth / windowWidth, y * frameHeight / windowHeight
model.Drag(px, py)
currentTopClickedPartId = getHitFeedback(px, py)
glfw.set_cursor_pos_callback(window, on_cursor_pos)
def on_framebuffer_resize(window, width, height):
nonlocal frameWidth, frameHeight
GL.glViewport(0, 0, width, height)
model.Resize(width, height)
frameWidth = width
frameHeight = height
glfw.set_framebuffer_size_callback(window, on_framebuffer_resize)
on_framebuffer_resize(window, *glfw.get_framebuffer_size(window))
def on_resize(window, w, h):
nonlocal windowWidth, windowHeight
windowWidth = w
windowHeight = h
glfw.set_window_size_callback(window, on_resize)
# Rotate animation
inc_per_sec = math.pi * 2 / 3
deg_max = 5
progress = 0
last_time = time.time()
fps_frames = 0
fps_timer = last_time
model.DestroyRenderer()
model.CreateRenderer()
# disable vsync for performance test
glfw.swap_interval(1)
while not glfw.window_should_close(window):
glfw.poll_events()
now = time.time()
progress += inc_per_sec * (now - last_time)
last_time = now
deg = math.sin(progress) * deg_max
model.Rotate(deg)
model.Update()
if currentTopClickedPartId is not None:
pidx = partIds.index(currentTopClickedPartId)
model.SetPartOpacity(pidx, 0.5)
model.SetPartMultiplyColor(pidx, 0.0, 0.0, 1.0, 0.9)
if wavHandler.Update():
model.SetParamById(StandardParams.ParamMouthOpenY, wavHandler.GetRms() * lipSyncN)
if not audioPlayed:
model.StartMotion("", 0, live2d.MotionPriority.FORCE,
on_start_motion_callback, on_finish_motion_callback)
audioPlayed = True
model.SetOffset(dx, dy)
model.SetScale(scale)
live2d.clearBuffer(1.0, 0.0, 0.0, 0.0)
model.Draw()
glfw.swap_buffers(window)
fps_frames += 1
if time.time() - fps_timer >= 1.0:
glfw.set_window_title(window, f"glfw - FPS: {fps_frames}")
fps_frames = 0
fps_timer = time.time()
live2d.dispose()
# if crashes when exiting, try to explicitly destroy the renderer before terminating glfw
# this is a workaround for a known issue in some environments where the OpenGL context is not properly released
glfw.terminate()
if __name__ == "__main__":
main()