persona-3-dual
A DS demake of Persona 3
Loading...
Searching...
No Matches
AnimationController.cpp
Go to the documentation of this file.
2#include "core/logger.hpp"
3#include <stdio.h>
4#include <string.h>
5
7
9{
10 if (instance == nullptr)
11 {
13 }
14}
15
17{
18 if (instance != nullptr)
19 {
20 delete instance;
21 }
22 instance = nullptr;
23}
24
26{
27 if (instance == nullptr)
28 {
29 create();
30 }
31 return instance;
32}
33
37
42
44{
45 if (px <= 8)
46 {
47 return TEXTURE_SIZE_8;
48 }
49 if (px <= 16)
50 {
51 return TEXTURE_SIZE_16;
52 }
53 if (px <= 32)
54 {
55 return TEXTURE_SIZE_32;
56 }
57 if (px <= 64)
58 {
59 return TEXTURE_SIZE_64;
60 }
61 if (px <= 128)
62 {
63 return TEXTURE_SIZE_128;
64 }
65 if (px <= 256)
66 {
67 return TEXTURE_SIZE_256;
68 }
69 if (px <= 512)
70 {
71 return TEXTURE_SIZE_512;
72 }
73 return TEXTURE_SIZE_1024;
74}
75
76// Identify the compiled model format.
78{
79 char magic[4];
80
81 fread(magic, 1, 4, file);
82
83 if (strncmp(magic, "MDL1", 4) == 0)
84 {
85 return ModelVersion::MDL1;
86 }
87
88 if (strncmp(magic, "MDL2", 4) == 0)
89 {
90 return ModelVersion::MDL2;
91 }
92
94}
95
96bool AnimationController::loadModel(const char* filepath)
97{
98 FILE* file = fopen(filepath, "rb");
99 if (!file)
100 {
101 logMessage(LogSeverity::ERROR, std::string("Failed to open model file: ") + (filepath ? filepath : "null"));
102 return false;
103 }
104
107 {
108 logMessage(LogSeverity::ERROR, std::string("Invalid model version in: ") + filepath);
109 fclose(file);
110 return false;
111 }
112
113 u32 numNodes, numAnims;
114 fread(&numNodes, sizeof(u32), 1, file);
115 fread(&numAnims, sizeof(u32), 1, file);
116
118 {
119 u32 texCount;
120 fread(&texCount, sizeof(u32), 1, file);
121 // Texture metadata is supplied by the generated model header.
122 fseek(file, (long)(texCount * 72), SEEK_CUR);
123 }
124
125 modelNodes.resize(numNodes);
126 rootNodes.clear();
127
128 for (u32 i = 0; i < numNodes; i++)
129 {
130 AnimNode& node = modelNodes[i];
131 node.id = i;
132 node.children.clear();
133 node.subLists.clear();
134
135 s32 pid, px, py, pz;
136 fread(&pid, sizeof(s32), 1, file);
137 fread(&px, sizeof(s32), 1, file);
138 fread(&py, sizeof(s32), 1, file);
139 fread(&pz, sizeof(s32), 1, file);
140
141 node.parentId = pid;
142 node.pivotX = (v16)px;
143 node.pivotY = (v16)py;
144 node.pivotZ = (v16)pz;
145
147 {
148 u32 subListCount;
149 fread(&subListCount, sizeof(u32), 1, file);
150 node.subLists.resize(subListCount);
151
152 for (u32 s = 0; s < subListCount; s++)
153 {
154 SubList& sl = node.subLists[s];
155 s32 texSlot;
156 u32 dlSize;
157 fread(&texSlot, sizeof(s32), 1, file);
158 fread(&dlSize, sizeof(u32), 1, file);
159
160 sl.texSlot = (int)texSlot;
161 sl.displayListSize = dlSize;
162 sl.displayList.resize(dlSize + 1);
163 sl.displayList[0] = dlSize;
164 if (dlSize > 0)
165 {
166 fread(&sl.displayList[1], sizeof(u32), dlSize, file);
167 }
168 }
169 }
170 else
171 {
172 // Legacy models contain one untextured display list per node.
173 u32 dlSize;
174 fread(&dlSize, sizeof(u32), 1, file);
175
176 SubList sl;
177 sl.texSlot = -1;
178 sl.displayListSize = dlSize;
179 sl.displayList.resize(dlSize + 1);
180 sl.displayList[0] = dlSize;
181 if (dlSize > 0)
182 {
183 fread(&sl.displayList[1], sizeof(u32), dlSize, file);
184 }
185 node.subLists.push_back(sl);
186 }
187
188 if (pid == -1)
189 {
190 rootNodes.push_back(i);
191 }
192 else if (pid >= 0 && pid < (int)numNodes)
193 {
194 modelNodes[pid].children.push_back(i);
195 }
196 }
197
198 animations.resize(numAnims);
199 for (u32 i = 0; i < numAnims; i++)
200 {
201 Animation& anim = animations[i];
202 fseek(file, 32, SEEK_CUR); // skip the 32-byte name string
203 fread(&anim.duration, sizeof(u32), 1, file);
204
205 anim.nodeTracks.resize(numNodes);
206 for (u32 n = 0; n < numNodes; n++)
207 {
208 AnimTrack& track = anim.nodeTracks[n];
209 u32 numFrames;
210 fread(&numFrames, sizeof(u32), 1, file);
211 track.frames.resize(numFrames);
212 if (numFrames > 0)
213 {
214 fread(track.frames.data(), sizeof(Keyframe), numFrames, file);
215 }
216 }
217 }
218
219 fclose(file);
220 trackIndices.assign(modelNodes.size(), 0);
221 logMessage(LogSeverity::DEBUG, "Model loaded successfully: " + std::string(filepath ? filepath : ""));
222 return true;
223}
224
226 int count, const unsigned int** bitmaps, const int* widths, const int* heights, const bool* isRGBA)
227{
229
230 textureIDs.resize(count, 0);
231
232 for (int i = 0; i < count; i++)
233 {
234 if (!bitmaps || !bitmaps[i])
235 {
236 continue;
237 }
238
239 glGenTextures(1, &textureIDs[i]);
240 glBindTexture(GL_TEXTURE_2D, textureIDs[i]);
241
242 GL_TEXTURE_TYPE_ENUM fmt = isRGBA[i] ? GL_RGBA : GL_RGB;
243
244 glTexImage2D(GL_TEXTURE_2D,
245 0,
246 fmt,
247 textureSizeToEnum(widths[i]),
248 textureSizeToEnum(heights[i]),
249 0,
250 TEXGEN_TEXCOORD | GL_TEXTURE_WRAP_S | GL_TEXTURE_WRAP_T,
251 bitmaps[i]);
252 }
253
254 return true;
255}
256
258{
259 if (textureIDs.empty())
260 {
261 return;
262 }
263
264 glDeleteTextures((int)textureIDs.size(), textureIDs.data());
265 textureIDs.clear();
266}
267
268void AnimationController::set(int animIndex, bool loop)
269{
270 if (animIndex < 0 || animIndex >= (int)animations.size())
271 {
272 logMessage(LogSeverity::WARNING, "Animation index out of bounds: " + std::to_string(animIndex));
273 return;
274 }
275 currentAnimIndex = animIndex;
276 currentFrameFP = 0;
277 animSpeedFP = 128; // 30FPS to 60FPS
278 isFinishing = false;
279 isLooping = loop;
280 fill(trackIndices.begin(), trackIndices.end(), 0);
281}
282
284{
285 if (currentAnimIndex == -1)
286 {
287 return;
288 }
289 isPlaying = true;
290 isFinishing = false;
291 if ((currentFrameFP >> 8) >= animations[currentAnimIndex].duration - 1)
292 {
293 currentFrameFP = 0;
294 fill(trackIndices.begin(), trackIndices.end(), 0);
295 }
296}
297
299{
300 isPlaying = false;
301 isFinishing = false;
302 currentFrameFP = 0;
303 fill(trackIndices.begin(), trackIndices.end(), 0);
304}
305
307{
308 isFinishing = true;
309}
310
312{
313 if (!isPlaying || currentAnimIndex == -1)
314 {
315 return;
316 }
317
319 int currentFrameInt = currentFrameFP >> 8;
320
321 if (currentFrameInt >= animations[currentAnimIndex].duration)
322 {
323 if (isFinishing || !isLooping)
324 {
325 isPlaying = false;
326 isFinishing = false;
327 if (!isLooping)
328 {
329 currentFrameFP = (animations[currentAnimIndex].duration - 1) << 8;
330 }
331 else
332 {
333 currentFrameFP = 0;
334 fill(trackIndices.begin(), trackIndices.end(), 0);
335 }
336 }
337 else
338 {
339 currentFrameFP = 0;
340 fill(trackIndices.begin(), trackIndices.end(), 0);
341 }
342 }
343}
344
346{
347 if (nodeId < 0 || nodeId >= (int)trackIndices.size())
348 {
349 logMessage(LogSeverity::ERROR, "Node ID out of bounds: " + std::to_string(nodeId));
350 return {0, 0, 0, 0, 0, 0, 0};
351 }
352
353 if (track.frames.empty())
354 {
355 return {0, 0, 0, 0, 0, 0, 0};
356 }
357 if (track.frames.size() == 1)
358 {
359 return track.frames[0];
360 }
361
362 int& cacheIdx = trackIndices[nodeId];
363
364 int timeInt = timeFP >> 8;
365
366 if (cacheIdx >= (int)track.frames.size() - 1 || timeInt < track.frames[cacheIdx].time)
367 {
368 cacheIdx = 0;
369 }
370 while (cacheIdx < (int)track.frames.size() - 1 && timeInt >= track.frames[cacheIdx + 1].time)
371 {
372 cacheIdx++;
373 }
374
375 Keyframe k1 = track.frames[cacheIdx];
376 if (cacheIdx >= (int)track.frames.size() - 1)
377 {
378 return k1;
379 }
380
381 Keyframe k2 = track.frames[cacheIdx + 1];
382 int range = k2.time - k1.time;
383 if (range == 0)
384 {
385 return k1;
386 }
387
388 int progressFP = timeFP - (k1.time << 8);
389 if (progressFP == 0)
390 {
391 return k1;
392 }
393
394 int t = (progressFP << 4) / range; // converts 8-bit frac to 12-bit frac (0..4096)
395
396 Keyframe result;
397 result.time = timeInt;
398 result.posX = k1.posX + (((k2.posX - k1.posX) * t) >> 12);
399 result.posY = k1.posY + (((k2.posY - k1.posY) * t) >> 12);
400 result.posZ = k1.posZ + (((k2.posZ - k1.posZ) * t) >> 12);
401 result.rotX = k1.rotX + (((k2.rotX - k1.rotX) * t) >> 12);
402 result.rotY = k1.rotY + (((k2.rotY - k1.rotY) * t) >> 12);
403 result.rotZ = k1.rotZ + (((k2.rotZ - k1.rotZ) * t) >> 12);
404 return result;
405}
406
408{
409 if (modelNodes.empty())
410 {
411 return;
412 }
413 glMatrixMode(GL_MODELVIEW);
414 for (int rootId : rootNodes)
415 {
416 renderNode(rootId);
417 }
418 // Wait until the geometry FIFO has consumed all commands.
419 while (GFX_BUSY)
420 {
421 }
422}
423
425{
426 if (nodeId < 0 || nodeId >= (int)modelNodes.size())
427 {
428 logMessage(LogSeverity::ERROR, "Node ID out of bounds: " + std::to_string(nodeId));
429 return;
430 }
431 AnimNode& node = modelNodes[nodeId];
432 glPushMatrix();
433
434 // Apply the current node transform around its pivot.
435 if (currentAnimIndex != -1)
436 {
437 AnimTrack& track = animations[currentAnimIndex].nodeTracks[nodeId];
438 Keyframe current = getInterpolatedFrame(track, currentFrameFP, nodeId);
439
440 glTranslatef32(node.pivotX + current.posX, node.pivotY + current.posY, node.pivotZ + current.posZ);
441 glRotateZi(current.rotZ);
442 glRotateYi(current.rotY);
443 glRotateXi(current.rotX);
444 glTranslatef32(-node.pivotX, -node.pivotY, -node.pivotZ);
445 }
446
447 // Bind textures only when the sub-list changes texture slots.
448 int currentTexSlot = -2; // -2 == "nothing bound yet this node"
449
450 for (SubList& sl : node.subLists)
451 {
452 if (sl.displayListSize == 0)
453 {
454 continue;
455 }
456
457 if (sl.texSlot != currentTexSlot)
458 {
459 while (GFX_BUSY)
460 {
461 }
462 if (sl.texSlot >= 0 && sl.texSlot < (int)textureIDs.size())
463 {
464 glBindTexture(GL_TEXTURE_2D, textureIDs[sl.texSlot]);
465 }
466 currentTexSlot = sl.texSlot;
467 }
468
469 glCallList(sl.displayList.data());
470 }
471
472 // Render child nodes recursively.
473 for (int childId : node.children)
474 {
475 renderNode(childId);
476 }
477
478 glPopMatrix(1);
479}
static ModelVersion readModelVersion(FILE *file)
ModelVersion
GameVersion version
Definition SaveTypes.hpp:0
Loads, animates, and renders a model in the DS geometry engine.
void pause()
Finishes the current animation at its next boundary.
void play()
Starts the selected animation.
std::vector< int > rootNodes
static void destroy()
Destroys the singleton instance and unloads model textures.
void render()
Renders the model hierarchy using the current animation frame.
static AnimationController * getInstance()
~AnimationController()
Releases texture objects owned by the controller.
Keyframe getInterpolatedFrame(const AnimTrack &track, int timeFP, int nodeId)
static void create()
Creates the singleton instance if it does not exist.
void update()
Advances the selected animation by one frame tick.
static int textureSizeToEnum(int px)
void stop()
Stops playback and resets the selected animation frame.
static AnimationController * instance
bool loadModel(const char *filepath)
Loads an MDL2 or legacy MDL1 model file.
std::vector< int > textureIDs
std::vector< int > trackIndices
bool loadTextures(int count, const unsigned int **bitmaps, const int *widths, const int *heights, const bool *isRGBA)
Uploads model textures to VRAM after loadModel().
std::vector< AnimNode > modelNodes
void set(int animIndex, bool loop=true)
Selects an animation.
void unloadTextures()
Deletes all model texture objects from VRAM.
std::vector< Animation > animations
void logMessage(LogSeverity severity, std::string_view message, std::source_location location)
Logs a diagnostic message and halts only for fatal messages.
Definition logger.cpp:110
Util to handle error logging.
std::vector< SubList > subLists
std::vector< int > children
std::vector< Keyframe > frames
std::vector< AnimTrack > nodeTracks
u32 displayListSize
std::vector< u32 > displayList