ZAPD Update (#2851)

* git subrepo clone --force --branch=rebase2 C:/ZeldaStuff/ZAPDTR ZAPDTR/

subrepo:
  subdir:   "ZAPDTR"
  merged:   "6aa54a551"
upstream:
  origin:   "C:/ZeldaStuff/ZAPDTR"
  branch:   "rebase2"
  commit:   "6aa54a551"
git-subrepo:
  version:  "0.4.3"
  origin:   "???"
  commit:   "???"

* git subrepo clone --force --branch=rebase2 C:/ZeldaStuff/ZAPDTR ZAPDTR/

subrepo:
  subdir:   "ZAPDTR"
  merged:   "88b012240"
upstream:
  origin:   "C:/ZeldaStuff/ZAPDTR"
  branch:   "rebase2"
  commit:   "88b012240"
git-subrepo:
  version:  "0.4.3"
  origin:   "???"
  commit:   "???"

* Update (its broken)

* fix the enum

* git subrepo push --remote=C:/ZeldaStuff/ZAPDTR/ ZAPDTR

subrepo:
  subdir:   "ZAPDTR"
  merged:   "b7b6e1c82"
upstream:
  origin:   "C:/ZeldaStuff/ZAPDTR/"
  branch:   "rebase2"
  commit:   "b7b6e1c82"
git-subrepo:
  version:  "0.4.3"
  origin:   "???"
  commit:   "???"

* New names for LUS actions

* git subrepo push --remote=C:/ZeldaStuff/ZAPDTR/ ZAPDTR

subrepo:
  subdir:   "ZAPDTR"
  merged:   "c5cfebeee"
upstream:
  origin:   "C:/ZeldaStuff/ZAPDTR/"
  branch:   "rebase2"
  commit:   "c5cfebeee"
git-subrepo:
  version:  "0.4.3"
  origin:   "???"
  commit:   "???"

* git subrepo clone (merge) --force --branch=rebase2 C:/ZeldaStuff/ZAPDTR ZAPDTR/

subrepo:
  subdir:   "ZAPDTR"
  merged:   "d5f4769b8"
upstream:
  origin:   "C:/ZeldaStuff/ZAPDTR"
  branch:   "rebase2"
  commit:   "d5f4769b8"
git-subrepo:
  version:  "0.4.3"
  origin:   "???"
  commit:   "???"

* Fix missing commands in the exporter.

* Cleanups.

* git subrepo pull --force --remote=https://github.com/harbourmasters/ZAPDTR --branch=master ZAPDTR

subrepo:
  subdir:   "ZAPDTR"
  merged:   "d4c35b90a"
upstream:
  origin:   "https://github.com/harbourmasters/ZAPDTR"
  branch:   "master"
  commit:   "d4c35b90a"
git-subrepo:
  version:  "0.4.3"
  origin:   "???"
  commit:   "???"

* Add unordered_map include to fix MacOS

* fix string_view

* Update Main.cpp

* fix string view

* So close I can almost taste it

* So close

* Fix missed git marker.

* Fix surface types and

* Update ZFile.cpp

* Delete Jenkinsfile

---------

Co-authored-by: Christopher Leggett <chris@leggett.dev>
Co-authored-by: briaguya <70942617+briaguya-ai@users.noreply.github.com>
This commit is contained in:
louist103 2023-05-07 19:58:50 -04:00 committed by GitHub
parent 778f548b01
commit f31a841789
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
91 changed files with 4385 additions and 7506 deletions

View File

@ -32,16 +32,18 @@ void OTRExporter_Collision::Save(ZResource* res, const fs::path& outPath, Binary
writer->Write(col->polygons[i].vtxA);
writer->Write(col->polygons[i].vtxB);
writer->Write(col->polygons[i].vtxC);
writer->Write(col->polygons[i].a);
writer->Write(col->polygons[i].b);
writer->Write(col->polygons[i].c);
writer->Write(col->polygons[i].d);
writer->Write(col->polygons[i].normX);
writer->Write(col->polygons[i].normY);
writer->Write(col->polygons[i].normZ);
writer->Write(col->polygons[i].dist);
}
writer->Write((uint32_t)col->polygonTypes.size());
writer->Write((uint32_t)col->PolygonTypes.size());
for (uint16_t i = 0; i < col->polygonTypes.size(); i++)
writer->Write(col->polygonTypes[i]);
for (uint16_t i = 0; i < col->PolygonTypes.size(); i++) {
writer->Write(col->PolygonTypes[i].data[0]);
writer->Write(col->PolygonTypes[i].data[1]);
}
writer->Write((uint32_t)col->camData->entries.size());

View File

@ -7,10 +7,9 @@ void OTRExporter_Cutscene::Save(ZResource* res, const fs::path& outPath, BinaryW
WriteHeader(cs, outPath, writer, Ship::ResourceType::SOH_Cutscene);
//writer->Write((uint32_t)cs->commands.size() + 2 + 2);
writer->Write((uint32_t)0);
int currentStream = writer->GetBaseAddress();
const auto currentStream = writer->GetBaseAddress();
writer->Write(CS_BEGIN_CUTSCENE(cs->numCommands, cs->endFrame));
@ -26,12 +25,13 @@ void OTRExporter_Cutscene::Save(ZResource* res, const fs::path& outPath, BinaryW
writer->Write(CMD_HH(0x0001, ((CutsceneCommandSetCameraPos*)cs->commands[i])->startFrame));
writer->Write(CMD_HH(cmdCamPos->endFrame, 0x0000));
for (auto& e : ((CutsceneCommandSetCameraPos*)cs->commands[i])->entries)
for (const auto& e : cs->commands[i]->entries)
{
writer->Write(CMD_BBH(e->continueFlag, e->cameraRoll, e->nextPointFrame));
writer->Write(e->viewAngle);
writer->Write(CMD_HH(e->posX, e->posY));
writer->Write(CMD_HH(e->posZ, e->unused));
CutsceneCameraPoint* point = (CutsceneCameraPoint*)e;
writer->Write(CMD_BBH(point->continueFlag, point->cameraRoll, point->nextPointFrame));
writer->Write(point->viewAngle);
writer->Write(CMD_HH(point->posX, point->posY));
writer->Write(CMD_HH(point->posZ, point->unused));
}
}
break;
@ -43,51 +43,54 @@ void OTRExporter_Cutscene::Save(ZResource* res, const fs::path& outPath, BinaryW
writer->Write(CMD_HH(0x0001, cmdCamPos->startFrame));
writer->Write(CMD_HH(cmdCamPos->endFrame, 0x0000));
for (auto& e : ((CutsceneCommandSetCameraPos*)cs->commands[i])->entries)
for (const auto& e : cs->commands[i]->entries)
{
writer->Write(CMD_BBH(e->continueFlag, e->cameraRoll, e->nextPointFrame));
writer->Write(e->viewAngle);
writer->Write(CMD_HH(e->posX, e->posY));
writer->Write(CMD_HH(e->posZ, e->unused));
CutsceneCameraPoint* point = (CutsceneCameraPoint*)e;
writer->Write(CMD_BBH(point->continueFlag, point->cameraRoll, point->nextPointFrame));
writer->Write(point->viewAngle);
writer->Write(CMD_HH(point->posX, point->posY));
writer->Write(CMD_HH(point->posZ, point->unused));
}
break;
}
case (uint32_t)CutsceneCommands::SpecialAction:
case (uint32_t)CutsceneCommands::Misc:
{
writer->Write(CS_CMD_MISC);
writer->Write((uint32_t)CMD_W(((CutsceneCommandSpecialAction*)cs->commands[i])->entries.size()));
for (auto& e : ((CutsceneCommandSpecialAction*)cs->commands[i])->entries) //All in OOT seem to only have 1 entry
writer->Write((uint32_t)CMD_W((cs->commands[i])->entries.size()));
for (const auto& e : cs->commands[i]->entries) //All in OOT seem to only have 1 entry
{
writer->Write(CMD_HH(e->base, e->startFrame));
writer->Write(CMD_HH(e->endFrame, e->unused0));
writer->Write(CMD_W(e->unused1));
writer->Write(CMD_W(e->unused2));
writer->Write(CMD_W(e->unused3));
writer->Write(CMD_W(e->unused4));
writer->Write(CMD_W(e->unused5));
writer->Write(CMD_W(e->unused6));
writer->Write(CMD_W(e->unused7));
writer->Write(CMD_W(e->unused8));
writer->Write(CMD_W(e->unused9));
writer->Write(CMD_W(e->unused10));
CutsceneSubCommandEntry_GenericCmd* cmd = (CutsceneSubCommandEntry_GenericCmd*)e;
writer->Write(CMD_HH(cmd->base, cmd->startFrame));
writer->Write(CMD_HH(cmd->endFrame, cmd->pad));
writer->Write(CMD_W(cmd->unused1));
writer->Write(CMD_W(cmd->unused2));
writer->Write(CMD_W(cmd->unused3));
writer->Write(CMD_W(cmd->unused4));
writer->Write(CMD_W(cmd->unused5));
writer->Write(CMD_W(cmd->unused6));
writer->Write(CMD_W(cmd->unused7));
writer->Write(CMD_W(cmd->unused8));
writer->Write(CMD_W(cmd->unused9));
writer->Write(CMD_W(cmd->unused10));
}
break;
}
case (uint32_t)CutsceneCommands::SetLighting:
{
writer->Write(CS_CMD_SET_LIGHTING);
writer->Write((uint32_t)CMD_W(((CutsceneCommandEnvLighting*)cs->commands[i])->entries.size()));
for (auto& e : ((CutsceneCommandEnvLighting*)cs->commands[i])->entries)
writer->Write((uint32_t)CMD_W((cs->commands[i])->entries.size()));
for (const auto& e : cs->commands[i]->entries)
{
writer->Write(CMD_HH(e->setting, e->startFrame));
writer->Write(CMD_HH(e->endFrame, e->unused0));
writer->Write(CMD_W(e->unused1));
writer->Write(CMD_W(e->unused2));
writer->Write(CMD_W(e->unused3));
writer->Write(CMD_W(e->unused4));
writer->Write(CMD_W(e->unused5));
writer->Write(CMD_W(e->unused6));
writer->Write(CMD_W(e->unused7));
CutsceneSubCommandEntry_GenericCmd* cmd = (CutsceneSubCommandEntry_GenericCmd*)e;
writer->Write(CMD_HH(cmd->base, cmd->startFrame));
writer->Write(CMD_HH(cmd->endFrame, cmd->pad));
writer->Write(CMD_W(cmd->unused1));
writer->Write(CMD_W(cmd->unused2));
writer->Write(CMD_W(cmd->unused3));
writer->Write(CMD_W(cmd->unused4));
writer->Write(CMD_W(cmd->unused5));
writer->Write(CMD_W(cmd->unused6));
writer->Write(CMD_W(cmd->unused7));
writer->Write((uint32_t)0x0);
writer->Write((uint32_t)0x0);
writer->Write((uint32_t)0x0);
@ -102,12 +105,13 @@ void OTRExporter_Cutscene::Save(ZResource* res, const fs::path& outPath, BinaryW
writer->Write(CMD_HH(0x0001, ((CutsceneCommandSetCameraPos*)cs->commands[i])->startFrame));
writer->Write(CMD_HH(cmdCamPos->endFrame, 0x0000));
for (auto& e : ((CutsceneCommandSetCameraPos*)cs->commands[i])->entries)
for (const auto& e : cs->commands[i]->entries)
{
writer->Write(CMD_BBH(e->continueFlag, e->cameraRoll, e->nextPointFrame));
writer->Write(e->viewAngle);
writer->Write(CMD_HH(e->posX, e->posY));
writer->Write(CMD_HH(e->posZ, e->unused));
CutsceneCameraPoint* point = (CutsceneCameraPoint*)e;
writer->Write(CMD_BBH(point->continueFlag, point->cameraRoll, point->nextPointFrame));
writer->Write(point->viewAngle);
writer->Write(CMD_HH(point->posX, point->posY));
writer->Write(CMD_HH(point->posZ, point->unused));
}
break;
}
@ -119,12 +123,13 @@ void OTRExporter_Cutscene::Save(ZResource* res, const fs::path& outPath, BinaryW
writer->Write(CMD_HH(0x0001, ((CutsceneCommandSetCameraPos*)cs->commands[i])->startFrame));
writer->Write(CMD_HH(cmdCamPos->endFrame, 0x0000));
for (auto& e : ((CutsceneCommandSetCameraPos*)cs->commands[i])->entries)
for (const auto& e : cs->commands[i]->entries)
{
writer->Write(CMD_BBH(e->continueFlag, e->cameraRoll, e->nextPointFrame));
writer->Write(e->viewAngle);
writer->Write(CMD_HH(e->posX, e->posY));
writer->Write(CMD_HH(e->posZ, e->unused));
CutsceneCameraPoint* point = (CutsceneCameraPoint*)e;
writer->Write(CMD_BBH(point->continueFlag, point->cameraRoll, point->nextPointFrame));
writer->Write(point->viewAngle);
writer->Write(CMD_HH(point->posX, point->posY));
writer->Write(CMD_HH(point->posZ, point->unused));
}
break;
}
@ -137,24 +142,26 @@ void OTRExporter_Cutscene::Save(ZResource* res, const fs::path& outPath, BinaryW
case (uint32_t)CutsceneCommands::Cmd09:
{
writer->Write(CS_CMD_09);
writer->Write((uint32_t)CMD_W(((CutsceneCommandUnknown9*)cs->commands[i])->entries.size()));
writer->Write((uint32_t)CMD_W(((CutsceneCommand_Rumble*)cs->commands[i])->entries.size()));
for (auto& e : ((CutsceneCommandUnknown9*)cs->commands[i])->entries)
for (const auto& e : cs->commands[i]->entries)
{
writer->Write(CMD_HH(e->base, e->startFrame));
writer->Write(CMD_HBB(e->endFrame, e->unk2, e->unk3));
writer->Write(CMD_BBH(e->unk4, e->unused0, e->unused1));
CutsceneSubCommandEntry_Rumble* r = (CutsceneSubCommandEntry_Rumble*)e;
writer->Write(CMD_HH(r->base, r->startFrame));
writer->Write(CMD_HBB(e->endFrame, r->unk_06, r->unk_07));
writer->Write(CMD_BBH(r->unk_08, r->unk_09, r->unk_0A));
}
break;
}
case 0x15:
case (uint32_t)CutsceneCommands::Unknown:
case 0x15://Both unused in OoT
case 0x1A://(uint32_t)CutsceneCommands::Unknown:
{
#if 0
CutsceneCommandUnknown* cmdUnk = (CutsceneCommandUnknown*)cs->commands[i];
writer->Write((uint32_t)cs->commands[i]->commandID);
writer->Write((uint32_t)cmdUnk->entries.size());
for (auto e : cmdUnk->entries)
for (const auto e : cmdUnk->entries)
{
writer->Write(CMD_W(e->unused0));
writer->Write(CMD_W(e->unused1));
@ -169,31 +176,33 @@ void OTRExporter_Cutscene::Save(ZResource* res, const fs::path& outPath, BinaryW
writer->Write(CMD_W(e->unused10));
writer->Write(CMD_W(e->unused11));
}
#endif
}
break;
case (uint32_t)CutsceneCommands::Textbox:
{
writer->Write(CS_CMD_TEXTBOX);
writer->Write((uint32_t)CMD_W(((CutsceneCommandTextbox*)cs->commands[i])->entries.size()));
writer->Write((uint32_t)CMD_W((cs->commands[i])->entries.size()));
for (auto& e : ((CutsceneCommandTextbox*)cs->commands[i])->entries)
for (const auto& e : cs->commands[i]->entries)
{
if (e->base == 0xFFFF) // CS_TEXT_NONE
CutsceneSubCommandEntry_TextBox* textBox = (CutsceneSubCommandEntry_TextBox*)e;
if (textBox->base == 0xFFFF) // CS_TEXT_NONE
{
writer->Write(CMD_HH(0xFFFF, e->startFrame));
writer->Write(CMD_HH(e->endFrame, 0xFFFF));
writer->Write(CMD_HH(0xFFFF, textBox->startFrame));
writer->Write(CMD_HH(textBox->endFrame, 0xFFFF));
writer->Write(CMD_HH(0xFFFF, 0xFFFF));
}
else // CS_TEXT_DISPLAY_TEXTBOX
{
writer->Write(CMD_HH(e->base, e->startFrame));
writer->Write(CMD_HH(e->endFrame, e->type));
writer->Write(CMD_HH(e->textID1, e->textID2));
writer->Write(CMD_HH(textBox->base, textBox->startFrame));
writer->Write(CMD_HH(textBox->endFrame, textBox->type));
writer->Write(CMD_HH(textBox->textId1, textBox->textId2));
}
}
break;
}
case (uint32_t)CutsceneCommands::SetActorAction0:
case 10: //ActorAction0
case (uint32_t)CutsceneCommands::SetActorAction1:
case 17:
case 18:
@ -292,11 +301,12 @@ void OTRExporter_Cutscene::Save(ZResource* res, const fs::path& outPath, BinaryW
case (uint32_t)CutsceneCommands::SetActorAction10:
{
writer->Write((uint32_t)(CutsceneCommands)cs->commands[i]->commandID);
writer->Write((uint32_t)CMD_W(((CutsceneCommandActorAction*)cs->commands[i])->entries.size()));
writer->Write((uint32_t)CMD_W(cs->commands[i]->entries.size()));
for (auto& actorAct : ((CutsceneCommandActorAction*)cs->commands[i])->entries)
for (const auto& e : cs->commands[i]->entries)
{
writer->Write(CMD_HH(actorAct->action, actorAct->startFrame));
CutsceneSubCommandEntry_ActorAction* actorAct = (CutsceneSubCommandEntry_ActorAction*)e;
writer->Write(CMD_HH(actorAct->base, actorAct->startFrame));
writer->Write(CMD_HH(actorAct->endFrame, actorAct->rotX));
writer->Write(CMD_HH(actorAct->rotY, actorAct->rotZ));
writer->Write(CMD_W(actorAct->startPosX));
@ -322,24 +332,23 @@ void OTRExporter_Cutscene::Save(ZResource* res, const fs::path& outPath, BinaryW
writer->Write(CMD_HH((((CutsceneCommandSceneTransFX*)cs->commands[i])->endFrame), ((CutsceneCommandSceneTransFX*)cs->commands[i])->endFrame));
break;
}
case (uint32_t)CutsceneCommands::Nop: //Not used in OOT
break;
case (uint32_t)CutsceneCommands::PlayBGM:
{
writer->Write(CS_CMD_PLAYBGM);
writer->Write((uint32_t)CMD_W(((CutsceneCommandPlayBGM*)cs->commands[i])->entries.size()));
writer->Write((uint32_t)CMD_W(cs->commands[i]->entries.size()));
for (auto& e : ((CutsceneCommandPlayBGM*)cs->commands[i])->entries)
for (const auto& e : cs->commands[i]->entries)
{
writer->Write(CMD_HH(e->sequence, e->startFrame));
writer->Write(CMD_HH(e->endFrame, e->unknown0));
writer->Write(CMD_W(e->unknown1));
writer->Write(CMD_W(e->unknown2));
writer->Write(CMD_W(e->unknown3));
writer->Write(CMD_W(e->unknown4));
writer->Write(CMD_W(e->unknown5));
writer->Write(CMD_W(e->unknown6));
writer->Write(CMD_W(e->unknown7));
CutsceneSubCommandEntry_GenericCmd* cmd = (CutsceneSubCommandEntry_GenericCmd*)e;
writer->Write(CMD_HH(cmd->base, cmd->startFrame));
writer->Write(CMD_HH(cmd->endFrame, cmd->pad));
writer->Write(CMD_W(cmd->unused1));
writer->Write(CMD_W(cmd->unused2));
writer->Write(CMD_W(cmd->unused3));
writer->Write(CMD_W(cmd->unused4));
writer->Write(CMD_W(cmd->unused5));
writer->Write(CMD_W(cmd->unused6));
writer->Write(CMD_W(cmd->unused7));
writer->Write((uint32_t)0);
writer->Write((uint32_t)0);
writer->Write((uint32_t)0);
@ -349,19 +358,20 @@ void OTRExporter_Cutscene::Save(ZResource* res, const fs::path& outPath, BinaryW
case (uint32_t)CutsceneCommands::StopBGM:
{
writer->Write(CS_CMD_STOPBGM);
writer->Write((uint32_t)CMD_W(((CutsceneCommandStopBGM*)cs->commands[i])->entries.size()));
writer->Write((uint32_t)CMD_W(cs->commands[i]->entries.size()));
for (auto& e : ((CutsceneCommandStopBGM*)cs->commands[i])->entries)
for (const auto& e : cs->commands[i]->entries)
{
writer->Write(CMD_HH(e->sequence, e->startFrame));
writer->Write(CMD_HH(e->endFrame, e->unknown0));
writer->Write(CMD_W(e->unknown1));
writer->Write(CMD_W(e->unknown2));
writer->Write(CMD_W(e->unknown3));
writer->Write(CMD_W(e->unknown4));
writer->Write(CMD_W(e->unknown5));
writer->Write(CMD_W(e->unknown6));
writer->Write(CMD_W(e->unknown7));
CutsceneSubCommandEntry_GenericCmd* cmd = (CutsceneSubCommandEntry_GenericCmd*)e;
writer->Write(CMD_HH(cmd->base, cmd->startFrame));
writer->Write(CMD_HH(cmd->endFrame, cmd->pad));
writer->Write(CMD_W(cmd->unused1));
writer->Write(CMD_W(cmd->unused2));
writer->Write(CMD_W(cmd->unused3));
writer->Write(CMD_W(cmd->unused4));
writer->Write(CMD_W(cmd->unused5));
writer->Write(CMD_W(cmd->unused6));
writer->Write(CMD_W(cmd->unused7));
writer->Write((uint32_t)0);
writer->Write((uint32_t)0);
writer->Write((uint32_t)0);
@ -371,19 +381,20 @@ void OTRExporter_Cutscene::Save(ZResource* res, const fs::path& outPath, BinaryW
case (uint32_t)CutsceneCommands::FadeBGM:
{
writer->Write(CS_CMD_FADEBGM);
writer->Write((uint32_t)CMD_W(((CutsceneCommandFadeBGM*)cs->commands[i])->entries.size()));
writer->Write((uint32_t)CMD_W(cs->commands[i]->entries.size()));
for (auto& e : ((CutsceneCommandFadeBGM*)cs->commands[i])->entries)
for (const auto& e : cs->commands[i]->entries)
{
writer->Write(CMD_HH(e->base, e->startFrame));
writer->Write(CMD_HH(e->endFrame, e->unknown0));
writer->Write(CMD_W(e->unknown1));
writer->Write(CMD_W(e->unknown2));
writer->Write(CMD_W(e->unknown3));
writer->Write(CMD_W(e->unknown4));
writer->Write(CMD_W(e->unknown5));
writer->Write(CMD_W(e->unknown6));
writer->Write(CMD_W(e->unknown7));
CutsceneSubCommandEntry_GenericCmd* cmd = (CutsceneSubCommandEntry_GenericCmd*)e;
writer->Write(CMD_HH(cmd->base, cmd->startFrame));
writer->Write(CMD_HH(cmd->endFrame, cmd->pad));
writer->Write(CMD_W(cmd->unused1));
writer->Write(CMD_W(cmd->unused2));
writer->Write(CMD_W(cmd->unused3));
writer->Write(CMD_W(cmd->unused4));
writer->Write(CMD_W(cmd->unused5));
writer->Write(CMD_W(cmd->unused6));
writer->Write(CMD_W(cmd->unused7));
writer->Write((uint32_t)0);
writer->Write((uint32_t)0);
writer->Write((uint32_t)0);
@ -393,22 +404,24 @@ void OTRExporter_Cutscene::Save(ZResource* res, const fs::path& outPath, BinaryW
case (uint32_t)CutsceneCommands::SetTime:
{
writer->Write(CS_CMD_SETTIME);
writer->Write((uint32_t)CMD_W(((CutsceneCommandDayTime*)cs->commands[i])->entries.size()));
writer->Write((uint32_t)CMD_W(cs->commands[i]->entries.size()));
for (auto& e : ((CutsceneCommandDayTime*)cs->commands[i])->entries)
for (const auto& e : cs->commands[i]->entries)
{
writer->Write(CMD_HH(e->base, e->startFrame));
writer->Write(CMD_HBB(e->endFrame, e->hour, e->minute));
writer->Write((uint32_t)CMD_W(e->unused));
CutsceneSubCommandEntry_SetTime* t = (CutsceneSubCommandEntry_SetTime*)e;
writer->Write(CMD_HH(t->base, t->startFrame));
writer->Write(CMD_HBB(t->endFrame, t->hour, t->minute));
writer->Write((uint32_t)CMD_W(t->unk_08));
}
break;
}
case (uint32_t)CutsceneCommands::Terminator:
{
CutsceneCommand_Terminator* t = (CutsceneCommand_Terminator*)cs->commands[i];
writer->Write(CS_CMD_TERMINATOR);
writer->Write((uint32_t)1);
writer->Write(CMD_HH(((CutsceneCommandTerminator*)cs->commands[i])->base, ((CutsceneCommandTerminator*)cs->commands[i])->startFrame));
writer->Write(CMD_HH(((CutsceneCommandTerminator*)cs->commands[i])->endFrame, ((CutsceneCommandTerminator*)cs->commands[i])->endFrame));
writer->Write(CMD_HH(t->base, t->startFrame));
writer->Write(CMD_HH(t->endFrame, t->endFrame));
break;
}
default:
@ -424,8 +437,8 @@ void OTRExporter_Cutscene::Save(ZResource* res, const fs::path& outPath, BinaryW
writer->Write(0xFFFFFFFF);
writer->Write((uint32_t)0);
int endStream = writer->GetBaseAddress();
writer->Seek(currentStream - 4, SeekOffsetType::Start);
const auto endStream = writer->GetBaseAddress();
writer->Seek((uint32_t)currentStream - 4, SeekOffsetType::Start);
writer->Write((uint32_t)((endStream - currentStream) / 4));
writer->Seek(endStream, SeekOffsetType::Start);
writer->Seek((uint32_t)endStream, SeekOffsetType::Start);
}

View File

@ -80,10 +80,8 @@ void OTRExporter_Room::Save(ZResource* res, const fs::path& outPath, BinaryWrite
// This can cause issues if we export actors with garbage data, so let's trust the command size
writer->Write((uint32_t)cmdSetActorList->numActors);
for (int i = 0; i < cmdSetActorList->numActors; i++)
for (const auto& entry : cmdSetActorList->actorList->actors)
{
const ActorSpawnEntry& entry = cmdSetActorList->actors[i];
writer->Write(entry.actorNum);
writer->Write(entry.posX);
writer->Write(entry.posY);
@ -91,7 +89,7 @@ void OTRExporter_Room::Save(ZResource* res, const fs::path& outPath, BinaryWrite
writer->Write(entry.rotX);
writer->Write(entry.rotY);
writer->Write(entry.rotZ);
writer->Write(entry.initVar);
writer->Write(entry.params);
}
}
break;
@ -393,7 +391,7 @@ void OTRExporter_Room::Save(ZResource* res, const fs::path& outPath, BinaryWrite
writer->Write(entry.rotX);
writer->Write(entry.rotY);
writer->Write(entry.rotZ);
writer->Write(entry.initVar);
writer->Write(entry.params);
}
}
break;
@ -441,18 +439,18 @@ void OTRExporter_Room::Save(ZResource* res, const fs::path& outPath, BinaryWrite
case RoomCommand::SetCutscenes:
{
SetCutscenes* cmdSetCutscenes = (SetCutscenes*)cmd;
std::string listName;
Globals::Instance->GetSegmentedPtrName(cmdSetCutscenes->cmdArg2, room->parent, "CutsceneData", listName, res->parent->workerID);
std::string fName = OTRExporter_DisplayList::GetPathToRes(room, listName);
//std::string fName = StringHelper::Sprintf("%s\\%s", OTRExporter_DisplayList::GetParentFolderName(room).c_str(), listName.c_str());
writer->Write(fName);
MemoryStream* csStream = new MemoryStream();
BinaryWriter csWriter = BinaryWriter(csStream);
OTRExporter_Cutscene cs;
cs.Save(cmdSetCutscenes->cutscenes[0], "", &csWriter);
AddFile(fName, csStream->ToVector());
}
break;

View File

@ -15,15 +15,15 @@ void OTRExporter_Skeleton::Save(ZResource* res, const fs::path& outPath, BinaryW
writer->Write((uint32_t)skel->limbCount);
writer->Write((uint32_t)skel->dListCount);
writer->Write((uint8_t)skel->limbsTable.limbType);
writer->Write((uint32_t)skel->limbsTable.count);
writer->Write((uint8_t)skel->limbsTable->limbType);
writer->Write((uint32_t)skel->limbsTable->count);
for (size_t i = 0; i < skel->limbsTable.count; i++)
for (size_t i = 0; i < skel->limbsTable->count; i++)
{
Declaration* skelDecl = skel->parent->GetDeclarationRanged(GETSEGOFFSET(skel->limbsTable.limbsAddresses[i]));
Declaration* skelDecl = skel->parent->GetDeclarationRanged(GETSEGOFFSET(skel->limbsTable->limbsAddresses[i]));
std::string name;
bool foundDecl = Globals::Instance->GetSegmentedPtrName(skel->limbsTable.limbsAddresses[i], skel->parent, "", name, res->parent->workerID);
bool foundDecl = Globals::Instance->GetSegmentedPtrName(skel->limbsTable->limbsAddresses[i], skel->parent, "", name, res->parent->workerID);
if (foundDecl)
{
if (name.at(0) == '&')

View File

@ -4,9 +4,9 @@
; git-subrepo command. See https://github.com/git-commands/git-subrepo#readme
;
[subrepo]
remote = https://github.com/HarbourMasters/ZAPDTR.git
remote = https://github.com/harbourmasters/ZAPDTR
branch = master
commit = e23b125d89bd973998d2eb00896bcbaf1b53a329
parent = 17b1a8e7fd5517f9232e531da0fed6ef80a87f04
commit = d4c35b90aed66eeed61066b4b76e488bfab52b4d
parent = 9d17e19a1dcf2b5c6cef0d3c93816f98a280eb58
method = rebase
cmdver = 0.4.3

View File

@ -50,17 +50,19 @@ void ExporterExample_Collision::Save(ZResource* res, [[maybe_unused]] const fs::
writer->Write(col->polygons[i].vtxA);
writer->Write(col->polygons[i].vtxB);
writer->Write(col->polygons[i].vtxC);
writer->Write(col->polygons[i].a);
writer->Write(col->polygons[i].b);
writer->Write(col->polygons[i].c);
writer->Write(col->polygons[i].d);
writer->Write(col->polygons[i].normX);
writer->Write(col->polygons[i].normY);
writer->Write(col->polygons[i].normZ);
writer->Write(col->polygons[i].dist);
}
writer->Seek(col->polyTypeDefSegmentOffset, SeekOffsetType::Start);
for (uint16_t i = 0; i < col->polygonTypes.size(); i++)
writer->Write(col->polygonTypes[i]);
for (const auto& poly : col->polygonTypes)
{
writer->Write(poly.data[0]);
writer->Write(poly.data[1]);
}
writer->Seek(col->camDataSegmentOffset, SeekOffsetType::Start);
for (auto entry : col->camData->entries)

View File

@ -1,160 +1,160 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{65608eb0-1a47-45ad-ab66-192fb64c762c}</ProjectGuid>
<RootNamespace>ExporterTest</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
<ProjectName>ExporterExample</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
<IncludePath>$(ProjectDir)..\ZAPD\;$(ProjectDir)..\ZAPDUtils;$(ProjectDir)..\lib\tinyxml2;$(ProjectDir)..\lib\libgfxd;$(ProjectDir)..\lib\elfio;$(ProjectDir)..\lib\stb;$(ProjectDir);$(IncludePath)</IncludePath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<LanguageStandard_C>stdc11</LanguageStandard_C>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="CollisionExporter.h" />
<ClInclude Include="TextureExporter.h" />
<ClInclude Include="RoomExporter.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="CollisionExporter.cpp" />
<ClCompile Include="TextureExporter.cpp" />
<ClCompile Include="Main.cpp" />
<ClCompile Include="RoomExporter.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{65608eb0-1a47-45ad-ab66-192fb64c762c}</ProjectGuid>
<RootNamespace>ExporterTest</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
<ProjectName>ExporterExample</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
<IncludePath>$(ProjectDir)..\ZAPD\;$(ProjectDir)..\ZAPDUtils;$(ProjectDir)..\lib\tinyxml2;$(ProjectDir)..\lib\libgfxd;$(ProjectDir)..\lib\elfio;$(ProjectDir)..\lib\stb;$(ProjectDir);$(IncludePath)</IncludePath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<LanguageStandard_C>stdc11</LanguageStandard_C>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="CollisionExporter.h" />
<ClInclude Include="TextureExporter.h" />
<ClInclude Include="RoomExporter.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="CollisionExporter.cpp" />
<ClCompile Include="TextureExporter.cpp" />
<ClCompile Include="Main.cpp" />
<ClCompile Include="RoomExporter.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -334,7 +334,7 @@ void ExporterExample_Room::Save(ZResource* res, const fs::path& outPath, BinaryW
writer->Write(entry.rotX);
writer->Write(entry.rotY);
writer->Write(entry.rotZ);
writer->Write(entry.initVar);
writer->Write(entry.params);
}
writer->Seek(oldOffset, SeekOffsetType::Start);

97
ZAPDTR/Jenkinsfile vendored
View File

@ -1,97 +0,0 @@
pipeline {
agent {
label 'ZAPD'
}
stages {
// Non-parallel ZAPD stage
stage('Build ZAPD') {
steps {
sh 'make -j WERROR=1'
}
}
// CHECKOUT THE REPOS
stage('Checkout Repos') {
parallel {
stage('Checkout oot') {
steps {
dir('oot') {
git url: 'https://github.com/zeldaret/oot.git'
}
}
}
stage('Checkout mm') {
steps{
dir('mm') {
git url: 'https://github.com/zeldaret/mm.git'
}
}
}
}
}
// SETUP THE REPOS
stage('Set up repos') {
parallel {
stage('Setup OOT') {
steps {
dir('oot') {
sh 'cp /usr/local/etc/roms/baserom_oot.z64 baserom_original.z64'
// Identical to `make setup` except for copying our newer ZAPD.out into oot
sh 'git submodule update --init --recursive'
sh 'make -C tools'
sh 'cp ../ZAPD.out tools/ZAPD/'
sh 'python3 fixbaserom.py'
sh 'python3 extract_baserom.py'
sh 'python3 extract_assets.py'
}
}
}
stage('Setup MM') {
steps {
dir('mm') {
sh 'cp /usr/local/etc/roms/mm.us.rev1.z64 baserom.mm.us.rev1.z64'
// Identical to `make setup` except for copying our newer ZAPD.out into mm
sh 'make -C tools'
sh 'cp ../ZAPD.out tools/ZAPD/'
sh 'python3 tools/fixbaserom.py'
sh 'python3 tools/extract_baserom.py'
sh 'python3 extract_assets.py -t$(nproc)'
}
}
}
}
}
// BUILD THE REPOS
stage('Build repos') {
parallel {
stage('Build oot') {
steps {
dir('oot') {
sh 'make -j'
}
}
}
stage('Build mm') {
steps {
dir('mm') {
sh 'make -j disasm'
sh 'make -j all'
}
}
}
}
}
}
post {
always {
cleanWs()
}
}
}

134
ZAPDTR/Makefile Normal file
View File

@ -0,0 +1,134 @@
# use variables in submakes
export
OPTIMIZATION_ON ?= 1
ASAN ?= 0
DEPRECATION_ON ?= 1
DEBUG ?= 0
COPYCHECK_ARGS ?=
LLD ?= 0
WERROR ?= 0
# Use clang++ if available, else use g++
ifeq ($(shell command -v clang++ >/dev/null 2>&1; echo $$?),0)
CXX := clang++
else
CXX := g++
endif
INC := -I ZAPD -I lib/libgfxd -I lib/tinyxml2 -I ZAPDUtils
CXXFLAGS := -fpic -std=c++17 -Wall -Wextra -fno-omit-frame-pointer
OPTFLAGS :=
ifneq ($(DEBUG),0)
OPTIMIZATION_ON = 0
CXXFLAGS += -g3 -DDEVELOPMENT -D_DEBUG
COPYCHECK_ARGS += --devel
DEPRECATION_ON = 0
endif
ifneq ($(WERROR),0)
CXXFLAGS += -Werror
endif
ifeq ($(OPTIMIZATION_ON),0)
OPTFLAGS := -O0
else
OPTFLAGS := -O2
endif
ifneq ($(ASAN),0)
CXXFLAGS += -fsanitize=address -fsanitize=pointer-compare -fsanitize=pointer-subtract -fsanitize=undefined
endif
ifneq ($(DEPRECATION_ON),0)
CXXFLAGS += -DDEPRECATION_ON
endif
# CXXFLAGS += -DTEXTURE_DEBUG
LDFLAGS := -lm -ldl -lpng
# Use LLD if available. Set LLD=0 to not use it
ifeq ($(shell command -v ld.lld >/dev/null 2>&1; echo $$?),0)
LLD := 1
endif
ifneq ($(LLD),0)
LDFLAGS += -fuse-ld=lld
endif
UNAME := $(shell uname)
UNAMEM := $(shell uname -m)
ifneq ($(UNAME), Darwin)
LDFLAGS += -Wl,-export-dynamic -lstdc++fs
EXPORTERS := -Wl,--whole-archive ExporterTest/ExporterTest.a -Wl,--no-whole-archive
else
EXPORTERS := -Wl,-force_load ExporterTest/ExporterTest.a
ifeq ($(UNAMEM),arm64)
ifeq ($(shell brew list libpng > /dev/null 2>&1; echo $$?),0)
LDFLAGS += -L $(shell brew --prefix)/lib
INC += -I $(shell brew --prefix)/include
else
$(error Please install libpng via Homebrew)
endif
endif
endif
ZAPD_SRC_DIRS := $(shell find ZAPD -type d)
SRC_DIRS = $(ZAPD_SRC_DIRS) lib/tinyxml2
ZAPD_CPP_FILES := $(foreach dir,$(ZAPD_SRC_DIRS),$(wildcard $(dir)/*.cpp))
ZAPD_H_FILES := $(foreach dir,$(ZAPD_SRC_DIRS),$(wildcard $(dir)/*.h))
CPP_FILES += $(ZAPD_CPP_FILES) lib/tinyxml2/tinyxml2.cpp
O_FILES := $(foreach f,$(CPP_FILES:.cpp=.o),build/$f)
O_FILES += build/ZAPD/BuildInfo.o
# create build directories
$(shell mkdir -p $(foreach dir,$(SRC_DIRS),build/$(dir)))
# Main targets
all: ZAPD.out copycheck
build/ZAPD/BuildInfo.o:
python3 ZAPD/genbuildinfo.py $(COPYCHECK_ARGS)
$(CXX) $(CXXFLAGS) $(OPTFLAGS) $(INC) -c $(OUTPUT_OPTION) build/ZAPD/BuildInfo.cpp
copycheck: ZAPD.out
python3 copycheck.py
clean:
rm -rf build ZAPD.out
$(MAKE) -C lib/libgfxd clean
$(MAKE) -C ZAPDUtils clean
$(MAKE) -C ExporterTest clean
rebuild: clean all
format:
clang-format-11 -i $(ZAPD_CPP_FILES) $(ZAPD_H_FILES)
$(MAKE) -C ZAPDUtils format
$(MAKE) -C ExporterTest format
.PHONY: all build/ZAPD/BuildInfo.o copycheck clean rebuild format
build/%.o: %.cpp
$(CXX) $(CXXFLAGS) $(OPTFLAGS) $(INC) -c $(OUTPUT_OPTION) $<
# Submakes
lib/libgfxd/libgfxd.a:
$(MAKE) -C lib/libgfxd
.PHONY: ExporterTest
ExporterTest:
$(MAKE) -C ExporterTest
.PHONY: ZAPDUtils
ZAPDUtils:
$(MAKE) -C ZAPDUtils
# Linking
ZAPD.out: $(O_FILES) lib/libgfxd/libgfxd.a ExporterTest ZAPDUtils
$(CXX) $(CXXFLAGS) $(O_FILES) lib/libgfxd/libgfxd.a ZAPDUtils/ZAPDUtils.a $(EXPORTERS) $(LDFLAGS) $(OUTPUT_OPTION)

View File

@ -71,9 +71,6 @@ ZAPD needs a _File parsing mode_ to be passed as first parameter. The options ar
- `blb`: "Build blob" mode.
- In this mode, ZAPD expects a BIN file as input and a filename as ouput.
- ZAPD will try to convert the given BIN into the contents of a `uint8_t` C array.
- `bovl`: "Build overlay" mode.
- In this mode, ZAPD expects an overlay C file as input, a filename as ouput and an overlay configuration path (`-cfg`).
- ZAPD will generate a reloc `.s` file.
ZAPD also accepts the following list of extra parameters:
@ -102,8 +99,6 @@ ZAPD also accepts the following list of extra parameters:
- `ia16`
- `ci4`
- `ci8`
- `-cfg PATH`: Set cfg path (for overlays).
- Can be used only in `bovl` mode.
- `-rconf PATH` Read Config File.
- `-eh`: Enable error handler.
- Only available in non-Windows environments.

View File

@ -17,6 +17,7 @@ set(Header_Files
"ImageBackend.h"
"OutputFormatter.h"
"WarningHandler.h"
"CrashHandler.h"
)
source_group("Header Files" FILES ${Header_Files})
@ -27,22 +28,6 @@ set(Header_Files__Libraries
)
source_group("Header Files\\Libraries" FILES ${Header_Files__Libraries})
set(Header_Files__Libraries__elfio
"../lib/elfio/elfio/elf_types.hpp"
"../lib/elfio/elfio/elfio.hpp"
"../lib/elfio/elfio/elfio_dump.hpp"
"../lib/elfio/elfio/elfio_dynamic.hpp"
"../lib/elfio/elfio/elfio_header.hpp"
"../lib/elfio/elfio/elfio_note.hpp"
"../lib/elfio/elfio/elfio_relocation.hpp"
"../lib/elfio/elfio/elfio_section.hpp"
"../lib/elfio/elfio/elfio_segment.hpp"
"../lib/elfio/elfio/elfio_strings.hpp"
"../lib/elfio/elfio/elfio_symbols.hpp"
"../lib/elfio/elfio/elfio_utils.hpp"
)
source_group("Header Files\\Libraries\\elfio" FILES ${Header_Files__Libraries__elfio})
set(Header_Files__Libraries__libgfxd
"../lib/libgfxd/gbi.h"
"../lib/libgfxd/gfxd.h"
@ -58,15 +43,17 @@ source_group("Header Files\\Yaz0" FILES ${Header_Files__Yaz0})
set(Header_Files__Z64
"OtherStructs/SkinLimbStructs.h"
"Overlays/ZOverlay.h"
"OtherStructs/CutsceneMM_Commands.h"
"OtherStructs/Cutscene_Commands.h"
"ZAnimation.h"
"ZActorList.h"
"ZArray.h"
"ZAudio.h"
"ZBackground.h"
"ZBlob.h"
"ZCollision.h"
"ZCollisionPoly.h"
"ZCutscene.h"
"ZCutsceneMM.h"
"ZDisplayList.h"
"ZFile.h"
"ZLimb.h"
@ -77,6 +64,7 @@ set(Header_Files__Z64
"ZRom.h"
"ZScalar.h"
"ZSkeleton.h"
"ZSurfaceType.h"
"ZString.h"
"ZSymbol.h"
"ZText.h"
@ -136,6 +124,7 @@ set(Resource_Files
source_group("Resource Files" FILES ${Resource_Files})
set(Source_Files
"CrashHandler.cpp"
"Declaration.cpp"
"FileWorker.cpp"
"GameConfig.cpp"
@ -165,16 +154,18 @@ source_group("Source Files\\Yaz0" FILES ${Source_Files__Yaz0})
set(Source_Files__Z64
"OtherStructs/SkinLimbStructs.cpp"
"Overlays/ZOverlay.cpp"
"OtherStructs/CutsceneMM_Commands.cpp"
"OtherStructs/Cutscene_Commands.cpp"
"ZAnimation.cpp"
"ZActorList.cpp"
"ZArray.cpp"
"ZAudio.cpp"
"ZAudioDecode.cpp"
"ZBackground.cpp"
"ZBlob.cpp"
"ZCollision.cpp"
"ZCollisionPoly.cpp"
"ZCutscene.cpp"
"ZCutsceneMM.cpp"
"ZDisplayList.cpp"
"ZFile.cpp"
"ZLimb.cpp"
@ -185,6 +176,7 @@ set(Source_Files__Z64
"ZRom.cpp"
"ZScalar.cpp"
"ZSkeleton.cpp"
"ZSurfaceType.cpp"
"ZString.cpp"
"ZSymbol.cpp"
"ZText.cpp"
@ -241,7 +233,6 @@ source_group("Source Files\\Z64\\ZRoom\\Commands" FILES ${Source_Files__Z64__ZRo
set(ALL_FILES
${Header_Files}
${Header_Files__Libraries}
${Header_Files__Libraries__elfio}
${Header_Files__Libraries__libgfxd}
${Header_Files__Yaz0}
${Header_Files__Z64}

View File

@ -0,0 +1,205 @@
#include "CrashHandler.h"
#include "Utils/StringHelper.h"
#if __has_include(<unistd.h>)
#define HAS_POSIX 1
#else
#define HAS_POSIX 0
#endif
#include <array>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#if HAS_POSIX == 1
#include <csignal>
#include <cxxabi.h> // for __cxa_demangle
#include <dlfcn.h> // for dladdr
#include <execinfo.h>
#include <unistd.h>
#elif defined(_MSC_VER)
#include <Windows.h>
#include <DbgHelp.h>
#include <inttypes.h>
#pragma comment(lib, "Dbghelp.lib")
#endif
// Feel free to add more crash messages.
static std::array<const char* const, 14> crashEasterEgg = {
"\tYou've met with a terrible fate, haven't you?",
"\tSEA BEARS FOAM. SLEEP BEARS DREAMS. \n\tBOTH END IN THE SAME WAY: CRASSSH!",
"\tZAPD has fallen and cannot get up.",
"\tIT'S A SECRET TO EVERYBODY. \n\tBut it shouldn't be, you'd better ask about it!",
"\tI AM ERROR.",
"\tGRUMBLE,GRUMBLE...",
"\tDODONGO DISLIKES SMOKE \n\tAnd ZAPD dislikes whatever you fed it.",
"\tMay the way of the Hero lead \n\tto the debugger.",
"\tTHE WIND FISH SLUMBERS LONG... \n\tTHE HERO'S LIFE GONE... ",
"\tSEA BEARS FOAM, SLEEP BEARS DREAMS. \n\tBOTH END IN THE SAME WAY CRASSSH!",
"\tYou've met with a terrible fate, haven't you?",
"\tMaster, I calculate a 100% probability that ZAPD has crashed. \n\tAdditionally, the "
"batteries in your Wii Remote are nearly depleted.",
"\t CONGRATURATIONS! \n"
"\tAll Pages are displayed.\n"
"\t THANK YOU! \n"
"\t You are great debugger!",
"\tRCP is HUNG UP!!\n"
"\tOh! MY GOD!!",
};
#if HAS_POSIX == 1
void ErrorHandler(int sig)
{
std::array<void*, 4096> arr;
constexpr size_t nMaxFrames = arr.size();
size_t size = backtrace(arr.data(), nMaxFrames);
char** symbols = backtrace_symbols(arr.data(), nMaxFrames);
fprintf(stderr, "\nZAPD crashed. (Signal: %i)\n", sig);
srand(time(nullptr));
auto easterIndex = rand() % crashEasterEgg.size();
fprintf(stderr, "\n%s\n\n", crashEasterEgg[easterIndex]);
fprintf(stderr, "Traceback:\n");
for (size_t i = 1; i < size; i++)
{
Dl_info info;
uint32_t gotAddress = dladdr(arr[i], &info);
std::string functionName(symbols[i]);
if (gotAddress != 0 && info.dli_sname != nullptr)
{
int32_t status;
char* demangled = abi::__cxa_demangle(info.dli_sname, nullptr, nullptr, &status);
const char* nameFound = info.dli_sname;
if (status == 0)
{
nameFound = demangled;
}
functionName = StringHelper::Sprintf("%s (+0x%X)", nameFound,
(char*)arr[i] - (char*)info.dli_saddr);
free(demangled);
}
fprintf(stderr, "%-3zd %s\n", i, functionName.c_str());
}
fprintf(stderr, "\n");
free(symbols);
exit(1);
}
#elif defined(_MSC_VER)
void printStack(CONTEXT* ctx)
{
BOOL result;
HANDLE process;
HANDLE thread;
HMODULE hModule;
ULONG frame;
DWORD64 displacement;
DWORD disp;
srand(time(nullptr));
auto easterIndex = rand() % crashEasterEgg.size();
fprintf(stderr, "\n%s\n\n", crashEasterEgg[easterIndex]);
#if defined(_M_AMD64)
STACKFRAME64 stack;
memset(&stack, 0, sizeof(STACKFRAME64));
#else
STACKFRAME stack;
memset(&stack, 0, sizeof(STACKFRAME));
#endif
char buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME + sizeof(TCHAR)];
char module[512];
PSYMBOL_INFO symbol = (PSYMBOL_INFO)buffer;
CONTEXT ctx2;
memcpy(&ctx2, ctx, sizeof(CONTEXT));
process = GetCurrentProcess();
thread = GetCurrentThread();
SymInitialize(process, nullptr, TRUE);
constexpr DWORD machineType =
#if defined(_M_AMD64)
IMAGE_FILE_MACHINE_AMD64;
#else
IMAGE_FILE_MACHINE_I386;
#endif
displacement = 0;
for (frame = 0;; frame++)
{
result = StackWalk(machineType, process, thread, &stack, &ctx2, nullptr,
SymFunctionTableAccess, SymGetModuleBase, nullptr);
if (!result)
{
break;
}
symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
symbol->MaxNameLen = MAX_SYM_NAME;
SymFromAddr(process, (ULONG64)stack.AddrPC.Offset, &displacement, symbol);
#if defined(_M_AMD64)
IMAGEHLP_LINE64 line;
line.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
#else
IMAGEHLP_LINE line;
line.SizeOfStruct = sizeof(IMAGEHLP_LINE);
#endif
if (SymGetLineFromAddr(process, stack.AddrPC.Offset, &disp, &line))
{
fprintf(stderr, "%u\t %s in %s: line: %lu: \n", frame, symbol->Name, line.FileName,
line.LineNumber);
}
else
{
fprintf(stderr, "%u\tat % s\n", frame, symbol->Name);
hModule = nullptr;
GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
(LPCTSTR)(stack.AddrPC.Offset), &hModule);
if (hModule != nullptr)
{
GetModuleFileNameA(hModule, module, 512 - 1);
}
fprintf(stderr, "%u\tIn %s\n", frame, module);
}
}
}
LONG seh_filter(_EXCEPTION_POINTERS* ex)
{
fprintf(stderr, "EXCEPTION 0x%x occured\n", ex->ExceptionRecord->ExceptionCode);
printStack(ex->ContextRecord);
return EXCEPTION_EXECUTE_HANDLER;
}
#endif
void CrashHandler_Init()
{
#if HAS_POSIX == 1
signal(SIGSEGV, ErrorHandler);
signal(SIGABRT, ErrorHandler);
#elif defined(_MSC_VER)
SetUnhandledExceptionFilter(seh_filter);
#else
HANDLE_WARNING(WarningType::Always,
"tried to set error handler, but this ZAPD build lacks support for one", "");
#endif
}

View File

@ -0,0 +1,6 @@
#ifndef CRASH_HANDLER_H
#define CRASH_HANDLER_H
void CrashHandler_Init();
#endif

View File

@ -178,7 +178,7 @@ std::string Declaration::GetExternalDeclarationStr() const
std::string Declaration::GetExternStr() const
{
if (IsStatic() || varType == "")
if (IsStatic() || varType == "" || isUnaccounted)
{
return "";
}

View File

@ -2,6 +2,7 @@
#include <functional>
#include <string_view>
#include <unordered_map>
#include "Utils/Directory.h"
#include "Utils/File.h"
@ -94,6 +95,26 @@ void GameConfig::ConfigFunc_ObjectList(const tinyxml2::XMLElement& element)
objectList.emplace_back(std::move(line));
}
void GameConfig::ConfigFunc_EntranceList(const tinyxml2::XMLElement& element)
{
std::string fileName = element.Attribute("File");
std::vector<std::string> lines =
File::ReadAllLines(Path::GetDirectoryName(configFilePath) / fileName);
for (auto& line : lines)
entranceList.emplace_back(std::move(line));
}
void GameConfig::ConfigFunc_specialEntranceList(const tinyxml2::XMLElement& element)
{
std::string fileName = element.Attribute("File");
std::vector<std::string> lines =
File::ReadAllLines(Path::GetDirectoryName(configFilePath) / fileName);
for (auto& line : lines)
specialEntranceList.emplace_back(std::move(line));
}
void GameConfig::ConfigFunc_TexturePool(const tinyxml2::XMLElement& element)
{
std::string fileName = element.Attribute("File");
@ -145,10 +166,12 @@ void GameConfig::ConfigFunc_ExternalFile(const tinyxml2::XMLElement& element)
void GameConfig::ReadConfigFile(const fs::path& argConfigFilePath)
{
static const std::map<std::string, ConfigFunc> ConfigFuncDictionary = {
static const std::unordered_map<std::string, ConfigFunc> ConfigFuncDictionary = {
{"SymbolMap", &GameConfig::ConfigFunc_SymbolMap},
{"ActorList", &GameConfig::ConfigFunc_ActorList},
{"ObjectList", &GameConfig::ConfigFunc_ObjectList},
{"EntranceList", &GameConfig::ConfigFunc_EntranceList},
{"SpecialEntranceList", &GameConfig::ConfigFunc_specialEntranceList},
{"TexturePool", &GameConfig::ConfigFunc_TexturePool},
{"BGConfig", &GameConfig::ConfigFunc_BGConfig},
{"ExternalXMLFolder", &GameConfig::ConfigFunc_ExternalXMLFolder},

View File

@ -31,6 +31,8 @@ public:
std::map<uint32_t, std::string> symbolMap;
std::vector<std::string> actorList;
std::vector<std::string> objectList;
std::vector<std::string> entranceList;
std::vector<std::string> specialEntranceList;
std::map<uint32_t, TexturePoolEntry> texturePool; // Key = CRC
// ZBackground
@ -49,6 +51,8 @@ public:
void ConfigFunc_SymbolMap(const tinyxml2::XMLElement& element);
void ConfigFunc_ActorList(const tinyxml2::XMLElement& element);
void ConfigFunc_ObjectList(const tinyxml2::XMLElement& element);
void ConfigFunc_EntranceList(const tinyxml2::XMLElement& element);
void ConfigFunc_specialEntranceList(const tinyxml2::XMLElement& element);
void ConfigFunc_TexturePool(const tinyxml2::XMLElement& element);
void ConfigFunc_BGConfig(const tinyxml2::XMLElement& element);
void ConfigFunc_ExternalXMLFolder(const tinyxml2::XMLElement& element);

View File

@ -398,7 +398,7 @@ void ImageBackend::SetPaletteIndex(size_t index, uint8_t nR, uint8_t nG, uint8_t
alphaPalette[index] = nA;
}
void ImageBackend::SetPalette(const ImageBackend& pal)
void ImageBackend::SetPalette(const ImageBackend& pal, uint32_t offset)
{
assert(isColorIndexed);
size_t bytePerPixel = pal.GetBytesPerPixel();
@ -422,7 +422,7 @@ void ImageBackend::SetPalette(const ImageBackend& pal)
uint8_t g = pal.pixelMatrix[y][x * bytePerPixel + 1];
uint8_t b = pal.pixelMatrix[y][x * bytePerPixel + 2];
uint8_t a = pal.pixelMatrix[y][x * bytePerPixel + 3];
SetPaletteIndex(index, r, g, b, a);
SetPaletteIndex(index + offset, r, g, b, a);
}
}
}

View File

@ -42,8 +42,9 @@ public:
void SetGrayscalePixel(size_t y, size_t x, uint8_t grayscale, uint8_t alpha = 0);
void SetIndexedPixel(size_t y, size_t x, uint8_t index, uint8_t grayscale);
void SetIndexedPixel(size_t y, size_t x, uint8_t index, RGBAPixel pixel);
void SetPaletteIndex(size_t index, uint8_t nR, uint8_t nG, uint8_t nB, uint8_t nA);
void SetPalette(const ImageBackend& pal);
void SetPalette(const ImageBackend& pal, uint32_t offset = 0);
uint32_t GetWidth() const;
uint32_t GetHeight() const;

View File

@ -1,5 +1,4 @@
#include "Globals.h"
#include "Overlays/ZOverlay.h"
#include "Utils/Directory.h"
#include "Utils/File.h"
#include "Utils/Path.h"
@ -72,15 +71,7 @@ ZRoom room(nullptr);
#include "ZFile.h"
#include "ZTexture.h"
#ifdef __linux__
#include <csignal>
#include <cstdlib>
#include <ctime>
#include <cxxabi.h> // for __cxa_demangle
#include <dlfcn.h> // for dladdr
#include <execinfo.h>
#include <unistd.h>
#endif
#include "CrashHandler.h"
#include <string>
#include <string_view>
@ -90,8 +81,6 @@ ZRoom room(nullptr);
//extern const char gBuildHash[];
const char gBuildHash[] = "";
// LINUX_TODO: remove, those are because of soh <-> lus dependency problems
bool Parse(const fs::path& xmlFilePath, const fs::path& basePath, const fs::path& outPath,
ZFileMode fileMode, int workerID);
@ -102,62 +91,6 @@ int ExtractFunc(int workerID, int fileListSize, std::string fileListItem, ZFileM
volatile int numWorkersLeft = 0;
#ifdef __linux__
#define ARRAY_COUNT(arr) (sizeof(arr) / sizeof(arr[0]))
void ErrorHandler(int sig)
{
void* array[4096];
const size_t nMaxFrames = sizeof(array) / sizeof(array[0]);
size_t size = backtrace(array, nMaxFrames);
char** symbols = backtrace_symbols(array, nMaxFrames);
fprintf(stderr, "\nZAPD crashed. (Signal: %i)\n", sig);
// Feel free to add more crash messages.
const char* crashEasterEgg[] = {
"\tYou've met with a terrible fate, haven't you?",
"\tSEA BEARS FOAM. SLEEP BEARS DREAMS. \n\tBOTH END IN THE SAME WAY: CRASSSH!",
"\tZAPD has fallen and cannot get up.",
};
srand(time(nullptr));
auto easterIndex = rand() % ARRAY_COUNT(crashEasterEgg);
fprintf(stderr, "\n%s\n\n", crashEasterEgg[easterIndex]);
fprintf(stderr, "Traceback:\n");
for (size_t i = 1; i < size; i++)
{
Dl_info info;
uint32_t gotAddress = dladdr(array[i], &info);
std::string functionName(symbols[i]);
if (gotAddress != 0 && info.dli_sname != nullptr)
{
int32_t status;
char* demangled = abi::__cxa_demangle(info.dli_sname, nullptr, nullptr, &status);
const char* nameFound = info.dli_sname;
if (status == 0)
{
nameFound = demangled;
}
functionName = StringHelper::Sprintf("%s (+0x%X)", nameFound,
(char*)array[i] - (char*)info.dli_saddr);
free(demangled);
}
fprintf(stderr, "%-3zd %s\n", i, functionName.c_str());
}
fprintf(stderr, "\n");
free(symbols);
exit(1);
}
#endif
extern void ImportExporters();
extern "C" int zapd_main(int argc, char* argv[])
@ -246,12 +179,6 @@ extern "C" int zapd_main(int argc, char* argv[])
{
Globals::Instance->texType = ZTexture::GetTextureTypeFromString(argv[++i]);
}
else if (arg == "-cfg") // Set cfg path (for overlays)
// TODO: Change the name of this to something else so it doesn't
// get confused with XML config files.
{
Globals::Instance->cfgPath = argv[++i];
}
else if (arg == "-fl") // Set baserom filelist path
{
Globals::Instance->fileListPath = argv[++i];
@ -262,16 +189,7 @@ extern "C" int zapd_main(int argc, char* argv[])
}
else if (arg == "-eh") // Enable Error Handler
{
#ifdef __linux__
signal(SIGSEGV, ErrorHandler);
signal(SIGABRT, ErrorHandler);
#else
// HANDLE_WARNING(WarningType::Always,
// "tried to set error handler, but this ZAPD build lacks support for one",
// "");
#endif
CrashHandler_Init();
}
else if (arg == "-v") // Verbose
{
@ -326,8 +244,6 @@ extern "C" int zapd_main(int argc, char* argv[])
fileMode = ZFileMode::BuildTexture;
else if (buildMode == "bren")
fileMode = ZFileMode::BuildBackground;
else if (buildMode == "bovl")
fileMode = ZFileMode::BuildOverlay;
else if (buildMode == "bsf")
fileMode = ZFileMode::BuildSourceFile;
else if (buildMode == "bblb")

View File

@ -0,0 +1,213 @@
#include "CutsceneMM_Commands.h"
#include <cassert>
#include <unordered_map>
#include "Utils/BitConverter.h"
#include "Utils/StringHelper.h"
// Specific for command lists where each entry has size 8 bytes
const std::unordered_map<CutsceneMMCommands, CsCommandListDescriptor> csCommandsDescMM = {
{CutsceneMMCommands::CS_CMD_MISC, {"CS_MISC", "(0x%02X, %i, %i, %i)"}},
{CutsceneMMCommands::CS_CMD_SET_LIGHTING, {"CS_LIGHTING", "(0x%02X, %i, %i)"}},
{CutsceneMMCommands::CS_CMD_SCENE_TRANS_FX, {"CS_SCENE_TRANS_FX", "(%i, %i, %i)"}},
{CutsceneMMCommands::CS_CMD_MOTIONBLUR, {"CS_MOTIONBLUR", "(%i, %i, %i)"}},
{CutsceneMMCommands::CS_CMD_GIVETATL, {"CS_GIVETATL", "(%i, %i, %i)"}},
{CutsceneMMCommands::CS_CMD_PLAYSEQ, {"CS_PLAYSEQ", "(0x%04X, %i, %i)"}},
{CutsceneMMCommands::CS_CMD_130, {"CS_SCENE_UNK_130", "(0x%04X, %i, %i, %i)"}},
{CutsceneMMCommands::CS_CMD_131, {"CS_SCENE_UNK_131", "(0x%04X, %i, %i, %i)"}},
{CutsceneMMCommands::CS_CMD_132, {"CS_SCENE_UNK_132", "(%i, %i, %i)"}},
{CutsceneMMCommands::CS_CMD_STOPSEQ, {"CS_STOPSEQ", "(0x%04X, %i, %i, %i)"}},
{CutsceneMMCommands::CS_CMD_PLAYAMBIENCE, {"CS_PLAYAMBIENCE", "(0x%04X, %i, %i, %i)"}},
{CutsceneMMCommands::CS_CMD_FADEAMBIENCE, {"CS_FADEAMBIENCE", "(0x%04X, %i, %i, %i)"}},
{CutsceneMMCommands::CS_CMD_TERMINATOR, {"CS_TERMINATOR", "(%i, %i, %i)"}},
{CutsceneMMCommands::CS_CMD_CHOOSE_CREDITS_SCENES,
{"CS_CHOOSE_CREDITS_SCENES", "(%i, %i, %i)"}},
};
CutsceneSubCommandEntry_GenericMMCmd::CutsceneSubCommandEntry_GenericMMCmd(
const std::vector<uint8_t>& rawData, offset_t rawDataIndex, CutsceneMMCommands cmdId)
: CutsceneSubCommandEntry(rawData, rawDataIndex), commandId(cmdId)
{
}
std::string CutsceneSubCommandEntry_GenericMMCmd::GetBodySourceCode() const
{
const auto& element = csCommandsDescMM.find(commandId);
std::string entryFmt = "CS_UNK_DATA(0x%02X, %i, %i, %i)";
if (element != csCommandsDescMM.end())
{
entryFmt = element->second.cmdMacro;
entryFmt += element->second.args;
}
return StringHelper::Sprintf(entryFmt.c_str(), base, startFrame, endFrame, pad);
}
CutsceneMMCommand_GenericCmd::CutsceneMMCommand_GenericCmd(const std::vector<uint8_t>& rawData,
offset_t rawDataIndex,
CutsceneMMCommands cmdId)
: CutsceneCommand(rawData, rawDataIndex)
{
rawDataIndex += 4;
commandID = static_cast<uint32_t>(cmdId);
entries.reserve(numEntries);
for (size_t i = 0; i < numEntries; i++)
{
auto* entry = new CutsceneSubCommandEntry_GenericMMCmd(rawData, rawDataIndex, cmdId);
entries.push_back(entry);
rawDataIndex += entry->GetRawSize();
}
}
std::string CutsceneMMCommand_GenericCmd::GetCommandMacro() const
{
const auto& element = csCommandsDescMM.find(static_cast<CutsceneMMCommands>(commandID));
if (element != csCommandsDescMM.end())
{
return StringHelper::Sprintf("%s_LIST(%i)", element->second.cmdMacro, numEntries);
}
return StringHelper::Sprintf("CS_UNK_DATA_LIST(0x%X, %i)", commandID, numEntries);
}
CutsceneSubCommandEntry_Camera::CutsceneSubCommandEntry_Camera(const std::vector<uint8_t>& rawData,
offset_t rawDataIndex)
: CutsceneSubCommandEntry(rawData, rawDataIndex)
{
}
std::string CutsceneSubCommandEntry_Camera::GetBodySourceCode() const
{
return StringHelper::Sprintf("CMD_HH(0x%04X, 0x%04X)", base, startFrame);
}
size_t CutsceneSubCommandEntry_Camera::GetRawSize() const
{
return 0x04;
}
CutsceneMMCommand_Camera::CutsceneMMCommand_Camera(const std::vector<uint8_t>& rawData,
offset_t rawDataIndex)
: CutsceneCommand(rawData, rawDataIndex)
{
rawDataIndex += 4;
entries.reserve(numEntries);
for (size_t i = 0; i < numEntries / 4; i++)
{
auto* entry = new CutsceneSubCommandEntry_Camera(rawData, rawDataIndex);
entries.push_back(entry);
rawDataIndex += entry->GetRawSize();
}
}
std::string CutsceneMMCommand_Camera::GetCommandMacro() const
{
return StringHelper::Sprintf("CS_CAMERA_LIST(%i)", numEntries);
}
CutsceneSubCommandEntry_FadeScreen::CutsceneSubCommandEntry_FadeScreen(
const std::vector<uint8_t>& rawData, offset_t rawDataIndex)
: CutsceneSubCommandEntry(rawData, rawDataIndex)
{
unk_06 = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x06);
unk_07 = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x07);
unk_08 = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x08);
unk_09 = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x09);
unk_0A = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x0A);
unk_0B = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x0B);
}
std::string CutsceneSubCommandEntry_FadeScreen::GetBodySourceCode() const
{
return StringHelper::Sprintf("CS_FADESCREEN(0x%02X, %i, %i, %i, %i, %i)", base, startFrame,
endFrame, unk_06, unk_07, unk_08);
}
size_t CutsceneSubCommandEntry_FadeScreen::GetRawSize() const
{
return 0x0C;
}
CutsceneMMCommand_FadeScreen::CutsceneMMCommand_FadeScreen(const std::vector<uint8_t>& rawData,
offset_t rawDataIndex)
: CutsceneCommand(rawData, rawDataIndex)
{
rawDataIndex += 4;
entries.reserve(numEntries);
for (size_t i = 0; i < numEntries; i++)
{
auto* entry = new CutsceneSubCommandEntry_FadeScreen(rawData, rawDataIndex);
entries.push_back(entry);
rawDataIndex += entry->GetRawSize();
}
}
std::string CutsceneMMCommand_FadeScreen::GetCommandMacro() const
{
return StringHelper::Sprintf("CS_FADESCREEN_LIST(%i)", numEntries);
}
CutsceneSubCommandEntry_FadeSeq::CutsceneSubCommandEntry_FadeSeq(
const std::vector<uint8_t>& rawData, offset_t rawDataIndex)
: CutsceneSubCommandEntry(rawData, rawDataIndex)
{
unk_08 = BitConverter::ToUInt32BE(rawData, rawDataIndex + 8);
}
std::string CutsceneSubCommandEntry_FadeSeq::GetBodySourceCode() const
{
return StringHelper::Sprintf("CS_FADESEQ(%i, %i, %i)", base, startFrame, endFrame);
}
size_t CutsceneSubCommandEntry_FadeSeq::GetRawSize() const
{
return 0x0C;
}
CutsceneMMCommand_FadeSeq::CutsceneMMCommand_FadeSeq(const std::vector<uint8_t>& rawData,
offset_t rawDataIndex)
: CutsceneCommand(rawData, rawDataIndex)
{
rawDataIndex += 4;
entries.reserve(numEntries);
for (size_t i = 0; i < numEntries; i++)
{
auto* entry = new CutsceneSubCommandEntry_FadeSeq(rawData, rawDataIndex);
entries.push_back(entry);
rawDataIndex += entry->GetRawSize();
}
}
std::string CutsceneMMCommand_FadeSeq::GetCommandMacro() const
{
return StringHelper::Sprintf("CS_FADESEQ_LIST(%i)", numEntries);
}
CutsceneSubCommandEntry_NonImplemented::CutsceneSubCommandEntry_NonImplemented(
const std::vector<uint8_t>& rawData, offset_t rawDataIndex)
: CutsceneSubCommandEntry(rawData, rawDataIndex)
{
}
CutsceneMMCommand_NonImplemented::CutsceneMMCommand_NonImplemented(
const std::vector<uint8_t>& rawData, offset_t rawDataIndex)
: CutsceneCommand(rawData, rawDataIndex)
{
rawDataIndex += 4;
entries.reserve(numEntries);
for (size_t i = 0; i < numEntries; i++)
{
auto* entry = new CutsceneSubCommandEntry_NonImplemented(rawData, rawDataIndex);
entries.push_back(entry);
rawDataIndex += entry->GetRawSize();
}
}

View File

@ -0,0 +1,140 @@
#pragma once
#include "Cutscene_Commands.h"
enum class CutsceneMMCommands
{
/* 0x00A */ CS_CMD_TEXTBOX = 0xA,
/* 0x05A */ CS_CMD_CAMERA = 0x5A,
/* 0x096 */ CS_CMD_MISC = 0x96,
/* 0x097 */ CS_CMD_SET_LIGHTING,
/* 0x098 */ CS_CMD_SCENE_TRANS_FX,
/* 0x099 */ CS_CMD_MOTIONBLUR,
/* 0x09A */ CS_CMD_GIVETATL,
/* 0x09B */ CS_CMD_FADESCREEN,
/* 0x09C */ CS_CMD_FADESEQ,
/* 0x09D */ CS_CMD_SETTIME,
/* 0x0C8 */ CS_CMD_SET_PLAYER_ACTION = 0xC8,
/* 0x0FA */ CS_CMD_UNK_FA = 0xFA,
/* 0x0FE */ CS_CMD_UNK_FE = 0xFE,
/* 0x0FF */ CS_CMD_UNK_FF,
/* 0x100 */ CS_CMD_UNK_100,
/* 0x101 */ CS_CMD_UNK_101,
/* 0x102 */ CS_CMD_UNK_102,
/* 0x103 */ CS_CMD_UNK_103,
/* 0x104 */ CS_CMD_UNK_104,
/* 0x105 */ CS_CMD_UNK_105,
/* 0x108 */ CS_CMD_UNK_108 = 0x108,
/* 0x109 */ CS_CMD_UNK_109,
/* 0x12C */ CS_CMD_PLAYSEQ = 0x12C,
/* 0x12D */ CS_CMD_UNK_12D,
/* 0x130 */ CS_CMD_130 = 0x130,
/* 0x131 */ CS_CMD_131 = 0x131,
/* 0x132 */ CS_CMD_132 = 0x132,
/* 0x133 */ CS_CMD_STOPSEQ,
/* 0x134 */ CS_CMD_PLAYAMBIENCE,
/* 0x135 */ CS_CMD_FADEAMBIENCE,
/* 0x15E */ CS_CMD_TERMINATOR = 0x15E,
/* 0x15F */ CS_CMD_CHOOSE_CREDITS_SCENES,
/* 0x190 */ CS_CMD_RUMBLE = 0x190,
};
class CutsceneSubCommandEntry_GenericMMCmd : public CutsceneSubCommandEntry
{
public:
CutsceneMMCommands commandId;
CutsceneSubCommandEntry_GenericMMCmd(const std::vector<uint8_t>& rawData, offset_t rawDataIndex,
CutsceneMMCommands cmdId);
std::string GetBodySourceCode() const override;
};
class CutsceneMMCommand_GenericCmd : public CutsceneCommand
{
public:
CutsceneMMCommand_GenericCmd(const std::vector<uint8_t>& rawData, offset_t rawDataIndex,
CutsceneMMCommands cmdId);
std::string GetCommandMacro() const override;
};
// TODO: MM cutscene camera command is implemented as a placeholder until we better understand how
// it works
class CutsceneSubCommandEntry_Camera : public CutsceneSubCommandEntry
{
public:
uint32_t unk_08;
CutsceneSubCommandEntry_Camera(const std::vector<uint8_t>& rawData, offset_t rawDataIndex);
std::string GetBodySourceCode() const override;
size_t GetRawSize() const override;
};
class CutsceneMMCommand_Camera : public CutsceneCommand
{
public:
CutsceneMMCommand_Camera(const std::vector<uint8_t>& rawData, offset_t rawDataIndex);
std::string GetCommandMacro() const override;
};
class CutsceneSubCommandEntry_FadeScreen : public CutsceneSubCommandEntry
{
public:
uint8_t unk_06;
uint8_t unk_07;
uint8_t unk_08;
uint8_t unk_09;
uint8_t unk_0A;
uint8_t unk_0B;
CutsceneSubCommandEntry_FadeScreen(const std::vector<uint8_t>& rawData, offset_t rawDataIndex);
std::string GetBodySourceCode() const override;
size_t GetRawSize() const override;
};
class CutsceneMMCommand_FadeScreen : public CutsceneCommand
{
public:
CutsceneMMCommand_FadeScreen(const std::vector<uint8_t>& rawData, offset_t rawDataIndex);
std::string GetCommandMacro() const override;
};
class CutsceneSubCommandEntry_FadeSeq : public CutsceneSubCommandEntry
{
public:
uint32_t unk_08;
CutsceneSubCommandEntry_FadeSeq(const std::vector<uint8_t>& rawData, offset_t rawDataIndex);
std::string GetBodySourceCode() const override;
size_t GetRawSize() const override;
};
class CutsceneMMCommand_FadeSeq : public CutsceneCommand
{
public:
CutsceneMMCommand_FadeSeq(const std::vector<uint8_t>& rawData, offset_t rawDataIndex);
std::string GetCommandMacro() const override;
};
class CutsceneSubCommandEntry_NonImplemented : public CutsceneSubCommandEntry
{
public:
CutsceneSubCommandEntry_NonImplemented(const std::vector<uint8_t>& rawData,
offset_t rawDataIndex);
};
class CutsceneMMCommand_NonImplemented : public CutsceneCommand
{
public:
CutsceneMMCommand_NonImplemented(const std::vector<uint8_t>& rawData, offset_t rawDataIndex);
};

View File

@ -0,0 +1,596 @@
#include "Cutscene_Commands.h"
#include <cassert>
#include <unordered_map>
#include "CutsceneMM_Commands.h"
#include "Globals.h"
#include "Utils/BitConverter.h"
#include "Utils/StringHelper.h"
/* CutsceneSubCommandEntry */
CutsceneSubCommandEntry::CutsceneSubCommandEntry(const std::vector<uint8_t>& rawData,
offset_t rawDataIndex)
{
base = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0);
startFrame = BitConverter::ToUInt16BE(rawData, rawDataIndex + 2);
endFrame = BitConverter::ToUInt16BE(rawData, rawDataIndex + 4);
pad = BitConverter::ToUInt16BE(rawData, rawDataIndex + 6);
}
std::string CutsceneSubCommandEntry::GetBodySourceCode() const
{
return StringHelper::Sprintf("CMD_HH(0x%04X, 0x%04X), CMD_HH(0x%04X, 0x%04X)", base, startFrame,
endFrame, pad);
}
size_t CutsceneSubCommandEntry::GetRawSize() const
{
return 0x08;
}
/* CutsceneCommand */
CutsceneCommand::CutsceneCommand(const std::vector<uint8_t>& rawData, offset_t rawDataIndex)
{
numEntries = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0);
}
CutsceneCommand::~CutsceneCommand()
{
for (auto& entry : entries)
{
delete entry;
}
}
std::string CutsceneCommand::GetCommandMacro() const
{
return StringHelper::Sprintf("CMD_W(0x%08X), CMD_W(0x%08X)", commandID, numEntries);
}
std::string CutsceneCommand::GenerateSourceCode() const
{
std::string result;
result += GetCommandMacro();
result += ",\n";
for (auto& entry : entries)
{
result += " ";
result += entry->GetBodySourceCode();
result += ",\n";
}
return result;
}
size_t CutsceneCommand::GetCommandSize() const
{
size_t size = 0;
if (entries.size() > 0)
{
size = entries.at(0)->GetRawSize() * entries.size();
}
else
{
size = 0x08 * numEntries;
}
return 0x08 + size;
}
void CutsceneCommand::SetCommandID(uint32_t nCommandID)
{
commandID = nCommandID;
for (auto& entry : entries)
{
entry->commandID = commandID;
}
}
// Specific for command lists where each entry has size 0x30 bytes
const std::unordered_map<CutsceneCommands, CsCommandListDescriptor> csCommandsDesc = {
{CutsceneCommands::Misc,
{"CS_MISC", "(0x%04X, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i)"}},
{CutsceneCommands::SetLighting,
{"CS_LIGHTING", "(0x%02X, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i)"}},
{CutsceneCommands::PlayBGM, {"CS_PLAY_BGM", "(%i, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i)"}},
{CutsceneCommands::StopBGM, {"CS_STOP_BGM", "(%i, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i)"}},
{CutsceneCommands::FadeBGM, {"CS_FADE_BGM", "(%i, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i)"}},
};
CutsceneSubCommandEntry_GenericCmd::CutsceneSubCommandEntry_GenericCmd(
const std::vector<uint8_t>& rawData, offset_t rawDataIndex, CutsceneCommands cmdId)
: CutsceneSubCommandEntry(rawData, rawDataIndex), commandId(cmdId)
{
word0 = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x0);
word1 = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x4);
unused1 = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x8);
unused2 = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0xC);
unused3 = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x10);
unused4 = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x14);
unused5 = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x18);
unused6 = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x1C);
unused7 = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x20);
unused8 = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x24);
unused9 = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x28);
unused10 = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x2C);
}
std::string CutsceneSubCommandEntry_GenericCmd::GetBodySourceCode() const
{
const auto& element = csCommandsDesc.find(commandId);
if (element != csCommandsDesc.end())
{
std::string entryFmt = element->second.cmdMacro;
entryFmt += element->second.args;
return StringHelper::Sprintf(entryFmt.c_str(), base, startFrame, endFrame, pad, unused1,
unused2, unused3, unused4, unused5, unused6, unused7, unused8,
unused9, unused10);
}
return StringHelper::Sprintf("CS_UNK_DATA(0x%08X, 0x%08X, 0x%08X, 0x%08X, 0x%08X, 0x%08X, "
"0x%08X, 0x%08X, 0x%08X, 0x%08X, 0x%08X, 0x%08X)",
word0, word1, unused1, unused2, unused3, unused4, unused5, unused6,
unused7, unused8, unused9, unused10);
}
size_t CutsceneSubCommandEntry_GenericCmd::GetRawSize() const
{
return 0x30;
}
CutsceneCommand_GenericCmd::CutsceneCommand_GenericCmd(const std::vector<uint8_t>& rawData,
offset_t rawDataIndex,
CutsceneCommands cmdId)
: CutsceneCommand(rawData, rawDataIndex)
{
rawDataIndex += 4;
commandID = static_cast<uint32_t>(cmdId);
entries.reserve(numEntries);
for (size_t i = 0; i < numEntries; i++)
{
auto* entry = new CutsceneSubCommandEntry_GenericCmd(rawData, rawDataIndex, cmdId);
entries.push_back(entry);
rawDataIndex += entry->GetRawSize();
}
}
std::string CutsceneCommand_GenericCmd::GetCommandMacro() const
{
const auto& element = csCommandsDesc.find(static_cast<CutsceneCommands>(commandID));
if (element != csCommandsDesc.end())
{
return StringHelper::Sprintf("%s_LIST(%i)", element->second.cmdMacro, numEntries);
}
return StringHelper::Sprintf("CS_UNK_DATA_LIST(0x%X, %i)", commandID, numEntries);
}
CutsceneCameraPoint::CutsceneCameraPoint(const std::vector<uint8_t>& rawData, offset_t rawDataIndex)
: CutsceneSubCommandEntry(rawData, rawDataIndex)
{
continueFlag = BitConverter::ToInt8BE(rawData, rawDataIndex + 0);
cameraRoll = BitConverter::ToInt8BE(rawData, rawDataIndex + 1);
nextPointFrame = BitConverter::ToInt16BE(rawData, rawDataIndex + 2);
viewAngle = BitConverter::ToFloatBE(rawData, rawDataIndex + 4);
posX = BitConverter::ToInt16BE(rawData, rawDataIndex + 8);
posY = BitConverter::ToInt16BE(rawData, rawDataIndex + 10);
posZ = BitConverter::ToInt16BE(rawData, rawDataIndex + 12);
unused = BitConverter::ToInt16BE(rawData, rawDataIndex + 14);
}
std::string CutsceneCameraPoint::GetBodySourceCode() const
{
std::string result = "";
if (commandID == (int32_t)CutsceneCommands::SetCameraFocus)
{
result += "CS_CAM_FOCUS_POINT";
}
else if (commandID == (int32_t)CutsceneCommands::SetCameraFocusLink)
{
result += "CS_CAM_FOCUS_POINT_PLAYER";
}
else if (commandID == (int32_t)CutsceneCommands::SetCameraPosLink)
{
result += "CS_CAM_POS_PLAYER";
}
else
{
result += "CS_CAM_POS";
}
std::string continueMacro = "CS_CMD_CONTINUE";
if (continueFlag != 0)
continueMacro = "CS_CMD_STOP";
result +=
StringHelper::Sprintf("(%s, 0x%02X, %i, %ff, %i, %i, %i, 0x%04X)", continueMacro.c_str(),
cameraRoll, nextPointFrame, viewAngle, posX, posY, posZ, unused);
return result;
}
size_t CutsceneCameraPoint::GetRawSize() const
{
return 0x10;
}
CutsceneCommandSetCameraPos::CutsceneCommandSetCameraPos(const std::vector<uint8_t>& rawData,
offset_t rawDataIndex)
: CutsceneCommand(rawData, rawDataIndex)
{
base = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0);
startFrame = BitConverter::ToUInt16BE(rawData, rawDataIndex + 2);
endFrame = BitConverter::ToUInt16BE(rawData, rawDataIndex + 4);
unused = BitConverter::ToUInt16BE(rawData, rawDataIndex + 6);
bool shouldContinue = true;
uint32_t currentPtr = rawDataIndex + 8;
while (shouldContinue)
{
CutsceneCameraPoint* camPoint = new CutsceneCameraPoint(rawData, currentPtr);
entries.push_back(camPoint);
if (camPoint->continueFlag == -1)
shouldContinue = false;
currentPtr += camPoint->GetRawSize();
}
}
std::string CutsceneCommandSetCameraPos::GetCommandMacro() const
{
std::string result;
std::string listStr;
if (commandID == (int32_t)CutsceneCommands::SetCameraFocus)
{
listStr = "CS_CAM_FOCUS_POINT_LIST";
}
else if (commandID == (int32_t)CutsceneCommands::SetCameraFocusLink)
{
listStr = "CS_CAM_FOCUS_POINT_PLAYER_LIST";
}
else if (commandID == (int32_t)CutsceneCommands::SetCameraPosLink)
{
listStr = "CS_CAM_POS_PLAYER_LIST";
}
else
{
listStr = "CS_CAM_POS_LIST";
}
result += StringHelper::Sprintf("%s(%i, %i)", listStr.c_str(), startFrame, endFrame);
return result;
}
size_t CutsceneCommandSetCameraPos::GetCommandSize() const
{
return 0x0C + entries.at(0)->GetRawSize() * entries.size();
}
CutsceneSubCommandEntry_Rumble::CutsceneSubCommandEntry_Rumble(const std::vector<uint8_t>& rawData,
offset_t rawDataIndex)
: CutsceneSubCommandEntry(rawData, rawDataIndex)
{
unk_06 = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x06);
unk_07 = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x07);
unk_08 = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x08);
unk_09 = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x09);
unk_0A = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x0A);
unk_0B = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x0B);
}
std::string CutsceneSubCommandEntry_Rumble::GetBodySourceCode() const
{
if (Globals::Instance->game == ZGame::MM_RETAIL)
{
return StringHelper::Sprintf("CS_RUMBLE(%i, %i, %i, 0x%02X, 0x%02X, 0x%02X)", base,
startFrame, endFrame, unk_06, unk_07, unk_08);
}
return StringHelper::Sprintf("CS_CMD_09(%i, %i, %i, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X)",
base, startFrame, endFrame, unk_06, unk_07, unk_08, unk_09, unk_0A,
unk_0B);
}
size_t CutsceneSubCommandEntry_Rumble::GetRawSize() const
{
return 0x0C;
}
CutsceneCommand_Rumble::CutsceneCommand_Rumble(const std::vector<uint8_t>& rawData,
offset_t rawDataIndex)
: CutsceneCommand(rawData, rawDataIndex)
{
rawDataIndex += 4;
entries.reserve(numEntries);
for (size_t i = 0; i < numEntries; i++)
{
auto* entry = new CutsceneSubCommandEntry_Rumble(rawData, rawDataIndex);
entries.push_back(entry);
rawDataIndex += entry->GetRawSize();
}
}
std::string CutsceneCommand_Rumble::GetCommandMacro() const
{
if (Globals::Instance->game == ZGame::MM_RETAIL)
{
return StringHelper::Sprintf("CS_RUMBLE_LIST(%i)", numEntries);
}
return StringHelper::Sprintf("CS_CMD_09_LIST(%i)", numEntries);
}
CutsceneSubCommandEntry_SetTime::CutsceneSubCommandEntry_SetTime(
const std::vector<uint8_t>& rawData, offset_t rawDataIndex)
: CutsceneSubCommandEntry(rawData, rawDataIndex)
{
hour = BitConverter::ToUInt8BE(rawData, rawDataIndex + 6);
minute = BitConverter::ToUInt8BE(rawData, rawDataIndex + 7);
unk_08 = BitConverter::ToUInt32BE(rawData, rawDataIndex + 8);
}
std::string CutsceneSubCommandEntry_SetTime::GetBodySourceCode() const
{
return StringHelper::Sprintf("CS_TIME(%i, %i, %i, %i, %i, %i)", base, startFrame, endFrame,
hour, minute, unk_08);
}
size_t CutsceneSubCommandEntry_SetTime::GetRawSize() const
{
return 0x0C;
}
CutsceneCommand_SetTime::CutsceneCommand_SetTime(const std::vector<uint8_t>& rawData,
offset_t rawDataIndex)
: CutsceneCommand(rawData, rawDataIndex)
{
rawDataIndex += 4;
entries.reserve(numEntries);
for (size_t i = 0; i < numEntries; i++)
{
auto* entry = new CutsceneSubCommandEntry_SetTime(rawData, rawDataIndex);
entries.push_back(entry);
rawDataIndex += entry->GetRawSize();
}
}
std::string CutsceneCommand_SetTime::GetCommandMacro() const
{
return StringHelper::Sprintf("CS_TIME_LIST(%i)", numEntries);
}
CutsceneSubCommandEntry_TextBox::CutsceneSubCommandEntry_TextBox(
const std::vector<uint8_t>& rawData, offset_t rawDataIndex)
: CutsceneSubCommandEntry(rawData, rawDataIndex)
{
type = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0x6);
textId1 = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0x8);
textId2 = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0xA);
}
std::string CutsceneSubCommandEntry_TextBox::GetBodySourceCode() const
{
if (type == 0xFFFF)
{
return StringHelper::Sprintf("CS_TEXT_NONE(%i, %i)", startFrame, endFrame);
}
if (type == 2)
{
return StringHelper::Sprintf("CS_TEXT_LEARN_SONG(%i, %i, %i, 0x%X)", base, startFrame,
endFrame, textId1);
}
if (Globals::Instance->game == ZGame::MM_RETAIL)
{
switch (type)
{
case 0:
return StringHelper::Sprintf("CS_TEXT_DEFAULT(0x%X, %i, %i, 0x%X, 0x%X)", base,
startFrame, endFrame, textId1, textId2);
case 1:
return StringHelper::Sprintf("CS_TEXT_TYPE_1(0x%X, %i, %i, 0x%X, 0x%X)", base,
startFrame, endFrame, textId1, textId2);
case 3:
return StringHelper::Sprintf("CS_TEXT_TYPE_3(0x%X, %i, %i, 0x%X, 0x%X)", base,
startFrame, endFrame, textId1, textId2);
case 4:
return StringHelper::Sprintf("CS_TEXT_BOSSES_REMAINS(0x%X, %i, %i, 0x%X)", base,
startFrame, endFrame, textId1);
case 5:
return StringHelper::Sprintf("CS_TEXT_ALL_NORMAL_MASKS(0x%X, %i, %i, 0x%X)", base,
startFrame, endFrame, textId1);
}
}
return StringHelper::Sprintf("CS_TEXT_DISPLAY_TEXTBOX(0x%X, %i, %i, %i, 0x%X, 0x%X)", base,
startFrame, endFrame, type, textId1, textId2);
}
size_t CutsceneSubCommandEntry_TextBox::GetRawSize() const
{
return 0x0C;
}
CutsceneCommand_TextBox::CutsceneCommand_TextBox(const std::vector<uint8_t>& rawData,
offset_t rawDataIndex)
: CutsceneCommand(rawData, rawDataIndex)
{
rawDataIndex += 4;
entries.reserve(numEntries);
for (size_t i = 0; i < numEntries; i++)
{
auto* entry = new CutsceneSubCommandEntry_TextBox(rawData, rawDataIndex);
entries.push_back(entry);
rawDataIndex += entry->GetRawSize();
}
}
std::string CutsceneCommand_TextBox::GetCommandMacro() const
{
return StringHelper::Sprintf("CS_TEXT_LIST(%i)", numEntries);
}
CutsceneSubCommandEntry_ActorAction::CutsceneSubCommandEntry_ActorAction(
const std::vector<uint8_t>& rawData, offset_t rawDataIndex)
: CutsceneSubCommandEntry(rawData, rawDataIndex)
{
rotX = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0x6);
rotY = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0x8);
rotZ = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0xA);
startPosX = BitConverter::ToInt32BE(rawData, rawDataIndex + 0xC);
startPosY = BitConverter::ToInt32BE(rawData, rawDataIndex + 0x10);
startPosZ = BitConverter::ToInt32BE(rawData, rawDataIndex + 0x14);
endPosX = BitConverter::ToInt32BE(rawData, rawDataIndex + 0x18);
endPosY = BitConverter::ToInt32BE(rawData, rawDataIndex + 0x1C);
endPosZ = BitConverter::ToInt32BE(rawData, rawDataIndex + 0x20);
normalX = BitConverter::ToFloatBE(rawData, rawDataIndex + 0x24);
normalY = BitConverter::ToFloatBE(rawData, rawDataIndex + 0x28);
normalZ = BitConverter::ToFloatBE(rawData, rawDataIndex + 0x2C);
}
std::string CutsceneSubCommandEntry_ActorAction::GetBodySourceCode() const
{
std::string result;
if (Globals::Instance->game == ZGame::MM_RETAIL)
{
if (static_cast<CutsceneMMCommands>(commandID) ==
CutsceneMMCommands::CS_CMD_SET_PLAYER_ACTION)
{
result = "CS_PLAYER_ACTION";
}
else
{
result = "CS_ACTOR_ACTION";
}
}
else
{
if (static_cast<CutsceneCommands>(commandID) == CutsceneCommands::SetPlayerAction)
{
result = "CS_PLAYER_ACTION";
}
else
{
result = "CS_NPC_ACTION";
}
}
result +=
StringHelper::Sprintf("(%i, %i, %i, 0x%04X, 0x%04X, 0x%04X, %i, %i, "
"%i, %i, %i, %i, %.11ef, %.11ef, %.11ef)",
base, startFrame, endFrame, rotX, rotY, rotZ, startPosX, startPosY,
startPosZ, endPosX, endPosY, endPosZ, normalX, normalY, normalZ);
return result;
}
size_t CutsceneSubCommandEntry_ActorAction::GetRawSize() const
{
return 0x30;
}
CutsceneCommand_ActorAction::CutsceneCommand_ActorAction(const std::vector<uint8_t>& rawData,
offset_t rawDataIndex)
: CutsceneCommand(rawData, rawDataIndex)
{
rawDataIndex += 4;
entries.reserve(numEntries);
for (size_t i = 0; i < numEntries; i++)
{
auto* entry = new CutsceneSubCommandEntry_ActorAction(rawData, rawDataIndex);
entries.push_back(entry);
rawDataIndex += entry->GetRawSize();
}
}
std::string CutsceneCommand_ActorAction::GetCommandMacro() const
{
if (Globals::Instance->game == ZGame::MM_RETAIL)
{
if (static_cast<CutsceneMMCommands>(commandID) ==
CutsceneMMCommands::CS_CMD_SET_PLAYER_ACTION)
{
return StringHelper::Sprintf("CS_PLAYER_ACTION_LIST(%i)", numEntries);
}
return StringHelper::Sprintf("CS_ACTOR_ACTION_LIST(0x%03X, %i)", commandID, numEntries);
}
if (static_cast<CutsceneCommands>(commandID) == CutsceneCommands::SetPlayerAction)
{
return StringHelper::Sprintf("CS_PLAYER_ACTION_LIST(%i)", entries.size());
}
return StringHelper::Sprintf("CS_NPC_ACTION_LIST(0x%03X, %i)", commandID, entries.size());
}
CutsceneCommand_Terminator::CutsceneCommand_Terminator(const std::vector<uint8_t>& rawData,
offset_t rawDataIndex)
: CutsceneCommand(rawData, rawDataIndex)
{
rawDataIndex += 4;
base = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0);
startFrame = BitConverter::ToUInt16BE(rawData, rawDataIndex + 2);
endFrame = BitConverter::ToUInt16BE(rawData, rawDataIndex + 4);
unknown = BitConverter::ToUInt16BE(rawData, rawDataIndex + 6); // endFrame duplicate
}
std::string CutsceneCommand_Terminator::GenerateSourceCode() const
{
std::string result;
result += StringHelper::Sprintf("CS_TERMINATOR(%i, %i, %i),\n", base, startFrame, endFrame);
return result;
}
size_t CutsceneCommand_Terminator::GetCommandSize() const
{
return 0x10;
}
CutsceneCommandSceneTransFX::CutsceneCommandSceneTransFX(const std::vector<uint8_t>& rawData,
offset_t rawDataIndex)
: CutsceneCommand(rawData, rawDataIndex)
{
rawDataIndex += 4;
base = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0);
startFrame = BitConverter::ToUInt16BE(rawData, rawDataIndex + 2);
endFrame = BitConverter::ToUInt16BE(rawData, rawDataIndex + 4);
}
std::string CutsceneCommandSceneTransFX::GenerateSourceCode() const
{
return StringHelper::Sprintf("CS_SCENE_TRANS_FX(%i, %i, %i),\n", base, startFrame, endFrame);
}
size_t CutsceneCommandSceneTransFX::GetCommandSize() const
{
return 0x10;
}

View File

@ -0,0 +1,267 @@
#pragma once
#include <cstdint>
#include <string>
#include <vector>
#include "Declaration.h"
enum class CutsceneCommands
{
SetCameraPos = 0x0001,
SetCameraFocus = 0x0002,
Misc = 0x0003,
SetLighting = 0x0004,
SetCameraPosLink = 0x0005,
SetCameraFocusLink = 0x0006,
Cmd07 = 0x0007,
Cmd08 = 0x0008,
Cmd09 = 0x0009, // Rumble
Textbox = 0x0013,
SetPlayerAction = 0x000A,
SetActorAction1 = 0x000F,
SetActorAction2 = 0x000E,
SetActorAction3 = 0x0019,
SetActorAction4 = 0x001D,
SetActorAction5 = 0x001E,
SetActorAction6 = 0x002C,
SetActorAction7 = 0x001F,
SetActorAction8 = 0x0031,
SetActorAction9 = 0x003E,
SetActorAction10 = 0x008F,
SetSceneTransFX = 0x002D,
PlayBGM = 0x0056,
StopBGM = 0x0057,
FadeBGM = 0x007C,
SetTime = 0x008C,
Terminator = 0x03E8,
};
typedef struct CsCommandListDescriptor
{
const char* cmdMacro;
const char* args;
} CsCommandListDescriptor;
class CutsceneSubCommandEntry
{
public:
uint16_t base;
uint16_t startFrame;
uint16_t endFrame;
uint16_t pad;
uint32_t commandID;
CutsceneSubCommandEntry(const std::vector<uint8_t>& rawData, offset_t rawDataIndex);
virtual ~CutsceneSubCommandEntry() = default;
virtual std::string GetBodySourceCode() const;
virtual size_t GetRawSize() const;
};
class CutsceneCommand
{
public:
uint32_t commandID;
uint32_t commandIndex;
uint32_t numEntries;
std::vector<CutsceneSubCommandEntry*> entries;
CutsceneCommand(const std::vector<uint8_t>& rawData, offset_t rawDataIndex);
virtual ~CutsceneCommand();
virtual std::string GetCommandMacro() const;
virtual std::string GenerateSourceCode() const;
virtual size_t GetCommandSize() const;
virtual void SetCommandID(uint32_t nCommandID);
};
class CutsceneSubCommandEntry_GenericCmd : public CutsceneSubCommandEntry
{
public:
CutsceneCommands commandId;
uint32_t word0 = 0;
uint32_t word1 = 0;
uint32_t unused1 = 0;
uint32_t unused2 = 0;
uint32_t unused3 = 0;
uint32_t unused4 = 0;
uint32_t unused5 = 0;
uint32_t unused6 = 0;
uint32_t unused7 = 0;
uint32_t unused8 = 0;
uint32_t unused9 = 0;
uint32_t unused10 = 0;
CutsceneSubCommandEntry_GenericCmd(const std::vector<uint8_t>& rawData, offset_t rawDataIndex,
CutsceneCommands cmdId);
std::string GetBodySourceCode() const override;
size_t GetRawSize() const override;
};
class CutsceneCommand_GenericCmd : public CutsceneCommand
{
public:
CutsceneCommand_GenericCmd(const std::vector<uint8_t>& rawData, offset_t rawDataIndex,
CutsceneCommands cmdId);
std::string GetCommandMacro() const override;
};
class CutsceneCameraPoint : public CutsceneSubCommandEntry
{
public:
int8_t continueFlag;
int8_t cameraRoll;
int16_t nextPointFrame;
float viewAngle;
int16_t posX, posY, posZ;
int16_t unused;
CutsceneCameraPoint(const std::vector<uint8_t>& rawData, offset_t rawDataIndex);
std::string GetBodySourceCode() const override;
size_t GetRawSize() const override;
};
class CutsceneCommandSetCameraPos : public CutsceneCommand
{
public:
uint16_t base;
uint16_t startFrame;
uint16_t endFrame;
uint16_t unused;
CutsceneCommandSetCameraPos(const std::vector<uint8_t>& rawData, offset_t rawDataIndex);
std::string GetCommandMacro() const override;
size_t GetCommandSize() const override;
};
class CutsceneCommandSceneTransFX : public CutsceneCommand
{
public:
uint16_t base;
uint16_t startFrame;
uint16_t endFrame;
CutsceneCommandSceneTransFX(const std::vector<uint8_t>& rawData, offset_t rawDataIndex);
std::string GenerateSourceCode() const override;
size_t GetCommandSize() const override;
};
class CutsceneSubCommandEntry_Rumble : public CutsceneSubCommandEntry
{
public:
uint8_t unk_06;
uint8_t unk_07;
uint8_t unk_08;
uint8_t unk_09;
uint8_t unk_0A;
uint8_t unk_0B;
CutsceneSubCommandEntry_Rumble(const std::vector<uint8_t>& rawData, offset_t rawDataIndex);
std::string GetBodySourceCode() const override;
size_t GetRawSize() const override;
};
class CutsceneCommand_Rumble : public CutsceneCommand
{
public:
CutsceneCommand_Rumble(const std::vector<uint8_t>& rawData, offset_t rawDataIndex);
std::string GetCommandMacro() const override;
};
class CutsceneSubCommandEntry_SetTime : public CutsceneSubCommandEntry
{
public:
uint8_t hour;
uint8_t minute;
uint32_t unk_08;
CutsceneSubCommandEntry_SetTime(const std::vector<uint8_t>& rawData, offset_t rawDataIndex);
std::string GetBodySourceCode() const override;
size_t GetRawSize() const override;
};
class CutsceneCommand_SetTime : public CutsceneCommand
{
public:
CutsceneCommand_SetTime(const std::vector<uint8_t>& rawData, offset_t rawDataIndex);
std::string GetCommandMacro() const override;
};
class CutsceneSubCommandEntry_TextBox : public CutsceneSubCommandEntry
{
public:
uint16_t type;
uint16_t textId1;
uint16_t textId2;
CutsceneSubCommandEntry_TextBox(const std::vector<uint8_t>& rawData, offset_t rawDataIndex);
std::string GetBodySourceCode() const override;
size_t GetRawSize() const override;
};
class CutsceneCommand_TextBox : public CutsceneCommand
{
public:
CutsceneCommand_TextBox(const std::vector<uint8_t>& rawData, offset_t rawDataIndex);
std::string GetCommandMacro() const override;
};
class CutsceneSubCommandEntry_ActorAction : public CutsceneSubCommandEntry
{
public:
uint16_t rotX, rotY, rotZ;
int32_t startPosX, startPosY, startPosZ;
int32_t endPosX, endPosY, endPosZ;
float normalX, normalY, normalZ;
CutsceneSubCommandEntry_ActorAction(const std::vector<uint8_t>& rawData, offset_t rawDataIndex);
std::string GetBodySourceCode() const override;
size_t GetRawSize() const override;
};
class CutsceneCommand_ActorAction : public CutsceneCommand
{
public:
CutsceneCommand_ActorAction(const std::vector<uint8_t>& rawData, offset_t rawDataIndex);
std::string GetCommandMacro() const override;
};
class CutsceneCommand_Terminator : public CutsceneCommand
{
public:
uint16_t base;
uint16_t startFrame;
uint16_t endFrame;
uint16_t unknown;
CutsceneCommand_Terminator(const std::vector<uint8_t>& rawData, offset_t rawDataIndex);
std::string GenerateSourceCode() const override;
size_t GetCommandSize() const override;
};

View File

@ -104,6 +104,8 @@ void Struct_800A598C::ParseRawData()
if (unk_8 != 0 && GETSEGNUM(unk_8) == parent->segment)
{
uint32_t unk_8_Offset = Seg2Filespace(unk_8, parent->baseAddress);
unk_8_arr.reserve(unk_0);
for (size_t i = 0; i < unk_0; i++)
{
Struct_800A57C0 unk8_data(parent);
@ -117,6 +119,8 @@ void Struct_800A598C::ParseRawData()
if (unk_C != 0 && GETSEGNUM(unk_8) == parent->segment)
{
uint32_t unk_C_Offset = Seg2Filespace(unk_C, parent->baseAddress);
unk_C_arr.reserve(unk_2);
for (size_t i = 0; i < unk_2; i++)
{
Struct_800A598C_2 unkC_data(parent);
@ -246,6 +250,8 @@ void Struct_800A5E28::ParseRawData()
if (unk_4 != 0 && GETSEGNUM(unk_4) == parent->segment)
{
uint32_t unk_4_Offset = Seg2Filespace(unk_4, parent->baseAddress);
unk_4_arr.reserve(unk_2);
for (size_t i = 0; i < unk_2; i++)
{
Struct_800A598C unk_4_data(parent);

View File

@ -199,8 +199,16 @@ bool WarningHandler::WasElevatedToError(WarningType warnType) {
* Print file/line/function info for debugging
*/
void WarningHandler::FunctionPreamble(const char* filename, int32_t line, const char* function) {
if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_DEBUG) {
fprintf(stderr, "%s:%i: in function %s:\n", filename, line, function);
bool forcePrint = false;
#ifdef DEVELOPMENT
forcePrint = true;
#endif
fprintf(stderr, "\n");
if (forcePrint || Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_DEBUG) {
fprintf(stderr, "%s:%i: in function <%s>:\n", filename, line, function);
}
}

372
ZAPDTR/ZAPD/ZAPD.vcxproj Normal file
View File

@ -0,0 +1,372 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\packages\YY.NuGet.Import.Helper.1.0.0.4\build\native\YY.NuGet.Import.Helper.props" Condition="Exists('..\packages\YY.NuGet.Import.Helper.1.0.0.4\build\native\YY.NuGet.Import.Helper.props')" />
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>15.0</VCProjectVersion>
<ProjectGuid>{B53F9E5B-0A58-4BAE-9AFE-856C8CBB8D36}</ProjectGuid>
<RootNamespace>ZAPD</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
<ProjectName>ZAPD</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LibraryPath>$(OutDir);$(ProjectDir)..\lib\libgfxd;$(ProjectDir)..\packages\libpng-v142.1.6.37.2\build\native\lib\x64\v142\Debug\;$(LibraryPath)</LibraryPath>
<IncludePath>$(ProjectDir)..\ZAPDUtils;$(ProjectDir)..\lib\tinyxml2;$(ProjectDir)..\lib\libgfxd;$(ProjectDir)..\lib\elfio;$(ProjectDir)..\lib\stb;$(ProjectDir);$(IncludePath)</IncludePath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<IncludePath>$(IncludePath)</IncludePath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<IncludePath>$(SolutionDir)ZAPD\lib\tinyxml2;$(SolutionDir)ZAPD\lib\libgfxd;$(SolutionDir)ZAPD\lib\elfio;$(SolutionDir)ZAPD\lib\stb;$(ProjectDir);$(IncludePath)</IncludePath>
<LibraryPath>$(SolutionDir)ZAPD\lib\libgfxd;$(SolutionDir)x64\Debug;$(SolutionDir)packages\libpng.1.6.28.1\build\native\lib\x64\v140\dynamic\Debug;$(LibraryPath)</LibraryPath>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<LanguageStandard_C>stdc11</LanguageStandard_C>
<PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<Profile>true</Profile>
<SubSystem>Console</SubSystem>
</Link>
<PreBuildEvent>
<Command>cd ..
mkdir build\ZAPD
python ZAPD/genbuildinfo.py</Command>
</PreBuildEvent>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<LanguageStandard_C>stdc11</LanguageStandard_C>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<Profile>true</Profile>
<AdditionalDependencies>ZAPDUtils.lib;/WHOLEARCHIVE:ExporterExample.lib;%(AdditionalDependencies)</AdditionalDependencies>
<IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
<SubSystem>Console</SubSystem>
</Link>
<PreBuildEvent>
<Command>cd ..
mkdir build\ZAPD
python ZAPD/genbuildinfo.py</Command>
</PreBuildEvent>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<ConformanceMode>true</ConformanceMode>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
<PreBuildEvent>
<Command>cd ..
mkdir build\ZAPD
python ZAPD/genbuildinfo.py</Command>
</PreBuildEvent>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpplatest</LanguageStandard>
<PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
<PreBuildEvent>
<Command>cd ..
mkdir build\ZAPD
python ZAPD/genbuildinfo.py</Command>
</PreBuildEvent>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="..\build\ZAPD\BuildInfo.cpp" />
<ClCompile Include="..\lib\libgfxd\gfxd.c" />
<ClCompile Include="..\lib\libgfxd\uc.c" />
<ClCompile Include="..\lib\libgfxd\uc_f3d.c" />
<ClCompile Include="..\lib\libgfxd\uc_f3db.c" />
<ClCompile Include="..\lib\libgfxd\uc_f3dex.c" />
<ClCompile Include="..\lib\libgfxd\uc_f3dex2.c" />
<ClCompile Include="..\lib\libgfxd\uc_f3dexb.c" />
<ClCompile Include="CrashHandler.cpp" />
<ClCompile Include="Declaration.cpp" />
<ClCompile Include="GameConfig.cpp" />
<ClCompile Include="Globals.cpp" />
<ClCompile Include="ImageBackend.cpp" />
<ClCompile Include="Main.cpp" />
<ClCompile Include="OtherStructs\CutsceneMM_Commands.cpp" />
<ClCompile Include="OtherStructs\Cutscene_Commands.cpp" />
<ClCompile Include="OtherStructs\SkinLimbStructs.cpp" />
<ClCompile Include="OutputFormatter.cpp" />
<ClCompile Include="WarningHandler.cpp" />
<ClCompile Include="ZActorList.cpp" />
<ClCompile Include="ZArray.cpp" />
<ClCompile Include="ZBackground.cpp" />
<ClCompile Include="ZCollisionPoly.cpp" />
<ClCompile Include="ZLimb.cpp" />
<ClCompile Include="ZMtx.cpp" />
<ClCompile Include="ZPath.cpp" />
<ClCompile Include="ZPlayerAnimationData.cpp" />
<ClCompile Include="ZRoom\Commands\SetActorCutsceneList.cpp" />
<ClCompile Include="ZRoom\Commands\SetAnimatedMaterialList.cpp" />
<ClCompile Include="ZRoom\Commands\SetCsCamera.cpp" />
<ClCompile Include="ZRoom\Commands\SetMinimapChests.cpp" />
<ClCompile Include="ZRoom\Commands\SetMinimapList.cpp" />
<ClCompile Include="ZRoom\Commands\SetWorldMapVisited.cpp" />
<ClCompile Include="ZRoom\Commands\Unused1D.cpp" />
<ClCompile Include="ZScalar.cpp" />
<ClCompile Include="ZAnimation.cpp" />
<ClCompile Include="ZBlob.cpp" />
<ClCompile Include="ZCollision.cpp" />
<ClCompile Include="ZCutscene.cpp" />
<ClCompile Include="ZDisplayList.cpp" />
<ClCompile Include="ZFile.cpp" />
<ClCompile Include="ZSkeleton.cpp" />
<ClCompile Include="ZResource.cpp" />
<ClCompile Include="ZRoom\Commands\EndMarker.cpp" />
<ClCompile Include="ZRoom\Commands\SetActorList.cpp" />
<ClCompile Include="ZRoom\Commands\SetAlternateHeaders.cpp" />
<ClCompile Include="ZRoom\Commands\SetCameraSettings.cpp" />
<ClCompile Include="ZRoom\Commands\SetCollisionHeader.cpp" />
<ClCompile Include="ZRoom\Commands\SetCutscenes.cpp" />
<ClCompile Include="ZRoom\Commands\SetEchoSettings.cpp" />
<ClCompile Include="ZRoom\Commands\SetEntranceList.cpp" />
<ClCompile Include="ZRoom\Commands\SetExitList.cpp" />
<ClCompile Include="ZRoom\Commands\SetLightingSettings.cpp" />
<ClCompile Include="ZRoom\Commands\SetLightList.cpp" />
<ClCompile Include="ZRoom\Commands\SetMesh.cpp" />
<ClCompile Include="ZRoom\Commands\SetObjectList.cpp" />
<ClCompile Include="ZRoom\Commands\SetPathways.cpp" />
<ClCompile Include="ZRoom\Commands\SetRoomBehavior.cpp" />
<ClCompile Include="ZRoom\Commands\SetRoomList.cpp" />
<ClCompile Include="ZRoom\Commands\SetSkyboxModifier.cpp" />
<ClCompile Include="ZRoom\Commands\SetSkyboxSettings.cpp" />
<ClCompile Include="ZRoom\Commands\SetSoundSettings.cpp" />
<ClCompile Include="ZRoom\Commands\SetSpecialObjects.cpp" />
<ClCompile Include="ZRoom\Commands\SetStartPositionList.cpp" />
<ClCompile Include="ZRoom\Commands\SetTimeSettings.cpp" />
<ClCompile Include="ZRoom\Commands\SetTransitionActorList.cpp" />
<ClCompile Include="ZRoom\Commands\SetWind.cpp" />
<ClCompile Include="ZRoom\Commands\Unused09.cpp" />
<ClCompile Include="ZRoom\Commands\ZRoomCommandUnk.cpp" />
<ClCompile Include="ZRoom\ZRoom.cpp" />
<ClCompile Include="ZRoom\ZRoomCommand.cpp" />
<ClCompile Include="ZString.cpp" />
<ClCompile Include="ZSurfaceType.cpp" />
<ClCompile Include="ZSymbol.cpp" />
<ClCompile Include="ZTexture.cpp" />
<ClCompile Include="ZTextureAnimation.cpp" />
<ClCompile Include="ZVector.cpp" />
<ClCompile Include="ZVtx.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\lib\elfio\elfio\elfio.hpp" />
<ClInclude Include="..\lib\elfio\elfio\elfio_dump.hpp" />
<ClInclude Include="..\lib\elfio\elfio\elfio_dynamic.hpp" />
<ClInclude Include="..\lib\elfio\elfio\elfio_header.hpp" />
<ClInclude Include="..\lib\elfio\elfio\elfio_note.hpp" />
<ClInclude Include="..\lib\elfio\elfio\elfio_relocation.hpp" />
<ClInclude Include="..\lib\elfio\elfio\elfio_section.hpp" />
<ClInclude Include="..\lib\elfio\elfio\elfio_segment.hpp" />
<ClInclude Include="..\lib\elfio\elfio\elfio_strings.hpp" />
<ClInclude Include="..\lib\elfio\elfio\elfio_symbols.hpp" />
<ClInclude Include="..\lib\elfio\elfio\elfio_utils.hpp" />
<ClInclude Include="..\lib\elfio\elfio\elf_types.hpp" />
<ClInclude Include="..\lib\libgfxd\gbi.h" />
<ClInclude Include="..\lib\libgfxd\gfxd.h" />
<ClInclude Include="..\lib\libgfxd\priv.h" />
<ClInclude Include="..\lib\stb\stb_image.h" />
<ClInclude Include="..\lib\stb\stb_image_write.h" />
<ClInclude Include="..\lib\stb\tinyxml2.h" />
<ClInclude Include="CrashHandler.h" />
<ClInclude Include="CRC32.h" />
<ClInclude Include="Declaration.h" />
<ClInclude Include="GameConfig.h" />
<ClInclude Include="Globals.h" />
<ClInclude Include="ImageBackend.h" />
<ClInclude Include="OtherStructs\CutsceneMM_Commands.h" />
<ClInclude Include="OtherStructs\Cutscene_Commands.h" />
<ClInclude Include="OtherStructs\SkinLimbStructs.h" />
<ClInclude Include="OutputFormatter.h" />
<ClInclude Include="WarningHandler.h" />
<ClInclude Include="ZActorList.h" />
<ClInclude Include="ZAnimation.h" />
<ClInclude Include="ZArray.h" />
<ClInclude Include="ZBackground.h" />
<ClInclude Include="ZBlob.h" />
<ClInclude Include="ZCollision.h" />
<ClInclude Include="ZCollisionPoly.h" />
<ClInclude Include="ZCutscene.h" />
<ClInclude Include="ZDisplayList.h" />
<ClInclude Include="ZFile.h" />
<ClInclude Include="ZLimb.h" />
<ClInclude Include="ZMtx.h" />
<ClInclude Include="ZPath.h" />
<ClInclude Include="ZPlayerAnimationData.h" />
<ClInclude Include="ZRoom\Commands\SetActorCutsceneList.h" />
<ClInclude Include="ZRoom\Commands\SetAnimatedMaterialList.h" />
<ClInclude Include="ZRoom\Commands\SetCsCamera.h" />
<ClInclude Include="ZRoom\Commands\SetMinimapChests.h" />
<ClInclude Include="ZRoom\Commands\SetMinimapList.h" />
<ClInclude Include="ZRoom\Commands\SetWorldMapVisited.h" />
<ClInclude Include="ZRoom\Commands\Unused1D.h" />
<ClInclude Include="ZScalar.h" />
<ClInclude Include="ZSkeleton.h" />
<ClInclude Include="ZResource.h" />
<ClInclude Include="ZRoom\Commands\EndMarker.h" />
<ClInclude Include="ZRoom\Commands\SetActorList.h" />
<ClInclude Include="ZRoom\Commands\SetAlternateHeaders.h" />
<ClInclude Include="ZRoom\Commands\SetCameraSettings.h" />
<ClInclude Include="ZRoom\Commands\SetCollisionHeader.h" />
<ClInclude Include="ZRoom\Commands\SetCutscenes.h" />
<ClInclude Include="ZRoom\Commands\SetEchoSettings.h" />
<ClInclude Include="ZRoom\Commands\SetEntranceList.h" />
<ClInclude Include="ZRoom\Commands\SetExitList.h" />
<ClInclude Include="ZRoom\Commands\SetLightingSettings.h" />
<ClInclude Include="ZRoom\Commands\SetLightList.h" />
<ClInclude Include="ZRoom\Commands\SetMesh.h" />
<ClInclude Include="ZRoom\Commands\SetObjectList.h" />
<ClInclude Include="ZRoom\Commands\SetPathways.h" />
<ClInclude Include="ZRoom\Commands\SetRoomBehavior.h" />
<ClInclude Include="ZRoom\Commands\SetRoomList.h" />
<ClInclude Include="ZRoom\Commands\SetSkyboxModifier.h" />
<ClInclude Include="ZRoom\Commands\SetSkyboxSettings.h" />
<ClInclude Include="ZRoom\Commands\SetSoundSettings.h" />
<ClInclude Include="ZRoom\Commands\SetSpecialObjects.h" />
<ClInclude Include="ZRoom\Commands\SetStartPositionList.h" />
<ClInclude Include="ZRoom\Commands\SetTimeSettings.h" />
<ClInclude Include="ZRoom\Commands\SetTransitionActorList.h" />
<ClInclude Include="ZRoom\Commands\SetWind.h" />
<ClInclude Include="ZRoom\Commands\Unused09.h" />
<ClInclude Include="ZRoom\Commands\ZRoomCommandUnk.h" />
<ClInclude Include="ZRoom\ZRoom.h" />
<ClInclude Include="ZRoom\ZRoomCommand.h" />
<ClInclude Include="ZString.h" />
<ClInclude Include="ZSurfaceType.h" />
<ClInclude Include="ZSymbol.h" />
<ClInclude Include="ZTexture.h" />
<ClInclude Include="ZTextureAnimation.h" />
<ClInclude Include="ZVector.h" />
<ClInclude Include="ZVtx.h" />
</ItemGroup>
<ItemGroup>
<Text Include="..\SymbolMap_OoTMqDbg.txt">
<DeploymentContent>true</DeploymentContent>
</Text>
<Text Include="any\any\zlib.static.txt" />
<Text Include="NuGet\libpng.static.txt" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
<Import Project="..\packages\zlib.v120.windesktop.msvcstl.dyn.rt-dyn.1.2.8.8\build\native\zlib.v120.windesktop.msvcstl.dyn.rt-dyn.targets" Condition="Exists('..\packages\zlib.v120.windesktop.msvcstl.dyn.rt-dyn.1.2.8.8\build\native\zlib.v120.windesktop.msvcstl.dyn.rt-dyn.targets')" />
<Import Project="..\packages\zlib.v140.windesktop.msvcstl.dyn.rt-dyn.1.2.8.8\build\native\zlib.v140.windesktop.msvcstl.dyn.rt-dyn.targets" Condition="Exists('..\packages\zlib.v140.windesktop.msvcstl.dyn.rt-dyn.1.2.8.8\build\native\zlib.v140.windesktop.msvcstl.dyn.rt-dyn.targets')" />
<Import Project="..\packages\YY.NuGet.Import.Helper.1.0.0.4\build\native\YY.NuGet.Import.Helper.targets" Condition="Exists('..\packages\YY.NuGet.Import.Helper.1.0.0.4\build\native\YY.NuGet.Import.Helper.targets')" />
<Import Project="..\packages\zlib.static.1.2.5\build\native\zlib.static.targets" Condition="Exists('..\packages\zlib.static.1.2.5\build\native\zlib.static.targets')" />
<Import Project="..\packages\libpng.static.1.6.37\build\native\libpng.static.targets" Condition="Exists('..\packages\libpng.static.1.6.37\build\native\libpng.static.targets')" />
</ImportGroup>
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\zlib.v120.windesktop.msvcstl.dyn.rt-dyn.1.2.8.8\build\native\zlib.v120.windesktop.msvcstl.dyn.rt-dyn.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\zlib.v120.windesktop.msvcstl.dyn.rt-dyn.1.2.8.8\build\native\zlib.v120.windesktop.msvcstl.dyn.rt-dyn.targets'))" />
<Error Condition="!Exists('..\packages\zlib.v140.windesktop.msvcstl.dyn.rt-dyn.1.2.8.8\build\native\zlib.v140.windesktop.msvcstl.dyn.rt-dyn.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\zlib.v140.windesktop.msvcstl.dyn.rt-dyn.1.2.8.8\build\native\zlib.v140.windesktop.msvcstl.dyn.rt-dyn.targets'))" />
<Error Condition="!Exists('..\packages\YY.NuGet.Import.Helper.1.0.0.4\build\native\YY.NuGet.Import.Helper.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\YY.NuGet.Import.Helper.1.0.0.4\build\native\YY.NuGet.Import.Helper.props'))" />
<Error Condition="!Exists('..\packages\YY.NuGet.Import.Helper.1.0.0.4\build\native\YY.NuGet.Import.Helper.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\YY.NuGet.Import.Helper.1.0.0.4\build\native\YY.NuGet.Import.Helper.targets'))" />
<Error Condition="!Exists('..\packages\zlib.static.1.2.5\build\native\zlib.static.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\zlib.static.1.2.5\build\native\zlib.static.targets'))" />
<Error Condition="!Exists('..\packages\libpng.static.1.6.37\build\native\libpng.static.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\libpng.static.1.6.37\build\native\libpng.static.targets'))" />
</Target>
</Project>

View File

@ -0,0 +1,572 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
<Filter Include="Source Files\Libraries">
<UniqueIdentifier>{02148456-5068-4613-8478-f10addc58e70}</UniqueIdentifier>
</Filter>
<Filter Include="Header Files\Libraries">
<UniqueIdentifier>{bcab3136-95ba-4839-833c-43d78ad6e335}</UniqueIdentifier>
</Filter>
<Filter Include="Header Files\Libraries\elfio">
<UniqueIdentifier>{dc06ed84-f6fe-4277-80f3-d62bd5cdbb98}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files\Z64">
<UniqueIdentifier>{6049c045-bc38-4221-b29e-ca6d4d8af4aa}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files\Z64\ZRoom">
<UniqueIdentifier>{490e3a08-047b-48d3-ab53-3a860a3b92aa}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files\Z64\ZRoom\Commands">
<UniqueIdentifier>{26c06845-8e8e-4b79-ad18-07c4f9c0f801}</UniqueIdentifier>
</Filter>
<Filter Include="Header Files\Z64">
<UniqueIdentifier>{d45c420d-2378-47ac-92c5-80db9475c195}</UniqueIdentifier>
</Filter>
<Filter Include="Header Files\Z64\ZRoom">
<UniqueIdentifier>{03cc56a2-e0e8-4167-80a0-98fb900a959a}</UniqueIdentifier>
</Filter>
<Filter Include="Header Files\Z64\ZRoom\Commands">
<UniqueIdentifier>{73db0879-6df8-4f6a-8cc2-a1f836e9e796}</UniqueIdentifier>
</Filter>
<Filter Include="Header Files\Libraries\fbx">
<UniqueIdentifier>{be9a5be0-ec6a-4200-8e39-bb58c7da7aa8}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files\Libraries\libgfxd">
<UniqueIdentifier>{7ee79d97-c6a8-4e82-93ef-37981f4d7838}</UniqueIdentifier>
</Filter>
<Filter Include="Header Files\Libraries\libgfxd">
<UniqueIdentifier>{85600275-99fe-491d-8189-bcc3dc1a8903}</UniqueIdentifier>
</Filter>
<Filter Include="any">
<UniqueIdentifier>{ba9990b0-1082-48bb-874c-6108534b5455}</UniqueIdentifier>
</Filter>
<Filter Include="any\any">
<UniqueIdentifier>{ce9d91b0-ba20-4296-bc2d-8630965bb392}</UniqueIdentifier>
</Filter>
<Filter Include="NuGet">
<UniqueIdentifier>{730beb67-6d59-4849-9d9b-702c4a565fc0}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="Main.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="ZRoom\ZRoom.cpp">
<Filter>Source Files\Z64\ZRoom</Filter>
</ClCompile>
<ClCompile Include="ZRoom\Commands\SetEchoSettings.cpp">
<Filter>Source Files\Z64\ZRoom\Commands</Filter>
</ClCompile>
<ClCompile Include="ZRoom\ZRoomCommand.cpp">
<Filter>Source Files\Z64\ZRoom</Filter>
</ClCompile>
<ClCompile Include="ZRoom\Commands\SetSoundSettings.cpp">
<Filter>Source Files\Z64\ZRoom\Commands</Filter>
</ClCompile>
<ClCompile Include="ZRoom\Commands\SetWind.cpp">
<Filter>Source Files\Z64\ZRoom\Commands</Filter>
</ClCompile>
<ClCompile Include="ZRoom\Commands\SetTimeSettings.cpp">
<Filter>Source Files\Z64\ZRoom\Commands</Filter>
</ClCompile>
<ClCompile Include="ZRoom\Commands\SetSpecialObjects.cpp">
<Filter>Source Files\Z64\ZRoom\Commands</Filter>
</ClCompile>
<ClCompile Include="ZRoom\Commands\SetRoomBehavior.cpp">
<Filter>Source Files\Z64\ZRoom\Commands</Filter>
</ClCompile>
<ClCompile Include="ZRoom\Commands\SetSkyboxSettings.cpp">
<Filter>Source Files\Z64\ZRoom\Commands</Filter>
</ClCompile>
<ClCompile Include="ZRoom\Commands\SetCameraSettings.cpp">
<Filter>Source Files\Z64\ZRoom\Commands</Filter>
</ClCompile>
<ClCompile Include="ZRoom\Commands\SetSkyboxModifier.cpp">
<Filter>Source Files\Z64\ZRoom\Commands</Filter>
</ClCompile>
<ClCompile Include="ZRoom\Commands\SetActorList.cpp">
<Filter>Source Files\Z64\ZRoom\Commands</Filter>
</ClCompile>
<ClCompile Include="ZRoom\Commands\SetEntranceList.cpp">
<Filter>Source Files\Z64\ZRoom\Commands</Filter>
</ClCompile>
<ClCompile Include="ZRoom\Commands\SetStartPositionList.cpp">
<Filter>Source Files\Z64\ZRoom\Commands</Filter>
</ClCompile>
<ClCompile Include="Globals.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="ZRoom\Commands\SetAlternateHeaders.cpp">
<Filter>Source Files\Z64\ZRoom\Commands</Filter>
</ClCompile>
<ClCompile Include="ZRoom\Commands\SetExitList.cpp">
<Filter>Source Files\Z64\ZRoom\Commands</Filter>
</ClCompile>
<ClCompile Include="ZRoom\Commands\EndMarker.cpp">
<Filter>Source Files\Z64\ZRoom\Commands</Filter>
</ClCompile>
<ClCompile Include="ZRoom\Commands\SetCollisionHeader.cpp">
<Filter>Source Files\Z64\ZRoom\Commands</Filter>
</ClCompile>
<ClCompile Include="ZRoom\Commands\SetRoomList.cpp">
<Filter>Source Files\Z64\ZRoom\Commands</Filter>
</ClCompile>
<ClCompile Include="ZRoom\Commands\SetObjectList.cpp">
<Filter>Source Files\Z64\ZRoom\Commands</Filter>
</ClCompile>
<ClCompile Include="ZRoom\Commands\SetMesh.cpp">
<Filter>Source Files\Z64\ZRoom\Commands</Filter>
</ClCompile>
<ClCompile Include="ZRoom\Commands\Unused09.cpp">
<Filter>Source Files\Z64\ZRoom\Commands</Filter>
</ClCompile>
<ClCompile Include="ZRoom\Commands\SetLightingSettings.cpp">
<Filter>Source Files\Z64\ZRoom\Commands</Filter>
</ClCompile>
<ClCompile Include="ZRoom\Commands\SetTransitionActorList.cpp">
<Filter>Source Files\Z64\ZRoom\Commands</Filter>
</ClCompile>
<ClCompile Include="ZRoom\Commands\SetPathways.cpp">
<Filter>Source Files\Z64\ZRoom\Commands</Filter>
</ClCompile>
<ClCompile Include="ZRoom\Commands\SetCutscenes.cpp">
<Filter>Source Files\Z64\ZRoom\Commands</Filter>
</ClCompile>
<ClCompile Include="ZAnimation.cpp">
<Filter>Source Files\Z64</Filter>
</ClCompile>
<ClCompile Include="ZBlob.cpp">
<Filter>Source Files\Z64</Filter>
</ClCompile>
<ClCompile Include="ZCutscene.cpp">
<Filter>Source Files\Z64</Filter>
</ClCompile>
<ClCompile Include="ZDisplayList.cpp">
<Filter>Source Files\Z64</Filter>
</ClCompile>
<ClCompile Include="ZFile.cpp">
<Filter>Source Files\Z64</Filter>
</ClCompile>
<ClCompile Include="ZResource.cpp">
<Filter>Source Files\Z64</Filter>
</ClCompile>
<ClCompile Include="ZTexture.cpp">
<Filter>Source Files\Z64</Filter>
</ClCompile>
<ClCompile Include="ZSkeleton.cpp">
<Filter>Source Files\Z64</Filter>
</ClCompile>
<ClCompile Include="ZRoom\Commands\SetLightList.cpp">
<Filter>Source Files\Z64\ZRoom\Commands</Filter>
</ClCompile>
<ClCompile Include="ZRoom\Commands\ZRoomCommandUnk.cpp">
<Filter>Source Files\Z64\ZRoom\Commands</Filter>
</ClCompile>
<ClCompile Include="ZCollision.cpp">
<Filter>Source Files\Z64</Filter>
</ClCompile>
<ClCompile Include="ZScalar.cpp">
<Filter>Source Files\Z64</Filter>
</ClCompile>
<ClCompile Include="ZVector.cpp">
<Filter>Source Files\Z64</Filter>
</ClCompile>
<ClCompile Include="ZArray.cpp">
<Filter>Source Files\Z64</Filter>
</ClCompile>
<ClCompile Include="ZVtx.cpp">
<Filter>Source Files\Z64</Filter>
</ClCompile>
<ClCompile Include="ZLimb.cpp">
<Filter>Source Files\Z64</Filter>
</ClCompile>
<ClCompile Include="OutputFormatter.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="ZSymbol.cpp">
<Filter>Source Files\Z64</Filter>
</ClCompile>
<ClCompile Include="..\lib\libgfxd\gfxd.c">
<Filter>Source Files\Libraries\libgfxd</Filter>
</ClCompile>
<ClCompile Include="..\lib\libgfxd\uc.c">
<Filter>Source Files\Libraries\libgfxd</Filter>
</ClCompile>
<ClCompile Include="..\lib\libgfxd\uc_f3d.c">
<Filter>Source Files\Libraries\libgfxd</Filter>
</ClCompile>
<ClCompile Include="..\lib\libgfxd\uc_f3db.c">
<Filter>Source Files\Libraries\libgfxd</Filter>
</ClCompile>
<ClCompile Include="..\lib\libgfxd\uc_f3dex.c">
<Filter>Source Files\Libraries\libgfxd</Filter>
</ClCompile>
<ClCompile Include="..\lib\libgfxd\uc_f3dex2.c">
<Filter>Source Files\Libraries\libgfxd</Filter>
</ClCompile>
<ClCompile Include="..\lib\libgfxd\uc_f3dexb.c">
<Filter>Source Files\Libraries\libgfxd</Filter>
</ClCompile>
<ClCompile Include="ZMtx.cpp">
<Filter>Source Files\Z64</Filter>
</ClCompile>
<ClCompile Include="ZRoom\Commands\SetWorldMapVisited.cpp">
<Filter>Source Files\Z64\ZRoom\Commands</Filter>
</ClCompile>
<ClCompile Include="ZRoom\Commands\Unused1D.cpp">
<Filter>Source Files\Z64\ZRoom\Commands</Filter>
</ClCompile>
<ClCompile Include="ZRoom\Commands\SetActorCutsceneList.cpp">
<Filter>Source Files\Z64\ZRoom\Commands</Filter>
</ClCompile>
<ClCompile Include="ZRoom\Commands\SetCsCamera.cpp">
<Filter>Source Files\Z64\ZRoom\Commands</Filter>
</ClCompile>
<ClCompile Include="ZRoom\Commands\SetMinimapChests.cpp">
<Filter>Source Files\Z64\ZRoom\Commands</Filter>
</ClCompile>
<ClCompile Include="ZRoom\Commands\SetMinimapList.cpp">
<Filter>Source Files\Z64\ZRoom\Commands</Filter>
</ClCompile>
<ClCompile Include="ZBackground.cpp">
<Filter>Source Files\Z64</Filter>
</ClCompile>
<ClCompile Include="ZRoom\Commands\SetAnimatedMaterialList.cpp">
<Filter>Source Files\Z64\ZRoom\Commands</Filter>
</ClCompile>
<ClCompile Include="ZPath.cpp">
<Filter>Source Files\Z64</Filter>
</ClCompile>
<ClCompile Include="Declaration.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="ImageBackend.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="ZString.cpp">
<Filter>Source Files\Z64</Filter>
</ClCompile>
<ClCompile Include="GameConfig.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="ZTextureAnimation.cpp">
<Filter>Source Files\Z64</Filter>
</ClCompile>
<ClCompile Include="OtherStructs\SkinLimbStructs.cpp">
<Filter>Source Files\Z64</Filter>
</ClCompile>
<ClCompile Include="..\build\ZAPD\BuildInfo.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="ZPlayerAnimationData.cpp">
<Filter>Source Files\Z64</Filter>
</ClCompile>
<ClCompile Include="WarningHandler.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="ZCollisionPoly.cpp">
<Filter>Source Files\Z64</Filter>
</ClCompile>
<ClCompile Include="OtherStructs\Cutscene_Commands.cpp">
<Filter>Source Files\Z64</Filter>
</ClCompile>
<ClCompile Include="OtherStructs\CutsceneMM_Commands.cpp">
<Filter>Source Files\Z64</Filter>
</ClCompile>
<ClCompile Include="CrashHandler.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="ZSurfaceType.cpp">
<Filter>Source Files\Z64</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="ZRoom\ZRoom.h">
<Filter>Header Files\Z64\ZRoom</Filter>
</ClInclude>
<ClInclude Include="ZRoom\ZRoomCommand.h">
<Filter>Header Files\Z64\ZRoom</Filter>
</ClInclude>
<ClInclude Include="ZRoom\Commands\SetEchoSettings.h">
<Filter>Header Files\Z64\ZRoom\Commands</Filter>
</ClInclude>
<ClInclude Include="ZRoom\Commands\SetSoundSettings.h">
<Filter>Header Files\Z64\ZRoom\Commands</Filter>
</ClInclude>
<ClInclude Include="ZRoom\Commands\SetWind.h">
<Filter>Header Files\Z64\ZRoom\Commands</Filter>
</ClInclude>
<ClInclude Include="ZRoom\Commands\SetTimeSettings.h">
<Filter>Header Files\Z64\ZRoom\Commands</Filter>
</ClInclude>
<ClInclude Include="ZRoom\Commands\SetSpecialObjects.h">
<Filter>Header Files\Z64\ZRoom\Commands</Filter>
</ClInclude>
<ClInclude Include="ZRoom\Commands\SetRoomBehavior.h">
<Filter>Header Files\Z64\ZRoom\Commands</Filter>
</ClInclude>
<ClInclude Include="ZRoom\Commands\SetSkyboxSettings.h">
<Filter>Header Files\Z64\ZRoom\Commands</Filter>
</ClInclude>
<ClInclude Include="ZRoom\Commands\SetCameraSettings.h">
<Filter>Header Files\Z64\ZRoom\Commands</Filter>
</ClInclude>
<ClInclude Include="ZRoom\Commands\SetSkyboxModifier.h">
<Filter>Header Files\Z64\ZRoom\Commands</Filter>
</ClInclude>
<ClInclude Include="ZRoom\Commands\SetActorList.h">
<Filter>Header Files\Z64\ZRoom\Commands</Filter>
</ClInclude>
<ClInclude Include="ZRoom\Commands\SetEntranceList.h">
<Filter>Header Files\Z64\ZRoom\Commands</Filter>
</ClInclude>
<ClInclude Include="ZRoom\Commands\SetStartPositionList.h">
<Filter>Header Files\Z64\ZRoom\Commands</Filter>
</ClInclude>
<ClInclude Include="..\lib\elfio\elfio\elf_types.hpp">
<Filter>Header Files\Libraries\elfio</Filter>
</ClInclude>
<ClInclude Include="..\lib\elfio\elfio\elfio.hpp">
<Filter>Header Files\Libraries\elfio</Filter>
</ClInclude>
<ClInclude Include="..\lib\elfio\elfio\elfio_dump.hpp">
<Filter>Header Files\Libraries\elfio</Filter>
</ClInclude>
<ClInclude Include="..\lib\elfio\elfio\elfio_dynamic.hpp">
<Filter>Header Files\Libraries\elfio</Filter>
</ClInclude>
<ClInclude Include="..\lib\elfio\elfio\elfio_header.hpp">
<Filter>Header Files\Libraries\elfio</Filter>
</ClInclude>
<ClInclude Include="..\lib\elfio\elfio\elfio_note.hpp">
<Filter>Header Files\Libraries\elfio</Filter>
</ClInclude>
<ClInclude Include="..\lib\elfio\elfio\elfio_relocation.hpp">
<Filter>Header Files\Libraries\elfio</Filter>
</ClInclude>
<ClInclude Include="..\lib\elfio\elfio\elfio_section.hpp">
<Filter>Header Files\Libraries\elfio</Filter>
</ClInclude>
<ClInclude Include="..\lib\elfio\elfio\elfio_segment.hpp">
<Filter>Header Files\Libraries\elfio</Filter>
</ClInclude>
<ClInclude Include="..\lib\elfio\elfio\elfio_strings.hpp">
<Filter>Header Files\Libraries\elfio</Filter>
</ClInclude>
<ClInclude Include="..\lib\elfio\elfio\elfio_symbols.hpp">
<Filter>Header Files\Libraries\elfio</Filter>
</ClInclude>
<ClInclude Include="..\lib\elfio\elfio\elfio_utils.hpp">
<Filter>Header Files\Libraries\elfio</Filter>
</ClInclude>
<ClInclude Include="Globals.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="ZRoom\Commands\SetAlternateHeaders.h">
<Filter>Header Files\Z64\ZRoom\Commands</Filter>
</ClInclude>
<ClInclude Include="ZRoom\Commands\SetExitList.h">
<Filter>Header Files\Z64\ZRoom\Commands</Filter>
</ClInclude>
<ClInclude Include="ZRoom\Commands\EndMarker.h">
<Filter>Header Files\Z64\ZRoom\Commands</Filter>
</ClInclude>
<ClInclude Include="ZRoom\Commands\SetCollisionHeader.h">
<Filter>Header Files\Z64\ZRoom\Commands</Filter>
</ClInclude>
<ClInclude Include="ZRoom\Commands\SetRoomList.h">
<Filter>Header Files\Z64\ZRoom\Commands</Filter>
</ClInclude>
<ClInclude Include="ZRoom\Commands\SetObjectList.h">
<Filter>Header Files\Z64\ZRoom\Commands</Filter>
</ClInclude>
<ClInclude Include="ZRoom\Commands\SetMesh.h">
<Filter>Header Files\Z64\ZRoom\Commands</Filter>
</ClInclude>
<ClInclude Include="ZRoom\Commands\Unused09.h">
<Filter>Header Files\Z64\ZRoom\Commands</Filter>
</ClInclude>
<ClInclude Include="ZRoom\Commands\SetLightingSettings.h">
<Filter>Header Files\Z64\ZRoom\Commands</Filter>
</ClInclude>
<ClInclude Include="ZRoom\Commands\SetTransitionActorList.h">
<Filter>Header Files\Z64\ZRoom\Commands</Filter>
</ClInclude>
<ClInclude Include="ZRoom\Commands\SetPathways.h">
<Filter>Header Files\Z64\ZRoom\Commands</Filter>
</ClInclude>
<ClInclude Include="ZRoom\Commands\SetCutscenes.h">
<Filter>Header Files\Z64\ZRoom\Commands</Filter>
</ClInclude>
<ClInclude Include="..\lib\stb\stb_image.h">
<Filter>Header Files\Libraries</Filter>
</ClInclude>
<ClInclude Include="..\lib\stb\stb_image_write.h">
<Filter>Header Files\Libraries</Filter>
</ClInclude>
<ClInclude Include="ZTexture.h">
<Filter>Header Files\Z64</Filter>
</ClInclude>
<ClInclude Include="ZAnimation.h">
<Filter>Header Files\Z64</Filter>
</ClInclude>
<ClInclude Include="ZBlob.h">
<Filter>Header Files\Z64</Filter>
</ClInclude>
<ClInclude Include="ZCutscene.h">
<Filter>Header Files\Z64</Filter>
</ClInclude>
<ClInclude Include="ZDisplayList.h">
<Filter>Header Files\Z64</Filter>
</ClInclude>
<ClInclude Include="ZFile.h">
<Filter>Header Files\Z64</Filter>
</ClInclude>
<ClInclude Include="ZResource.h">
<Filter>Header Files\Z64</Filter>
</ClInclude>
<ClInclude Include="ZSkeleton.h">
<Filter>Header Files\Z64</Filter>
</ClInclude>
<ClInclude Include="ZRoom\Commands\SetLightList.h">
<Filter>Header Files\Z64\ZRoom\Commands</Filter>
</ClInclude>
<ClInclude Include="ZRoom\Commands\ZRoomCommandUnk.h">
<Filter>Header Files\Z64\ZRoom\Commands</Filter>
</ClInclude>
<ClInclude Include="ZCollision.h">
<Filter>Header Files\Z64</Filter>
</ClInclude>
<ClInclude Include="ZScalar.h">
<Filter>Header Files\Z64</Filter>
</ClInclude>
<ClInclude Include="ZVector.h">
<Filter>Header Files\Z64</Filter>
</ClInclude>
<ClInclude Include="..\lib\stb\tinyxml2.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="ZArray.h">
<Filter>Header Files\Z64</Filter>
</ClInclude>
<ClInclude Include="ZVtx.h">
<Filter>Header Files\Z64</Filter>
</ClInclude>
<ClInclude Include="CRC32.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="ZLimb.h">
<Filter>Header Files\Z64</Filter>
</ClInclude>
<ClInclude Include="OutputFormatter.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="ZSymbol.h">
<Filter>Header Files\Z64</Filter>
</ClInclude>
<ClInclude Include="..\lib\libgfxd\gbi.h">
<Filter>Header Files\Libraries\libgfxd</Filter>
</ClInclude>
<ClInclude Include="..\lib\libgfxd\gfxd.h">
<Filter>Header Files\Libraries\libgfxd</Filter>
</ClInclude>
<ClInclude Include="..\lib\libgfxd\priv.h">
<Filter>Header Files\Libraries\libgfxd</Filter>
</ClInclude>
<ClInclude Include="ZMtx.h">
<Filter>Header Files\Z64</Filter>
</ClInclude>
<ClInclude Include="ZRoom\Commands\SetWorldMapVisited.h">
<Filter>Header Files\Z64\ZRoom\Commands</Filter>
</ClInclude>
<ClInclude Include="ZRoom\Commands\SetActorCutsceneList.h">
<Filter>Header Files\Z64\ZRoom\Commands</Filter>
</ClInclude>
<ClInclude Include="ZRoom\Commands\Unused1D.h">
<Filter>Header Files\Z64\ZRoom\Commands</Filter>
</ClInclude>
<ClInclude Include="ZRoom\Commands\SetCsCamera.h">
<Filter>Header Files\Z64\ZRoom\Commands</Filter>
</ClInclude>
<ClInclude Include="ZRoom\Commands\SetMinimapChests.h">
<Filter>Header Files\Z64\ZRoom\Commands</Filter>
</ClInclude>
<ClInclude Include="ZRoom\Commands\SetMinimapList.h">
<Filter>Header Files\Z64\ZRoom\Commands</Filter>
</ClInclude>
<ClInclude Include="ZBackground.h">
<Filter>Header Files\Z64</Filter>
</ClInclude>
<ClInclude Include="ZRoom\Commands\SetAnimatedMaterialList.h">
<Filter>Header Files\Z64\ZRoom\Commands</Filter>
</ClInclude>
<ClInclude Include="ImageBackend.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="ZPath.h">
<Filter>Header Files\Z64</Filter>
</ClInclude>
<ClInclude Include="Declaration.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="ZString.h">
<Filter>Header Files\Z64</Filter>
</ClInclude>
<ClInclude Include="GameConfig.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="ZTextureAnimation.h">
<Filter>Header Files\Z64</Filter>
</ClInclude>
<ClInclude Include="OtherStructs\SkinLimbStructs.h">
<Filter>Header Files\Z64</Filter>
</ClInclude>
<ClInclude Include="ZPlayerAnimationData.h">
<Filter>Header Files\Z64</Filter>
</ClInclude>
<ClInclude Include="WarningHandler.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="ZCollisionPoly.h">
<Filter>Header Files\Z64</Filter>
</ClInclude>
<ClInclude Include="OtherStructs\Cutscene_Commands.h">
<Filter>Header Files\Z64</Filter>
</ClInclude>
<ClInclude Include="OtherStructs\CutsceneMM_Commands.h">
<Filter>Header Files\Z64</Filter>
</ClInclude>
<ClInclude Include="CrashHandler.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="ZSurfaceType.h">
<Filter>Header Files\Z64</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<Text Include="..\SymbolMap_OoTMqDbg.txt">
<Filter>Resource Files</Filter>
</Text>
<Text Include="any\any\zlib.static.txt">
<Filter>any\any</Filter>
</Text>
<Text Include="NuGet\libpng.static.txt">
<Filter>NuGet</Filter>
</Text>
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
</Project>

194
ZAPDTR/ZAPD/ZActorList.cpp Normal file
View File

@ -0,0 +1,194 @@
#include "ZActorList.h"
#include "Globals.h"
#include "Utils/BitConverter.h"
#include "WarningHandler.h"
#include "ZFile.h"
#include "ZRoom/ZNames.h"
REGISTER_ZFILENODE(ActorList, ZActorList);
ZActorList::ZActorList(ZFile* nParent) : ZResource(nParent)
{
RegisterRequiredAttribute("Count");
}
void ZActorList::ExtractFromBinary(uint32_t nRawDataIndex, uint8_t nNumActors)
{
rawDataIndex = nRawDataIndex;
numActors = nNumActors;
// Don't parse raw data of external files
if (parent->GetMode() == ZFileMode::ExternalFile)
return;
ParseRawData();
}
void ZActorList::ParseXML(tinyxml2::XMLElement* reader)
{
ZResource::ParseXML(reader);
numActors = StringHelper::StrToL(registeredAttributes.at("Count").value);
if (numActors < 1)
{
HANDLE_ERROR_RESOURCE(
WarningType::InvalidAttributeValue, parent, this, rawDataIndex,
StringHelper::Sprintf("invalid value '%d' found for 'NumPaths' attribute", numActors),
"Should be at least '1'");
}
}
void ZActorList::ParseRawData()
{
ZResource::ParseRawData();
offset_t currentPtr = rawDataIndex;
size_t largestlength = 0;
for (size_t i = 0; i < numActors; i++)
{
ActorSpawnEntry entry(parent->GetRawData(), currentPtr);
currentPtr += entry.GetRawDataSize();
actors.push_back(entry);
size_t actorNameLength = ZNames::GetActorName(entry.GetActorId()).size();
if (actorNameLength > largestlength)
largestlength = actorNameLength;
}
for (auto& entry : actors)
{
entry.SetLargestActorName(largestlength);
}
}
Declaration* ZActorList::DeclareVar(const std::string& prefix, const std::string& bodyStr)
{
std::string auxName = name;
if (name == "")
auxName = GetDefaultName(prefix);
Declaration* decl =
parent->AddDeclarationArray(rawDataIndex, GetDeclarationAlignment(), GetRawDataSize(),
GetSourceTypeName(), name, GetActorListArraySize(), bodyStr);
decl->staticConf = staticConf;
return decl;
}
std::string ZActorList::GetBodySourceCode() const
{
std::string declaration;
size_t index = 0;
for (auto& entry : actors)
{
declaration += StringHelper::Sprintf("\t{ %s },", entry.GetBodySourceCode().c_str());
if (index < actors.size() - 1)
declaration += "\n";
index++;
}
return declaration;
}
std::string ZActorList::GetSourceTypeName() const
{
return actors.front().GetSourceTypeName();
}
ZResourceType ZActorList::GetResourceType() const
{
return ZResourceType::ActorList;
}
size_t ZActorList::GetRawDataSize() const
{
return actors.size() * actors.front().GetRawDataSize();
}
size_t ZActorList::GetActorListArraySize() const
{
size_t actorCount = 0;
// Doing an else-if here so we only do the loop when the game is SW97.
// Actor 0x22 is removed from SW97, so we need to ensure that we don't increment the actor count
// for it.
if (Globals::Instance->game == ZGame::OOT_SW97)
{
actorCount = 0;
for (const auto& entry : actors)
if (entry.GetActorId() != 0x22)
actorCount++;
}
else
{
actorCount = actors.size();
}
return actorCount;
}
/* ActorSpawnEntry */
ActorSpawnEntry::ActorSpawnEntry(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex)
{
actorNum = BitConverter::ToInt16BE(rawData, rawDataIndex + 0);
posX = BitConverter::ToInt16BE(rawData, rawDataIndex + 2);
posY = BitConverter::ToInt16BE(rawData, rawDataIndex + 4);
posZ = BitConverter::ToInt16BE(rawData, rawDataIndex + 6);
rotX = BitConverter::ToUInt16BE(rawData, rawDataIndex + 8);
rotY = BitConverter::ToUInt16BE(rawData, rawDataIndex + 10);
rotZ = BitConverter::ToUInt16BE(rawData, rawDataIndex + 12);
params = BitConverter::ToInt16BE(rawData, rawDataIndex + 14);
}
std::string ActorSpawnEntry::GetBodySourceCode() const
{
std::string body;
std::string actorNameFmt = StringHelper::Sprintf("%%-%zus ", largestActorName + 1);
body =
StringHelper::Sprintf(actorNameFmt.c_str(), (ZNames::GetActorName(actorNum) + ",").c_str());
body += StringHelper::Sprintf("{ %6i, %6i, %6i }, ", posX, posY, posZ);
if (Globals::Instance->game == ZGame::MM_RETAIL)
body += StringHelper::Sprintf("{ SPAWN_ROT_FLAGS(%#5hX, 0x%04X)"
", SPAWN_ROT_FLAGS(%#5hX, 0x%04X)"
", SPAWN_ROT_FLAGS(%#5hX, 0x%04X) }, ",
(rotX >> 7) & 0b111111111, rotX & 0b1111111,
(rotY >> 7) & 0b111111111, rotY & 0b1111111,
(rotZ >> 7) & 0b111111111, rotZ & 0b1111111);
else
body += StringHelper::Sprintf("{ %#6hX, %#6hX, %#6hX }, ", rotX, rotY, rotZ);
body += StringHelper::Sprintf("0x%04X", params);
return body;
}
std::string ActorSpawnEntry::GetSourceTypeName() const
{
return "ActorEntry";
}
size_t ActorSpawnEntry::GetRawDataSize() const
{
return 16;
}
uint16_t ActorSpawnEntry::GetActorId() const
{
return actorNum;
}
void ActorSpawnEntry::SetLargestActorName(size_t nameSize)
{
largestActorName = nameSize;
}

52
ZAPDTR/ZAPD/ZActorList.h Normal file
View File

@ -0,0 +1,52 @@
#pragma once
#include "ZResource.h"
class ActorSpawnEntry
{
public:
uint16_t actorNum;
int16_t posX;
int16_t posY;
int16_t posZ;
uint16_t rotX;
uint16_t rotY;
uint16_t rotZ;
uint16_t params;
size_t largestActorName = 16;
ActorSpawnEntry(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex);
std::string GetBodySourceCode() const;
std::string GetSourceTypeName() const;
size_t GetRawDataSize() const;
uint16_t GetActorId() const;
void SetLargestActorName(size_t nameSize);
};
class ZActorList : public ZResource
{
public:
std::vector<ActorSpawnEntry> actors;
uint32_t numActors = 0;
ZActorList(ZFile* nParent);
void ExtractFromBinary(offset_t nRawDataIndex, uint8_t nNumActors);
void ParseXML(tinyxml2::XMLElement* reader) override;
void ParseRawData() override;
Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr) override;
std::string GetBodySourceCode() const override;
std::string GetSourceTypeName() const override;
ZResourceType GetResourceType() const override;
size_t GetRawDataSize() const override;
protected:
size_t GetActorListArraySize() const;
};

View File

@ -67,7 +67,7 @@ void ZNormalAnimation::ParseRawData()
{
ZAnimation::ParseRawData();
const uint8_t* data = parent->GetRawData().data();
auto& data = parent->GetRawData();
rotationValuesSeg = BitConverter::ToInt32BE(data, rawDataIndex + 4);
rotationIndicesSeg = BitConverter::ToInt32BE(data, rawDataIndex + 8);

View File

@ -44,6 +44,7 @@ void ZArray::ParseXML(tinyxml2::XMLElement* reader)
auto nodeMap = ZFile::GetNodeMap();
size_t childIndex = rawDataIndex;
resList.reserve(arrayCnt);
for (size_t i = 0; i < arrayCnt; i++)
{
ZResource* res = nodeMap->at(childName)(parent);
@ -95,17 +96,27 @@ Declaration* ZArray::DeclareVar(const std::string& prefix, const std::string& bo
std::string ZArray::GetBodySourceCode() const
{
std::string output = "";
std::string output;
for (size_t i = 0; i < arrayCnt; i++)
{
const auto& res = resList[i];
output += "\t";
if (res->GetResourceType() == ZResourceType::Scalar || res->GetResourceType() == ZResourceType::Vertex)
switch (res->GetResourceType())
{
case ZResourceType::Pointer:
case ZResourceType::Scalar:
case ZResourceType::Vertex:
case ZResourceType::CollisionPoly:
case ZResourceType::SurfaceType:
output += resList.at(i)->GetBodySourceCode();
else
break;
default:
output += StringHelper::Sprintf("{ %s }", resList.at(i)->GetBodySourceCode().c_str());
break;
}
if (i < arrayCnt - 1 || res->IsExternalResource())
output += ",\n";
@ -117,7 +128,7 @@ std::string ZArray::GetBodySourceCode() const
size_t ZArray::GetRawDataSize() const
{
size_t size = 0;
for (auto res : resList)
for (const auto res : resList)
size += res->GetRawDataSize();
return size;
}

View File

@ -1,5 +1,6 @@
#include "ZCollision.h"
#include <cassert>
#include <cstdint>
#include <string>
@ -51,7 +52,7 @@ void ZCollisionHeader::ParseRawData()
vertices.reserve(numVerts);
polygons.reserve(numPolygons);
uint32_t currentPtr = vtxSegmentOffset;
offset_t currentPtr = vtxSegmentOffset;
for (uint16_t i = 0; i < numVerts; i++)
{
@ -63,23 +64,67 @@ void ZCollisionHeader::ParseRawData()
}
for (uint16_t i = 0; i < numPolygons; i++)
polygons.push_back(PolygonEntry(rawData, polySegmentOffset + (i * 16)));
{
ZCollisionPoly poly(parent);
poly.SetRawDataIndex(polySegmentOffset + (i * 16));
poly.ParseRawData();
polygons.push_back(poly);
}
uint16_t highestPolyType = 0;
for (PolygonEntry poly : polygons)
for (const ZCollisionPoly& poly : polygons)
{
if (poly.type > highestPolyType)
highestPolyType = poly.type;
}
for (uint16_t i = 0; i < highestPolyType + 1; i++)
polygonTypes.push_back(
BitConverter::ToUInt64BE(rawData, polyTypeDefSegmentOffset + (i * 8)));
{
ZSurfaceType surfaceType(parent);
surfaceType.SetRawDataIndex(polyTypeDefSegmentOffset + (i * 8));
surfaceType.ParseRawData();
PolygonTypes.push_back(surfaceType);
}
// polygonTypes.push_back(
// BitConverter::ToUInt64BE(rawData, polyTypeDefSegmentOffset + (i * 8)));
if (camDataAddress != 0)
camData = new CameraDataList(parent, name, rawData, camDataSegmentOffset,
polyTypeDefSegmentOffset, polygonTypes.size());
if (camDataAddress != SEGMENTED_NULL)
{
// Try to guess how many elements the CamDataList array has.
// The "guessing algorithm" is basically a "best effort" one and it
// is error-prone.
// This is based mostly on observation of how CollisionHeader data is
// usually ordered. If for some reason the data was in some other funny
// order, this would probably break.
// The most common ordering is:
// - *CamData*
// - SurfaceType
// - CollisionPoly
// - Vertices
// - WaterBoxes
// - CollisionHeader
offset_t upperCameraBoundary = polyTypeDefSegmentOffset;
if (upperCameraBoundary == 0)
{
upperCameraBoundary = polySegmentOffset;
}
if (upperCameraBoundary == 0)
{
upperCameraBoundary = vtxSegmentOffset;
}
if (upperCameraBoundary == 0)
{
upperCameraBoundary = waterBoxSegmentOffset;
}
if (upperCameraBoundary == 0)
{
upperCameraBoundary = rawDataIndex;
}
camData =
new CameraDataList(parent, name, rawData, camDataSegmentOffset, upperCameraBoundary);
}
for (uint16_t i = 0; i < numWaterBoxes; i++)
waterBoxes.push_back(WaterBoxHeader(
@ -110,8 +155,7 @@ void ZCollisionHeader::DeclareReferences(const std::string& prefix)
parent->AddDeclarationArray(
waterBoxSegmentOffset, DeclarationAlignment::Align4, 16 * waterBoxes.size(), "WaterBox",
StringHelper::Sprintf("%s_waterBoxes_%06X", auxName.c_str(), waterBoxSegmentOffset),
waterBoxes.size(), declaration);
StringHelper::Sprintf("%sWaterBoxes", auxName.c_str()), waterBoxes.size(), declaration);
}
if (polygons.size() > 0)
@ -122,40 +166,31 @@ void ZCollisionHeader::DeclareReferences(const std::string& prefix)
{
for (size_t i = 0; i < polygons.size(); i++)
{
declaration += StringHelper::Sprintf(
"\t{ 0x%04X, 0x%04X, 0x%04X, 0x%04X, 0x%04X, 0x%04X, 0x%04X, 0x%04X },",
polygons[i].type, polygons[i].vtxA, polygons[i].vtxB, polygons[i].vtxC,
polygons[i].a, polygons[i].b, polygons[i].c, polygons[i].d);
declaration +=
StringHelper::Sprintf("\t%s,", polygons[i].GetBodySourceCode().c_str());
if (i + 1 < polygons.size())
declaration += "\n";
}
}
parent->AddDeclarationArray(
polySegmentOffset, DeclarationAlignment::Align4, polygons.size() * 16, "CollisionPoly",
StringHelper::Sprintf("%s_polygons_%08X", auxName.c_str(), polySegmentOffset),
polygons.size(), declaration);
parent->AddDeclarationArray(polySegmentOffset, DeclarationAlignment::Align4,
polygons.size() * 16, polygons[0].GetSourceTypeName().c_str(),
StringHelper::Sprintf("%sPolygons", auxName.c_str()),
polygons.size(), declaration);
}
declaration.clear();
if (!Globals::Instance->otrMode)
for (const auto& polyType : PolygonTypes)
{
for (size_t i = 0; i < polygonTypes.size(); i++)
{
declaration += StringHelper::Sprintf("\t{ 0x%08lX, 0x%08lX },", polygonTypes[i] >> 32,
polygonTypes[i] & 0xFFFFFFFF);
if (i < polygonTypes.size() - 1)
declaration += "\n";
}
declaration += StringHelper::Sprintf("\t%s,", polyType.GetBodySourceCode().c_str());
}
if (polyTypeDefAddress != 0)
parent->AddDeclarationArray(
polyTypeDefSegmentOffset, DeclarationAlignment::Align4, polygonTypes.size() * 8,
"SurfaceType",
StringHelper::Sprintf("%s_surfaceType_%08X", auxName.c_str(), polyTypeDefSegmentOffset),
polygonTypes.size(), declaration);
if (polyTypeDefAddress != SEGMENTED_NULL)
parent->AddDeclarationArray(polyTypeDefSegmentOffset, DeclarationAlignment::Align4,
PolygonTypes.size() * 8,
PolygonTypes[0].GetSourceTypeName().c_str(),
StringHelper::Sprintf("%sSurfaceType", auxName.c_str()),
PolygonTypes.size(), declaration);
declaration.clear();
@ -180,8 +215,7 @@ void ZCollisionHeader::DeclareReferences(const std::string& prefix)
parent->AddDeclarationArray(
vtxSegmentOffset, first.GetDeclarationAlignment(),
vertices.size() * first.GetRawDataSize(), first.GetSourceTypeName(),
StringHelper::Sprintf("%s_vtx_%08X", auxName.c_str(), vtxSegmentOffset),
vertices.size(), declaration);
StringHelper::Sprintf("%sVertices", auxName.c_str()), vertices.size(), declaration);
}
}
@ -244,34 +278,18 @@ size_t ZCollisionHeader::GetRawDataSize() const
return 44;
}
PolygonEntry::PolygonEntry(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex)
{
const uint8_t* data = rawData.data();
type = BitConverter::ToUInt16BE(data, rawDataIndex + 0);
vtxA = BitConverter::ToUInt16BE(data, rawDataIndex + 2);
vtxB = BitConverter::ToUInt16BE(data, rawDataIndex + 4);
vtxC = BitConverter::ToUInt16BE(data, rawDataIndex + 6);
a = BitConverter::ToUInt16BE(data, rawDataIndex + 8);
b = BitConverter::ToUInt16BE(data, rawDataIndex + 10);
c = BitConverter::ToUInt16BE(data, rawDataIndex + 12);
d = BitConverter::ToUInt16BE(data, rawDataIndex + 14);
}
WaterBoxHeader::WaterBoxHeader(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex)
{
const uint8_t* data = rawData.data();
xMin = BitConverter::ToInt16BE(data, rawDataIndex + 0);
ySurface = BitConverter::ToInt16BE(data, rawDataIndex + 2);
zMin = BitConverter::ToInt16BE(data, rawDataIndex + 4);
xLength = BitConverter::ToInt16BE(data, rawDataIndex + 6);
zLength = BitConverter::ToInt16BE(data, rawDataIndex + 8);
xMin = BitConverter::ToInt16BE(rawData, rawDataIndex + 0);
ySurface = BitConverter::ToInt16BE(rawData, rawDataIndex + 2);
zMin = BitConverter::ToInt16BE(rawData, rawDataIndex + 4);
xLength = BitConverter::ToInt16BE(rawData, rawDataIndex + 6);
zLength = BitConverter::ToInt16BE(rawData, rawDataIndex + 8);
if (Globals::Instance->game == ZGame::OOT_SW97)
properties = BitConverter::ToInt16BE(data, rawDataIndex + 10);
properties = BitConverter::ToInt16BE(rawData, rawDataIndex + 10);
else
properties = BitConverter::ToInt32BE(data, rawDataIndex + 12);
properties = BitConverter::ToInt32BE(rawData, rawDataIndex + 12);
}
std::string WaterBoxHeader::GetBodySourceCode() const
@ -281,16 +299,17 @@ std::string WaterBoxHeader::GetBodySourceCode() const
}
CameraDataList::CameraDataList(ZFile* parent, const std::string& prefix,
const std::vector<uint8_t>& rawData, uint32_t rawDataIndex,
uint32_t polyTypeDefSegmentOffset,
[[maybe_unused]] uint32_t polygonTypesCnt)
const std::vector<uint8_t>& rawData, offset_t rawDataIndex,
offset_t upperCameraBoundary)
{
std::string declaration;
// Parse CameraDataEntries
int32_t numElements = (polyTypeDefSegmentOffset - rawDataIndex) / 8;
uint32_t cameraPosDataSeg = rawDataIndex;
for (int32_t i = 0; i < numElements; i++)
size_t numElements = (upperCameraBoundary - rawDataIndex) / 8;
assert(numElements < 10000);
offset_t cameraPosDataSeg = rawDataIndex;
for (size_t i = 0; i < numElements; i++)
{
CameraDataEntry* entry = new CameraDataEntry();
@ -322,8 +341,7 @@ CameraDataList::CameraDataList(ZFile* parent, const std::string& prefix,
{
int32_t index =
((entries[i]->cameraPosDataSeg & 0x00FFFFFF) - cameraPosDataOffset) / 0x6;
sprintf(camSegLine, "&%s_camPosData_%08X[%i]", prefix.c_str(), cameraPosDataOffset,
index);
sprintf(camSegLine, "&%sCamPosData[%i]", prefix.c_str(), index);
}
else
sprintf(camSegLine, "NULL");
@ -338,7 +356,7 @@ CameraDataList::CameraDataList(ZFile* parent, const std::string& prefix,
parent->AddDeclarationArray(
rawDataIndex, DeclarationAlignment::Align4, entries.size() * 8, "CamData",
StringHelper::Sprintf("%s_camDataList_%08X", prefix.c_str(), rawDataIndex), entries.size(),
StringHelper::Sprintf("%sCamDataList", prefix.c_str(), rawDataIndex), entries.size(),
declaration);
uint32_t numDataTotal = (rawDataIndex - cameraPosDataOffset) / 0x6;
@ -359,10 +377,9 @@ CameraDataList::CameraDataList(ZFile* parent, const std::string& prefix,
int32_t cameraPosDataIndex = GETSEGOFFSET(cameraPosDataSeg);
uint32_t entrySize = numDataTotal * 0x6;
parent->AddDeclarationArray(
cameraPosDataIndex, DeclarationAlignment::Align4, entrySize, "Vec3s",
StringHelper::Sprintf("%s_camPosData_%08X", prefix.c_str(), cameraPosDataIndex),
numDataTotal, declaration);
parent->AddDeclarationArray(cameraPosDataIndex, DeclarationAlignment::Align4, entrySize,
"Vec3s", StringHelper::Sprintf("%sCamPosData", prefix.c_str()),
numDataTotal, declaration);
}
}

View File

@ -1,20 +1,12 @@
#pragma once
#include "ZCollisionPoly.h"
#include "ZFile.h"
#include "ZResource.h"
#include "ZRoom/ZRoom.h"
#include "ZSurfaceType.h"
#include "ZVector.h"
class PolygonEntry
{
public:
uint16_t type;
uint16_t vtxA, vtxB, vtxC;
uint16_t a, b, c, d;
PolygonEntry(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex);
};
class WaterBoxHeader
{
public:
@ -54,8 +46,7 @@ public:
std::vector<CameraPositionData*> cameraPositionData;
CameraDataList(ZFile* parent, const std::string& prefix, const std::vector<uint8_t>& rawData,
uint32_t rawDataIndex, uint32_t polyTypeDefSegmentOffset,
uint32_t polygonTypesCnt);
offset_t rawDataIndex, offset_t upperCameraBoundary);
~CameraDataList();
};
@ -78,8 +69,8 @@ public:
waterBoxSegmentOffset;
std::vector<ZVector> vertices;
std::vector<PolygonEntry> polygons;
std::vector<uint64_t> polygonTypes;
std::vector<ZCollisionPoly> polygons;
std::vector<ZSurfaceType> PolygonTypes;
std::vector<WaterBoxHeader> waterBoxes;
CameraDataList* camData = nullptr;

View File

@ -0,0 +1,78 @@
#include "ZCollisionPoly.h"
#include "Globals.h"
#include "Utils/BitConverter.h"
#include "Utils/StringHelper.h"
REGISTER_ZFILENODE(CollisionPoly, ZCollisionPoly);
ZCollisionPoly::ZCollisionPoly(ZFile* nParent) : ZResource(nParent)
{
}
ZCollisionPoly::~ZCollisionPoly()
{
}
void ZCollisionPoly::ParseRawData()
{
const auto& rawData = parent->GetRawData();
type = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0);
vtxA = BitConverter::ToUInt16BE(rawData, rawDataIndex + 2);
vtxB = BitConverter::ToUInt16BE(rawData, rawDataIndex + 4);
vtxC = BitConverter::ToUInt16BE(rawData, rawDataIndex + 6);
normX = BitConverter::ToUInt16BE(rawData, rawDataIndex + 8);
normY = BitConverter::ToUInt16BE(rawData, rawDataIndex + 10);
normZ = BitConverter::ToUInt16BE(rawData, rawDataIndex + 12);
dist = BitConverter::ToUInt16BE(rawData, rawDataIndex + 14);
}
void ZCollisionPoly::DeclareReferences(const std::string& prefix)
{
std::string declaration;
std::string auxName = name;
if (name == "")
auxName = GetDefaultName(prefix);
parent->AddDeclaration(rawDataIndex, DeclarationAlignment::Align4, GetRawDataSize(),
GetSourceTypeName(), name.c_str(), GetBodySourceCode());
}
std::string ZCollisionPoly::GetBodySourceCode() const
{
std::string declaration;
declaration +=
StringHelper::Sprintf("{0x%04X, 0x%04X, 0x%04X, 0x%04X, 0x%04X, 0x%04X, 0x%04X, 0x%04X}",
type, vtxA, vtxB, vtxC, normX, normY, normZ, dist);
return declaration;
}
std::string ZCollisionPoly::GetDefaultName(const std::string& prefix) const
{
return StringHelper::Sprintf("%sCollisionPoly_%06X", prefix.c_str(), rawDataIndex);
}
ZResourceType ZCollisionPoly::GetResourceType() const
{
return ZResourceType::CollisionPoly;
}
size_t ZCollisionPoly::GetRawDataSize() const
{
return 16;
}
std::string ZCollisionPoly::GetSourceTypeName() const
{
return "CollisionPoly";
}
bool ZCollisionPoly::DoesSupportArray() const
{
return true;
}

View File

@ -0,0 +1,29 @@
#pragma once
#include "ZFile.h"
#include "ZResource.h"
class ZCollisionPoly : public ZResource
{
public:
uint16_t type;
uint16_t vtxA, vtxB, vtxC;
uint16_t normX, normY, normZ;
uint16_t dist;
ZCollisionPoly(ZFile* nParent);
~ZCollisionPoly();
void ParseRawData() override;
void DeclareReferences(const std::string& prefix) override;
std::string GetBodySourceCode() const override;
std::string GetDefaultName(const std::string& prefix) const override;
std::string GetSourceTypeName() const override;
ZResourceType GetResourceType() const override;
bool DoesSupportArray() const override;
size_t GetRawDataSize() const override;
};

File diff suppressed because it is too large Load Diff

View File

@ -3,422 +3,13 @@
#include <cstdint>
#include <string>
#include <vector>
#include "ZFile.h"
#include "ZResource.h"
#include "tinyxml2.h"
enum class CutsceneCommands
{
Cmd00 = 0x0000,
SetCameraPos = 0x0001,
SetCameraFocus = 0x0002,
SpecialAction = 0x0003,
SetLighting = 0x0004,
SetCameraPosLink = 0x0005,
SetCameraFocusLink = 0x0006,
Cmd07 = 0x0007,
Cmd08 = 0x0008,
Cmd09 = 0x0009,
Unknown = 0x001A,
Textbox = 0x0013,
SetActorAction0 = 0x000A,
SetActorAction1 = 0x000F,
SetActorAction2 = 0x000E,
SetActorAction3 = 0x0019,
SetActorAction4 = 0x001D,
SetActorAction5 = 0x001E,
SetActorAction6 = 0x002C,
SetActorAction7 = 0x001F,
SetActorAction8 = 0x0031,
SetActorAction9 = 0x003E,
SetActorAction10 = 0x008F,
SetSceneTransFX = 0x002D,
Nop = 0x000B,
PlayBGM = 0x0056,
StopBGM = 0x0057,
FadeBGM = 0x007C,
SetTime = 0x008C,
Terminator = 0x03E8,
End = 0xFFFF,
Error = 0xFEAF,
};
#include "OtherStructs/Cutscene_Commands.h"
#include "ZFile.h"
#include "ZResource.h"
class CutsceneCameraPoint
{
public:
int8_t continueFlag;
int8_t cameraRoll;
int16_t nextPointFrame;
float viewAngle;
int16_t posX, posY, posZ;
int16_t unused;
CutsceneCameraPoint(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex);
};
class CutsceneCommand
{
public:
uint32_t commandID;
uint32_t commandIndex;
virtual ~CutsceneCommand();
CutsceneCommand(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex);
virtual std::string GetCName();
virtual std::string GenerateSourceCode(uint32_t baseAddress);
virtual size_t GetCommandSize();
};
class CutsceneCommandSetCameraPos : public CutsceneCommand
{
public:
uint16_t base;
uint16_t startFrame;
uint16_t endFrame;
uint16_t unused;
std::vector<CutsceneCameraPoint*> entries;
~CutsceneCommandSetCameraPos();
CutsceneCommandSetCameraPos(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex);
std::string GetCName();
std::string GenerateSourceCode(uint32_t baseAddress);
size_t GetCommandSize();
};
class SpecialActionEntry
{
public:
uint16_t base;
uint16_t startFrame;
uint16_t endFrame;
uint16_t unused0;
uint32_t unused1;
uint32_t unused2;
uint32_t unused3;
uint32_t unused4;
uint32_t unused5;
uint32_t unused6;
uint32_t unused7;
uint32_t unused8;
uint32_t unused9;
uint32_t unused10;
SpecialActionEntry(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex);
};
class CutsceneCommandSpecialAction : public CutsceneCommand
{
public:
std::vector<SpecialActionEntry*> entries;
CutsceneCommandSpecialAction(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex);
~CutsceneCommandSpecialAction();
std::string GetCName();
std::string GenerateSourceCode(uint32_t baseAddress);
size_t GetCommandSize();
};
class MusicFadeEntry
{
public:
uint16_t base;
uint16_t startFrame;
uint16_t endFrame;
uint16_t unknown0;
uint32_t unknown1;
uint32_t unknown2;
uint32_t unknown3;
uint32_t unknown4;
uint32_t unknown5;
uint32_t unknown6;
uint32_t unknown7;
uint32_t unknown8;
uint32_t unknown9;
uint32_t unknown10;
MusicFadeEntry(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex);
};
class CutsceneCommandFadeBGM : public CutsceneCommand
{
public:
std::vector<MusicFadeEntry*> entries;
CutsceneCommandFadeBGM(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex);
~CutsceneCommandFadeBGM();
std::string GetCName();
std::string GenerateSourceCode(uint32_t baseAddress);
size_t GetCommandSize();
};
class MusicChangeEntry
{
public:
uint16_t sequence;
uint16_t startFrame;
uint16_t endFrame;
uint16_t unknown0;
uint32_t unknown1;
uint32_t unknown2;
uint32_t unknown3;
uint32_t unknown4;
uint32_t unknown5;
uint32_t unknown6;
uint32_t unknown7;
MusicChangeEntry(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex);
};
class CutsceneCommandPlayBGM : public CutsceneCommand
{
public:
std::vector<MusicChangeEntry*> entries;
CutsceneCommandPlayBGM(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex);
~CutsceneCommandPlayBGM();
std::string GetCName();
std::string GenerateSourceCode(uint32_t baseAddress);
size_t GetCommandSize();
};
class CutsceneCommandStopBGM : public CutsceneCommand
{
public:
std::vector<MusicChangeEntry*> entries;
CutsceneCommandStopBGM(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex);
~CutsceneCommandStopBGM();
std::string GetCName();
std::string GenerateSourceCode(uint32_t baseAddress);
size_t GetCommandSize();
};
class EnvLightingEntry
{
public:
uint16_t setting;
uint16_t startFrame;
uint16_t endFrame;
uint16_t unused0;
uint32_t unused1;
uint32_t unused2;
uint32_t unused3;
uint32_t unused4;
uint32_t unused5;
uint32_t unused6;
uint32_t unused7;
EnvLightingEntry(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex);
};
class CutsceneCommandEnvLighting : public CutsceneCommand
{
public:
std::vector<EnvLightingEntry*> entries;
CutsceneCommandEnvLighting(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex);
~CutsceneCommandEnvLighting();
std::string GetCName();
std::string GenerateSourceCode(uint32_t baseAddress);
size_t GetCommandSize();
};
class CutsceneCommandSceneTransFX : public CutsceneCommand
{
public:
uint16_t base;
uint16_t startFrame;
uint16_t endFrame;
~CutsceneCommandSceneTransFX();
CutsceneCommandSceneTransFX(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex);
std::string GetCName();
std::string GenerateSourceCode(uint32_t baseAddress);
size_t GetCommandSize();
};
class Unknown9Entry
{
public:
uint16_t base;
uint16_t startFrame;
uint16_t endFrame;
uint16_t unk2;
uint16_t unk3;
uint16_t unk4;
uint8_t unused0;
uint8_t unused1;
Unknown9Entry(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex);
};
class CutsceneCommandUnknown9 : public CutsceneCommand
{
public:
std::vector<Unknown9Entry*> entries;
CutsceneCommandUnknown9(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex);
~CutsceneCommandUnknown9();
std::string GetCName();
std::string GenerateSourceCode(uint32_t baseAddress);
size_t GetCommandSize();
};
class UnkEntry
{
public:
uint32_t unused0;
uint32_t unused1;
uint32_t unused2;
uint32_t unused3;
uint32_t unused4;
uint32_t unused5;
uint32_t unused6;
uint32_t unused7;
uint32_t unused8;
uint32_t unused9;
uint32_t unused10;
uint32_t unused11;
UnkEntry(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex);
};
class CutsceneCommandUnknown : public CutsceneCommand
{
public:
std::vector<UnkEntry*> entries;
CutsceneCommandUnknown(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex);
~CutsceneCommandUnknown();
std::string GetCName();
std::string GenerateSourceCode(uint32_t baseAddress);
size_t GetCommandSize();
};
class DayTimeEntry
{
public:
uint16_t base;
uint16_t startFrame;
uint16_t endFrame;
uint8_t hour;
uint8_t minute;
uint8_t unused;
DayTimeEntry(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex);
};
class CutsceneCommandDayTime : public CutsceneCommand
{
public:
std::vector<DayTimeEntry*> entries;
CutsceneCommandDayTime(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex);
~CutsceneCommandDayTime();
std::string GetCName();
std::string GenerateSourceCode(uint32_t baseAddress);
size_t GetCommandSize();
};
class TextboxEntry
{
public:
uint16_t base;
uint16_t startFrame;
uint16_t endFrame;
uint16_t type;
uint16_t textID1;
uint16_t textID2;
TextboxEntry(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex);
};
class CutsceneCommandTextbox : public CutsceneCommand
{
public:
std::vector<TextboxEntry*> entries;
CutsceneCommandTextbox(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex);
~CutsceneCommandTextbox();
std::string GetCName();
std::string GenerateSourceCode(uint32_t baseAddress);
size_t GetCommandSize();
};
class ActorAction
{
public:
uint16_t action;
uint16_t startFrame;
uint16_t endFrame;
int16_t rotX, rotY, rotZ;
int32_t startPosX, startPosY, startPosZ;
int32_t endPosX, endPosY, endPosZ;
float normalX, normalY, normalZ;
ActorAction(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex);
};
class CutsceneCommandActorAction : public CutsceneCommand
{
public:
std::vector<ActorAction*> entries;
CutsceneCommandActorAction(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex);
~CutsceneCommandActorAction();
std::string GetCName();
std::string GenerateSourceCode(uint32_t baseAddress);
size_t GetCommandSize();
};
class CutsceneCommandTerminator : public CutsceneCommand
{
public:
uint16_t base;
uint16_t startFrame;
uint16_t endFrame;
uint16_t unknown;
CutsceneCommandTerminator(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex);
std::string GetCName();
std::string GenerateSourceCode(uint32_t baseAddress);
size_t GetCommandSize();
};
class CutsceneCommandEnd : public CutsceneCommand
{
public:
uint16_t base;
uint16_t startFrame;
uint16_t endFrame;
CutsceneCommandEnd(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex);
std::string GetCName();
std::string GenerateSourceCode(uint32_t baseAddress);
size_t GetCommandSize();
};
class CutsceneCommandNop : public CutsceneCommand
{
public:
uint16_t base;
uint16_t startFrame;
uint16_t endFrame;
CutsceneCommandNop(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex);
std::string GetCName();
size_t GetCommandSize();
};
class ZCutsceneBase : public ZResource
{
public:
ZCutsceneBase(ZFile* nParent);
Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr) override;
std::string GetSourceTypeName() const override;
};
class ZCutscene : public ZCutsceneBase
class ZCutscene : public ZResource
{
public:
ZCutscene(ZFile* nParent);
@ -426,15 +17,20 @@ public:
void ParseRawData() override;
Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr) override;
std::string GetBodySourceCode() const override;
size_t GetRawDataSize() const override;
std::string GetSourceTypeName() const override;
ZResourceType GetResourceType() const override;
CutsceneCommands GetCommandFromID(int32_t id);
int32_t numCommands;
int32_t endFrame;
std::vector<CutsceneCommand*> commands;
protected:
CutsceneCommand* GetCommandOoT(uint32_t id, offset_t currentPtr) const;
CutsceneCommand* GetCommandMM(uint32_t id, offset_t currentPtr) const;
};

View File

@ -1,61 +0,0 @@
#include "ZCutsceneMM.h"
#include "Utils/BitConverter.h"
#include "Utils/StringHelper.h"
ZCutsceneMM::ZCutsceneMM(ZFile* nParent) : ZCutsceneBase(nParent)
{
}
ZCutsceneMM::~ZCutsceneMM()
{
for (CutsceneCommand* cmd : commands)
delete cmd;
}
std::string ZCutsceneMM::GetBodySourceCode() const
{
std::string output;
output += StringHelper::Sprintf(" CS_BEGIN_CUTSCENE(%i, %i),", numCommands, endFrame);
for (size_t i = 0; i < data.size(); i++)
{
if ((i % 4) == 0)
output += "\n ";
output += StringHelper::Sprintf("0x%08X, ", data[i]);
}
return output;
}
size_t ZCutsceneMM::GetRawDataSize() const
{
return 8 + data.size() * 4;
}
void ZCutsceneMM::ParseRawData()
{
const auto& rawData = parent->GetRawData();
numCommands = BitConverter::ToInt32BE(rawData, rawDataIndex + 0);
commands = std::vector<CutsceneCommand*>();
endFrame = BitConverter::ToInt32BE(rawData, rawDataIndex + 4);
uint32_t currentPtr = rawDataIndex + 8;
uint32_t lastData = 0;
// TODO currently cutscenes aren't being parsed, so just consume words until we see an end
// marker.
do
{
lastData = BitConverter::ToInt32BE(rawData, currentPtr);
data.push_back(lastData);
currentPtr += 4;
} while (lastData != 0xFFFFFFFF);
}
ZResourceType ZCutsceneMM::GetResourceType() const
{
return ZResourceType::Cutscene;
}

View File

@ -1,29 +0,0 @@
#pragma once
#include <cstdint>
#include <string>
#include <vector>
#include "ZCutscene.h"
#include "ZFile.h"
#include "tinyxml2.h"
class ZCutsceneMM : public ZCutsceneBase
{
public:
ZCutsceneMM(ZFile* nParent);
virtual ~ZCutsceneMM();
std::string GetBodySourceCode() const override;
size_t GetRawDataSize() const override;
void ParseRawData() override;
ZResourceType GetResourceType() const override;
protected:
int32_t numCommands;
int32_t endFrame;
std::vector<CutsceneCommand*> commands;
std::vector<uint32_t> data;
};

View File

@ -213,6 +213,7 @@ void ZDisplayList::ParseRawData()
instructions.reserve(numInstructions);
uint32_t ptr = rawDataIndex;
instructions.reserve(numInstructions);
for (size_t i = 0; i < numInstructions; i++)
{
instructions.push_back(BitConverter::ToUInt64BE(rawData, ptr));
@ -1981,7 +1982,7 @@ void ZDisplayList::DeclareReferences(const std::string& prefix)
// Generate Vertex Declarations
std::vector<int32_t> vtxKeys;
vtxKeys.reserve(vertices.size());
for (auto& item : vertices)
vtxKeys.push_back(item.first);

View File

@ -224,7 +224,12 @@ void ZFile::ParseXML(tinyxml2::XMLElement* reader, const std::string& filename)
// Check for repeated attributes.
if (offsetXml != nullptr)
{
rawDataIndex = strtol(StringHelper::Split(std::string(offsetXml), "0x")[1].c_str(), NULL, 16);
if (!StringHelper::IsValidOffset(std::string_view(offsetXml)))
{
HANDLE_ERROR(WarningType::InvalidXML,
StringHelper::Sprintf("Invalid offset %s entered", offsetXml), "");
}
rawDataIndex = strtol(offsetXml, NULL, 16);
if (offsetSet.find(offsetXml) != offsetSet.end())
{
@ -433,7 +438,7 @@ void ZFile::AddResource(ZResource* res)
resources.push_back(res);
}
ZResource* ZFile::FindResource(uint32_t rawDataIndex)
ZResource* ZFile::FindResource(offset_t rawDataIndex)
{
for (ZResource* res : resources)
{
@ -447,6 +452,7 @@ ZResource* ZFile::FindResource(uint32_t rawDataIndex)
std::vector<ZResource*> ZFile::GetResourcesOfType(ZResourceType resType)
{
std::vector<ZResource*> resList;
resList.reserve(resources.size());
for (ZResource* res : resources)
{
@ -722,7 +728,7 @@ bool ZFile::GetDeclarationArrayIndexedName(segptr_t segAddress, size_t elementSi
return true;
}
Declaration* ZFile::GetDeclaration(uint32_t address) const
Declaration* ZFile::GetDeclaration(offset_t address) const
{
if (declarations.find(address) != declarations.end())
return declarations.at(address);
@ -730,7 +736,7 @@ Declaration* ZFile::GetDeclaration(uint32_t address) const
return nullptr;
}
Declaration* ZFile::GetDeclarationRanged(uint32_t address) const
Declaration* ZFile::GetDeclarationRanged(offset_t address) const
{
for (const auto decl : declarations)
{
@ -741,7 +747,7 @@ Declaration* ZFile::GetDeclarationRanged(uint32_t address) const
return nullptr;
}
bool ZFile::HasDeclaration(uint32_t address)
bool ZFile::HasDeclaration(offset_t address)
{
assert(GETSEGNUM(address) == 0);
return declarations.find(address) != declarations.end();
@ -805,9 +811,14 @@ void ZFile::GenerateSourceFiles()
void ZFile::GenerateSourceHeaderFiles()
{
OutputFormatter formatter;
std::string guard = outName.stem().string();
std::transform(guard.begin(), guard.end(), guard.begin(), ::toupper);
formatter.Write("#pragma once\n\n");
formatter.Write(
StringHelper::Sprintf("#ifndef %s_H\n#define %s_H 1\n\n", guard.c_str(), guard.c_str()));
formatter.Write("#include \"align_asset_macro.h\"\n");
std::set<std::string> nameSet;
for (ZResource* res : resources)
{
@ -827,6 +838,8 @@ void ZFile::GenerateSourceHeaderFiles()
formatter.Write(ProcessExterns());
formatter.Write("#endif\n");
fs::path headerFilename = GetSourceOutputFolderPath() / outName.stem().concat(".h");
if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_INFO)
@ -1244,6 +1257,10 @@ void ZFile::HandleUnaccountedData()
uint32_t lastSize = 0;
std::vector<offset_t> declsAddresses;
if (Globals::Instance->otrMode)
return;
declsAddresses.reserve(declarations.size());
if (Globals::Instance->otrMode)
return;

View File

@ -32,8 +32,8 @@ class ZFile
{
public:
std::map<offset_t, Declaration*> declarations;
std::string defines;
std::vector<ZResource*> resources;
std::string defines;
int workerID;
bool isCompilable = false;
@ -56,7 +56,7 @@ public:
void ExtractResources();
void BuildSourceFile();
void AddResource(ZResource* res);
ZResource* FindResource(uint32_t rawDataIndex);
ZResource* FindResource(offset_t rawDataIndex);
std::vector<ZResource*> GetResourcesOfType(ZResourceType resType);
Declaration* AddDeclaration(offset_t address, DeclarationAlignment alignment, size_t size,
@ -85,9 +85,9 @@ public:
const std::string& expectedType,
std::string& declName) const;
Declaration* GetDeclaration(uint32_t address) const;
Declaration* GetDeclarationRanged(uint32_t address) const;
bool HasDeclaration(uint32_t address);
Declaration* GetDeclaration(offset_t address) const;
Declaration* GetDeclarationRanged(offset_t address) const;
bool HasDeclaration(offset_t address);
std::string GetHeaderInclude() const;
std::string GetZRoomHeaderInclude() const;

View File

@ -4,12 +4,15 @@
#include "Globals.h"
#include "Utils/BitConverter.h"
#include "Utils/StringHelper.h"
#include "WarningHandler.h"
#include "ZSkeleton.h"
REGISTER_ZFILENODE(Limb, ZLimb);
ZLimb::ZLimb(ZFile* nParent) : ZResource(nParent), segmentStruct(nParent)
{
RegisterOptionalAttribute("EnumName");
RegisterOptionalAttribute("LimbType");
RegisterOptionalAttribute("Type");
}
@ -30,6 +33,12 @@ void ZLimb::ParseXML(tinyxml2::XMLElement* reader)
{
ZResource::ParseXML(reader);
auto& enumNameXml = registeredAttributes.at("EnumName").value;
if (enumNameXml != "")
{
enumName = enumNameXml;
}
// Reading from a <Skeleton/>
std::string limbType = registeredAttributes.at("LimbType").value;
if (limbType == "") // Reading from a <Limb/>
@ -247,11 +256,24 @@ std::string ZLimb::GetBodySourceCode() const
}
else
{
std::string childStr;
std::string siblingStr;
if (limbsTable != nullptr)
{
childStr = limbsTable->GetLimbEnumName(childIndex);
siblingStr = limbsTable->GetLimbEnumName(siblingIndex);
}
else
{
childStr = StringHelper::Sprintf("0x%02X", childIndex);
siblingStr = StringHelper::Sprintf("0x%02X", siblingIndex);
}
if (type != ZLimbType::Curve)
{
entryStr += StringHelper::Sprintf("{ %i, %i, %i }, ", transX, transY, transZ);
}
entryStr += StringHelper::Sprintf("0x%02X, 0x%02X,\n", childIndex, siblingIndex);
entryStr += StringHelper::Sprintf("%s, %s,\n", childStr.c_str(), siblingStr.c_str());
switch (type)
{
@ -360,6 +382,11 @@ ZLimbType ZLimb::GetTypeByAttributeName(const std::string& attrName)
return ZLimbType::Invalid;
}
void ZLimb::SetLimbIndex(uint8_t nLimbIndex)
{
limbIndex = nLimbIndex;
}
void ZLimb::DeclareDList(segptr_t dListSegmentedPtr, const std::string& prefix,
const std::string& limbSuffix)
{

View File

@ -18,9 +18,14 @@ enum class ZLimbType
Legacy,
};
class ZLimbTable;
class ZLimb : public ZResource
{
public:
std::string enumName;
ZLimbTable* limbsTable = nullptr; // borrowed pointer, do not delete!
ZLimbType type = ZLimbType::Standard;
ZLimbSkinType skinSegmentType = ZLimbSkinType::SkinType_0; // Skin only
@ -39,6 +44,8 @@ public:
int16_t transX = 0, transY = 0, transZ = 0;
uint8_t childIndex = 0, siblingIndex = 0;
uint8_t limbIndex = 0;
ZLimb(ZFile* nParent);
void ExtractFromBinary(uint32_t nRawDataIndex, ZLimbType nType);
@ -59,6 +66,8 @@ public:
static const char* GetSourceTypeName(ZLimbType limbType);
static ZLimbType GetTypeByAttributeName(const std::string& attrName);
void SetLimbIndex(uint8_t nLimbIndex);
protected:
void DeclareDList(segptr_t dListSegmentedPtr, const std::string& prefix,
const std::string& limbSuffix);

View File

@ -35,6 +35,7 @@ void ZPath::ParseRawData()
uint32_t currentPtr = rawDataIndex;
pathways.reserve(numPaths);
for (size_t pathIndex = 0; pathIndex < numPaths; pathIndex++)
{
PathwayEntry path(parent);
@ -125,6 +126,7 @@ void PathwayEntry::ParseRawData()
uint32_t currentPtr = GETSEGOFFSET(listSegmentAddress);
points.reserve(numPoints);
for (int32_t i = 0; i < numPoints; i++)
{
ZVector vec(parent);

57
ZAPDTR/ZAPD/ZPointer.cpp Normal file
View File

@ -0,0 +1,57 @@
#include "ZPointer.h"
#include "Globals.h"
#include "Utils/BitConverter.h"
#include "Utils/StringHelper.h"
#include "WarningHandler.h"
#include "ZFile.h"
REGISTER_ZFILENODE(Pointer, ZPointer);
ZPointer::ZPointer(ZFile* nParent) : ZResource(nParent)
{
RegisterRequiredAttribute("Type");
}
void ZPointer::ParseXML(tinyxml2::XMLElement* reader)
{
ZResource::ParseXML(reader);
type = registeredAttributes.at("Type").value;
}
void ZPointer::ParseRawData()
{
auto& rawData = parent->GetRawData();
ptr = BitConverter::ToUInt32BE(rawData, rawDataIndex);
}
std::string ZPointer::GetBodySourceCode() const
{
std::string ptrName;
Globals::Instance->GetSegmentedPtrName(ptr, parent, "", ptrName);
return ptrName;
}
bool ZPointer::DoesSupportArray() const
{
return true;
}
std::string ZPointer::GetSourceTypeName() const
{
return type + "*";
}
ZResourceType ZPointer::GetResourceType() const
{
return ZResourceType::Pointer;
}
size_t ZPointer::GetRawDataSize() const
{
return 0x04;
}

22
ZAPDTR/ZAPD/ZPointer.h Normal file
View File

@ -0,0 +1,22 @@
#pragma once
#include "ZResource.h"
class ZPointer : public ZResource
{
public:
segptr_t ptr = SEGMENTED_NULL;
std::string type;
ZPointer(ZFile* nParent);
void ParseXML(tinyxml2::XMLElement* reader) override;
void ParseRawData() override;
std::string GetBodySourceCode() const override;
bool DoesSupportArray() const override;
std::string GetSourceTypeName() const override;
ZResourceType GetResourceType() const override;
size_t GetRawDataSize() const override;
};

View File

@ -261,6 +261,11 @@ offset_t ZResource::GetRawDataIndex() const
return rawDataIndex;
}
void ZResource::SetRawDataIndex(offset_t nRawDataIndex)
{
rawDataIndex = nRawDataIndex;
}
std::string ZResource::GetBodySourceCode() const
{
return "ERROR";

View File

@ -52,7 +52,11 @@ enum class ZResourceType
Vector,
Vertex,
Text,
Audio
Audio,
ActorList,
CollisionPoly,
Pointer,
SurfaceType,
};
class ResourceAttribute
@ -153,6 +157,8 @@ public:
[[nodiscard]] const std::string& GetOutName() const;
void SetOutName(const std::string& nName);
[[nodiscard]] offset_t GetRawDataIndex() const;
void SetRawDataIndex(offset_t nRawDataIndex);
/**
* The size of the current struct being extracted, not counting data referenced by it
*/

View File

@ -14,8 +14,9 @@ void SetActorCutsceneList::ParseRawData()
{
ZRoomCommand::ParseRawData();
int numCutscenes = cmdArg1;
int32_t currentPtr = segmentOffset;
offset_t currentPtr = segmentOffset;
cutscenes.reserve(numCutscenes);
for (int32_t i = 0; i < numCutscenes; i++)
{
ActorCutsceneEntry entry(parent->GetRawData(), currentPtr);

View File

@ -1,10 +1,10 @@
#include "SetActorList.h"
#include <cassert>
#include "Globals.h"
#include "Utils/BitConverter.h"
#include "Utils/StringHelper.h"
#include "ZFile.h"
#include "ZRoom/ZNames.h"
#include "ZRoom/ZRoom.h"
SetActorList::SetActorList(ZFile* nParent) : ZRoomCommand(nParent)
@ -15,67 +15,28 @@ void SetActorList::ParseRawData()
{
ZRoomCommand::ParseRawData();
numActors = cmdArg1;
actorList = new ZActorList(parent);
actorList->ExtractFromBinary(segmentOffset, numActors);
}
void SetActorList::DeclareReferences(const std::string& prefix)
{
if (numActors != 0 && cmdArg2 != 0)
if (parent->HasDeclaration(segmentOffset))
{
std::string varName =
StringHelper::Sprintf("%sActorList_%06X", prefix.c_str(), segmentOffset);
parent->AddDeclarationPlaceholder(segmentOffset, varName);
}
}
void SetActorList::ParseRawDataLate()
{
ZRoomCommand::ParseRawDataLate();
size_t actorsAmount = zRoom->GetDeclarationSizeFromNeighbor(segmentOffset) / 0x10;
uint32_t currentPtr = segmentOffset;
for (size_t i = 0; i < actorsAmount; i++)
{
ActorSpawnEntry entry(parent->GetRawData(), currentPtr);
currentPtr += entry.GetRawDataSize();
actors.push_back(entry);
}
}
void SetActorList::DeclareReferencesLate(const std::string& prefix)
{
if (actors.empty())
delete actorList;
actorList = static_cast<ZActorList*>(parent->FindResource(segmentOffset));
assert(actorList != nullptr);
assert(actorList->GetResourceType() == ZResourceType::ActorList);
return;
std::string declaration;
size_t largestlength = 0;
for (const auto& entry : actors)
{
size_t actorNameLength = ZNames::GetActorName(entry.GetActorId()).size();
if (actorNameLength > largestlength)
largestlength = actorNameLength;
}
size_t index = 0;
for (auto& entry : actors)
if (actorList->GetName() == "")
{
entry.SetLargestActorName(largestlength);
declaration += StringHelper::Sprintf("\t{ %s },", entry.GetBodySourceCode().c_str());
if (index < actors.size() - 1)
declaration += "\n";
index++;
actorList->SetName(actorList->GetDefaultName(prefix));
}
const auto& entry = actors.front();
std::string varName = StringHelper::Sprintf("%sActorList_%06X", prefix.c_str(), segmentOffset);
parent->AddDeclarationArray(segmentOffset, DeclarationAlignment::Align4,
actors.size() * entry.GetRawDataSize(), entry.GetSourceTypeName(),
varName, GetActorListArraySize(), declaration);
actorList->DeclareVar(prefix, "");
parent->AddResource(actorList);
}
std::string SetActorList::GetBodySourceCode() const
@ -83,37 +44,10 @@ std::string SetActorList::GetBodySourceCode() const
std::string listName;
Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "ActorEntry", listName,
parent->workerID);
if (numActors != actors.size())
{
printf("%s: numActors(%i) ~ actors(%li)\n", parent->GetName().c_str(), numActors,
actors.size());
}
return StringHelper::Sprintf("SCENE_CMD_ACTOR_LIST(%i, %s)", numActors, listName.c_str());
}
size_t SetActorList::GetActorListArraySize() const
{
size_t actorCount = 0;
// Doing an else-if here so we only do the loop when the game is SW97.
// Actor 0x22 is removed from SW97, so we need to ensure that we don't increment the actor count
// for it.
if (Globals::Instance->game == ZGame::OOT_SW97)
{
actorCount = 0;
for (const auto& entry : actors)
if (entry.GetActorId() != 0x22)
actorCount++;
}
else
{
actorCount = actors.size();
}
return actorCount;
}
std::string SetActorList::GetCommandCName() const
{
return "SCmdActorList";
@ -123,58 +57,3 @@ RoomCommand SetActorList::GetRoomCommand() const
{
return RoomCommand::SetActorList;
}
ActorSpawnEntry::ActorSpawnEntry(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex)
{
actorNum = BitConverter::ToInt16BE(rawData, rawDataIndex + 0);
posX = BitConverter::ToInt16BE(rawData, rawDataIndex + 2);
posY = BitConverter::ToInt16BE(rawData, rawDataIndex + 4);
posZ = BitConverter::ToInt16BE(rawData, rawDataIndex + 6);
rotX = BitConverter::ToUInt16BE(rawData, rawDataIndex + 8);
rotY = BitConverter::ToUInt16BE(rawData, rawDataIndex + 10);
rotZ = BitConverter::ToUInt16BE(rawData, rawDataIndex + 12);
initVar = BitConverter::ToInt16BE(rawData, rawDataIndex + 14);
}
std::string ActorSpawnEntry::GetBodySourceCode() const
{
std::string body;
std::string actorNameFmt = StringHelper::Sprintf("%%-%zus ", largestActorName + 1);
body =
StringHelper::Sprintf(actorNameFmt.c_str(), (ZNames::GetActorName(actorNum) + ",").c_str());
body += StringHelper::Sprintf("{ %6i, %6i, %6i }, ", posX, posY, posZ);
if (Globals::Instance->game == ZGame::MM_RETAIL)
body += StringHelper::Sprintf("{ SPAWN_ROT_FLAGS(%#5hX, 0x%04X)"
", SPAWN_ROT_FLAGS(%#5hX, 0x%04X)"
", SPAWN_ROT_FLAGS(%#5hX, 0x%04X) }, ",
(rotX >> 7) & 0b111111111, rotX & 0b1111111,
(rotY >> 7) & 0b111111111, rotY & 0b1111111,
(rotZ >> 7) & 0b111111111, rotZ & 0b1111111);
else
body += StringHelper::Sprintf("{ %#6hX, %#6hX, %#6hX }, ", rotX, rotY, rotZ);
body += StringHelper::Sprintf("0x%04X", initVar);
return body;
}
std::string ActorSpawnEntry::GetSourceTypeName() const
{
return "ActorEntry";
}
int32_t ActorSpawnEntry::GetRawDataSize() const
{
return 16;
}
uint16_t ActorSpawnEntry::GetActorId() const
{
return actorNum;
}
void ActorSpawnEntry::SetLargestActorName(size_t nameSize)
{
largestActorName = nameSize;
}

View File

@ -1,45 +1,19 @@
#pragma once
#include "ZActorList.h"
#include "ZRoom/ZRoomCommand.h"
class ActorSpawnEntry
{
public:
uint16_t actorNum;
int16_t posX;
int16_t posY;
int16_t posZ;
uint16_t rotX;
uint16_t rotY;
uint16_t rotZ;
uint16_t initVar;
size_t largestActorName = 16;
ActorSpawnEntry(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex);
std::string GetBodySourceCode() const;
std::string GetSourceTypeName() const;
int32_t GetRawDataSize() const;
uint16_t GetActorId() const;
void SetLargestActorName(size_t nameSize);
};
class SetActorList : public ZRoomCommand
{
public:
uint8_t numActors;
std::vector<ActorSpawnEntry> actors;
uint32_t numActors;
ZActorList* actorList = nullptr;
SetActorList(ZFile* nParent);
void ParseRawData() override;
void DeclareReferences(const std::string& prefix) override;
void ParseRawDataLate() override;
void DeclareReferencesLate(const std::string& prefix) override;
std::string GetBodySourceCode() const override;
RoomCommand GetRoomCommand() const override;

View File

@ -21,9 +21,10 @@ void SetAlternateHeaders::DeclareReferences([[maybe_unused]] const std::string&
void SetAlternateHeaders::ParseRawDataLate()
{
int numHeaders = zRoom->GetDeclarationSizeFromNeighbor(segmentOffset) / 4;
size_t numHeaders = zRoom->GetDeclarationSizeFromNeighbor(segmentOffset) / 4;
for (int32_t i = 0; i < numHeaders; i++)
headers.reserve(numHeaders);
for (uint32_t i = 0; i < numHeaders; i++)
{
int32_t address = BitConverter::ToInt32BE(parent->GetRawData(), segmentOffset + (i * 4));
headers.push_back(address);

View File

@ -18,6 +18,7 @@ void SetCsCamera::ParseRawData()
uint32_t currentPtr = segmentOffset;
int32_t numPoints = 0;
cameras.reserve(numCameras);
for (int32_t i = 0; i < numCameras; i++)
{
CsCameraEntry entry(parent->GetRawData(), currentPtr);
@ -31,6 +32,7 @@ void SetCsCamera::ParseRawData()
{
uint32_t currentPtr = cameras.at(0).GetSegmentOffset();
points.reserve(numPoints);
for (int32_t i = 0; i < numPoints; i++)
{
ZVector vec(parent);

View File

@ -10,19 +10,25 @@ SetCutscenes::SetCutscenes(ZFile* nParent) : ZRoomCommand(nParent)
{
}
SetCutscenes::~SetCutscenes()
{
for (ZCutsceneBase* cutscene : cutscenes)
delete cutscene;
}
void SetCutscenes::ParseRawData()
{
ZRoomCommand::ParseRawData();
std::string output;
numCutscenes = cmdArg1;
if (Globals::Instance->game == ZGame::OOT_RETAIL || Globals::Instance->game == ZGame::OOT_SW97)
if (Globals::Instance->game == ZGame::MM_RETAIL)
{
int32_t currentPtr = segmentOffset;
cutsceneEntries.reserve(numCutscenes);
for (uint8_t i = 0; i < numCutscenes; i++)
{
CutsceneEntry entry(parent->GetRawData(), currentPtr);
cutsceneEntries.push_back(entry);
currentPtr += 8;
}
}
else if (Globals::Instance->game == ZGame::OOT_RETAIL || Globals::Instance->game == ZGame::OOT_SW97)
{
ZCutscene* cutscene = new ZCutscene(parent);
cutscene->ExtractFromFile(segmentOffset);
@ -35,28 +41,48 @@ void SetCutscenes::ParseRawData()
cutscenes.push_back(cutscene);
}
else
}
void SetCutscenes::DeclareReferences(const std::string& prefix)
{
std::string varPrefix = name;
if (varPrefix == "")
varPrefix = prefix;
if (Globals::Instance->game == ZGame::MM_RETAIL)
{
int32_t currentPtr = segmentOffset;
std::string declaration;
size_t i = 0;
for (uint8_t i = 0; i < numCutscenes; i++)
for (const auto& entry : cutsceneEntries)
{
CutsceneEntry entry(parent->GetRawData(), currentPtr);
cutsceneEntries.push_back(entry);
currentPtr += 8;
if (entry.segmentPtr != SEGMENTED_NULL &&
GETSEGNUM(entry.segmentPtr) == parent->segment)
{
offset_t csOffset = Seg2Filespace(entry.segmentPtr, parent->baseAddress);
if (!parent->HasDeclaration(csOffset))
{
auto* cutscene = new ZCutscene(parent);
cutscene->ExtractFromFile(csOffset);
cutscene->SetName(cutscene->GetDefaultName(varPrefix));
cutscene->DeclareVar(varPrefix, "");
cutscene->DeclareReferences(varPrefix);
parent->AddResource(cutscene);
}
}
// TODO: don't hardcode %sCutsceneData_%06X, look up for the declared name instead
declaration += StringHelper::Sprintf(
" { %sCutsceneData_%06X, 0x%04X, 0x%02X, 0x%02X },", zRoom->GetName().c_str(),
entry.segmentOffset, entry.exit, entry.entrance, entry.flag);
std::string csName;
Globals::Instance->GetSegmentedPtrName(entry.segmentPtr, parent, "CutsceneData",
csName, parent->workerID);
if (i < numCutscenes - 1)
declaration +=
StringHelper::Sprintf(" { %s, 0x%04X, 0x%02X, 0x%02X },", csName.c_str(),
entry.exit, entry.entrance, entry.flag);
if (i + 1 < numCutscenes)
declaration += "\n";
ZCutsceneMM* cutscene = new ZCutsceneMM(parent);
cutscene->ExtractFromFile(entry.segmentOffset);
cutscenes.push_back(cutscene);
i++;
}
parent->AddDeclarationArray(segmentOffset, DeclarationAlignment::Align4,
@ -65,19 +91,19 @@ void SetCutscenes::ParseRawData()
zRoom->GetName().c_str(), segmentOffset),
cutsceneEntries.size(), declaration);
}
for (ZCutsceneBase* cutscene : cutscenes)
else
{
if (cutscene->GetRawDataIndex() != 0)
if (cmdArg2 != SEGMENTED_NULL && GETSEGNUM(cmdArg2) == parent->segment)
{
Declaration* decl = parent->GetDeclaration(cutscene->GetRawDataIndex());
if (decl == nullptr)
offset_t csOffset = Seg2Filespace(cmdArg2, parent->baseAddress);
if (!parent->HasDeclaration(csOffset))
{
cutscene->GetSourceOutputCode(zRoom->GetName());
}
else if (decl->text == "")
{
decl->text = cutscene->GetBodySourceCode();
auto* cutscene = new ZCutscene(parent);
cutscene->ExtractFromFile(csOffset);
cutscene->SetName(cutscene->GetDefaultName(varPrefix));
cutscene->DeclareVar(varPrefix, "");
cutscene->DeclareReferences(varPrefix);
parent->AddResource(cutscene);
}
}
}
@ -90,8 +116,15 @@ std::string SetCutscenes::GetBodySourceCode() const
parent->workerID);
if (Globals::Instance->game == ZGame::MM_RETAIL)
{
Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "CutsceneEntry", listName,
parent->workerID);
return StringHelper::Sprintf("SCENE_CMD_CUTSCENE_LIST(%i, %s)", numCutscenes,
listName.c_str());
}
Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "CutsceneData", listName,
parent->workerID);
return StringHelper::Sprintf("SCENE_CMD_CUTSCENE_DATA(%s)", listName.c_str());
}
@ -106,7 +139,7 @@ RoomCommand SetCutscenes::GetRoomCommand() const
}
CutsceneEntry::CutsceneEntry(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex)
: segmentOffset(GETSEGOFFSET(BitConverter::ToInt32BE(rawData, rawDataIndex + 0))),
: segmentPtr(BitConverter::ToInt32BE(rawData, rawDataIndex + 0)),
exit(BitConverter::ToInt16BE(rawData, rawDataIndex + 4)), entrance(rawData[rawDataIndex + 6]),
flag(rawData[rawDataIndex + 7])
{

View File

@ -1,7 +1,6 @@
#pragma once
#include "ZCutscene.h"
#include "ZCutsceneMM.h"
#include "ZRoom/ZRoomCommand.h"
class CutsceneEntry
@ -9,7 +8,7 @@ class CutsceneEntry
public:
CutsceneEntry(const std::vector<uint8_t>& rawData, uint32_t rawDataIndex);
uint32_t segmentOffset;
segptr_t segmentPtr;
uint16_t exit;
uint8_t entrance;
uint8_t flag;
@ -18,14 +17,14 @@ public:
class SetCutscenes : public ZRoomCommand
{
public:
std::vector<ZCutsceneBase*> cutscenes;
std::vector<ZCutscene*> cutscenes;
std::vector<CutsceneEntry> cutsceneEntries; // (MM Only)
uint8_t numCutscenes; // (MM Only)
SetCutscenes(ZFile* nParent);
~SetCutscenes();
void ParseRawData() override;
void DeclareReferences(const std::string& prefix) override;
std::string GetBodySourceCode() const override;

View File

@ -24,10 +24,11 @@ void SetEntranceList::DeclareReferences([[maybe_unused]] const std::string& pref
void SetEntranceList::ParseRawDataLate()
{
// Parse Entrances and Generate Declaration
int numEntrances = zRoom->GetDeclarationSizeFromNeighbor(segmentOffset) / 2;
uint32_t numEntrances = zRoom->GetDeclarationSizeFromNeighbor(segmentOffset) / 2;
uint32_t currentPtr = segmentOffset;
for (int32_t i = 0; i < numEntrances; i++)
entrances.reserve(numEntrances);
for (uint32_t i = 0; i < numEntrances; i++)
{
EntranceEntry entry(parent->GetRawData(), currentPtr);
entrances.push_back(entry);

View File

@ -4,6 +4,7 @@
#include "Utils/BitConverter.h"
#include "Utils/StringHelper.h"
#include "ZFile.h"
#include "ZRoom/ZNames.h"
#include "ZRoom/ZRoom.h"
SetExitList::SetExitList(ZFile* nParent) : ZRoomCommand(nParent)
@ -23,10 +24,11 @@ void SetExitList::DeclareReferences([[maybe_unused]] const std::string& prefix)
void SetExitList::ParseRawDataLate()
{
// Parse Entrances and Generate Declaration
int numEntrances = zRoom->GetDeclarationSizeFromNeighbor(segmentOffset) / 2;
uint32_t numEntrances = zRoom->GetDeclarationSizeFromNeighbor(segmentOffset) / 2;
uint32_t currentPtr = segmentOffset;
for (int32_t i = 0; i < numEntrances; i++)
exits.reserve(numEntrances);
for (uint32_t i = 0; i < numEntrances; i++)
{
uint16_t exit = BitConverter::ToUInt16BE(parent->GetRawData(), currentPtr);
exits.push_back(exit);
@ -43,7 +45,8 @@ void SetExitList::DeclareReferencesLate([[maybe_unused]] const std::string& pref
for (size_t i = 0; i < exits.size(); i++)
{
declaration += StringHelper::Sprintf(" 0x%04X,", exits.at(i));
declaration +=
StringHelper::Sprintf(" %s,", ZNames::GetEntranceName(exits[i]).c_str());
if (i + 1 < exits.size())
declaration += "\n";
}

View File

@ -15,6 +15,8 @@ void SetLightList::ParseRawData()
numLights = cmdArg1;
int32_t currentPtr = segmentOffset;
lights.reserve(this->numLights);
for (int i = 0; i < this->numLights; i++)
{
LightInfo light(parent->GetRawData(), currentPtr);

View File

@ -15,6 +15,7 @@ void SetLightingSettings::ParseRawData()
ZRoomCommand::ParseRawData();
uint8_t numLights = cmdArg1;
settings.reserve(numLights);
for (int i = 0; i < numLights; i++)
settings.push_back(LightingSettings(parent->GetRawData(), segmentOffset + (i * 22)));
}

View File

@ -442,6 +442,8 @@ void PolygonType1::DeclareReferences(const std::string& prefix)
{
listAddress = Seg2Filespace(list, parent->baseAddress);
uint32_t auxPtr = listAddress;
multiList.reserve(count);
for (size_t i = 0; i < count; ++i)
{
BgImage bg(false, prefix, auxPtr, parent);
@ -545,6 +547,8 @@ void PolygonType2::ParseRawData()
end = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x08);
uint32_t currentPtr = GETSEGOFFSET(start);
polyDLists.reserve(num);
for (size_t i = 0; i < num; i++)
{
PolygonDlist entry(parent);

View File

@ -15,8 +15,9 @@ void SetMinimapChests::ParseRawData()
ZRoomCommand::ParseRawData();
int numChests = cmdArg1;
int32_t currentPtr = segmentOffset;
offset_t currentPtr = segmentOffset;
chests.reserve(numChests);
for (int32_t i = 0; i < numChests; i++)
{
MinimapChest chest(parent->GetRawData(), currentPtr);

View File

@ -17,8 +17,9 @@ void SetMinimapList::ParseRawData()
listSegmentOffset = GETSEGOFFSET(listSegmentAddr);
unk4 = BitConverter::ToInt32BE(parent->GetRawData(), segmentOffset + 4);
int32_t currentPtr = listSegmentOffset;
uint32_t currentPtr = listSegmentOffset;
minimaps.reserve(zRoom->roomCount);
for (int32_t i = 0; i < zRoom->roomCount; i++)
{
MinimapEntry entry(parent->GetRawData(), currentPtr);

View File

@ -17,6 +17,7 @@ void SetObjectList::ParseRawData()
uint8_t objectCnt = parent->GetRawData().at(rawDataIndex + 1);
uint32_t currentPtr = segmentOffset;
objects.reserve(objectCnt);
for (uint8_t i = 0; i < objectCnt; i++)
{
uint16_t objectIndex = BitConverter::ToInt16BE(parent->GetRawData(), currentPtr);

View File

@ -69,6 +69,7 @@ void RomFile::ParseRawData()
uint32_t currentPtr = rawDataIndex;
rooms.reserve(numRooms);
for (int32_t i = 0; i < numRooms; i++)
{
RoomEntry entry(parent->GetRawData(), currentPtr);
@ -104,9 +105,9 @@ std::string RomFile::GetBodySourceCode() const
if (!isFirst)
declaration += "\n";
declaration +=
StringHelper::Sprintf("\t{ (u32)_%sSegmentRomStart, (u32)_%sSegmentRomEnd },",
roomName.c_str(), roomName.c_str());
declaration += StringHelper::Sprintf(
"\t{ (uintptr_t)_%sSegmentRomStart, (uintptr_t)_%sSegmentRomEnd },",
roomName.c_str(), roomName.c_str());
isFirst = false;
}
}

View File

@ -16,9 +16,10 @@ void SetStartPositionList::ParseRawData()
ZRoomCommand::ParseRawData();
uint8_t numActors = cmdArg1;
uint32_t currentPtr = segmentOffset;
offset_t currentPtr = segmentOffset;
for (int32_t i = 0; i < numActors; i++)
actors.reserve(numActors);
for (uint32_t i = 0; i < numActors; i++)
{
actors.push_back(ActorSpawnEntry(parent->GetRawData(), currentPtr));
currentPtr += 16;

View File

@ -17,6 +17,7 @@ void SetTransitionActorList::ParseRawData()
int numActors = cmdArg1;
uint32_t currentPtr = segmentOffset;
transitionActors.reserve(numActors);
for (int32_t i = 0; i < numActors; i++)
{
TransitionActorEntry entry(parent->GetRawData(), currentPtr);

View File

@ -12,17 +12,17 @@ public:
{
if (id >= Globals::Instance->cfg.objectList.size())
return StringHelper::Sprintf("0x%04X", id);
return Globals::Instance->cfg.objectList.at(id);
return Globals::Instance->cfg.objectList[id];
}
static std::string GetActorName(int32_t id)
static std::string GetActorName(uint16_t id)
{
switch (Globals::Instance->game)
{
case ZGame::OOT_RETAIL:
case ZGame::OOT_SW97:
if (id < ZNames::GetNumActors())
return Globals::Instance->cfg.actorList.at(id);
return Globals::Instance->cfg.actorList[id];
else
return StringHelper::Sprintf("0x%04X", id);
case ZGame::MM_RETAIL:
@ -31,7 +31,7 @@ public:
id &= 0xFFF;
std::string name;
if (id < ZNames::GetNumActors())
name = Globals::Instance->cfg.actorList.at(id);
name = Globals::Instance->cfg.actorList[id];
else
name = StringHelper::Sprintf("0x%04X", id);
@ -45,5 +45,20 @@ public:
return "";
}
static int32_t GetNumActors() { return Globals::Instance->cfg.actorList.size(); }
static std::string GetEntranceName(uint16_t id)
{
if (ZNames::GetNumEntrances() == 0 || ZNames::GetNumSpecialEntrances() == 0)
return StringHelper::Sprintf("0x%04X", id);
if (id < ZNames::GetNumEntrances())
return Globals::Instance->cfg.entranceList[id];
else if ((id >= 0x7FF9 && id <= 0x7FFF) && !((id - 0x7FF9U) > GetNumSpecialEntrances())) // Special entrances
return Globals::Instance->cfg.specialEntranceList[id - 0x7FF9];
else
return StringHelper::Sprintf("0x%04X", id);
}
static size_t GetNumActors() { return Globals::Instance->cfg.actorList.size(); }
static size_t GetNumEntrances() { return Globals::Instance->cfg.entranceList.size(); }
static size_t GetNumSpecialEntrances() { return Globals::Instance->cfg.specialEntranceList.size(); }
};

View File

@ -10,10 +10,15 @@
REGISTER_ZFILENODE(Skeleton, ZSkeleton);
REGISTER_ZFILENODE(LimbTable, ZLimbTable);
ZSkeleton::ZSkeleton(ZFile* nParent) : ZResource(nParent), limbsTable(nParent)
ZSkeleton::ZSkeleton(ZFile* nParent) : ZResource(nParent)
{
RegisterRequiredAttribute("Type");
RegisterRequiredAttribute("LimbType");
genOTRDef = true;
RegisterOptionalAttribute("EnumName");
RegisterOptionalAttribute("LimbNone");
RegisterOptionalAttribute("LimbMax");
genOTRDef = true;
}
@ -44,6 +49,41 @@ void ZSkeleton::ParseXML(tinyxml2::XMLElement* reader)
limbTypeXml.c_str()),
"Defaulting to 'Standard'.");
}
enumName = registeredAttributes.at("EnumName").value;
limbNoneName = registeredAttributes.at("LimbNone").value;
limbMaxName = registeredAttributes.at("LimbMax").value;
if (enumName != "")
{
if (limbNoneName == "" || limbMaxName == "")
{
HANDLE_ERROR_RESOURCE(WarningType::MissingAttribute, parent, this, rawDataIndex,
"'EnumName' attribute was used but either 'LimbNone' or "
"'LimbMax' attribute is missing",
"");
}
}
if (limbNoneName != "")
{
if (limbMaxName == "")
{
HANDLE_ERROR_RESOURCE(
WarningType::MissingAttribute, parent, this, rawDataIndex,
"'LimbNone' attribute was used but 'LimbMax' attribute is missing", "");
}
}
if (limbMaxName != "")
{
if (limbNoneName == "")
{
HANDLE_ERROR_RESOURCE(
WarningType::MissingAttribute, parent, this, rawDataIndex,
"'LimbMax' attribute was used but 'LimbNone' attribute is missing", "");
}
}
}
void ZSkeleton::ParseRawData()
@ -58,12 +98,6 @@ void ZSkeleton::ParseRawData()
{
dListCount = BitConverter::ToUInt8BE(rawData, rawDataIndex + 8);
}
if (limbsArrayAddress != 0 && GETSEGNUM(limbsArrayAddress) == parent->segment)
{
uint32_t ptr = Seg2Filespace(limbsArrayAddress, parent->baseAddress);
limbsTable.ExtractFromBinary(ptr, limbType, limbCount);
}
}
void ZSkeleton::DeclareReferences(const std::string& prefix)
@ -74,14 +108,33 @@ void ZSkeleton::DeclareReferences(const std::string& prefix)
ZResource::DeclareReferences(defaultPrefix);
if (limbsArrayAddress != 0 && GETSEGNUM(limbsArrayAddress) == parent->segment)
if (limbsArrayAddress != SEGMENTED_NULL && GETSEGNUM(limbsArrayAddress) == parent->segment)
{
uint32_t ptr = Seg2Filespace(limbsArrayAddress, parent->baseAddress);
offset_t ptr = Seg2Filespace(limbsArrayAddress, parent->baseAddress);
if (!parent->HasDeclaration(ptr))
{
limbsTable.SetName(StringHelper::Sprintf("%sLimbs", defaultPrefix.c_str()));
limbsTable.DeclareReferences(prefix);
limbsTable.GetSourceOutputCode(prefix);
limbsTable = new ZLimbTable(parent);
limbsTable->ExtractFromBinary(ptr, limbType, limbCount);
limbsTable->SetName(StringHelper::Sprintf("%sLimbs", defaultPrefix.c_str()));
parent->AddResource(limbsTable);
}
else
{
limbsTable = static_cast<ZLimbTable*>(parent->FindResource(ptr));
}
if (limbsTable->enumName == "")
{
limbsTable->enumName = enumName;
}
if (limbsTable->limbNoneName == "")
{
limbsTable->limbNoneName = limbNoneName;
}
if (limbsTable->limbMaxName == "")
{
limbsTable->limbMaxName = limbMaxName;
}
}
}
@ -92,15 +145,27 @@ std::string ZSkeleton::GetBodySourceCode() const
Globals::Instance->GetSegmentedPtrName(limbsArrayAddress, parent, "", limbArrayName,
parent->workerID);
std::string countStr;
assert(limbsTable != nullptr);
// There are some Skeletons with the wrong limb count on them, so this check is necessary.
if (limbsTable->count == limbCount)
{
countStr = StringHelper::Sprintf("ARRAY_COUNT(%s)", limbArrayName.c_str());
}
else
{
countStr = StringHelper::Sprintf("%i", limbCount);
}
switch (type)
{
case ZSkeletonType::Normal:
case ZSkeletonType::Curve:
return StringHelper::Sprintf("\n\t%s, %i\n", limbArrayName.c_str(), limbCount);
return StringHelper::Sprintf("\n\t%s, %s\n", limbArrayName.c_str(), countStr.c_str());
case ZSkeletonType::Flex:
return StringHelper::Sprintf("\n\t{ %s, %i }, %i\n", limbArrayName.c_str(), limbCount,
dListCount);
return StringHelper::Sprintf("\n\t{ %s, %s }, %i\n", limbArrayName.c_str(),
countStr.c_str(), dListCount);
}
// TODO: Throw exception?
@ -156,6 +221,9 @@ ZLimbTable::ZLimbTable(ZFile* nParent) : ZResource(nParent)
{
RegisterRequiredAttribute("LimbType");
RegisterRequiredAttribute("Count");
RegisterOptionalAttribute("EnumName");
RegisterOptionalAttribute("LimbNone");
RegisterOptionalAttribute("LimbMax");
}
void ZLimbTable::ExtractFromBinary(uint32_t nRawDataIndex, ZLimbType nLimbType, size_t nCount)
@ -182,6 +250,40 @@ void ZLimbTable::ParseXML(tinyxml2::XMLElement* reader)
}
count = StringHelper::StrToL(registeredAttributes.at("Count").value);
enumName = registeredAttributes.at("EnumName").value;
limbNoneName = registeredAttributes.at("LimbNone").value;
limbMaxName = registeredAttributes.at("LimbMax").value;
if (enumName != "")
{
if (limbNoneName == "" || limbMaxName == "")
{
HANDLE_ERROR_RESOURCE(
WarningType::MissingAttribute, parent, this, rawDataIndex,
"'EnumName' attribute was used but 'LimbNone'/'LimbMax' attributes is missing", "");
}
}
if (limbNoneName != "")
{
if (limbMaxName == "")
{
HANDLE_ERROR_RESOURCE(
WarningType::MissingAttribute, parent, this, rawDataIndex,
"'LimbNone' attribute was used but 'LimbMax' attribute is missing", "");
}
}
if (limbMaxName != "")
{
if (limbNoneName == "")
{
HANDLE_ERROR_RESOURCE(
WarningType::MissingAttribute, parent, this, rawDataIndex,
"'LimbMax' attribute was used but 'LimbNone' attribute is missing", "");
}
}
}
void ZLimbTable::ParseRawData()
@ -190,6 +292,8 @@ void ZLimbTable::ParseRawData()
const auto& rawData = parent->GetRawData();
uint32_t ptr = rawDataIndex;
limbsAddresses.reserve(count);
for (size_t i = 0; i < count; i++)
{
limbsAddresses.push_back(BitConverter::ToUInt32BE(rawData, ptr));
@ -204,7 +308,7 @@ void ZLimbTable::DeclareReferences(const std::string& prefix)
varPrefix = prefix;
ZResource::DeclareReferences(varPrefix);
limbsReferences.reserve(count);
for (size_t i = 0; i < count; i++)
{
segptr_t limbAddress = limbsAddresses[i];
@ -212,15 +316,28 @@ void ZLimbTable::DeclareReferences(const std::string& prefix)
if (limbAddress != 0 && GETSEGNUM(limbAddress) == parent->segment)
{
uint32_t limbOffset = Seg2Filespace(limbAddress, parent->baseAddress);
ZLimb* limb;
if (!parent->HasDeclaration(limbOffset))
{
ZLimb* limb = new ZLimb(parent);
limb = new ZLimb(parent);
limb->ExtractFromBinary(limbOffset, limbType);
limb->SetName(limb->GetDefaultName(varPrefix));
limb->DeclareVar(varPrefix, "");
limb->DeclareReferences(varPrefix);
parent->AddResource(limb);
}
else
{
limb = static_cast<ZLimb*>(parent->FindResource(limbOffset));
assert(limb != nullptr);
assert(limb->GetResourceType() == ZResourceType::Limb);
}
limb->limbsTable = this;
limb->SetLimbIndex(i + 1);
limbsReferences.push_back(limb);
}
}
}
@ -250,6 +367,13 @@ std::string ZLimbTable::GetBodySourceCode() const
parent->workerID);
body += StringHelper::Sprintf("\t%s,", limbName.c_str());
auto& limb = limbsReferences.at(i);
std::string limbEnumName = limb->enumName;
if (limbEnumName != "")
{
body += StringHelper::Sprintf(" /* %s */", limbEnumName.c_str());
}
if (i + 1 < count)
body += "\n";
}
@ -257,6 +381,46 @@ std::string ZLimbTable::GetBodySourceCode() const
return body;
}
std::string ZLimbTable::GetSourceOutputHeader([[maybe_unused]] const std::string& prefix)
{
if (limbNoneName == "" || limbMaxName == "" || enumName == "")
{
// Don't produce a enum of any of those attributes is missing
return "";
}
std::string limbEnum = StringHelper::Sprintf("typedef enum %s {\n", enumName.c_str());
// This assumes there isn't any skeleton with more than 0x100 limbs
limbEnum += StringHelper::Sprintf(" /* 0x00 */ %s,\n", limbNoneName.c_str());
size_t i = 0;
for (; i < count; i++)
{
auto& limb = limbsReferences.at(i);
std::string limbEnumName = limb->enumName;
if (limbEnumName == "")
{
HANDLE_ERROR_RESOURCE(
WarningType::MissingAttribute, parent, this, rawDataIndex,
"Skeleton's enum attributes were used but at least one limb is missing its "
"'LimbName' attribute",
StringHelper::Sprintf("When processing limb %02i, named '%s' at offset '0x%X'",
i + 1, limb->GetName().c_str(), limb->GetRawDataIndex()));
}
limbEnum += StringHelper::Sprintf(" /* 0x%02X */ %s,\n", i + 1, limbEnumName.c_str());
}
limbEnum += StringHelper::Sprintf(" /* 0x%02X */ %s\n", i + 1, limbMaxName.c_str());
limbEnum += StringHelper::Sprintf("} %s;\n", enumName.c_str());
return limbEnum;
}
std::string ZLimbTable::GetSourceTypeName() const
{
switch (limbType)
@ -287,3 +451,28 @@ size_t ZLimbTable::GetRawDataSize() const
{
return 4 * limbsAddresses.size();
}
std::string ZLimbTable::GetLimbEnumName(uint8_t limbIndex) const
{
if (limbIndex == 0xFF)
{
return "LIMB_DONE";
}
if (limbIndex < count)
{
std::string limbEnumName = limbsReferences.at(limbIndex)->enumName;
if (limbEnumName != "")
{
return StringHelper::Sprintf("%s - 1", limbEnumName.c_str());
}
}
else
{
HANDLE_WARNING_RESOURCE(WarningType::InvalidExtractedData, parent, this, rawDataIndex,
StringHelper::Sprintf("Limb index '%02i' out of range", limbIndex),
"");
}
return StringHelper::Sprintf("0x%02X", limbIndex);
}

View File

@ -20,7 +20,14 @@ class ZLimbTable : public ZResource
public:
ZLimbType limbType = ZLimbType::Standard;
size_t count = 0;
std::vector<segptr_t> limbsAddresses;
std::vector<ZLimb*> limbsReferences; // borrowed pointers, do not delete!
// XML attributes
std::string enumName;
std::string limbNoneName;
std::string limbMaxName;
ZLimbTable(ZFile* nParent);
@ -34,10 +41,14 @@ public:
std::string GetBodySourceCode() const override;
std::string GetSourceOutputHeader([[maybe_unused]] const std::string& prefix);
std::string GetSourceTypeName() const override;
ZResourceType GetResourceType() const override;
size_t GetRawDataSize() const override;
std::string GetLimbEnumName(uint8_t limbIndex) const;
};
class ZSkeleton : public ZResource
@ -45,10 +56,13 @@ class ZSkeleton : public ZResource
public:
ZSkeletonType type = ZSkeletonType::Normal;
ZLimbType limbType = ZLimbType::Standard;
std::string enumName;
std::string limbNoneName;
std::string limbMaxName;
segptr_t limbsArrayAddress;
uint8_t limbCount = 0;
uint8_t dListCount = 0; // FLEX SKELETON ONLY
ZLimbTable limbsTable;
ZSkeleton(ZFile* nParent);
@ -65,4 +79,7 @@ public:
DeclarationAlignment GetDeclarationAlignment() const override;
uint8_t GetLimbCount();
ZLimbTable* limbsTable = nullptr; // borrowed pointer, do not delete!
};

View File

@ -0,0 +1,65 @@
#include "ZSurfaceType.h"
#include "Globals.h"
#include "Utils/BitConverter.h"
#include "Utils/StringHelper.h"
REGISTER_ZFILENODE(SurfaceType, ZSurfaceType);
ZSurfaceType::ZSurfaceType(ZFile* nParent) : ZResource(nParent)
{
}
ZSurfaceType::~ZSurfaceType()
{
}
void ZSurfaceType::ParseRawData()
{
const auto& rawData = parent->GetRawData();
data[0] = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0);
data[1] = BitConverter::ToUInt32BE(rawData, rawDataIndex + 4);
}
void ZSurfaceType::DeclareReferences(const std::string& prefix)
{
std::string declaration;
std::string auxName = name;
if (name == "")
auxName = GetDefaultName(prefix);
parent->AddDeclaration(rawDataIndex, DeclarationAlignment::Align4, GetRawDataSize(),
GetSourceTypeName(), name.c_str(), GetBodySourceCode());
}
std::string ZSurfaceType::GetBodySourceCode() const
{
return StringHelper::Sprintf("{0x%08X, 0x%08X}", data[0], data[1]);
}
std::string ZSurfaceType::GetDefaultName(const std::string& prefix) const
{
return StringHelper::Sprintf("%sSurfaceType_%06X", prefix.c_str(), rawDataIndex);
}
ZResourceType ZSurfaceType::GetResourceType() const
{
return ZResourceType::SurfaceType;
}
size_t ZSurfaceType::GetRawDataSize() const
{
return 8;
}
std::string ZSurfaceType::GetSourceTypeName() const
{
return "SurfaceType";
}
bool ZSurfaceType::DoesSupportArray() const
{
return true;
}

View File

@ -0,0 +1,27 @@
#pragma once
#include <array>
#include "ZFile.h"
#include "ZResource.h"
class ZSurfaceType : public ZResource
{
public:
std::array<uint32_t, 2> data;
ZSurfaceType(ZFile* nParent);
~ZSurfaceType();
void ParseRawData() override;
void DeclareReferences(const std::string& prefix) override;
std::string GetBodySourceCode() const override;
std::string GetDefaultName(const std::string& prefix) const override;
std::string GetSourceTypeName() const override;
ZResourceType GetResourceType() const override;
bool DoesSupportArray() const override;
size_t GetRawDataSize() const override;
};

View File

@ -18,11 +18,15 @@ ZTexture::ZTexture(ZFile* nParent) : ZResource(nParent)
height = 0;
dWordAligned = true;
genOTRDef = true;
splitTlut = false;
RegisterRequiredAttribute("Width");
RegisterRequiredAttribute("Height");
RegisterRequiredAttribute("Format");
RegisterOptionalAttribute("TlutOffset");
RegisterOptionalAttribute("ExternalTlut");
RegisterOptionalAttribute("ExternalTlutOffset");
RegisterOptionalAttribute("SplitTlut");
}
void ZTexture::ExtractFromBinary(uint32_t nRawDataIndex, int32_t nWidth, int32_t nHeight,
@ -57,6 +61,7 @@ void ZTexture::ParseXML(tinyxml2::XMLElement* reader)
std::string widthXml = registeredAttributes.at("Width").value;
std::string heightXml = registeredAttributes.at("Height").value;
std::string SplitTlutXml = registeredAttributes.at("SplitTlut").value;
if (!StringHelper::HasOnlyDigits(widthXml))
{
@ -73,6 +78,27 @@ void ZTexture::ParseXML(tinyxml2::XMLElement* reader)
errorHeader, "");
}
if (!registeredAttributes.at("ExternalTlut").wasSet &&
registeredAttributes.at("SplitTlut").wasSet)
{
std::string errorHeader =
StringHelper::Sprintf("SplitTlut set without using an external tlut");
HANDLE_WARNING_RESOURCE(WarningType::InvalidAttributeValue, parent, this, rawDataIndex,
errorHeader, "");
}
if (!SplitTlutXml.empty())
{
if (!tinyxml2::XMLUtil::ToBool(SplitTlutXml.c_str(), &splitTlut))
{
std::string errorHeader = StringHelper::Sprintf(
"Invalid value passed to SplitTlut: '%s'. Valid values are true, false, 1, 0",
SplitTlutXml.c_str());
HANDLE_ERROR_RESOURCE(WarningType::InvalidAttributeValue, parent, this, rawDataIndex,
errorHeader, "");
}
}
width = StringHelper::StrToL(widthXml);
height = StringHelper::StrToL(heightXml);
@ -146,6 +172,47 @@ void ZTexture::ParseRawData()
}
}
void ZTexture::ParseRawDataLate()
{
if (registeredAttributes["ExternalTlut"].wasSet)
{
const std::string externPalette = registeredAttributes["ExternalTlut"].value;
for (const auto& file : Globals::Instance->files)
{
if (file->GetName() == externPalette)
{
offset_t palOffset = 0;
if (registeredAttributes["ExternalTlutOffset"].wasSet)
{
palOffset =
StringHelper::StrToL(registeredAttributes["ExternalTlutOffset"].value, 16);
}
else
{
HANDLE_WARNING_RESOURCE(
WarningType::MissingOffsets, parent, this, rawDataIndex,
StringHelper::Sprintf(
"No ExternalTlutOffset Given. Assuming offset of 0x0"),
"");
}
for (const auto& res : file->resources)
{
if (res->GetRawDataIndex() == palOffset)
{
ZTexture* palette = (ZTexture*)res;
ZTexture tlutTemp(file);
tlut = &tlutTemp;
tlut->ExtractFromBinary(palOffset, palette->width, palette->height,
TextureType::RGBA16bpp, true);
SetTlut(tlut);
}
}
}
}
}
}
void ZTexture::PrepareBitmapRGBA16()
{
textureData.InitEmptyRGBImage(width, height, true);
@ -351,34 +418,42 @@ void ZTexture::DeclareReferences([[maybe_unused]] const std::string& prefix)
void ZTexture::PrepareRawDataFromFile(const fs::path& pngFilePath)
{
textureData.ReadPng(pngFilePath);
width = textureData.GetWidth();
height = textureData.GetHeight();
textureDataRaw.clear();
textureDataRaw.resize(GetRawDataSize());
switch (format)
{
case TextureType::RGBA16bpp:
PrepareRawDataRGBA16(pngFilePath);
PrepareRawDataRGBA16();
break;
case TextureType::RGBA32bpp:
PrepareRawDataRGBA32(pngFilePath);
PrepareRawDataRGBA32();
break;
case TextureType::Grayscale4bpp:
PrepareRawDataGrayscale4(pngFilePath);
PrepareRawDataGrayscale4();
break;
case TextureType::Grayscale8bpp:
PrepareRawDataGrayscale8(pngFilePath);
PrepareRawDataGrayscale8();
break;
case TextureType::GrayscaleAlpha4bpp:
PrepareRawDataGrayscaleAlpha4(pngFilePath);
PrepareRawDataGrayscaleAlpha4();
break;
case TextureType::GrayscaleAlpha8bpp:
PrepareRawDataGrayscaleAlpha8(pngFilePath);
PrepareRawDataGrayscaleAlpha8();
break;
case TextureType::GrayscaleAlpha16bpp:
PrepareRawDataGrayscaleAlpha16(pngFilePath);
PrepareRawDataGrayscaleAlpha16();
break;
case TextureType::Palette4bpp:
PrepareRawDataPalette4(pngFilePath);
PrepareRawDataPalette4();
break;
case TextureType::Palette8bpp:
PrepareRawDataPalette8(pngFilePath);
PrepareRawDataPalette8();
break;
case TextureType::Error:
HANDLE_ERROR_PROCESS(WarningType::InvalidPNG, "Input PNG file has invalid format type", "");
@ -386,15 +461,8 @@ void ZTexture::PrepareRawDataFromFile(const fs::path& pngFilePath)
}
}
void ZTexture::PrepareRawDataRGBA16(const fs::path& rgbaPath)
void ZTexture::PrepareRawDataRGBA16()
{
textureData.ReadPng(rgbaPath);
width = textureData.GetWidth();
height = textureData.GetHeight();
textureDataRaw.clear();
textureDataRaw.resize(GetRawDataSize());
for (uint16_t y = 0; y < height; y++)
{
for (uint16_t x = 0; x < width; x++)
@ -416,15 +484,8 @@ void ZTexture::PrepareRawDataRGBA16(const fs::path& rgbaPath)
}
}
void ZTexture::PrepareRawDataRGBA32(const fs::path& rgbaPath)
void ZTexture::PrepareRawDataRGBA32()
{
textureData.ReadPng(rgbaPath);
width = textureData.GetWidth();
height = textureData.GetHeight();
textureDataRaw.clear();
textureDataRaw.resize(GetRawDataSize());
for (uint16_t y = 0; y < height; y++)
{
for (uint16_t x = 0; x < width; x++)
@ -440,15 +501,8 @@ void ZTexture::PrepareRawDataRGBA32(const fs::path& rgbaPath)
}
}
void ZTexture::PrepareRawDataGrayscale4(const fs::path& grayPath)
void ZTexture::PrepareRawDataGrayscale4()
{
textureData.ReadPng(grayPath);
width = textureData.GetWidth();
height = textureData.GetHeight();
textureDataRaw.clear();
textureDataRaw.resize(GetRawDataSize());
for (uint16_t y = 0; y < height; y++)
{
for (uint16_t x = 0; x < width; x += 2)
@ -462,15 +516,8 @@ void ZTexture::PrepareRawDataGrayscale4(const fs::path& grayPath)
}
}
void ZTexture::PrepareRawDataGrayscale8(const fs::path& grayPath)
void ZTexture::PrepareRawDataGrayscale8()
{
textureData.ReadPng(grayPath);
width = textureData.GetWidth();
height = textureData.GetHeight();
textureDataRaw.clear();
textureDataRaw.resize(GetRawDataSize());
for (uint16_t y = 0; y < height; y++)
{
for (uint16_t x = 0; x < width; x++)
@ -482,15 +529,8 @@ void ZTexture::PrepareRawDataGrayscale8(const fs::path& grayPath)
}
}
void ZTexture::PrepareRawDataGrayscaleAlpha4(const fs::path& grayAlphaPath)
void ZTexture::PrepareRawDataGrayscaleAlpha4()
{
textureData.ReadPng(grayAlphaPath);
width = textureData.GetWidth();
height = textureData.GetHeight();
textureDataRaw.clear();
textureDataRaw.resize(GetRawDataSize());
for (uint16_t y = 0; y < height; y++)
{
for (uint16_t x = 0; x < width; x += 2)
@ -515,15 +555,8 @@ void ZTexture::PrepareRawDataGrayscaleAlpha4(const fs::path& grayAlphaPath)
}
}
void ZTexture::PrepareRawDataGrayscaleAlpha8(const fs::path& grayAlphaPath)
void ZTexture::PrepareRawDataGrayscaleAlpha8()
{
textureData.ReadPng(grayAlphaPath);
width = textureData.GetWidth();
height = textureData.GetHeight();
textureDataRaw.clear();
textureDataRaw.resize(GetRawDataSize());
for (uint16_t y = 0; y < height; y++)
{
for (uint16_t x = 0; x < width; x++)
@ -539,15 +572,8 @@ void ZTexture::PrepareRawDataGrayscaleAlpha8(const fs::path& grayAlphaPath)
}
}
void ZTexture::PrepareRawDataGrayscaleAlpha16(const fs::path& grayAlphaPath)
void ZTexture::PrepareRawDataGrayscaleAlpha16()
{
textureData.ReadPng(grayAlphaPath);
width = textureData.GetWidth();
height = textureData.GetHeight();
textureDataRaw.clear();
textureDataRaw.resize(GetRawDataSize());
for (uint16_t y = 0; y < height; y++)
{
for (uint16_t x = 0; x < width; x++)
@ -564,15 +590,8 @@ void ZTexture::PrepareRawDataGrayscaleAlpha16(const fs::path& grayAlphaPath)
}
}
void ZTexture::PrepareRawDataPalette4(const fs::path& palPath)
void ZTexture::PrepareRawDataPalette4()
{
textureData.ReadPng(palPath);
width = textureData.GetWidth();
height = textureData.GetHeight();
textureDataRaw.clear();
textureDataRaw.resize(GetRawDataSize());
for (uint16_t y = 0; y < height; y++)
{
for (uint16_t x = 0; x < width; x += 2)
@ -587,15 +606,8 @@ void ZTexture::PrepareRawDataPalette4(const fs::path& palPath)
}
}
void ZTexture::PrepareRawDataPalette8(const fs::path& palPath)
void ZTexture::PrepareRawDataPalette8()
{
textureData.ReadPng(palPath);
width = textureData.GetWidth();
height = textureData.GetHeight();
textureDataRaw.clear();
textureDataRaw.resize(GetRawDataSize());
for (uint16_t y = 0; y < height; y++)
{
for (uint16_t x = 0; x < width; x++)
@ -728,11 +740,7 @@ void ZTexture::Save(const fs::path& outFolder)
if (!Directory::Exists(outPath.string()))
Directory::CreateDirectory(outPath.string());
//#ifdef _MSC_VER
fs::path outFileName;
//#else
//std::filesystem::__cxx11::path outFileName;
//#endif
if (!dWordAligned)
outFileName = outPath / (outName + ".u32" + "." + GetExternalExtension() + ".png");
@ -790,9 +798,8 @@ Declaration* ZTexture::DeclareVar(const std::string& prefix,
incStr = StringHelper::Sprintf("%s.%s.inc.c", poolEntry->second.path.c_str(),
GetExternalExtension().c_str());
else
incStr =
StringHelper::Sprintf("%s.u32.%s.inc.c", poolEntry->second.path.c_str(),
GetExternalExtension().c_str());
incStr = StringHelper::Sprintf("%s.u32.%s.inc.c", poolEntry->second.path.c_str(),
GetExternalExtension().c_str());
}
}
size_t texSizeDivisor = (dWordAligned) ? 8 : 4;
@ -951,7 +958,7 @@ void ZTexture::SetTlut(ZTexture* nTlut)
assert(nTlut->isPalette);
tlut = nTlut;
textureData.SetPalette(tlut->textureData);
textureData.SetPalette(tlut->textureData, splitTlut ? 128 : 0);
}
bool ZTexture::HasTlut() const

View File

@ -28,6 +28,7 @@ protected:
std::vector<uint8_t> textureDataRaw; // When reading from a PNG file.
uint32_t tlutOffset = static_cast<uint32_t>(-1);
ZTexture* tlut = nullptr;
bool splitTlut;
void PrepareBitmapRGBA16();
void PrepareBitmapRGBA32();
@ -40,15 +41,15 @@ protected:
void PrepareBitmapPalette8();
void PrepareRawDataFromFile(const fs::path& inFolder);
void PrepareRawDataRGBA16(const fs::path& rgbaPath);
void PrepareRawDataRGBA32(const fs::path& rgbaPath);
void PrepareRawDataGrayscale4(const fs::path& grayPath);
void PrepareRawDataGrayscale8(const fs::path& grayPath);
void PrepareRawDataGrayscaleAlpha4(const fs::path& grayAlphaPath);
void PrepareRawDataGrayscaleAlpha8(const fs::path& grayAlphaPath);
void PrepareRawDataGrayscaleAlpha16(const fs::path& grayAlphaPath);
void PrepareRawDataPalette4(const fs::path& palPath);
void PrepareRawDataPalette8(const fs::path& palPath);
void PrepareRawDataRGBA16();
void PrepareRawDataRGBA32();
void PrepareRawDataGrayscale4();
void PrepareRawDataGrayscale8();
void PrepareRawDataGrayscaleAlpha4();
void PrepareRawDataGrayscaleAlpha8();
void PrepareRawDataGrayscaleAlpha16();
void PrepareRawDataPalette4();
void PrepareRawDataPalette8();
public:
ZTexture(ZFile* nParent);
@ -88,4 +89,5 @@ public:
bool IsColorIndexed() const;
void SetTlut(ZTexture* nTlut);
bool HasTlut() const;
void ParseRawDataLate() override;
};

View File

@ -48,7 +48,7 @@ void ZVector::ParseRawData()
int32_t currentRawDataIndex = rawDataIndex;
// TODO: this shouldn't be necessary.
scalars.clear();
scalars.reserve(dimensions);
for (uint32_t i = 0; i < dimensions; i++)
{
ZScalar scalar(parent);

View File

@ -9,6 +9,7 @@ This document aims to be a small reference of how to create a compatible xml fil
- [Basic XML](#basic-xml)
- [Resources types](#resources-types)
- [File](#file)
- [ExternalFile](#externalfile)
- [Texture](#texture)
- [Background](#background)
- [Blob](#blob)
@ -33,6 +34,7 @@ This document aims to be a small reference of how to create a compatible xml fil
- [Array](#array)
- [Path](#path)
- [PlayerAnimationData](#playeranimationdata)
- [Pointer](#pointer)
## Basic XML
@ -147,12 +149,15 @@ u64 gCraterSmokeConeTex[] = {
- Attributes:
- `Name`: Required. Suxffixed by `Tex`, unless it is a palette, in that case it is suffixed by `TLUT`.
- `Name`: Required. Suffixed by `Tex`, unless it is a palette, in that case it is suffixed by `TLUT`.
- `OutName`: Required. The filename of the extracted `.png` file.
- `Format`: Required. The format of the image. Valid values: `rgba32`, `rgba16`, `i4`, `i8`, `ia4`, `ia8`, `ia16`, `ci4` and `ci8`.
- `Width`: Required. Width in pixels of the image.
- `Height`: Required. Height in pixels of the image.
- `TlutOffset`: Optional. Specifies the tlut's offset used by this texture. This attribute is only valid if `Format` is either `ci4` or `ci8`, otherwise an exception would be thrown.
- `ExternalTlut`: Optional. Specifies that the texture's tlut is in a different file. Takes the filename of the file that contains the tlut.
- `ExternalTlutOffset`: Optional. Specifies the offset in the `ExternalTlut` of the tlut for the given texture.
- `SplitTlut`: Optional. Specifies that the given texture should take from the upper half of the tlut. Takes a bool, i.e. one of `true`, `false`, `1`, `0`.
The following is a list of the texture formats the Nintendo 64 supports, with their gfxdis names and ZAPD format names.
@ -183,7 +188,7 @@ If you want to know more about this formats, you can check [`gsDPLoadTextureBloc
- Attributes:
- `Name`: Required. Suxffixed by `Background`.
- `Name`: Required. Suffixed by `Background`.
- `OutName`: Required. The filename of the extracted `.jpg` file.
※ Explicit use of this tag isn't often necesary because it would probably be extracted automatically by another extracted element. You can use this to name them if you don't like the autogenerated name.
@ -211,7 +216,7 @@ u8 gFireTempleBlob_00CCC0[] = {
- Attributes:
- `Name`: Required. Suxffixed by `Blob`.
- `Name`: Required. Suffixed by `Blob`.
- `Size`: Required. Amount of bytes to extract. Hex.
※ We usually use blobs when we can't figure out the content's type of chunk of data.
@ -230,7 +235,7 @@ A.k.a. Display list, or Gfx.
- Attributes:
- `Name`: Required. Suxffixed by `DL`.
- `Name`: Required. Suffixed by `DL`.
-------------------------
@ -244,7 +249,7 @@ A data type exclusive to Majora's Mask, that has scrolling, color changing, and
- Attributes:
- `Name`: Required. Suxffixed by `TexAnim`.
- `Name`: Required. Suffixed by `TexAnim`.
-------------------------
@ -304,7 +309,7 @@ Like `Scene`s and `Room`s, `AltHeader`s is special too. It should always be decl
- Attributes:
- `Name`: Required. Suxffixed by `AltHeader`.
- `Name`: Required. Suffixed by `AltHeader`.
-------------------------
@ -318,7 +323,7 @@ Like `Scene`s and `Room`s, `AltHeader`s is special too. It should always be decl
- Attributes:
- `Name`: Required. Suxffixed by `Anim`.
- `Name`: Required. Suffixed by `Anim`.
-------------------------
@ -332,7 +337,7 @@ Like `Scene`s and `Room`s, `AltHeader`s is special too. It should always be decl
- Attributes:
- `Name`: Required. Suxffixed by `Anim`.
- `Name`: Required. Suffixed by `Anim`.
-------------------------
@ -346,7 +351,7 @@ Like `Scene`s and `Room`s, `AltHeader`s is special too. It should always be decl
- Attributes:
- `Name`: Required. Suxffixed by `Anim`.
- `Name`: Required. Suffixed by `Anim`.
- `SkelOffset`: Required. Offset of the `CurveSkeleton` (I.e. a [`Skeleton`](#skeleton) resource with `Type="Curve"`) related to this animation.
-------------------------
@ -363,7 +368,7 @@ Useful only for the unused `object_human`'s animation data.
- Attributes:
- `Name`: Required. Suxffixed by `Anim`.
- `Name`: Required. Suffixed by `Anim`.
-------------------------
@ -377,9 +382,16 @@ Useful only for the unused `object_human`'s animation data.
- Attributes:
- `Name`: Required. Suxffixed by `Skel`.
- `Name`: Required. Suffixed by `Skel`.
- `Type`: Required. Valid values: `Normal`, `Flex` and `Curve`.
- `LimbType`: Required. Valid values: `Standard`, `LOD`, `Skin`, `Curve` and `Legacy`.
- `EnumName`: Optional. The name of `typedef`'d limb enum.
- `LimbNone`: Optional. The name of the limb with index zero in the limb enum.
- `LimbMax`: Optional. The name of the max limb index in the limb enum.
ZAPD is able to generate a limb enum by itself only if all the required data is provided. Providing some but not all the required data would trigger an error and the execution will halt.
The required data is providing the `EnumName`, `LimbNone` and `LimbMax` attributes in the `Skeleton` or `LimbTable` node and the `EnumName` attribute in every `Limb` of this skeleton.
※ There are no restrictions in the `Type` and `LimbType` attributes besides the valid values, so any skeleton type can be combined with any limb type.
@ -395,9 +407,14 @@ Useful only for the unused `object_human`'s animation data.
- Attributes:
- `Name`: Required. Suxffixed by `Skel`.
- `Name`: Required. Suffixed by `Skel`.
- `LimbType`: Required. Valid values: `Standard`, `LOD`, `Skin`, `Curve` and `Legacy`.
- `Count`: Required. Amount of limbs. Integer.
- `EnumName`: Optional. The name of `typedef`'d limb enum.
- `LimbNone`: Optional. The name of the limb with index zero in the limb enum.
- `LimbMax`: Optional. The name of the max limb index in the limb enum.
See [Skeleton](#skeleton) for info on the limb enum generation.
-------------------------
@ -411,8 +428,11 @@ Useful only for the unused `object_human`'s animation data.
- Attributes:
- `Name`: Required. Suxffixed by `Limb`.
- `Name`: Required. Suffixed by `Limb`.
- `LimbType`: Required. Valid values: `Standard`, `LOD`, `Skin`, `Curve` and `Legacy`.
- `EnumName`: Optional. The name used for this limb in the limbs enum. It must be either present in every limb or in none.
See [Skeleton](#skeleton) for info on the limb enum generation.
-------------------------
@ -451,7 +471,7 @@ extern u8 gJsjutanShadowTex[2048];
- Attributes:
- `Name`: Required. Suxffixed by `Col`.
- `Name`: Required. Suffixed by `Col`.
-------------------------
@ -473,7 +493,7 @@ u64 pad34F8 = { 0 };
- Attributes:
- `Name`: Required. Suxffixed by ~~`TBD`~~.
- `Name`: Required. Suffixed by ~~`TBD`~~.
- `Type`: Required. Valid values: `s8`, `u8`, `x8`, `s16`, `u16`, `x16`, `s32`, `u32`, `x32`, `s64`, `u64`, `x64`, `f32` and `f64`.
※ Can be wrapped in an [`Array`](#array) tag.
@ -527,7 +547,7 @@ Vec3s gLinkPauseChildDekuShieldJointTable[24] = {
- Attributes:
- `Name`: Required. Suxffixed by ~~`TBD`~~.
- `Name`: Required. Suffixed by ~~`TBD`~~.
- `Type`: Required. Specifies the vector's type (`Vec3s`, `Vec3i` and `Vec3f`). Valid values: `s16`, `s32` and `f32`.
- `Dimensions`: Required. The amount of dimensions of the vector. Valid values: `3`.
@ -547,7 +567,7 @@ Vec3s gLinkPauseChildDekuShieldJointTable[24] = {
- Attributes:
- `Name`: Required. Suxffixed by `Vtx`.
- `Name`: Required. Suffixed by `Vtx`.
※ Can be wrapped in an [`Array`](#array) tag.
@ -563,7 +583,7 @@ Vec3s gLinkPauseChildDekuShieldJointTable[24] = {
- Attributes:
- `Name`: Required. Suxffixed by `Mtx`.
- `Name`: Required. Suffixed by `Mtx`.
※ Explicit use of this tag isn't often necesary because it would probably be extracted automatically by another extracted element.
@ -579,7 +599,7 @@ Vec3s gLinkPauseChildDekuShieldJointTable[24] = {
- Attributes:
- `Name`: Required. Suxffixed by `Cs`.
- `Name`: Required. Suffixed by `Cs`.
※ Explicit use of this tag isn't often necesary because it would probably be extracted automatically by another extracted element.
@ -589,7 +609,7 @@ Vec3s gLinkPauseChildDekuShieldJointTable[24] = {
The `Array` element is special, because it needs an inner element to work. It will declare an array of its inner element.
Currently, only [`Scalar`](#scalar), [`Vector`](#vector) and [`Vtx`](#vtx) support being wrapped in an array.
Currently, only [`Pointer`](#pointer), [`Scalar`](#scalar), [`Vector`](#vector) and [`Vtx`](#vtx) support being wrapped in an array.
- Example:
@ -616,7 +636,7 @@ Currently, only [`Scalar`](#scalar), [`Vector`](#vector) and [`Vtx`](#vtx) suppo
- Attributes:
- `Name`: Required. Suxffixed by `Path`.
- `Name`: Required. Suffixed by `Path`.
- `NumPaths`: Optional. The amount of paths contained in the array. It must be a positive integer.
-------------------------
@ -633,7 +653,28 @@ Allows the extraction of the specific data of the player animations which are fo
- Attributes:
- `Name`: Required. Suxffixed by `AnimData`.
- `Name`: Required. Suffixed by `AnimData`.
- `FrameCount`: Required. The length of the animation in frames. It must be a positive integer.
-------------------------
### Pointer
Allows the extraction of a variable that contains a pointer
- Example:
```xml
<Array Name="object_hanareyama_obj_DLArray_004638" Count="54" Offset="0x4638">
<Pointer Type="Gfx"/>
</Array>
```
- Attributes:
- `Name`: Required.
- `Type`: Required. The type of the extracted pointer.
※ Can be wrapped in an [`Array`](#array) tag.
-------------------------

View File

@ -1,851 +0,0 @@
/*
Copyright (C) 2001-2015 by Serge Lamikhov-Center
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef ELFTYPES_H
#define ELFTYPES_H
#ifndef ELFIO_NO_OWN_TYPES
#if !defined(ELFIO_NO_CSTDINT) && !defined(ELFIO_NO_INTTYPES)
#include <stdint.h>
#else
typedef unsigned char uint8_t;
typedef signed char int8_t;
typedef unsigned short uint16_t;
typedef signed short int16_t;
#ifdef _MSC_VER
typedef unsigned __int32 uint32_t;
typedef signed __int32 int32_t;
typedef unsigned __int64 uint64_t;
typedef signed __int64 int64_t;
#else
typedef unsigned int uint32_t;
typedef signed int int32_t;
typedef unsigned long long uint64_t;
typedef signed long long int64_t;
#endif // _MSC_VER
#endif // ELFIO_NO_CSTDINT
#endif // ELFIO_NO_OWN_TYPES
namespace ELFIO {
// Attention! Platform depended definitions.
typedef uint16_t Elf_Half;
typedef uint32_t Elf_Word;
typedef int32_t Elf_Sword;
typedef uint64_t Elf_Xword;
typedef int64_t Elf_Sxword;
typedef uint32_t Elf32_Addr;
typedef uint32_t Elf32_Off;
typedef uint64_t Elf64_Addr;
typedef uint64_t Elf64_Off;
#define Elf32_Half Elf_Half
#define Elf64_Half Elf_Half
#define Elf32_Word Elf_Word
#define Elf64_Word Elf_Word
#define Elf32_Sword Elf_Sword
#define Elf64_Sword Elf_Sword
///////////////////////
// ELF Header Constants
// File type
#define ET_NONE 0
#define ET_REL 1
#define ET_EXEC 2
#define ET_DYN 3
#define ET_CORE 4
#define ET_LOOS 0xFE00
#define ET_HIOS 0xFEFF
#define ET_LOPROC 0xFF00
#define ET_HIPROC 0xFFFF
#define EM_NONE 0 // No machine
#define EM_M32 1 // AT&T WE 32100
#define EM_SPARC 2 // SUN SPARC
#define EM_386 3 // Intel 80386
#define EM_68K 4 // Motorola m68k family
#define EM_88K 5 // Motorola m88k family
#define EM_486 6 // Intel 80486// Reserved for future use
#define EM_860 7 // Intel 80860
#define EM_MIPS 8 // MIPS R3000 (officially, big-endian only)
#define EM_S370 9 // IBM System/370
#define EM_MIPS_RS3_LE 10 // MIPS R3000 little-endian (Oct 4 1999 Draft) Deprecated
#define EM_res011 11 // Reserved
#define EM_res012 12 // Reserved
#define EM_res013 13 // Reserved
#define EM_res014 14 // Reserved
#define EM_PARISC 15 // HPPA
#define EM_res016 16 // Reserved
#define EM_VPP550 17 // Fujitsu VPP500
#define EM_SPARC32PLUS 18 // Sun's "v8plus"
#define EM_960 19 // Intel 80960
#define EM_PPC 20 // PowerPC
#define EM_PPC64 21 // 64-bit PowerPC
#define EM_S390 22 // IBM S/390
#define EM_SPU 23 // Sony/Toshiba/IBM SPU
#define EM_res024 24 // Reserved
#define EM_res025 25 // Reserved
#define EM_res026 26 // Reserved
#define EM_res027 27 // Reserved
#define EM_res028 28 // Reserved
#define EM_res029 29 // Reserved
#define EM_res030 30 // Reserved
#define EM_res031 31 // Reserved
#define EM_res032 32 // Reserved
#define EM_res033 33 // Reserved
#define EM_res034 34 // Reserved
#define EM_res035 35 // Reserved
#define EM_V800 36 // NEC V800 series
#define EM_FR20 37 // Fujitsu FR20
#define EM_RH32 38 // TRW RH32
#define EM_MCORE 39 // Motorola M*Core // May also be taken by Fujitsu MMA
#define EM_RCE 39 // Old name for MCore
#define EM_ARM 40 // ARM
#define EM_OLD_ALPHA 41 // Digital Alpha
#define EM_SH 42 // Renesas (formerly Hitachi) / SuperH SH
#define EM_SPARCV9 43 // SPARC v9 64-bit
#define EM_TRICORE 44 // Siemens Tricore embedded processor
#define EM_ARC 45 // ARC Cores
#define EM_H8_300 46 // Renesas (formerly Hitachi) H8/300
#define EM_H8_300H 47 // Renesas (formerly Hitachi) H8/300H
#define EM_H8S 48 // Renesas (formerly Hitachi) H8S
#define EM_H8_500 49 // Renesas (formerly Hitachi) H8/500
#define EM_IA_64 50 // Intel IA-64 Processor
#define EM_MIPS_X 51 // Stanford MIPS-X
#define EM_COLDFIRE 52 // Motorola Coldfire
#define EM_68HC12 53 // Motorola M68HC12
#define EM_MMA 54 // Fujitsu Multimedia Accelerator
#define EM_PCP 55 // Siemens PCP
#define EM_NCPU 56 // Sony nCPU embedded RISC processor
#define EM_NDR1 57 // Denso NDR1 microprocesspr
#define EM_STARCORE 58 // Motorola Star*Core processor
#define EM_ME16 59 // Toyota ME16 processor
#define EM_ST100 60 // STMicroelectronics ST100 processor
#define EM_TINYJ 61 // Advanced Logic Corp. TinyJ embedded processor
#define EM_X86_64 62 // Advanced Micro Devices X86-64 processor
#define EM_PDSP 63 // Sony DSP Processor
#define EM_PDP10 64 // Digital Equipment Corp. PDP-10
#define EM_PDP11 65 // Digital Equipment Corp. PDP-11
#define EM_FX66 66 // Siemens FX66 microcontroller
#define EM_ST9PLUS 67 // STMicroelectronics ST9+ 8/16 bit microcontroller
#define EM_ST7 68 // STMicroelectronics ST7 8-bit microcontroller
#define EM_68HC16 69 // Motorola MC68HC16 Microcontroller
#define EM_68HC11 70 // Motorola MC68HC11 Microcontroller
#define EM_68HC08 71 // Motorola MC68HC08 Microcontroller
#define EM_68HC05 72 // Motorola MC68HC05 Microcontroller
#define EM_SVX 73 // Silicon Graphics SVx
#define EM_ST19 74 // STMicroelectronics ST19 8-bit cpu
#define EM_VAX 75 // Digital VAX
#define EM_CRIS 76 // Axis Communications 32-bit embedded processor
#define EM_JAVELIN 77 // Infineon Technologies 32-bit embedded cpu
#define EM_FIREPATH 78 // Element 14 64-bit DSP processor
#define EM_ZSP 79 // LSI Logic's 16-bit DSP processor
#define EM_MMIX 80 // Donald Knuth's educational 64-bit processor
#define EM_HUANY 81 // Harvard's machine-independent format
#define EM_PRISM 82 // SiTera Prism
#define EM_AVR 83 // Atmel AVR 8-bit microcontroller
#define EM_FR30 84 // Fujitsu FR30
#define EM_D10V 85 // Mitsubishi D10V
#define EM_D30V 86 // Mitsubishi D30V
#define EM_V850 87 // NEC v850
#define EM_M32R 88 // Renesas M32R (formerly Mitsubishi M32R)
#define EM_MN10300 89 // Matsushita MN10300
#define EM_MN10200 90 // Matsushita MN10200
#define EM_PJ 91 // picoJava
#define EM_OPENRISC 92 // OpenRISC 32-bit embedded processor
#define EM_ARC_A5 93 // ARC Cores Tangent-A5
#define EM_XTENSA 94 // Tensilica Xtensa Architecture
#define EM_VIDEOCORE 95 // Alphamosaic VideoCore processor
#define EM_TMM_GPP 96 // Thompson Multimedia General Purpose Processor
#define EM_NS32K 97 // National Semiconductor 32000 series
#define EM_TPC 98 // Tenor Network TPC processor
#define EM_SNP1K 99 // Trebia SNP 1000 processor
#define EM_ST200 100 // STMicroelectronics ST200 microcontroller
#define EM_IP2K 101 // Ubicom IP2022 micro controller
#define EM_MAX 102 // MAX Processor
#define EM_CR 103 // National Semiconductor CompactRISC
#define EM_F2MC16 104 // Fujitsu F2MC16
#define EM_MSP430 105 // TI msp430 micro controller
#define EM_BLACKFIN 106 // ADI Blackfin
#define EM_SE_C33 107 // S1C33 Family of Seiko Epson processors
#define EM_SEP 108 // Sharp embedded microprocessor
#define EM_ARCA 109 // Arca RISC Microprocessor
#define EM_UNICORE 110 // Microprocessor series from PKU-Unity Ltd. and MPRC of Peking University
#define EM_EXCESS 111 // eXcess: 16/32/64-bit configurable embedded CPU
#define EM_DXP 112 // Icera Semiconductor Inc. Deep Execution Processor
#define EM_ALTERA_NIOS2 113 // Altera Nios II soft-core processor
#define EM_CRX 114 // National Semiconductor CRX
#define EM_XGATE 115 // Motorola XGATE embedded processor
#define EM_C166 116 // Infineon C16x/XC16x processor
#define EM_M16C 117 // Renesas M16C series microprocessors
#define EM_DSPIC30F 118 // Microchip Technology dsPIC30F Digital Signal Controller
#define EM_CE 119 // Freescale Communication Engine RISC core
#define EM_M32C 120 // Renesas M32C series microprocessors
#define EM_res121 121 // Reserved
#define EM_res122 122 // Reserved
#define EM_res123 123 // Reserved
#define EM_res124 124 // Reserved
#define EM_res125 125 // Reserved
#define EM_res126 126 // Reserved
#define EM_res127 127 // Reserved
#define EM_res128 128 // Reserved
#define EM_res129 129 // Reserved
#define EM_res130 130 // Reserved
#define EM_TSK3000 131 // Altium TSK3000 core
#define EM_RS08 132 // Freescale RS08 embedded processor
#define EM_res133 133 // Reserved
#define EM_ECOG2 134 // Cyan Technology eCOG2 microprocessor
#define EM_SCORE 135 // Sunplus Score
#define EM_SCORE7 135 // Sunplus S+core7 RISC processor
#define EM_DSP24 136 // New Japan Radio (NJR) 24-bit DSP Processor
#define EM_VIDEOCORE3 137 // Broadcom VideoCore III processor
#define EM_LATTICEMICO32 138 // RISC processor for Lattice FPGA architecture
#define EM_SE_C17 139 // Seiko Epson C17 family
#define EM_TI_C6000 140 // Texas Instruments TMS320C6000 DSP family
#define EM_TI_C2000 141 // Texas Instruments TMS320C2000 DSP family
#define EM_TI_C5500 142 // Texas Instruments TMS320C55x DSP family
#define EM_res143 143 // Reserved
#define EM_res144 144 // Reserved
#define EM_res145 145 // Reserved
#define EM_res146 146 // Reserved
#define EM_res147 147 // Reserved
#define EM_res148 148 // Reserved
#define EM_res149 149 // Reserved
#define EM_res150 150 // Reserved
#define EM_res151 151 // Reserved
#define EM_res152 152 // Reserved
#define EM_res153 153 // Reserved
#define EM_res154 154 // Reserved
#define EM_res155 155 // Reserved
#define EM_res156 156 // Reserved
#define EM_res157 157 // Reserved
#define EM_res158 158 // Reserved
#define EM_res159 159 // Reserved
#define EM_MMDSP_PLUS 160 // STMicroelectronics 64bit VLIW Data Signal Processor
#define EM_CYPRESS_M8C 161 // Cypress M8C microprocessor
#define EM_R32C 162 // Renesas R32C series microprocessors
#define EM_TRIMEDIA 163 // NXP Semiconductors TriMedia architecture family
#define EM_QDSP6 164 // QUALCOMM DSP6 Processor
#define EM_8051 165 // Intel 8051 and variants
#define EM_STXP7X 166 // STMicroelectronics STxP7x family
#define EM_NDS32 167 // Andes Technology compact code size embedded RISC processor family
#define EM_ECOG1 168 // Cyan Technology eCOG1X family
#define EM_ECOG1X 168 // Cyan Technology eCOG1X family
#define EM_MAXQ30 169 // Dallas Semiconductor MAXQ30 Core Micro-controllers
#define EM_XIMO16 170 // New Japan Radio (NJR) 16-bit DSP Processor
#define EM_MANIK 171 // M2000 Reconfigurable RISC Microprocessor
#define EM_CRAYNV2 172 // Cray Inc. NV2 vector architecture
#define EM_RX 173 // Renesas RX family
#define EM_METAG 174 // Imagination Technologies META processor architecture
#define EM_MCST_ELBRUS 175 // MCST Elbrus general purpose hardware architecture
#define EM_ECOG16 176 // Cyan Technology eCOG16 family
#define EM_CR16 177 // National Semiconductor CompactRISC 16-bit processor
#define EM_ETPU 178 // Freescale Extended Time Processing Unit
#define EM_SLE9X 179 // Infineon Technologies SLE9X core
#define EM_L1OM 180 // Intel L1OM
#define EM_INTEL181 181 // Reserved by Intel
#define EM_INTEL182 182 // Reserved by Intel
#define EM_res183 183 // Reserved by ARM
#define EM_res184 184 // Reserved by ARM
#define EM_AVR32 185 // Atmel Corporation 32-bit microprocessor family
#define EM_STM8 186 // STMicroeletronics STM8 8-bit microcontroller
#define EM_TILE64 187 // Tilera TILE64 multicore architecture family
#define EM_TILEPRO 188 // Tilera TILEPro multicore architecture family
#define EM_MICROBLAZE 189 // Xilinx MicroBlaze 32-bit RISC soft processor core
#define EM_CUDA 190 // NVIDIA CUDA architecture
#define EM_TILEGX 191 // Tilera TILE-Gx multicore architecture family
#define EM_CLOUDSHIELD 192 // CloudShield architecture family
#define EM_COREA_1ST 193 // KIPO-KAIST Core-A 1st generation processor family
#define EM_COREA_2ND 194 // KIPO-KAIST Core-A 2nd generation processor family
#define EM_ARC_COMPACT2 195 // Synopsys ARCompact V2
#define EM_OPEN8 196 // Open8 8-bit RISC soft processor core
#define EM_RL78 197 // Renesas RL78 family
#define EM_VIDEOCORE5 198 // Broadcom VideoCore V processor
#define EM_78KOR 199 // Renesas 78KOR family
#define EM_56800EX 200 // Freescale 56800EX Digital Signal Controller (DSC)
#define EM_BA1 201 // Beyond BA1 CPU architecture
#define EM_BA2 202 // Beyond BA2 CPU architecture
#define EM_XCORE 203 // XMOS xCORE processor family
#define EM_MCHP_PIC 204 // Microchip 8-bit PIC(r) family
#define EM_INTEL205 205 // Reserved by Intel
#define EM_INTEL206 206 // Reserved by Intel
#define EM_INTEL207 207 // Reserved by Intel
#define EM_INTEL208 208 // Reserved by Intel
#define EM_INTEL209 209 // Reserved by Intel
#define EM_KM32 210 // KM211 KM32 32-bit processor
#define EM_KMX32 211 // KM211 KMX32 32-bit processor
#define EM_KMX16 212 // KM211 KMX16 16-bit processor
#define EM_KMX8 213 // KM211 KMX8 8-bit processor
#define EM_KVARC 214 // KM211 KVARC processor
#define EM_CDP 215 // Paneve CDP architecture family
#define EM_COGE 216 // Cognitive Smart Memory Processor
#define EM_COOL 217 // iCelero CoolEngine
#define EM_NORC 218 // Nanoradio Optimized RISC
#define EM_CSR_KALIMBA 219 // CSR Kalimba architecture family
#define EM_Z80 220 // Zilog Z80
#define EM_VISIUM 221 // Controls and Data Services VISIUMcore processor
#define EM_FT32 222 // FTDI Chip FT32 high performance 32-bit RISC architecture
#define EM_MOXIE 223 // Moxie processor family
#define EM_AMDGPU 224 // AMD GPU architecture
#define EM_RISCV 243 // RISC-V
#define EM_LANAI 244 // Lanai processor
#define EM_CEVA 245 // CEVA Processor Architecture Family
#define EM_CEVA_X2 246 // CEVA X2 Processor Family
#define EM_BPF 247 // Linux BPF in-kernel virtual machine
// File version
#define EV_NONE 0
#define EV_CURRENT 1
// Identification index
#define EI_MAG0 0
#define EI_MAG1 1
#define EI_MAG2 2
#define EI_MAG3 3
#define EI_CLASS 4
#define EI_DATA 5
#define EI_VERSION 6
#define EI_OSABI 7
#define EI_ABIVERSION 8
#define EI_PAD 9
#define EI_NIDENT 16
// Magic number
#define ELFMAG0 0x7F
#define ELFMAG1 'E'
#define ELFMAG2 'L'
#define ELFMAG3 'F'
// File class
#define ELFCLASSNONE 0
#define ELFCLASS32 1
#define ELFCLASS64 2
// Encoding
#define ELFDATANONE 0
#define ELFDATA2LSB 1
#define ELFDATA2MSB 2
// OS extensions
#define ELFOSABI_NONE 0 // No extensions or unspecified
#define ELFOSABI_HPUX 1 // Hewlett-Packard HP-UX
#define ELFOSABI_NETBSD 2 // NetBSD
#define ELFOSABI_LINUX 3 // Linux
#define ELFOSABI_SOLARIS 6 // Sun Solaris
#define ELFOSABI_AIX 7 // AIX
#define ELFOSABI_IRIX 8 // IRIX
#define ELFOSABI_FREEBSD 9 // FreeBSD
#define ELFOSABI_TRU64 10 // Compaq TRU64 UNIX
#define ELFOSABI_MODESTO 11 // Novell Modesto
#define ELFOSABI_OPENBSD 12 // Open BSD
#define ELFOSABI_OPENVMS 13 // Open VMS
#define ELFOSABI_NSK 14 // Hewlett-Packard Non-Stop Kernel
#define ELFOSABI_AROS 15 // Amiga Research OS
#define ELFOSABI_FENIXOS 16 // The FenixOS highly scalable multi-core OS
// 64-255 Architecture-specific value range
#define ELFOSABI_AMDGPU_HSA 64 // AMDGPU OS for HSA compatible compute
// kernels.
#define ELFOSABI_AMDGPU_PAL 65 // AMDGPU OS for AMD PAL compatible graphics
// shaders and compute kernels.
#define ELFOSABI_AMDGPU_MESA3D 66 // AMDGPU OS for Mesa3D compatible graphics
// shaders and compute kernels.
// AMDGPU specific e_flags
#define EF_AMDGPU_MACH 0x0ff // AMDGPU processor selection mask.
#define EF_AMDGPU_XNACK 0x100 // Indicates if the XNACK target feature is
// enabled for all code contained in the ELF.
// AMDGPU processors
#define EF_AMDGPU_MACH_NONE 0x000 // Unspecified processor.
#define EF_AMDGPU_MACH_R600_R600 0x001
#define EF_AMDGPU_MACH_R600_R630 0x002
#define EF_AMDGPU_MACH_R600_RS880 0x003
#define EF_AMDGPU_MACH_R600_RV670 0x004
#define EF_AMDGPU_MACH_R600_RV710 0x005
#define EF_AMDGPU_MACH_R600_RV730 0x006
#define EF_AMDGPU_MACH_R600_RV770 0x007
#define EF_AMDGPU_MACH_R600_CEDAR 0x008
#define EF_AMDGPU_MACH_R600_CYPRESS 0x009
#define EF_AMDGPU_MACH_R600_JUNIPER 0x00a
#define EF_AMDGPU_MACH_R600_REDWOOD 0x00b
#define EF_AMDGPU_MACH_R600_SUMO 0x00c
#define EF_AMDGPU_MACH_R600_BARTS 0x00d
#define EF_AMDGPU_MACH_R600_CAICOS 0x00e
#define EF_AMDGPU_MACH_R600_CAYMAN 0x00f
#define EF_AMDGPU_MACH_R600_TURKS 0x010
#define EF_AMDGPU_MACH_R600_RESERVED_FIRST 0x011
#define EF_AMDGPU_MACH_R600_RESERVED_LAST 0x01f
#define EF_AMDGPU_MACH_R600_FIRST EF_AMDGPU_MACH_R600_R600
#define EF_AMDGPU_MACH_R600_LAST EF_AMDGPU_MACH_R600_TURKS
#define EF_AMDGPU_MACH_AMDGCN_GFX600 0x020
#define EF_AMDGPU_MACH_AMDGCN_GFX601 0x021
#define EF_AMDGPU_MACH_AMDGCN_GFX700 0x022
#define EF_AMDGPU_MACH_AMDGCN_GFX701 0x023
#define EF_AMDGPU_MACH_AMDGCN_GFX702 0x024
#define EF_AMDGPU_MACH_AMDGCN_GFX703 0x025
#define EF_AMDGPU_MACH_AMDGCN_GFX704 0x026
#define EF_AMDGPU_MACH_AMDGCN_GFX801 0x028
#define EF_AMDGPU_MACH_AMDGCN_GFX802 0x029
#define EF_AMDGPU_MACH_AMDGCN_GFX803 0x02a
#define EF_AMDGPU_MACH_AMDGCN_GFX810 0x02b
#define EF_AMDGPU_MACH_AMDGCN_GFX900 0x02c
#define EF_AMDGPU_MACH_AMDGCN_GFX902 0x02d
#define EF_AMDGPU_MACH_AMDGCN_GFX904 0x02e
#define EF_AMDGPU_MACH_AMDGCN_GFX906 0x02f
#define EF_AMDGPU_MACH_AMDGCN_RESERVED0 0x027
#define EF_AMDGPU_MACH_AMDGCN_RESERVED1 0x030
#define EF_AMDGPU_MACH_AMDGCN_FIRST EF_AMDGPU_MACH_AMDGCN_GFX600
#define EF_AMDGPU_MACH_AMDGCN_LAST EF_AMDGPU_MACH_AMDGCN_GFX906
/////////////////////
// Sections constants
// Section indexes
#define SHN_UNDEF 0
#define SHN_LORESERVE 0xFF00
#define SHN_LOPROC 0xFF00
#define SHN_HIPROC 0xFF1F
#define SHN_LOOS 0xFF20
#define SHN_HIOS 0xFF3F
#define SHN_ABS 0xFFF1
#define SHN_COMMON 0xFFF2
#define SHN_XINDEX 0xFFFF
#define SHN_HIRESERVE 0xFFFF
// Section types
#define SHT_NULL 0
#define SHT_PROGBITS 1
#define SHT_SYMTAB 2
#define SHT_STRTAB 3
#define SHT_RELA 4
#define SHT_HASH 5
#define SHT_DYNAMIC 6
#define SHT_NOTE 7
#define SHT_NOBITS 8
#define SHT_REL 9
#define SHT_SHLIB 10
#define SHT_DYNSYM 11
#define SHT_INIT_ARRAY 14
#define SHT_FINI_ARRAY 15
#define SHT_PREINIT_ARRAY 16
#define SHT_GROUP 17
#define SHT_SYMTAB_SHNDX 18
#define SHT_LOOS 0x60000000
#define SHT_HIOS 0x6fffffff
#define SHT_LOPROC 0x70000000
#define SHT_HIPROC 0x7FFFFFFF
#define SHT_LOUSER 0x80000000
#define SHT_HIUSER 0xFFFFFFFF
// Section attribute flags
#define SHF_WRITE 0x1
#define SHF_ALLOC 0x2
#define SHF_EXECINSTR 0x4
#define SHF_MERGE 0x10
#define SHF_STRINGS 0x20
#define SHF_INFO_LINK 0x40
#define SHF_LINK_ORDER 0x80
#define SHF_OS_NONCONFORMING 0x100
#define SHF_GROUP 0x200
#define SHF_TLS 0x400
#define SHF_MASKOS 0x0ff00000
#define SHF_MASKPROC 0xF0000000
// Section group flags
#define GRP_COMDAT 0x1
#define GRP_MASKOS 0x0ff00000
#define GRP_MASKPROC 0xf0000000
// Symbol binding
#define STB_LOCAL 0
#define STB_GLOBAL 1
#define STB_WEAK 2
#define STB_LOOS 10
#define STB_HIOS 12
#define STB_MULTIDEF 13
#define STB_LOPROC 13
#define STB_HIPROC 15
// Note types
#define NT_AMDGPU_METADATA 1
#define NT_AMD_AMDGPU_HSA_METADATA 10
#define NT_AMD_AMDGPU_ISA 11
#define NT_AMD_AMDGPU_PAL_METADATA 12
// Symbol types
#define STT_NOTYPE 0
#define STT_OBJECT 1
#define STT_FUNC 2
#define STT_SECTION 3
#define STT_FILE 4
#define STT_COMMON 5
#define STT_TLS 6
#define STT_LOOS 10
#define STT_AMDGPU_HSA_KERNEL 10
#define STT_HIOS 12
#define STT_LOPROC 13
#define STT_HIPROC 15
// Symbol visibility
#define STV_DEFAULT 0
#define STV_INTERNAL 1
#define STV_HIDDEN 2
#define STV_PROTECTED 3
// Undefined name
#define STN_UNDEF 0
// Relocation types
#define R_386_NONE 0
#define R_X86_64_NONE 0
#define R_AMDGPU_NONE 0
#define R_386_32 1
#define R_X86_64_64 1
#define R_AMDGPU_ABS32_LO 1
#define R_386_PC32 2
#define R_X86_64_PC32 2
#define R_AMDGPU_ABS32_HI 2
#define R_386_GOT32 3
#define R_X86_64_GOT32 3
#define R_AMDGPU_ABS64 3
#define R_386_PLT32 4
#define R_X86_64_PLT32 4
#define R_AMDGPU_REL32 4
#define R_386_COPY 5
#define R_X86_64_COPY 5
#define R_AMDGPU_REL64 5
#define R_386_GLOB_DAT 6
#define R_X86_64_GLOB_DAT 6
#define R_AMDGPU_ABS32 6
#define R_386_JMP_SLOT 7
#define R_X86_64_JUMP_SLOT 7
#define R_AMDGPU_GOTPCREL 7
#define R_386_RELATIVE 8
#define R_X86_64_RELATIVE 8
#define R_AMDGPU_GOTPCREL32_LO 8
#define R_386_GOTOFF 9
#define R_X86_64_GOTPCREL 9
#define R_AMDGPU_GOTPCREL32_HI 9
#define R_386_GOTPC 10
#define R_X86_64_32 10
#define R_AMDGPU_REL32_LO 10
#define R_386_32PLT 11
#define R_X86_64_32S 11
#define R_AMDGPU_REL32_HI 11
#define R_X86_64_16 12
#define R_X86_64_PC16 13
#define R_AMDGPU_RELATIVE64 13
#define R_386_TLS_TPOFF 14
#define R_X86_64_8 14
#define R_386_TLS_IE 15
#define R_X86_64_PC8 15
#define R_386_TLS_GOTIE 16
#define R_X86_64_DTPMOD64 16
#define R_386_TLS_LE 17
#define R_X86_64_DTPOFF64 17
#define R_386_TLS_GD 18
#define R_X86_64_TPOFF64 18
#define R_386_TLS_LDM 19
#define R_X86_64_TLSGD 19
#define R_386_16 20
#define R_X86_64_TLSLD 20
#define R_386_PC16 21
#define R_X86_64_DTPOFF32 21
#define R_386_8 22
#define R_X86_64_GOTTPOFF 22
#define R_386_PC8 23
#define R_X86_64_TPOFF32 23
#define R_386_TLS_GD_32 24
#define R_X86_64_PC64 24
#define R_386_TLS_GD_PUSH 25
#define R_X86_64_GOTOFF64 25
#define R_386_TLS_GD_CALL 26
#define R_X86_64_GOTPC32 26
#define R_386_TLS_GD_POP 27
#define R_X86_64_GOT64 27
#define R_386_TLS_LDM_32 28
#define R_X86_64_GOTPCREL64 28
#define R_386_TLS_LDM_PUSH 29
#define R_X86_64_GOTPC64 29
#define R_386_TLS_LDM_CALL 30
#define R_X86_64_GOTPLT64 30
#define R_386_TLS_LDM_POP 31
#define R_X86_64_PLTOFF64 31
#define R_386_TLS_LDO_32 32
#define R_386_TLS_IE_32 33
#define R_386_TLS_LE_32 34
#define R_X86_64_GOTPC32_TLSDESC 34
#define R_386_TLS_DTPMOD32 35
#define R_X86_64_TLSDESC_CALL 35
#define R_386_TLS_DTPOFF32 36
#define R_X86_64_TLSDESC 36
#define R_386_TLS_TPOFF32 37
#define R_X86_64_IRELATIVE 37
#define R_386_SIZE32 38
#define R_386_TLS_GOTDESC 39
#define R_386_TLS_DESC_CALL 40
#define R_386_TLS_DESC 41
#define R_386_IRELATIVE 42
#define R_386_GOT32X 43
#define R_X86_64_GNU_VTINHERIT 250
#define R_X86_64_GNU_VTENTRY 251
// Segment types
#define PT_NULL 0
#define PT_LOAD 1
#define PT_DYNAMIC 2
#define PT_INTERP 3
#define PT_NOTE 4
#define PT_SHLIB 5
#define PT_PHDR 6
#define PT_TLS 7
#define PT_LOOS 0x60000000
#define PT_HIOS 0x6fffffff
#define PT_LOPROC 0x70000000
#define PT_HIPROC 0x7FFFFFFF
// Segment flags
#define PF_X 1 // Execute
#define PF_W 2 // Write
#define PF_R 4 // Read
#define PF_MASKOS 0x0ff00000 // Unspecified
#define PF_MASKPROC 0xf0000000 // Unspecified
// Dynamic Array Tags
#define DT_NULL 0
#define DT_NEEDED 1
#define DT_PLTRELSZ 2
#define DT_PLTGOT 3
#define DT_HASH 4
#define DT_STRTAB 5
#define DT_SYMTAB 6
#define DT_RELA 7
#define DT_RELASZ 8
#define DT_RELAENT 9
#define DT_STRSZ 10
#define DT_SYMENT 11
#define DT_INIT 12
#define DT_FINI 13
#define DT_SONAME 14
#define DT_RPATH 15
#define DT_SYMBOLIC 16
#define DT_REL 17
#define DT_RELSZ 18
#define DT_RELENT 19
#define DT_PLTREL 20
#define DT_DEBUG 21
#define DT_TEXTREL 22
#define DT_JMPREL 23
#define DT_BIND_NOW 24
#define DT_INIT_ARRAY 25
#define DT_FINI_ARRAY 26
#define DT_INIT_ARRAYSZ 27
#define DT_FINI_ARRAYSZ 28
#define DT_RUNPATH 29
#define DT_FLAGS 30
#define DT_ENCODING 32
#define DT_PREINIT_ARRAY 32
#define DT_PREINIT_ARRAYSZ 33
#define DT_MAXPOSTAGS 34
#define DT_LOOS 0x6000000D
#define DT_HIOS 0x6ffff000
#define DT_LOPROC 0x70000000
#define DT_HIPROC 0x7FFFFFFF
// DT_FLAGS values
#define DF_ORIGIN 0x1
#define DF_SYMBOLIC 0x2
#define DF_TEXTREL 0x4
#define DF_BIND_NOW 0x8
#define DF_STATIC_TLS 0x10
// ELF file header
struct Elf32_Ehdr {
unsigned char e_ident[EI_NIDENT];
Elf_Half e_type;
Elf_Half e_machine;
Elf_Word e_version;
Elf32_Addr e_entry;
Elf32_Off e_phoff;
Elf32_Off e_shoff;
Elf_Word e_flags;
Elf_Half e_ehsize;
Elf_Half e_phentsize;
Elf_Half e_phnum;
Elf_Half e_shentsize;
Elf_Half e_shnum;
Elf_Half e_shstrndx;
};
struct Elf64_Ehdr {
unsigned char e_ident[EI_NIDENT];
Elf_Half e_type;
Elf_Half e_machine;
Elf_Word e_version;
Elf64_Addr e_entry;
Elf64_Off e_phoff;
Elf64_Off e_shoff;
Elf_Word e_flags;
Elf_Half e_ehsize;
Elf_Half e_phentsize;
Elf_Half e_phnum;
Elf_Half e_shentsize;
Elf_Half e_shnum;
Elf_Half e_shstrndx;
};
// Section header
struct Elf32_Shdr {
Elf_Word sh_name;
Elf_Word sh_type;
Elf_Word sh_flags;
Elf32_Addr sh_addr;
Elf32_Off sh_offset;
Elf_Word sh_size;
Elf_Word sh_link;
Elf_Word sh_info;
Elf_Word sh_addralign;
Elf_Word sh_entsize;
};
struct Elf64_Shdr {
Elf_Word sh_name;
Elf_Word sh_type;
Elf_Xword sh_flags;
Elf64_Addr sh_addr;
Elf64_Off sh_offset;
Elf_Xword sh_size;
Elf_Word sh_link;
Elf_Word sh_info;
Elf_Xword sh_addralign;
Elf_Xword sh_entsize;
};
// Segment header
struct Elf32_Phdr {
Elf_Word p_type;
Elf32_Off p_offset;
Elf32_Addr p_vaddr;
Elf32_Addr p_paddr;
Elf_Word p_filesz;
Elf_Word p_memsz;
Elf_Word p_flags;
Elf_Word p_align;
};
struct Elf64_Phdr {
Elf_Word p_type;
Elf_Word p_flags;
Elf64_Off p_offset;
Elf64_Addr p_vaddr;
Elf64_Addr p_paddr;
Elf_Xword p_filesz;
Elf_Xword p_memsz;
Elf_Xword p_align;
};
// Symbol table entry
struct Elf32_Sym {
Elf_Word st_name;
Elf32_Addr st_value;
Elf_Word st_size;
unsigned char st_info;
unsigned char st_other;
Elf_Half st_shndx;
};
struct Elf64_Sym {
Elf_Word st_name;
unsigned char st_info;
unsigned char st_other;
Elf_Half st_shndx;
Elf64_Addr st_value;
Elf_Xword st_size;
};
#define ELF_ST_BIND(i) ((i)>>4)
#define ELF_ST_TYPE(i) ((i)&0xf)
#define ELF_ST_INFO(b,t) (((b)<<4)+((t)&0xf))
#define ELF_ST_VISIBILITY(o) ((o)&0x3)
// Relocation entries
struct Elf32_Rel {
Elf32_Addr r_offset;
Elf_Word r_info;
};
struct Elf32_Rela {
Elf32_Addr r_offset;
Elf_Word r_info;
Elf_Sword r_addend;
};
struct Elf64_Rel {
Elf64_Addr r_offset;
Elf_Xword r_info;
};
struct Elf64_Rela {
Elf64_Addr r_offset;
Elf_Xword r_info;
Elf_Sxword r_addend;
};
#define ELF32_R_SYM(i) ((i)>>8)
#define ELF32_R_TYPE(i) ((unsigned char)(i))
#define ELF32_R_INFO(s,t) (((s)<<8 )+(unsigned char)(t))
#define ELF64_R_SYM(i) ((i)>>32)
#define ELF64_R_TYPE(i) ((i)&0xffffffffL)
#define ELF64_R_INFO(s,t) ((((int64_t)(s))<<32)+((t)&0xffffffffL))
// Dynamic structure
struct Elf32_Dyn {
Elf_Sword d_tag;
union {
Elf_Word d_val;
Elf32_Addr d_ptr;
} d_un;
};
struct Elf64_Dyn {
Elf_Sxword d_tag;
union {
Elf_Xword d_val;
Elf64_Addr d_ptr;
} d_un;
};
} // namespace ELFIO
#endif // ELFTYPES_H

View File

@ -1,955 +0,0 @@
/*
Copyright (C) 2001-2015 by Serge Lamikhov-Center
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef ELFIO_HPP
#define ELFIO_HPP
#ifdef _MSC_VER
#pragma warning ( push )
#pragma warning(disable:4996)
#pragma warning(disable:4355)
#pragma warning(disable:4244)
#endif
#include <string>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <deque>
#include <iterator>
#include <typeinfo>
#include <elfio/elf_types.hpp>
#include <elfio/elfio_utils.hpp>
#include <elfio/elfio_header.hpp>
#include <elfio/elfio_section.hpp>
#include <elfio/elfio_segment.hpp>
#include <elfio/elfio_strings.hpp>
#define ELFIO_HEADER_ACCESS_GET( TYPE, FNAME ) \
TYPE \
get_##FNAME() const \
{ \
return header? header->get_##FNAME() : 0; \
}
#define ELFIO_HEADER_ACCESS_GET_SET( TYPE, FNAME ) \
TYPE \
get_##FNAME() const \
{ \
return header? header->get_##FNAME() : 0; \
} \
void \
set_##FNAME( TYPE val ) \
{ \
if (header) { \
header->set_##FNAME( val ); \
} \
} \
namespace ELFIO {
//------------------------------------------------------------------------------
class elfio
{
public:
//------------------------------------------------------------------------------
elfio() : sections( this ), segments( this )
{
header = 0;
current_file_pos = 0;
create( ELFCLASS32, ELFDATA2LSB );
}
//------------------------------------------------------------------------------
~elfio()
{
clean();
}
//------------------------------------------------------------------------------
void create( unsigned char file_class, unsigned char encoding )
{
clean();
convertor.setup( encoding );
header = create_header( file_class, encoding );
create_mandatory_sections();
}
//------------------------------------------------------------------------------
bool load( const std::string& file_name )
{
std::ifstream stream;
stream.open( file_name.c_str(), std::ios::in | std::ios::binary );
if ( !stream ) {
return false;
}
return load(stream);
}
//------------------------------------------------------------------------------
bool load( std::istream &stream )
{
clean();
unsigned char e_ident[EI_NIDENT];
// Read ELF file signature
stream.read( reinterpret_cast<char*>( &e_ident ), sizeof( e_ident ) );
// Is it ELF file?
if ( stream.gcount() != sizeof( e_ident ) ||
e_ident[EI_MAG0] != ELFMAG0 ||
e_ident[EI_MAG1] != ELFMAG1 ||
e_ident[EI_MAG2] != ELFMAG2 ||
e_ident[EI_MAG3] != ELFMAG3 ) {
return false;
}
if ( ( e_ident[EI_CLASS] != ELFCLASS64 ) &&
( e_ident[EI_CLASS] != ELFCLASS32 )) {
return false;
}
convertor.setup( e_ident[EI_DATA] );
header = create_header( e_ident[EI_CLASS], e_ident[EI_DATA] );
if ( 0 == header ) {
return false;
}
if ( !header->load( stream ) ) {
return false;
}
load_sections( stream );
bool is_still_good = load_segments( stream );
return is_still_good;
}
//------------------------------------------------------------------------------
bool save( const std::string& file_name )
{
std::ofstream stream;
stream.open( file_name.c_str(), std::ios::out | std::ios::binary );
if ( !stream ) {
return false;
}
return save(stream);
}
//------------------------------------------------------------------------------
bool save( std::ostream &stream )
{
if ( !stream || !header) {
return false;
}
bool is_still_good = true;
// Define layout specific header fields
// The position of the segment table is fixed after the header.
// The position of the section table is variable and needs to be fixed
// before saving.
header->set_segments_num( segments.size() );
header->set_segments_offset( segments.size() ? header->get_header_size() : 0 );
header->set_sections_num( sections.size() );
header->set_sections_offset( 0 );
// Layout the first section right after the segment table
current_file_pos = header->get_header_size() +
header->get_segment_entry_size() * header->get_segments_num();
calc_segment_alignment();
is_still_good = layout_segments_and_their_sections();
is_still_good = is_still_good && layout_sections_without_segments();
is_still_good = is_still_good && layout_section_table();
is_still_good = is_still_good && save_header( stream );
is_still_good = is_still_good && save_sections( stream );
is_still_good = is_still_good && save_segments( stream );
return is_still_good;
}
//------------------------------------------------------------------------------
// ELF header access functions
ELFIO_HEADER_ACCESS_GET( unsigned char, class );
ELFIO_HEADER_ACCESS_GET( unsigned char, elf_version );
ELFIO_HEADER_ACCESS_GET( unsigned char, encoding );
ELFIO_HEADER_ACCESS_GET( Elf_Word, version );
ELFIO_HEADER_ACCESS_GET( Elf_Half, header_size );
ELFIO_HEADER_ACCESS_GET( Elf_Half, section_entry_size );
ELFIO_HEADER_ACCESS_GET( Elf_Half, segment_entry_size );
ELFIO_HEADER_ACCESS_GET_SET( unsigned char, os_abi );
ELFIO_HEADER_ACCESS_GET_SET( unsigned char, abi_version );
ELFIO_HEADER_ACCESS_GET_SET( Elf_Half, type );
ELFIO_HEADER_ACCESS_GET_SET( Elf_Half, machine );
ELFIO_HEADER_ACCESS_GET_SET( Elf_Word, flags );
ELFIO_HEADER_ACCESS_GET_SET( Elf64_Addr, entry );
ELFIO_HEADER_ACCESS_GET_SET( Elf64_Off, sections_offset );
ELFIO_HEADER_ACCESS_GET_SET( Elf64_Off, segments_offset );
ELFIO_HEADER_ACCESS_GET_SET( Elf_Half, section_name_str_index );
//------------------------------------------------------------------------------
const endianess_convertor& get_convertor() const
{
return convertor;
}
//------------------------------------------------------------------------------
Elf_Xword get_default_entry_size( Elf_Word section_type ) const
{
switch( section_type ) {
case SHT_RELA:
if ( header->get_class() == ELFCLASS64 ) {
return sizeof( Elf64_Rela );
}
else {
return sizeof( Elf32_Rela );
}
case SHT_REL:
if ( header->get_class() == ELFCLASS64 ) {
return sizeof( Elf64_Rel );
}
else {
return sizeof( Elf32_Rel );
}
case SHT_SYMTAB:
if ( header->get_class() == ELFCLASS64 ) {
return sizeof( Elf64_Sym );
}
else {
return sizeof( Elf32_Sym );
}
case SHT_DYNAMIC:
if ( header->get_class() == ELFCLASS64 ) {
return sizeof( Elf64_Dyn );
}
else {
return sizeof( Elf32_Dyn );
}
default:
return 0;
}
}
//------------------------------------------------------------------------------
private:
bool is_offset_in_section( Elf64_Off offset, const section* sec ) const {
return offset >= sec->get_offset() && offset < sec->get_offset()+sec->get_size();
}
//------------------------------------------------------------------------------
public:
//! returns an empty string if no problems are detected,
//! or a string containing an error message if problems are found
std::string validate() const {
// check for overlapping sections in the file
for ( int i = 0; i < sections.size(); ++i) {
for ( int j = i+1; j < sections.size(); ++j ) {
const section* a = sections[i];
const section* b = sections[j];
if ( !(a->get_type() & SHT_NOBITS)
&& !(b->get_type() & SHT_NOBITS)
&& (a->get_size() > 0)
&& (b->get_size() > 0)
&& (a->get_offset() > 0)
&& (b->get_offset() > 0)) {
if ( is_offset_in_section( a->get_offset(), b )
|| is_offset_in_section( a->get_offset()+a->get_size()-1, b )
|| is_offset_in_section( b->get_offset(), a )
|| is_offset_in_section( b->get_offset()+b->get_size()-1, a )) {
return "Sections " + a->get_name() + " and " + b->get_name() + " overlap in file";
}
}
}
}
// more checks to be added here...
return "";
}
//------------------------------------------------------------------------------
private:
//------------------------------------------------------------------------------
void clean()
{
delete header;
header = 0;
std::vector<section*>::const_iterator it;
for ( it = sections_.begin(); it != sections_.end(); ++it ) {
delete *it;
}
sections_.clear();
std::vector<segment*>::const_iterator it1;
for ( it1 = segments_.begin(); it1 != segments_.end(); ++it1 ) {
delete *it1;
}
segments_.clear();
}
//------------------------------------------------------------------------------
elf_header* create_header( unsigned char file_class, unsigned char encoding )
{
elf_header* new_header = 0;
if ( file_class == ELFCLASS64 ) {
new_header = new elf_header_impl< Elf64_Ehdr >( &convertor,
encoding );
}
else if ( file_class == ELFCLASS32 ) {
new_header = new elf_header_impl< Elf32_Ehdr >( &convertor,
encoding );
}
else {
return 0;
}
return new_header;
}
//------------------------------------------------------------------------------
section* create_section()
{
section* new_section;
unsigned char file_class = get_class();
if ( file_class == ELFCLASS64 ) {
new_section = new section_impl<Elf64_Shdr>( &convertor );
}
else if ( file_class == ELFCLASS32 ) {
new_section = new section_impl<Elf32_Shdr>( &convertor );
}
else {
return 0;
}
new_section->set_index( (Elf_Half)sections_.size() );
sections_.push_back( new_section );
return new_section;
}
//------------------------------------------------------------------------------
segment* create_segment()
{
segment* new_segment;
unsigned char file_class = header->get_class();
if ( file_class == ELFCLASS64 ) {
new_segment = new segment_impl<Elf64_Phdr>( &convertor );
}
else if ( file_class == ELFCLASS32 ) {
new_segment = new segment_impl<Elf32_Phdr>( &convertor );
}
else {
return 0;
}
new_segment->set_index( (Elf_Half)segments_.size() );
segments_.push_back( new_segment );
return new_segment;
}
//------------------------------------------------------------------------------
void create_mandatory_sections()
{
// Create null section without calling to 'add_section' as no string
// section containing section names exists yet
section* sec0 = create_section();
sec0->set_index( 0 );
sec0->set_name( "" );
sec0->set_name_string_offset( 0 );
set_section_name_str_index( 1 );
section* shstrtab = sections.add( ".shstrtab" );
shstrtab->set_type( SHT_STRTAB );
shstrtab->set_addr_align( 1 );
}
//------------------------------------------------------------------------------
Elf_Half load_sections( std::istream& stream )
{
Elf_Half entry_size = header->get_section_entry_size();
Elf_Half num = header->get_sections_num();
Elf64_Off offset = header->get_sections_offset();
for ( Elf_Half i = 0; i < num; ++i ) {
section* sec = create_section();
sec->load( stream, (std::streamoff)offset + i * entry_size );
sec->set_index( i );
// To mark that the section is not permitted to reassign address
// during layout calculation
sec->set_address( sec->get_address() );
}
Elf_Half shstrndx = get_section_name_str_index();
if ( SHN_UNDEF != shstrndx ) {
string_section_accessor str_reader( sections[shstrndx] );
for ( Elf_Half i = 0; i < num; ++i ) {
Elf_Word section_offset = sections[i]->get_name_string_offset();
const char* p = str_reader.get_string( section_offset );
if ( p != 0 ) {
sections[i]->set_name( p );
}
}
}
return num;
}
//------------------------------------------------------------------------------
//! Checks whether the addresses of the section entirely fall within the given segment.
//! It doesn't matter if the addresses are memory addresses, or file offsets,
//! they just need to be in the same address space
bool is_sect_in_seg ( Elf64_Off sect_begin, Elf_Xword sect_size, Elf64_Off seg_begin, Elf64_Off seg_end ) {
return seg_begin <= sect_begin
&& sect_begin + sect_size <= seg_end
&& sect_begin < seg_end; // this is important criteria when sect_size == 0
// Example: seg_begin=10, seg_end=12 (-> covering the bytes 10 and 11)
// sect_begin=12, sect_size=0 -> shall return false!
}
//------------------------------------------------------------------------------
bool load_segments( std::istream& stream )
{
Elf_Half entry_size = header->get_segment_entry_size();
Elf_Half num = header->get_segments_num();
Elf64_Off offset = header->get_segments_offset();
for ( Elf_Half i = 0; i < num; ++i ) {
segment* seg;
unsigned char file_class = header->get_class();
if ( file_class == ELFCLASS64 ) {
seg = new segment_impl<Elf64_Phdr>( &convertor );
}
else if ( file_class == ELFCLASS32 ) {
seg = new segment_impl<Elf32_Phdr>( &convertor );
}
else {
return false;
}
seg->load( stream, (std::streamoff)offset + i * entry_size );
seg->set_index( i );
// Add sections to the segments (similar to readelfs algorithm)
Elf64_Off segBaseOffset = seg->get_offset();
Elf64_Off segEndOffset = segBaseOffset + seg->get_file_size();
Elf64_Off segVBaseAddr = seg->get_virtual_address();
Elf64_Off segVEndAddr = segVBaseAddr + seg->get_memory_size();
for( Elf_Half j = 0; j < sections.size(); ++j ) {
const section* psec = sections[j];
// SHF_ALLOC sections are matched based on the virtual address
// otherwise the file offset is matched
if( psec->get_flags() & SHF_ALLOC
? is_sect_in_seg( psec->get_address(), psec->get_size(), segVBaseAddr, segVEndAddr )
: is_sect_in_seg( psec->get_offset(), psec->get_size(), segBaseOffset, segEndOffset )) {
// Alignment of segment shall not be updated, to preserve original value
// It will be re-calculated on saving.
seg->add_section_index( psec->get_index(), 0 );
}
}
// Add section into the segments' container
segments_.push_back( seg );
}
return true;
}
//------------------------------------------------------------------------------
bool save_header( std::ostream& stream )
{
return header->save( stream );
}
//------------------------------------------------------------------------------
bool save_sections( std::ostream& stream )
{
for ( unsigned int i = 0; i < sections_.size(); ++i ) {
section *sec = sections_.at(i);
std::streampos headerPosition =
(std::streamoff)header->get_sections_offset() +
header->get_section_entry_size() * sec->get_index();
sec->save(stream,headerPosition,sec->get_offset());
}
return true;
}
//------------------------------------------------------------------------------
bool save_segments( std::ostream& stream )
{
for ( unsigned int i = 0; i < segments_.size(); ++i ) {
segment *seg = segments_.at(i);
std::streampos headerPosition = header->get_segments_offset() +
header->get_segment_entry_size()*seg->get_index();
seg->save( stream, headerPosition, seg->get_offset() );
}
return true;
}
//------------------------------------------------------------------------------
bool is_section_without_segment( unsigned int section_index )
{
bool found = false;
for ( unsigned int j = 0; !found && ( j < segments.size() ); ++j ) {
for ( unsigned int k = 0;
!found && ( k < segments[j]->get_sections_num() );
++k ) {
found = segments[j]->get_section_index_at( k ) == section_index;
}
}
return !found;
}
//------------------------------------------------------------------------------
bool is_subsequence_of( segment* seg1, segment* seg2 )
{
// Return 'true' if sections of seg1 are a subset of sections in seg2
const std::vector<Elf_Half>& sections1 = seg1->get_sections();
const std::vector<Elf_Half>& sections2 = seg2->get_sections();
bool found = false;
if ( sections1.size() < sections2.size() ) {
found = std::includes( sections2.begin(), sections2.end(),
sections1.begin(), sections1.end() );
}
return found;
}
//------------------------------------------------------------------------------
std::vector<segment*> get_ordered_segments( )
{
std::vector<segment*> res;
std::deque<segment*> worklist;
res.reserve(segments.size());
std::copy( segments_.begin(), segments_.end(),
std::back_inserter( worklist )) ;
// Bring the segments which start at address 0 to the front
size_t nextSlot = 0;
for( size_t i = 0; i < worklist.size(); ++i ) {
if( i != nextSlot && worklist[i]->is_offset_initialized()
&& worklist[i]->get_offset() == 0 ) {
if (worklist[nextSlot]->get_offset() == 0) {
++nextSlot;
}
std::swap(worklist[i],worklist[nextSlot]);
++nextSlot;
}
}
while ( !worklist.empty() ) {
segment *seg = worklist.front();
worklist.pop_front();
size_t i = 0;
for ( ; i < worklist.size(); ++i ) {
if ( is_subsequence_of( seg, worklist[i] ) ) {
break;
}
}
if ( i < worklist.size() )
worklist.push_back(seg);
else
res.push_back(seg);
}
return res;
}
//------------------------------------------------------------------------------
bool layout_sections_without_segments( )
{
for ( unsigned int i = 0; i < sections_.size(); ++i ) {
if ( is_section_without_segment( i ) ) {
section *sec = sections_[i];
Elf_Xword section_align = sec->get_addr_align();
if ( section_align > 1 && current_file_pos % section_align != 0 ) {
current_file_pos += section_align -
current_file_pos % section_align;
}
if ( 0 != sec->get_index() )
sec->set_offset(current_file_pos);
if ( SHT_NOBITS != sec->get_type() &&
SHT_NULL != sec->get_type() ) {
current_file_pos += sec->get_size();
}
}
}
return true;
}
//------------------------------------------------------------------------------
void calc_segment_alignment( )
{
for( std::vector<segment*>::iterator s = segments_.begin(); s != segments_.end(); ++s ) {
segment* seg = *s;
for ( int i = 0; i < seg->get_sections_num(); ++i ) {
section* sect = sections_[ seg->get_section_index_at(i) ];
if ( sect->get_addr_align() > seg->get_align() ) {
seg->set_align( sect->get_addr_align() );
}
}
}
}
//------------------------------------------------------------------------------
bool layout_segments_and_their_sections( )
{
std::vector<segment*> worklist;
std::vector<bool> section_generated(sections.size(),false);
// Get segments in a order in where segments which contain a
// sub sequence of other segments are located at the end
worklist = get_ordered_segments();
for ( unsigned int i = 0; i < worklist.size(); ++i ) {
Elf_Xword segment_memory = 0;
Elf_Xword segment_filesize = 0;
Elf_Xword seg_start_pos = current_file_pos;
segment* seg = worklist[i];
// Special case: PHDR segment
// This segment contains the program headers but no sections
if ( seg->get_type() == PT_PHDR && seg->get_sections_num() == 0 ) {
seg_start_pos = header->get_segments_offset();
segment_memory = segment_filesize =
header->get_segment_entry_size() * header->get_segments_num();
}
// Special case:
// Segments which start with the NULL section and have further sections
else if ( seg->get_sections_num() > 1
&& sections[seg->get_section_index_at( 0 )]->get_type() == SHT_NULL ) {
seg_start_pos = 0;
if ( seg->get_sections_num() ) {
segment_memory = segment_filesize = current_file_pos;
}
}
// New segments with not generated sections
// have to be aligned
else if ( seg->get_sections_num()
&& !section_generated[seg->get_section_index_at( 0 )] ) {
Elf_Xword align = seg->get_align() > 0 ? seg->get_align() : 1;
Elf64_Off cur_page_alignment = current_file_pos % align;
Elf64_Off req_page_alignment = seg->get_virtual_address() % align;
Elf64_Off error = req_page_alignment - cur_page_alignment;
current_file_pos += ( seg->get_align() + error ) % align;
seg_start_pos = current_file_pos;
}
else if ( seg->get_sections_num() ) {
seg_start_pos = sections[seg->get_section_index_at( 0 )]->get_offset();
}
// Write segment's data
for ( unsigned int j = 0; j < seg->get_sections_num(); ++j ) {
Elf_Half index = seg->get_section_index_at( j );
section* sec = sections[ index ];
// The NULL section is always generated
if ( SHT_NULL == sec->get_type()) {
section_generated[index] = true;
continue;
}
Elf_Xword secAlign = 0;
// Fix up the alignment
if ( !section_generated[index] && sec->is_address_initialized()
&& SHT_NOBITS != sec->get_type()
&& SHT_NULL != sec->get_type()
&& 0 != sec->get_size() ) {
// Align the sections based on the virtual addresses
// when possible (this is what matters for execution)
Elf64_Off req_offset = sec->get_address() - seg->get_virtual_address();
Elf64_Off cur_offset = current_file_pos - seg_start_pos;
if ( req_offset < cur_offset) {
// something has gone awfully wrong, abort!
// secAlign would turn out negative, seeking backwards and overwriting previous data
return false;
}
secAlign = req_offset - cur_offset;
}
else if (!section_generated[index] && !sec->is_address_initialized() ) {
// If no address has been specified then only the section
// alignment constraint has to be matched
Elf_Xword align = sec->get_addr_align();
if (align == 0) {
align = 1;
}
Elf64_Off error = current_file_pos % align;
secAlign = ( align - error ) % align;
}
else if (section_generated[index] ) {
// Alignment for already generated sections
secAlign = sec->get_offset() - seg_start_pos - segment_filesize;
}
// Determine the segment file and memory sizes
// Special case .tbss section (NOBITS) in non TLS segment
if ( (sec->get_flags() & SHF_ALLOC)
&& !( (sec->get_flags() & SHF_TLS) && (seg->get_type() != PT_TLS)
&& ( SHT_NOBITS == sec->get_type())) )
segment_memory += sec->get_size() + secAlign;
if ( SHT_NOBITS != sec->get_type() && SHT_NULL != sec->get_type() )
segment_filesize += sec->get_size() + secAlign;
// Nothing to be done when generating nested segments
if(section_generated[index]) {
continue;
}
current_file_pos += secAlign;
// Set the section addresses when missing
if ( !sec->is_address_initialized() )
sec->set_address( seg->get_virtual_address()
+ current_file_pos - seg_start_pos);
if ( 0 != sec->get_index() )
sec->set_offset(current_file_pos);
if ( SHT_NOBITS != sec->get_type() && SHT_NULL != sec->get_type() )
current_file_pos += sec->get_size();
section_generated[index] = true;
}
seg->set_file_size( segment_filesize );
// If we already have a memory size from loading an elf file (value > 0),
// it must not shrink!
// Memory size may be bigger than file size and it is the loader's job to do something
// with the surplus bytes in memory, like initializing them with a defined value.
if ( seg->get_memory_size() < segment_memory ) {
seg->set_memory_size( segment_memory );
}
seg->set_offset(seg_start_pos);
}
return true;
}
//------------------------------------------------------------------------------
bool layout_section_table()
{
// Simply place the section table at the end for now
Elf64_Off alignmentError = current_file_pos % 4;
current_file_pos += ( 4 - alignmentError ) % 4;
header->set_sections_offset(current_file_pos);
return true;
}
//------------------------------------------------------------------------------
public:
friend class Sections;
class Sections {
public:
//------------------------------------------------------------------------------
Sections( elfio* parent_ ) :
parent( parent_ )
{
}
//------------------------------------------------------------------------------
Elf_Half size() const
{
return (Elf_Half)parent->sections_.size();
}
//------------------------------------------------------------------------------
section* operator[]( unsigned int index ) const
{
section* sec = 0;
if ( index < parent->sections_.size() ) {
sec = parent->sections_[index];
}
return sec;
}
//------------------------------------------------------------------------------
section* operator[]( const std::string& name ) const
{
section* sec = 0;
std::vector<section*>::const_iterator it;
for ( it = parent->sections_.begin();
it != parent->sections_.end();
++it ) {
if ( (*it)->get_name() == name ) {
sec = *it;
break;
}
}
return sec;
}
//------------------------------------------------------------------------------
section* add( const std::string& name )
{
section* new_section = parent->create_section();
new_section->set_name( name );
Elf_Half str_index = parent->get_section_name_str_index();
section* string_table( parent->sections_[str_index] );
string_section_accessor str_writer( string_table );
Elf_Word pos = str_writer.add_string( name );
new_section->set_name_string_offset( pos );
return new_section;
}
//------------------------------------------------------------------------------
std::vector<section*>::iterator begin() {
return parent->sections_.begin();
}
//------------------------------------------------------------------------------
std::vector<section*>::iterator end() {
return parent->sections_.end();
}
//------------------------------------------------------------------------------
std::vector<section*>::const_iterator begin() const {
return parent->sections_.cbegin();
}
//------------------------------------------------------------------------------
std::vector<section*>::const_iterator end() const {
return parent->sections_.cend();
}
//------------------------------------------------------------------------------
private:
elfio* parent;
} sections;
//------------------------------------------------------------------------------
public:
friend class Segments;
class Segments {
public:
//------------------------------------------------------------------------------
Segments( elfio* parent_ ) :
parent( parent_ )
{
}
//------------------------------------------------------------------------------
Elf_Half size() const
{
return (Elf_Half)parent->segments_.size();
}
//------------------------------------------------------------------------------
segment* operator[]( unsigned int index ) const
{
return parent->segments_[index];
}
//------------------------------------------------------------------------------
segment* add()
{
return parent->create_segment();
}
//------------------------------------------------------------------------------
std::vector<segment*>::iterator begin() {
return parent->segments_.begin();
}
//------------------------------------------------------------------------------
std::vector<segment*>::iterator end() {
return parent->segments_.end();
}
//------------------------------------------------------------------------------
std::vector<segment*>::const_iterator begin() const {
return parent->segments_.cbegin();
}
//------------------------------------------------------------------------------
std::vector<segment*>::const_iterator end() const {
return parent->segments_.cend();
}
//------------------------------------------------------------------------------
private:
elfio* parent;
} segments;
//------------------------------------------------------------------------------
private:
elf_header* header;
std::vector<section*> sections_;
std::vector<segment*> segments_;
endianess_convertor convertor;
Elf_Xword current_file_pos;
};
} // namespace ELFIO
#include <elfio/elfio_symbols.hpp>
#include <elfio/elfio_note.hpp>
#include <elfio/elfio_relocation.hpp>
#include <elfio/elfio_dynamic.hpp>
#ifdef _MSC_VER
#pragma warning ( pop )
#endif
#endif // ELFIO_HPP

View File

@ -1,976 +0,0 @@
/*
Copyright (C) 2001-2015 by Serge Lamikhov-Center
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef ELFIO_DUMP_HPP
#define ELFIO_DUMP_HPP
#include <algorithm>
#include <string>
#include <ostream>
#include <sstream>
#include <iomanip>
#include <elfio/elfio.hpp>
namespace ELFIO {
static struct class_table_t {
const char key;
const char* str;
} class_table [] =
{
{ ELFCLASS32, "ELF32" },
{ ELFCLASS64, "ELF64" },
};
static struct endian_table_t {
const char key;
const char* str;
} endian_table [] =
{
{ ELFDATANONE, "None" },
{ ELFDATA2LSB, "Little endian" },
{ ELFDATA2MSB, "Big endian" },
};
static struct version_table_t {
const Elf64_Word key;
const char* str;
} version_table [] =
{
{ EV_NONE , "None" },
{ EV_CURRENT, "Current" },
};
static struct type_table_t {
const Elf32_Half key;
const char* str;
} type_table [] =
{
{ ET_NONE, "No file type" },
{ ET_REL , "Relocatable file" },
{ ET_EXEC, "Executable file" },
{ ET_DYN , "Shared object file" },
{ ET_CORE, "Core file" },
};
static struct machine_table_t {
const Elf64_Half key;
const char* str;
} machine_table [] =
{
{ EM_NONE , "No machine" },
{ EM_M32 , "AT&T WE 32100" },
{ EM_SPARC , "SUN SPARC" },
{ EM_386 , "Intel 80386" },
{ EM_68K , "Motorola m68k family" },
{ EM_88K , "Motorola m88k family" },
{ EM_486 , "Intel 80486// Reserved for future use" },
{ EM_860 , "Intel 80860" },
{ EM_MIPS , "MIPS R3000 (officially, big-endian only)" },
{ EM_S370 , "IBM System/370" },
{ EM_MIPS_RS3_LE , "MIPS R3000 little-endian (Oct 4 1999 Draft) Deprecated" },
{ EM_res011 , "Reserved" },
{ EM_res012 , "Reserved" },
{ EM_res013 , "Reserved" },
{ EM_res014 , "Reserved" },
{ EM_PARISC , "HPPA" },
{ EM_res016 , "Reserved" },
{ EM_VPP550 , "Fujitsu VPP500" },
{ EM_SPARC32PLUS , "Sun's v8plus" },
{ EM_960 , "Intel 80960" },
{ EM_PPC , "PowerPC" },
{ EM_PPC64 , "64-bit PowerPC" },
{ EM_S390 , "IBM S/390" },
{ EM_SPU , "Sony/Toshiba/IBM SPU" },
{ EM_res024 , "Reserved" },
{ EM_res025 , "Reserved" },
{ EM_res026 , "Reserved" },
{ EM_res027 , "Reserved" },
{ EM_res028 , "Reserved" },
{ EM_res029 , "Reserved" },
{ EM_res030 , "Reserved" },
{ EM_res031 , "Reserved" },
{ EM_res032 , "Reserved" },
{ EM_res033 , "Reserved" },
{ EM_res034 , "Reserved" },
{ EM_res035 , "Reserved" },
{ EM_V800 , "NEC V800 series" },
{ EM_FR20 , "Fujitsu FR20" },
{ EM_RH32 , "TRW RH32" },
{ EM_MCORE , "Motorola M*Core // May also be taken by Fujitsu MMA" },
{ EM_RCE , "Old name for MCore" },
{ EM_ARM , "ARM" },
{ EM_OLD_ALPHA , "Digital Alpha" },
{ EM_SH , "Renesas (formerly Hitachi) / SuperH SH" },
{ EM_SPARCV9 , "SPARC v9 64-bit" },
{ EM_TRICORE , "Siemens Tricore embedded processor" },
{ EM_ARC , "ARC Cores" },
{ EM_H8_300 , "Renesas (formerly Hitachi) H8/300" },
{ EM_H8_300H , "Renesas (formerly Hitachi) H8/300H" },
{ EM_H8S , "Renesas (formerly Hitachi) H8S" },
{ EM_H8_500 , "Renesas (formerly Hitachi) H8/500" },
{ EM_IA_64 , "Intel IA-64 Processor" },
{ EM_MIPS_X , "Stanford MIPS-X" },
{ EM_COLDFIRE , "Motorola Coldfire" },
{ EM_68HC12 , "Motorola M68HC12" },
{ EM_MMA , "Fujitsu Multimedia Accelerator" },
{ EM_PCP , "Siemens PCP" },
{ EM_NCPU , "Sony nCPU embedded RISC processor" },
{ EM_NDR1 , "Denso NDR1 microprocesspr" },
{ EM_STARCORE , "Motorola Star*Core processor" },
{ EM_ME16 , "Toyota ME16 processor" },
{ EM_ST100 , "STMicroelectronics ST100 processor" },
{ EM_TINYJ , "Advanced Logic Corp. TinyJ embedded processor" },
{ EM_X86_64 , "Advanced Micro Devices X86-64 processor" },
{ EM_PDSP , "Sony DSP Processor" },
{ EM_PDP10 , "Digital Equipment Corp. PDP-10" },
{ EM_PDP11 , "Digital Equipment Corp. PDP-11" },
{ EM_FX66 , "Siemens FX66 microcontroller" },
{ EM_ST9PLUS , "STMicroelectronics ST9+ 8/16 bit microcontroller" },
{ EM_ST7 , "STMicroelectronics ST7 8-bit microcontroller" },
{ EM_68HC16 , "Motorola MC68HC16 Microcontroller" },
{ EM_68HC11 , "Motorola MC68HC11 Microcontroller" },
{ EM_68HC08 , "Motorola MC68HC08 Microcontroller" },
{ EM_68HC05 , "Motorola MC68HC05 Microcontroller" },
{ EM_SVX , "Silicon Graphics SVx" },
{ EM_ST19 , "STMicroelectronics ST19 8-bit cpu" },
{ EM_VAX , "Digital VAX" },
{ EM_CRIS , "Axis Communications 32-bit embedded processor" },
{ EM_JAVELIN , "Infineon Technologies 32-bit embedded cpu" },
{ EM_FIREPATH , "Element 14 64-bit DSP processor" },
{ EM_ZSP , "LSI Logic's 16-bit DSP processor" },
{ EM_MMIX , "Donald Knuth's educational 64-bit processor" },
{ EM_HUANY , "Harvard's machine-independent format" },
{ EM_PRISM , "SiTera Prism" },
{ EM_AVR , "Atmel AVR 8-bit microcontroller" },
{ EM_FR30 , "Fujitsu FR30" },
{ EM_D10V , "Mitsubishi D10V" },
{ EM_D30V , "Mitsubishi D30V" },
{ EM_V850 , "NEC v850" },
{ EM_M32R , "Renesas M32R (formerly Mitsubishi M32R)" },
{ EM_MN10300 , "Matsushita MN10300" },
{ EM_MN10200 , "Matsushita MN10200" },
{ EM_PJ , "picoJava" },
{ EM_OPENRISC , "OpenRISC 32-bit embedded processor" },
{ EM_ARC_A5 , "ARC Cores Tangent-A5" },
{ EM_XTENSA , "Tensilica Xtensa Architecture" },
{ EM_VIDEOCORE , "Alphamosaic VideoCore processor" },
{ EM_TMM_GPP , "Thompson Multimedia General Purpose Processor" },
{ EM_NS32K , "National Semiconductor 32000 series" },
{ EM_TPC , "Tenor Network TPC processor" },
{ EM_SNP1K , "Trebia SNP 1000 processor" },
{ EM_ST200 , "STMicroelectronics ST200 microcontroller" },
{ EM_IP2K , "Ubicom IP2022 micro controller" },
{ EM_MAX , "MAX Processor" },
{ EM_CR , "National Semiconductor CompactRISC" },
{ EM_F2MC16 , "Fujitsu F2MC16" },
{ EM_MSP430 , "TI msp430 micro controller" },
{ EM_BLACKFIN , "ADI Blackfin" },
{ EM_SE_C33 , "S1C33 Family of Seiko Epson processors" },
{ EM_SEP , "Sharp embedded microprocessor" },
{ EM_ARCA , "Arca RISC Microprocessor" },
{ EM_UNICORE , "Microprocessor series from PKU-Unity Ltd. and MPRC of Peking University" },
{ EM_EXCESS , "eXcess: 16/32/64-bit configurable embedded CPU" },
{ EM_DXP , "Icera Semiconductor Inc. Deep Execution Processor" },
{ EM_ALTERA_NIOS2 , "Altera Nios II soft-core processor" },
{ EM_CRX , "National Semiconductor CRX" },
{ EM_XGATE , "Motorola XGATE embedded processor" },
{ EM_C166 , "Infineon C16x/XC16x processor" },
{ EM_M16C , "Renesas M16C series microprocessors" },
{ EM_DSPIC30F , "Microchip Technology dsPIC30F Digital Signal Controller" },
{ EM_CE , "Freescale Communication Engine RISC core" },
{ EM_M32C , "Renesas M32C series microprocessors" },
{ EM_res121 , "Reserved" },
{ EM_res122 , "Reserved" },
{ EM_res123 , "Reserved" },
{ EM_res124 , "Reserved" },
{ EM_res125 , "Reserved" },
{ EM_res126 , "Reserved" },
{ EM_res127 , "Reserved" },
{ EM_res128 , "Reserved" },
{ EM_res129 , "Reserved" },
{ EM_res130 , "Reserved" },
{ EM_TSK3000 , "Altium TSK3000 core" },
{ EM_RS08 , "Freescale RS08 embedded processor" },
{ EM_res133 , "Reserved" },
{ EM_ECOG2 , "Cyan Technology eCOG2 microprocessor" },
{ EM_SCORE , "Sunplus Score" },
{ EM_SCORE7 , "Sunplus S+core7 RISC processor" },
{ EM_DSP24 , "New Japan Radio (NJR) 24-bit DSP Processor" },
{ EM_VIDEOCORE3 , "Broadcom VideoCore III processor" },
{ EM_LATTICEMICO32, "RISC processor for Lattice FPGA architecture" },
{ EM_SE_C17 , "Seiko Epson C17 family" },
{ EM_TI_C6000 , "Texas Instruments TMS320C6000 DSP family" },
{ EM_TI_C2000 , "Texas Instruments TMS320C2000 DSP family" },
{ EM_TI_C5500 , "Texas Instruments TMS320C55x DSP family" },
{ EM_res143 , "Reserved" },
{ EM_res144 , "Reserved" },
{ EM_res145 , "Reserved" },
{ EM_res146 , "Reserved" },
{ EM_res147 , "Reserved" },
{ EM_res148 , "Reserved" },
{ EM_res149 , "Reserved" },
{ EM_res150 , "Reserved" },
{ EM_res151 , "Reserved" },
{ EM_res152 , "Reserved" },
{ EM_res153 , "Reserved" },
{ EM_res154 , "Reserved" },
{ EM_res155 , "Reserved" },
{ EM_res156 , "Reserved" },
{ EM_res157 , "Reserved" },
{ EM_res158 , "Reserved" },
{ EM_res159 , "Reserved" },
{ EM_MMDSP_PLUS , "STMicroelectronics 64bit VLIW Data Signal Processor" },
{ EM_CYPRESS_M8C , "Cypress M8C microprocessor" },
{ EM_R32C , "Renesas R32C series microprocessors" },
{ EM_TRIMEDIA , "NXP Semiconductors TriMedia architecture family" },
{ EM_QDSP6 , "QUALCOMM DSP6 Processor" },
{ EM_8051 , "Intel 8051 and variants" },
{ EM_STXP7X , "STMicroelectronics STxP7x family" },
{ EM_NDS32 , "Andes Technology compact code size embedded RISC processor family" },
{ EM_ECOG1 , "Cyan Technology eCOG1X family" },
{ EM_ECOG1X , "Cyan Technology eCOG1X family" },
{ EM_MAXQ30 , "Dallas Semiconductor MAXQ30 Core Micro-controllers" },
{ EM_XIMO16 , "New Japan Radio (NJR) 16-bit DSP Processor" },
{ EM_MANIK , "M2000 Reconfigurable RISC Microprocessor" },
{ EM_CRAYNV2 , "Cray Inc. NV2 vector architecture" },
{ EM_RX , "Renesas RX family" },
{ EM_METAG , "Imagination Technologies META processor architecture" },
{ EM_MCST_ELBRUS , "MCST Elbrus general purpose hardware architecture" },
{ EM_ECOG16 , "Cyan Technology eCOG16 family" },
{ EM_CR16 , "National Semiconductor CompactRISC 16-bit processor" },
{ EM_ETPU , "Freescale Extended Time Processing Unit" },
{ EM_SLE9X , "Infineon Technologies SLE9X core" },
{ EM_L1OM , "Intel L1OM" },
{ EM_INTEL181 , "Reserved by Intel" },
{ EM_INTEL182 , "Reserved by Intel" },
{ EM_res183 , "Reserved by ARM" },
{ EM_res184 , "Reserved by ARM" },
{ EM_AVR32 , "Atmel Corporation 32-bit microprocessor family" },
{ EM_STM8 , "STMicroeletronics STM8 8-bit microcontroller" },
{ EM_TILE64 , "Tilera TILE64 multicore architecture family" },
{ EM_TILEPRO , "Tilera TILEPro multicore architecture family" },
{ EM_MICROBLAZE , "Xilinx MicroBlaze 32-bit RISC soft processor core" },
{ EM_CUDA , "NVIDIA CUDA architecture " },
};
static struct section_type_table_t {
const Elf64_Half key;
const char* str;
} section_type_table [] =
{
{ SHT_NULL , "NULL" },
{ SHT_PROGBITS , "PROGBITS" },
{ SHT_SYMTAB , "SYMTAB" },
{ SHT_STRTAB , "STRTAB" },
{ SHT_RELA , "RELA" },
{ SHT_HASH , "HASH" },
{ SHT_DYNAMIC , "DYNAMIC" },
{ SHT_NOTE , "NOTE" },
{ SHT_NOBITS , "NOBITS" },
{ SHT_REL , "REL" },
{ SHT_SHLIB , "SHLIB" },
{ SHT_DYNSYM , "DYNSYM" },
{ SHT_INIT_ARRAY , "INIT_ARRAY" },
{ SHT_FINI_ARRAY , "FINI_ARRAY" },
{ SHT_PREINIT_ARRAY, "PREINIT_ARRAY" },
{ SHT_GROUP , "GROUP" },
{ SHT_SYMTAB_SHNDX , "SYMTAB_SHNDX " },
};
static struct segment_type_table_t {
const Elf_Word key;
const char* str;
} segment_type_table [] =
{
{ PT_NULL , "NULL" },
{ PT_LOAD , "LOAD" },
{ PT_DYNAMIC, "DYNAMIC" },
{ PT_INTERP , "INTERP" },
{ PT_NOTE , "NOTE" },
{ PT_SHLIB , "SHLIB" },
{ PT_PHDR , "PHDR" },
{ PT_TLS , "TLS" },
};
static struct segment_flag_table_t {
const Elf_Word key;
const char* str;
} segment_flag_table [] =
{
{ 0, "" },
{ 1, "X" },
{ 2, "W" },
{ 3, "WX" },
{ 4, "R" },
{ 5, "RX" },
{ 6, "RW" },
{ 7, "RWX" },
};
static struct symbol_bind_t {
const Elf_Word key;
const char* str;
} symbol_bind_table [] =
{
{ STB_LOCAL , "LOCAL" },
{ STB_GLOBAL , "GLOBAL" },
{ STB_WEAK , "WEAK" },
{ STB_LOOS , "LOOS" },
{ STB_HIOS , "HIOS" },
{ STB_MULTIDEF, "MULTIDEF" },
{ STB_LOPROC , "LOPROC" },
{ STB_HIPROC , "HIPROC" },
};
static struct symbol_type_t {
const Elf_Word key;
const char* str;
} symbol_type_table [] =
{
{ STT_NOTYPE , "NOTYPE" },
{ STT_OBJECT , "OBJECT" },
{ STT_FUNC , "FUNC" },
{ STT_SECTION, "SECTION" },
{ STT_FILE , "FILE" },
{ STT_COMMON , "COMMON" },
{ STT_TLS , "TLS" },
{ STT_LOOS , "LOOS" },
{ STT_HIOS , "HIOS" },
{ STT_LOPROC , "LOPROC" },
{ STT_HIPROC , "HIPROC" },
};
static struct dynamic_tag_t {
const Elf_Word key;
const char* str;
} dynamic_tag_table [] =
{
{ DT_NULL , "NULL" },
{ DT_NEEDED , "NEEDED" },
{ DT_PLTRELSZ , "PLTRELSZ" },
{ DT_PLTGOT , "PLTGOT" },
{ DT_HASH , "HASH" },
{ DT_STRTAB , "STRTAB" },
{ DT_SYMTAB , "SYMTAB" },
{ DT_RELA , "RELA" },
{ DT_RELASZ , "RELASZ" },
{ DT_RELAENT , "RELAENT" },
{ DT_STRSZ , "STRSZ" },
{ DT_SYMENT , "SYMENT" },
{ DT_INIT , "INIT" },
{ DT_FINI , "FINI" },
{ DT_SONAME , "SONAME" },
{ DT_RPATH , "RPATH" },
{ DT_SYMBOLIC , "SYMBOLIC" },
{ DT_REL , "REL" },
{ DT_RELSZ , "RELSZ" },
{ DT_RELENT , "RELENT" },
{ DT_PLTREL , "PLTREL" },
{ DT_DEBUG , "DEBUG" },
{ DT_TEXTREL , "TEXTREL" },
{ DT_JMPREL , "JMPREL" },
{ DT_BIND_NOW , "BIND_NOW" },
{ DT_INIT_ARRAY , "INIT_ARRAY" },
{ DT_FINI_ARRAY , "FINI_ARRAY" },
{ DT_INIT_ARRAYSZ , "INIT_ARRAYSZ" },
{ DT_FINI_ARRAYSZ , "FINI_ARRAYSZ" },
{ DT_RUNPATH , "RUNPATH" },
{ DT_FLAGS , "FLAGS" },
{ DT_ENCODING , "ENCODING" },
{ DT_PREINIT_ARRAY , "PREINIT_ARRAY" },
{ DT_PREINIT_ARRAYSZ, "PREINIT_ARRAYSZ" },
{ DT_MAXPOSTAGS , "MAXPOSTAGS" },
};
static const ELFIO::Elf_Xword MAX_DATA_ENTRIES = 64;
//------------------------------------------------------------------------------
class dump
{
#define DUMP_DEC_FORMAT( width ) std::setw(width) << std::setfill( ' ' ) << \
std::dec << std::right
#define DUMP_HEX_FORMAT( width ) std::setw(width) << std::setfill( '0' ) << \
std::hex << std::right
#define DUMP_STR_FORMAT( width ) std::setw(width) << std::setfill( ' ' ) << \
std::hex << std::left
public:
//------------------------------------------------------------------------------
static void
header( std::ostream& out, const elfio& reader )
{
if (!reader.get_header_size())
{
return;
}
out << "ELF Header" << std::endl << std::endl
<< " Class: " << str_class( reader.get_class() ) << std::endl
<< " Encoding: " << str_endian( reader.get_encoding() ) << std::endl
<< " ELFVersion: " << str_version( reader.get_elf_version() ) << std::endl
<< " Type: " << str_type( reader.get_type() ) << std::endl
<< " Machine: " << str_machine( reader.get_machine() ) << std::endl
<< " Version: " << str_version( reader.get_version() ) << std::endl
<< " Entry: " << "0x" << std::hex << reader.get_entry() << std::endl
<< " Flags: " << "0x" << std::hex << reader.get_flags() << std::endl
<< std::endl;
}
//------------------------------------------------------------------------------
static void
section_headers( std::ostream& out, const elfio& reader )
{
Elf_Half n = reader.sections.size();
if ( n == 0 ) {
return;
}
out << "Section Headers:" << std::endl;
if ( reader.get_class() == ELFCLASS32 ) { // Output for 32-bit
out << "[ Nr ] Type Addr Size ES Flg Lk Inf Al Name" << std::endl;
}
else { // Output for 64-bit
out << "[ Nr ] Type Addr Size ES Flg" << std::endl
<< " Lk Inf Al Name" << std::endl;
}
for ( Elf_Half i = 0; i < n; ++i ) { // For all sections
section* sec = reader.sections[i];
section_header( out, i, sec, reader.get_class() );
}
out << "Key to Flags: W (write), A (alloc), X (execute)\n\n"
<< std::endl;
}
//------------------------------------------------------------------------------
static void
section_header( std::ostream& out, Elf_Half no, const section* sec,
unsigned char elf_class )
{
std::ios_base::fmtflags original_flags = out.flags();
if ( elf_class == ELFCLASS32 ) { // Output for 32-bit
out << "["
<< DUMP_DEC_FORMAT( 5 ) << no
<< "] "
<< DUMP_STR_FORMAT( 17 ) << str_section_type( sec->get_type() ) << " "
<< DUMP_HEX_FORMAT( 8 ) << sec->get_address() << " "
<< DUMP_HEX_FORMAT( 8 ) << sec->get_size() << " "
<< DUMP_HEX_FORMAT( 2 ) << sec->get_entry_size() << " "
<< DUMP_STR_FORMAT( 3 ) << section_flags( sec->get_flags() ) << " "
<< DUMP_HEX_FORMAT( 2 ) << sec->get_link() << " "
<< DUMP_HEX_FORMAT( 3 ) << sec->get_info() << " "
<< DUMP_HEX_FORMAT( 2 ) << sec->get_addr_align() << " "
<< DUMP_STR_FORMAT( 17 ) << sec->get_name() << " "
<< std::endl;
}
else { // Output for 64-bit
out << "["
<< DUMP_DEC_FORMAT( 5 ) << no
<< "] "
<< DUMP_STR_FORMAT( 17 ) << str_section_type( sec->get_type() ) << " "
<< DUMP_HEX_FORMAT( 16 ) << sec->get_address() << " "
<< DUMP_HEX_FORMAT( 16 ) << sec->get_size() << " "
<< DUMP_HEX_FORMAT( 4 ) << sec->get_entry_size() << " "
<< DUMP_STR_FORMAT( 3 ) << section_flags( sec->get_flags() ) << " "
<< std::endl
<< " "
<< DUMP_HEX_FORMAT( 4 ) << sec->get_link() << " "
<< DUMP_HEX_FORMAT( 4 ) << sec->get_info() << " "
<< DUMP_HEX_FORMAT( 4 ) << sec->get_addr_align() << " "
<< DUMP_STR_FORMAT( 17 ) << sec->get_name() << " "
<< std::endl;
}
out.flags(original_flags);
return;
}
//------------------------------------------------------------------------------
static void
segment_headers( std::ostream& out, const elfio& reader )
{
Elf_Half n = reader.segments.size();
if ( n == 0 ) {
return;
}
out << "Segment headers:" << std::endl;
if ( reader.get_class() == ELFCLASS32 ) { // Output for 32-bit
out << "[ Nr ] Type VirtAddr PhysAddr FileSize Mem.Size Flags Align"
<< std::endl;
}
else { // Output for 64-bit
out << "[ Nr ] Type VirtAddr PhysAddr Flags" << std::endl
<< " FileSize Mem.Size Align"
<< std::endl;
}
for ( Elf_Half i = 0; i < n; ++i ) {
segment* seg = reader.segments[i];
segment_header( out, i, seg, reader.get_class() );
}
out << std::endl;
}
//------------------------------------------------------------------------------
static void
segment_header( std::ostream& out, Elf_Half no, const segment* seg,
unsigned int elf_class )
{
std::ios_base::fmtflags original_flags = out.flags();
if ( elf_class == ELFCLASS32 ) { // Output for 32-bit
out << "["
<< DUMP_DEC_FORMAT( 5 ) << no
<< "] "
<< DUMP_STR_FORMAT( 14 ) << str_segment_type( seg->get_type() ) << " "
<< DUMP_HEX_FORMAT( 8 ) << seg->get_virtual_address() << " "
<< DUMP_HEX_FORMAT( 8 ) << seg->get_physical_address() << " "
<< DUMP_HEX_FORMAT( 8 ) << seg->get_file_size() << " "
<< DUMP_HEX_FORMAT( 8 ) << seg->get_memory_size() << " "
<< DUMP_STR_FORMAT( 8 ) << str_segment_flag( seg->get_flags() ) << " "
<< DUMP_HEX_FORMAT( 8 ) << seg->get_align() << " "
<< std::endl;
}
else { // Output for 64-bit
out << "["
<< DUMP_DEC_FORMAT( 5 ) << no
<< "] "
<< DUMP_STR_FORMAT( 14 ) << str_segment_type( seg->get_type() ) << " "
<< DUMP_HEX_FORMAT( 16 ) << seg->get_virtual_address() << " "
<< DUMP_HEX_FORMAT( 16 ) << seg->get_physical_address() << " "
<< DUMP_STR_FORMAT( 16 ) << str_segment_flag( seg->get_flags() ) << " "
<< std::endl
<< " "
<< DUMP_HEX_FORMAT( 16 ) << seg->get_file_size() << " "
<< DUMP_HEX_FORMAT( 16 ) << seg->get_memory_size() << " "
<< DUMP_HEX_FORMAT( 16 ) << seg->get_align() << " "
<< std::endl;
}
out.flags(original_flags);
}
//------------------------------------------------------------------------------
static void
symbol_tables( std::ostream& out, const elfio& reader )
{
Elf_Half n = reader.sections.size();
for ( Elf_Half i = 0; i < n; ++i ) { // For all sections
section* sec = reader.sections[i];
if ( SHT_SYMTAB == sec->get_type() || SHT_DYNSYM == sec->get_type() ) {
symbol_section_accessor symbols( reader, sec );
Elf_Xword sym_no = symbols.get_symbols_num();
if ( sym_no > 0 ) {
out << "Symbol table (" << sec->get_name() << ")" << std::endl;
if ( reader.get_class() == ELFCLASS32 ) { // Output for 32-bit
out << "[ Nr ] Value Size Type Bind Sect Name"
<< std::endl;
}
else { // Output for 64-bit
out << "[ Nr ] Value Size Type Bind Sect" << std::endl
<< " Name"
<< std::endl;
}
for ( Elf_Half i = 0; i < sym_no; ++i ) {
std::string name;
Elf64_Addr value = 0;
Elf_Xword size = 0;
unsigned char bind = 0;
unsigned char type = 0;
Elf_Half section = 0;
unsigned char other = 0;
symbols.get_symbol( i, name, value, size, bind, type, section, other );
symbol_table( out, i, name, value, size, bind, type, section, reader.get_class() );
}
out << std::endl;
}
}
}
}
//------------------------------------------------------------------------------
static void
symbol_table( std::ostream& out,
Elf_Half no,
std::string& name,
Elf64_Addr value,
Elf_Xword size,
unsigned char bind,
unsigned char type,
Elf_Half section,
unsigned int elf_class )
{
std::ios_base::fmtflags original_flags = out.flags();
if ( elf_class == ELFCLASS32 ) { // Output for 32-bit
out << "["
<< DUMP_DEC_FORMAT( 5 ) << no
<< "] "
<< DUMP_HEX_FORMAT( 8 ) << value << " "
<< DUMP_HEX_FORMAT( 8 ) << size << " "
<< DUMP_STR_FORMAT( 7 ) << str_symbol_type( type ) << " "
<< DUMP_STR_FORMAT( 8 ) << str_symbol_bind( bind ) << " "
<< DUMP_DEC_FORMAT( 5 ) << section << " "
<< DUMP_STR_FORMAT( 1 ) << name << " "
<< std::endl;
}
else { // Output for 64-bit
out << "["
<< DUMP_DEC_FORMAT( 5 ) << no
<< "] "
<< DUMP_HEX_FORMAT( 16 ) << value << " "
<< DUMP_HEX_FORMAT( 16 ) << size << " "
<< DUMP_STR_FORMAT( 7 ) << str_symbol_type( type ) << " "
<< DUMP_STR_FORMAT( 8 ) << str_symbol_bind( bind ) << " "
<< DUMP_DEC_FORMAT( 5 ) << section << " "
<< std::endl
<< " "
<< DUMP_STR_FORMAT( 1 ) << name << " "
<< std::endl;
}
out.flags(original_flags);
}
//------------------------------------------------------------------------------
static void
notes( std::ostream& out, const elfio& reader )
{
Elf_Half no = reader.sections.size();
for ( Elf_Half i = 0; i < no; ++i ) { // For all sections
section* sec = reader.sections[i];
if ( SHT_NOTE == sec->get_type() ) { // Look at notes
note_section_accessor notes( reader, sec );
int no_notes = notes.get_notes_num();
if ( no > 0 ) {
out << "Note section (" << sec->get_name() << ")" << std::endl
<< " No Type Name"
<< std::endl;
for ( int j = 0; j < no_notes; ++j ) { // For all notes
Elf_Word type;
std::string name;
void* desc;
Elf_Word descsz;
if ( notes.get_note(j, type, name, desc, descsz) ) {
// 'name' usually contains \0 at the end. Try to fix it
name = name.c_str();
note( out, j, type, name );
}
}
out << std::endl;
}
}
}
}
//------------------------------------------------------------------------------
static void
note( std::ostream& out,
int no,
Elf_Word type,
const std::string& name )
{
out << " ["
<< DUMP_DEC_FORMAT( 2 ) << no
<< "] "
<< DUMP_HEX_FORMAT( 8 ) << type << " "
<< DUMP_STR_FORMAT( 1 ) << name
<< std::endl;
}
//------------------------------------------------------------------------------
static void
dynamic_tags( std::ostream& out, const elfio& reader )
{
Elf_Half n = reader.sections.size();
for ( Elf_Half i = 0; i < n; ++i ) { // For all sections
section* sec = reader.sections[i];
if ( SHT_DYNAMIC == sec->get_type() ) {
dynamic_section_accessor dynamic( reader, sec );
Elf_Xword dyn_no = dynamic.get_entries_num();
if ( dyn_no > 0 ) {
out << "Dynamic section (" << sec->get_name() << ")" << std::endl;
out << "[ Nr ] Tag Name/Value" << std::endl;
for ( Elf_Xword i = 0; i < dyn_no; ++i ) {
Elf_Xword tag = 0;
Elf_Xword value = 0;
std::string str;
dynamic.get_entry( i, tag, value, str );
dynamic_tag( out, i, tag, value, str, reader.get_class() );
if ( DT_NULL == tag ) {
break;
}
}
out << std::endl;
}
}
}
}
//------------------------------------------------------------------------------
static void
dynamic_tag( std::ostream& out,
Elf_Xword no,
Elf_Xword tag,
Elf_Xword value,
std::string str,
unsigned int /*elf_class*/ )
{
out << "["
<< DUMP_DEC_FORMAT( 5 ) << no
<< "] "
<< DUMP_STR_FORMAT( 16 ) << str_dynamic_tag( tag ) << " ";
if ( str.empty() ) {
out << DUMP_HEX_FORMAT( 16 ) << value << " ";
}
else {
out << DUMP_STR_FORMAT( 32 ) << str << " ";
}
out << std::endl;
}
//------------------------------------------------------------------------------
static void
section_data( std::ostream& out, const section* sec )
{
std::ios_base::fmtflags original_flags = out.flags();
out << sec->get_name() << std::endl;
const char* pdata = sec->get_data();
if ( pdata ){
ELFIO::Elf_Xword i;
for ( i = 0; i < std::min( sec->get_size(), MAX_DATA_ENTRIES ); ++i ) {
if ( i % 16 == 0 ) {
out << "[" << DUMP_HEX_FORMAT( 8 ) << i << "]";
}
out << " " << DUMP_HEX_FORMAT( 2 ) << ( pdata[i] & 0x000000FF );
if ( i % 16 == 15 ) {
out << std::endl;
}
}
if ( i % 16 != 0 ) {
out << std::endl;
}
out.flags(original_flags);
}
return;
}
//------------------------------------------------------------------------------
static void
section_datas( std::ostream& out, const elfio& reader )
{
Elf_Half n = reader.sections.size();
if ( n == 0 ) {
return;
}
out << "Section Data:" << std::endl;
for ( Elf_Half i = 1; i < n; ++i ) { // For all sections
section* sec = reader.sections[i];
if ( sec->get_type() == SHT_NOBITS ) {
continue;
}
section_data( out, sec );
}
out << std::endl;
}
//------------------------------------------------------------------------------
static void
segment_data( std::ostream& out, Elf_Half no, const segment* seg )
{
std::ios_base::fmtflags original_flags = out.flags();
out << "Segment # " << no << std::endl;
const char* pdata = seg->get_data();
if ( pdata ) {
ELFIO::Elf_Xword i;
for ( i = 0; i < std::min( seg->get_file_size(), MAX_DATA_ENTRIES ); ++i ) {
if ( i % 16 == 0 ) {
out << "[" << DUMP_HEX_FORMAT( 8 ) << i << "]";
}
out << " " << DUMP_HEX_FORMAT( 2 ) << ( pdata[i] & 0x000000FF );
if ( i % 16 == 15 ) {
out << std::endl;
}
}
if ( i % 16 != 0 ) {
out << std::endl;
}
out.flags(original_flags);
}
return;
}
//------------------------------------------------------------------------------
static void
segment_datas( std::ostream& out, const elfio& reader )
{
Elf_Half n = reader.segments.size();
if ( n == 0 ) {
return;
}
out << "Segment Data:" << std::endl;
for ( Elf_Half i = 0; i < n; ++i ) { // For all sections
segment* seg = reader.segments[i];
segment_data( out, i, seg );
}
out << std::endl;
}
private:
//------------------------------------------------------------------------------
template< typename T, typename K >
std::string
static
find_value_in_table( const T& table, const K& key )
{
std::string res = "?";
for ( unsigned int i = 0; i < sizeof( table )/sizeof( table[0] ); ++i ) {
if ( table[i].key == key ) {
res = table[i].str;
break;
}
}
return res;
}
//------------------------------------------------------------------------------
template< typename T, typename K >
static
std::string
format_assoc( const T& table, const K& key )
{
std::string str = find_value_in_table( table, key );
if ( str == "?" ) {
std::ostringstream oss;
oss << str << " (0x" << std::hex << key << ")";
str = oss.str();
}
return str;
}
//------------------------------------------------------------------------------
template< typename T >
static
std::string
format_assoc( const T& table, const char key )
{
return format_assoc( table, (const int)key );
}
//------------------------------------------------------------------------------
static
std::string
section_flags( Elf_Xword flags )
{
std::string ret = "";
if ( flags & SHF_WRITE ) {
ret += "W";
}
if ( flags & SHF_ALLOC ) {
ret += "A";
}
if ( flags & SHF_EXECINSTR ) {
ret += "X";
}
return ret;
}
//------------------------------------------------------------------------------
#define STR_FUNC_TABLE( name ) \
template< typename T > \
static \
std::string \
str_##name( const T key ) \
{ \
return format_assoc( name##_table, key ); \
}
STR_FUNC_TABLE( class )
STR_FUNC_TABLE( endian )
STR_FUNC_TABLE( version )
STR_FUNC_TABLE( type )
STR_FUNC_TABLE( machine )
STR_FUNC_TABLE( section_type )
STR_FUNC_TABLE( segment_type )
STR_FUNC_TABLE( segment_flag )
STR_FUNC_TABLE( symbol_bind )
STR_FUNC_TABLE( symbol_type )
STR_FUNC_TABLE( dynamic_tag )
#undef STR_FUNC_TABLE
#undef DUMP_DEC_FORMAT
#undef DUMP_HEX_FORMAT
#undef DUMP_STR_FORMAT
}; // class dump
}; // namespace ELFIO
#endif // ELFIO_DUMP_HPP

View File

@ -1,257 +0,0 @@
/*
Copyright (C) 2001-2015 by Serge Lamikhov-Center
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef ELFIO_DYNAMIC_HPP
#define ELFIO_DYNAMIC_HPP
namespace ELFIO {
//------------------------------------------------------------------------------
template< class S >
class dynamic_section_accessor_template
{
public:
//------------------------------------------------------------------------------
dynamic_section_accessor_template( const elfio& elf_file_, S* section_ ) :
elf_file( elf_file_ ),
dynamic_section( section_ )
{
}
//------------------------------------------------------------------------------
Elf_Xword
get_entries_num() const
{
Elf_Xword nRet = 0;
if ( 0 != dynamic_section->get_entry_size() ) {
nRet = dynamic_section->get_size() / dynamic_section->get_entry_size();
}
return nRet;
}
//------------------------------------------------------------------------------
bool
get_entry( Elf_Xword index,
Elf_Xword& tag,
Elf_Xword& value,
std::string& str ) const
{
if ( index >= get_entries_num() ) { // Is index valid
return false;
}
if ( elf_file.get_class() == ELFCLASS32 ) {
generic_get_entry_dyn< Elf32_Dyn >( index, tag, value );
}
else {
generic_get_entry_dyn< Elf64_Dyn >( index, tag, value );
}
// If the tag may have a string table reference, prepare the string
if ( tag == DT_NEEDED ||
tag == DT_SONAME ||
tag == DT_RPATH ||
tag == DT_RUNPATH ) {
string_section_accessor strsec =
elf_file.sections[ get_string_table_index() ];
const char* result = strsec.get_string( value );
if ( 0 == result ) {
str.clear();
return false;
}
str = result;
}
else {
str.clear();
}
return true;
}
//------------------------------------------------------------------------------
void
add_entry( Elf_Xword tag,
Elf_Xword value )
{
if ( elf_file.get_class() == ELFCLASS32 ) {
generic_add_entry< Elf32_Dyn >( tag, value );
}
else {
generic_add_entry< Elf64_Dyn >( tag, value );
}
}
//------------------------------------------------------------------------------
void
add_entry( Elf_Xword tag,
const std::string& str )
{
string_section_accessor strsec =
elf_file.sections[ get_string_table_index() ];
Elf_Xword value = strsec.add_string( str );
add_entry( tag, value );
}
//------------------------------------------------------------------------------
private:
//------------------------------------------------------------------------------
Elf_Half
get_string_table_index() const
{
return (Elf_Half)dynamic_section->get_link();
}
//------------------------------------------------------------------------------
template< class T >
void
generic_get_entry_dyn( Elf_Xword index,
Elf_Xword& tag,
Elf_Xword& value ) const
{
const endianess_convertor& convertor = elf_file.get_convertor();
// Check unusual case when dynamic section has no data
if( dynamic_section->get_data() == 0 ||
( index + 1 ) * dynamic_section->get_entry_size() > dynamic_section->get_size() ) {
tag = DT_NULL;
value = 0;
return;
}
const T* pEntry = reinterpret_cast<const T*>(
dynamic_section->get_data() +
index * dynamic_section->get_entry_size() );
tag = convertor( pEntry->d_tag );
switch ( tag ) {
case DT_NULL:
case DT_SYMBOLIC:
case DT_TEXTREL:
case DT_BIND_NOW:
value = 0;
break;
case DT_NEEDED:
case DT_PLTRELSZ:
case DT_RELASZ:
case DT_RELAENT:
case DT_STRSZ:
case DT_SYMENT:
case DT_SONAME:
case DT_RPATH:
case DT_RELSZ:
case DT_RELENT:
case DT_PLTREL:
case DT_INIT_ARRAYSZ:
case DT_FINI_ARRAYSZ:
case DT_RUNPATH:
case DT_FLAGS:
case DT_PREINIT_ARRAYSZ:
value = convertor( pEntry->d_un.d_val );
break;
case DT_PLTGOT:
case DT_HASH:
case DT_STRTAB:
case DT_SYMTAB:
case DT_RELA:
case DT_INIT:
case DT_FINI:
case DT_REL:
case DT_DEBUG:
case DT_JMPREL:
case DT_INIT_ARRAY:
case DT_FINI_ARRAY:
case DT_PREINIT_ARRAY:
default:
value = convertor( pEntry->d_un.d_ptr );
break;
}
}
//------------------------------------------------------------------------------
template< class T >
void
generic_add_entry( Elf_Xword tag, Elf_Xword value )
{
const endianess_convertor& convertor = elf_file.get_convertor();
T entry;
switch ( tag ) {
case DT_NULL:
case DT_SYMBOLIC:
case DT_TEXTREL:
case DT_BIND_NOW:
value = 0;
case DT_NEEDED:
case DT_PLTRELSZ:
case DT_RELASZ:
case DT_RELAENT:
case DT_STRSZ:
case DT_SYMENT:
case DT_SONAME:
case DT_RPATH:
case DT_RELSZ:
case DT_RELENT:
case DT_PLTREL:
case DT_INIT_ARRAYSZ:
case DT_FINI_ARRAYSZ:
case DT_RUNPATH:
case DT_FLAGS:
case DT_PREINIT_ARRAYSZ:
entry.d_un.d_val = convertor( value );
break;
case DT_PLTGOT:
case DT_HASH:
case DT_STRTAB:
case DT_SYMTAB:
case DT_RELA:
case DT_INIT:
case DT_FINI:
case DT_REL:
case DT_DEBUG:
case DT_JMPREL:
case DT_INIT_ARRAY:
case DT_FINI_ARRAY:
case DT_PREINIT_ARRAY:
default:
entry.d_un.d_ptr = convertor( value );
break;
}
entry.d_tag = convertor( tag );
dynamic_section->append_data( reinterpret_cast<char*>( &entry ), sizeof( entry ) );
}
//------------------------------------------------------------------------------
private:
const elfio& elf_file;
S* dynamic_section;
};
using dynamic_section_accessor = dynamic_section_accessor_template<section>;
using const_dynamic_section_accessor = dynamic_section_accessor_template<const section>;
} // namespace ELFIO
#endif // ELFIO_DYNAMIC_HPP

View File

@ -1,145 +0,0 @@
/*
Copyright (C) 2001-2015 by Serge Lamikhov-Center
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef ELF_HEADER_HPP
#define ELF_HEADER_HPP
#include <iostream>
namespace ELFIO {
class elf_header
{
public:
virtual ~elf_header() {};
virtual bool load( std::istream& stream ) = 0;
virtual bool save( std::ostream& stream ) const = 0;
// ELF header functions
ELFIO_GET_ACCESS_DECL( unsigned char, class );
ELFIO_GET_ACCESS_DECL( unsigned char, elf_version );
ELFIO_GET_ACCESS_DECL( unsigned char, encoding );
ELFIO_GET_ACCESS_DECL( Elf_Half, header_size );
ELFIO_GET_ACCESS_DECL( Elf_Half, section_entry_size );
ELFIO_GET_ACCESS_DECL( Elf_Half, segment_entry_size );
ELFIO_GET_SET_ACCESS_DECL( Elf_Word, version );
ELFIO_GET_SET_ACCESS_DECL( unsigned char, os_abi );
ELFIO_GET_SET_ACCESS_DECL( unsigned char, abi_version );
ELFIO_GET_SET_ACCESS_DECL( Elf_Half, type );
ELFIO_GET_SET_ACCESS_DECL( Elf_Half, machine );
ELFIO_GET_SET_ACCESS_DECL( Elf_Word, flags );
ELFIO_GET_SET_ACCESS_DECL( Elf64_Addr, entry );
ELFIO_GET_SET_ACCESS_DECL( Elf_Half, sections_num );
ELFIO_GET_SET_ACCESS_DECL( Elf64_Off, sections_offset );
ELFIO_GET_SET_ACCESS_DECL( Elf_Half, segments_num );
ELFIO_GET_SET_ACCESS_DECL( Elf64_Off, segments_offset );
ELFIO_GET_SET_ACCESS_DECL( Elf_Half, section_name_str_index );
};
template< class T > struct elf_header_impl_types;
template<> struct elf_header_impl_types<Elf32_Ehdr> {
typedef Elf32_Phdr Phdr_type;
typedef Elf32_Shdr Shdr_type;
static const unsigned char file_class = ELFCLASS32;
};
template<> struct elf_header_impl_types<Elf64_Ehdr> {
typedef Elf64_Phdr Phdr_type;
typedef Elf64_Shdr Shdr_type;
static const unsigned char file_class = ELFCLASS64;
};
template< class T > class elf_header_impl : public elf_header
{
public:
elf_header_impl( endianess_convertor* convertor_,
unsigned char encoding )
{
convertor = convertor_;
std::fill_n( reinterpret_cast<char*>( &header ), sizeof( header ), '\0' );
header.e_ident[EI_MAG0] = ELFMAG0;
header.e_ident[EI_MAG1] = ELFMAG1;
header.e_ident[EI_MAG2] = ELFMAG2;
header.e_ident[EI_MAG3] = ELFMAG3;
header.e_ident[EI_CLASS] = elf_header_impl_types<T>::file_class;
header.e_ident[EI_DATA] = encoding;
header.e_ident[EI_VERSION] = EV_CURRENT;
header.e_version = (*convertor)( (Elf_Word)EV_CURRENT );
header.e_ehsize = ( sizeof( header ) );
header.e_ehsize = (*convertor)( header.e_ehsize );
header.e_shstrndx = (*convertor)( (Elf_Half)1 );
header.e_phentsize = sizeof( typename elf_header_impl_types<T>::Phdr_type );
header.e_shentsize = sizeof( typename elf_header_impl_types<T>::Shdr_type );
header.e_phentsize = (*convertor)( header.e_phentsize );
header.e_shentsize = (*convertor)( header.e_shentsize );
}
bool
load( std::istream& stream )
{
stream.seekg( 0 );
stream.read( reinterpret_cast<char*>( &header ), sizeof( header ) );
return (stream.gcount() == sizeof( header ) );
}
bool
save( std::ostream& stream ) const
{
stream.seekp( 0 );
stream.write( reinterpret_cast<const char*>( &header ), sizeof( header ) );
return stream.good();
}
// ELF header functions
ELFIO_GET_ACCESS( unsigned char, class, header.e_ident[EI_CLASS] );
ELFIO_GET_ACCESS( unsigned char, elf_version, header.e_ident[EI_VERSION] );
ELFIO_GET_ACCESS( unsigned char, encoding, header.e_ident[EI_DATA] );
ELFIO_GET_ACCESS( Elf_Half, header_size, header.e_ehsize );
ELFIO_GET_ACCESS( Elf_Half, section_entry_size, header.e_shentsize );
ELFIO_GET_ACCESS( Elf_Half, segment_entry_size, header.e_phentsize );
ELFIO_GET_SET_ACCESS( Elf_Word, version, header.e_version);
ELFIO_GET_SET_ACCESS( unsigned char, os_abi, header.e_ident[EI_OSABI] );
ELFIO_GET_SET_ACCESS( unsigned char, abi_version, header.e_ident[EI_ABIVERSION] );
ELFIO_GET_SET_ACCESS( Elf_Half, type, header.e_type );
ELFIO_GET_SET_ACCESS( Elf_Half, machine, header.e_machine );
ELFIO_GET_SET_ACCESS( Elf_Word, flags, header.e_flags );
ELFIO_GET_SET_ACCESS( Elf_Half, section_name_str_index, header.e_shstrndx );
ELFIO_GET_SET_ACCESS( Elf64_Addr, entry, header.e_entry );
ELFIO_GET_SET_ACCESS( Elf_Half, sections_num, header.e_shnum );
ELFIO_GET_SET_ACCESS( Elf64_Off, sections_offset, header.e_shoff );
ELFIO_GET_SET_ACCESS( Elf_Half, segments_num, header.e_phnum );
ELFIO_GET_SET_ACCESS( Elf64_Off, segments_offset, header.e_phoff );
private:
T header;
endianess_convertor* convertor;
};
} // namespace ELFIO
#endif // ELF_HEADER_HPP

View File

@ -1,170 +0,0 @@
/*
Copyright (C) 2001-2015 by Serge Lamikhov-Center
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef ELFIO_NOTE_HPP
#define ELFIO_NOTE_HPP
namespace ELFIO {
//------------------------------------------------------------------------------
// There are discrepancies in documentations. SCO documentation
// (http://www.sco.com/developers/gabi/latest/ch5.pheader.html#note_section)
// requires 8 byte entries alignment for 64-bit ELF file,
// but Oracle's definition uses the same structure
// for 32-bit and 64-bit formats.
// (https://docs.oracle.com/cd/E23824_01/html/819-0690/chapter6-18048.html)
//
// It looks like EM_X86_64 Linux implementation is similar to Oracle's
// definition. Therefore, the same alignment works for both formats
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
template< class S >
class note_section_accessor_template
{
public:
//------------------------------------------------------------------------------
note_section_accessor_template( const elfio& elf_file_, S* section_ ) :
elf_file( elf_file_ ), note_section( section_ )
{
process_section();
}
//------------------------------------------------------------------------------
Elf_Word
get_notes_num() const
{
return (Elf_Word)note_start_positions.size();
}
//------------------------------------------------------------------------------
bool
get_note( Elf_Word index,
Elf_Word& type,
std::string& name,
void*& desc,
Elf_Word& descSize ) const
{
if ( index >= note_section->get_size() ) {
return false;
}
const char* pData = note_section->get_data() + note_start_positions[index];
int align = sizeof( Elf_Word );
const endianess_convertor& convertor = elf_file.get_convertor();
type = convertor( *(const Elf_Word*)( pData + 2*align ) );
Elf_Word namesz = convertor( *(const Elf_Word*)( pData ) );
descSize = convertor( *(const Elf_Word*)( pData + sizeof( namesz ) ) );
Elf_Xword max_name_size = note_section->get_size() - note_start_positions[index];
if ( namesz > max_name_size ||
namesz + descSize > max_name_size ) {
return false;
}
name.assign( pData + 3*align, namesz - 1);
if ( 0 == descSize ) {
desc = 0;
}
else {
desc = const_cast<char*> ( pData + 3*align +
( ( namesz + align - 1 )/align )*align );
}
return true;
}
//------------------------------------------------------------------------------
void add_note( Elf_Word type,
const std::string& name,
const void* desc,
Elf_Word descSize )
{
const endianess_convertor& convertor = elf_file.get_convertor();
int align = sizeof( Elf_Word );
Elf_Word nameLen = (Elf_Word)name.size() + 1;
Elf_Word nameLenConv = convertor( nameLen );
std::string buffer( reinterpret_cast<char*>( &nameLenConv ), align );
Elf_Word descSizeConv = convertor( descSize );
buffer.append( reinterpret_cast<char*>( &descSizeConv ), align );
type = convertor( type );
buffer.append( reinterpret_cast<char*>( &type ), align );
buffer.append( name );
buffer.append( 1, '\x00' );
const char pad[] = { '\0', '\0', '\0', '\0' };
if ( nameLen % align != 0 ) {
buffer.append( pad, align - nameLen % align );
}
if ( desc != 0 && descSize != 0 ) {
buffer.append( reinterpret_cast<const char*>( desc ), descSize );
if ( descSize % align != 0 ) {
buffer.append( pad, align - descSize % align );
}
}
note_start_positions.push_back( note_section->get_size() );
note_section->append_data( buffer );
}
private:
//------------------------------------------------------------------------------
void process_section()
{
const endianess_convertor& convertor = elf_file.get_convertor();
const char* data = note_section->get_data();
Elf_Xword size = note_section->get_size();
Elf_Xword current = 0;
note_start_positions.clear();
// Is it empty?
if ( 0 == data || 0 == size ) {
return;
}
int align = sizeof( Elf_Word );
while ( current + 3*align <= size ) {
note_start_positions.push_back( current );
Elf_Word namesz = convertor(
*(const Elf_Word*)( data + current ) );
Elf_Word descsz = convertor(
*(const Elf_Word*)( data + current + sizeof( namesz ) ) );
current += 3*sizeof( Elf_Word ) +
( ( namesz + align - 1 ) / align ) * align +
( ( descsz + align - 1 ) / align ) * align;
}
}
//------------------------------------------------------------------------------
private:
const elfio& elf_file;
S* note_section;
std::vector<Elf_Xword> note_start_positions;
};
using note_section_accessor = note_section_accessor_template<section>;
using const_note_section_accessor = note_section_accessor_template<const section>;
} // namespace ELFIO
#endif // ELFIO_NOTE_HPP

View File

@ -1,373 +0,0 @@
/*
Copyright (C) 2001-2015 by Serge Lamikhov-Center
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef ELFIO_RELOCATION_HPP
#define ELFIO_RELOCATION_HPP
namespace ELFIO {
template<typename T> struct get_sym_and_type;
template<> struct get_sym_and_type< Elf32_Rel >
{
static int get_r_sym( Elf_Xword info )
{
return ELF32_R_SYM( (Elf_Word)info );
}
static int get_r_type( Elf_Xword info )
{
return ELF32_R_TYPE( (Elf_Word)info );
}
};
template<> struct get_sym_and_type< Elf32_Rela >
{
static int get_r_sym( Elf_Xword info )
{
return ELF32_R_SYM( (Elf_Word)info );
}
static int get_r_type( Elf_Xword info )
{
return ELF32_R_TYPE( (Elf_Word)info );
}
};
template<> struct get_sym_and_type< Elf64_Rel >
{
static int get_r_sym( Elf_Xword info )
{
return ELF64_R_SYM( info );
}
static int get_r_type( Elf_Xword info )
{
return ELF64_R_TYPE( info );
}
};
template<> struct get_sym_and_type< Elf64_Rela >
{
static int get_r_sym( Elf_Xword info )
{
return ELF64_R_SYM( info );
}
static int get_r_type( Elf_Xword info )
{
return ELF64_R_TYPE( info );
}
};
//------------------------------------------------------------------------------
template< class S >
class relocation_section_accessor_template
{
public:
//------------------------------------------------------------------------------
relocation_section_accessor_template( const elfio& elf_file_, S* section_ ) :
elf_file( elf_file_ ),
relocation_section( section_ )
{
}
//------------------------------------------------------------------------------
Elf_Xword
get_entries_num() const
{
Elf_Xword nRet = 0;
if ( 0 != relocation_section->get_entry_size() ) {
nRet = relocation_section->get_size() / relocation_section->get_entry_size();
}
return nRet;
}
//------------------------------------------------------------------------------
bool
get_entry( Elf_Xword index,
Elf64_Addr& offset,
Elf_Word& symbol,
Elf_Word& type,
Elf_Sxword& addend ) const
{
if ( index >= get_entries_num() ) { // Is index valid
return false;
}
if ( elf_file.get_class() == ELFCLASS32 ) {
if ( SHT_REL == relocation_section->get_type() ) {
generic_get_entry_rel< Elf32_Rel >( index, offset, symbol,
type, addend );
}
else if ( SHT_RELA == relocation_section->get_type() ) {
generic_get_entry_rela< Elf32_Rela >( index, offset, symbol,
type, addend );
}
}
else {
if ( SHT_REL == relocation_section->get_type() ) {
generic_get_entry_rel< Elf64_Rel >( index, offset, symbol,
type, addend );
}
else if ( SHT_RELA == relocation_section->get_type() ) {
generic_get_entry_rela< Elf64_Rela >( index, offset, symbol,
type, addend );
}
}
return true;
}
//------------------------------------------------------------------------------
bool
get_entry( Elf_Xword index,
Elf64_Addr& offset,
Elf64_Addr& symbolValue,
std::string& symbolName,
Elf_Word& type,
Elf_Sxword& addend,
Elf_Sxword& calcValue ) const
{
// Do regular job
Elf_Word symbol;
bool ret = get_entry( index, offset, symbol, type, addend );
// Find the symbol
Elf_Xword size;
unsigned char bind;
unsigned char symbolType;
Elf_Half section;
unsigned char other;
symbol_section_accessor symbols( elf_file, elf_file.sections[get_symbol_table_index()] );
ret = ret && symbols.get_symbol( symbol, symbolName, symbolValue,
size, bind, symbolType, section, other );
if ( ret ) { // Was it successful?
switch ( type ) {
case R_386_NONE: // none
calcValue = 0;
break;
case R_386_32: // S + A
calcValue = symbolValue + addend;
break;
case R_386_PC32: // S + A - P
calcValue = symbolValue + addend - offset;
break;
case R_386_GOT32: // G + A - P
calcValue = 0;
break;
case R_386_PLT32: // L + A - P
calcValue = 0;
break;
case R_386_COPY: // none
calcValue = 0;
break;
case R_386_GLOB_DAT: // S
case R_386_JMP_SLOT: // S
calcValue = symbolValue;
break;
case R_386_RELATIVE: // B + A
calcValue = addend;
break;
case R_386_GOTOFF: // S + A - GOT
calcValue = 0;
break;
case R_386_GOTPC: // GOT + A - P
calcValue = 0;
break;
default: // Not recognized symbol!
calcValue = 0;
break;
}
}
return ret;
}
//------------------------------------------------------------------------------
void
add_entry( Elf64_Addr offset, Elf_Xword info )
{
if ( elf_file.get_class() == ELFCLASS32 ) {
generic_add_entry< Elf32_Rel >( offset, info );
}
else {
generic_add_entry< Elf64_Rel >( offset, info );
}
}
//------------------------------------------------------------------------------
void
add_entry( Elf64_Addr offset, Elf_Word symbol, unsigned char type )
{
Elf_Xword info;
if ( elf_file.get_class() == ELFCLASS32 ) {
info = ELF32_R_INFO( (Elf_Xword)symbol, type );
}
else {
info = ELF64_R_INFO((Elf_Xword)symbol, type );
}
add_entry( offset, info );
}
//------------------------------------------------------------------------------
void
add_entry( Elf64_Addr offset, Elf_Xword info, Elf_Sxword addend )
{
if ( elf_file.get_class() == ELFCLASS32 ) {
generic_add_entry< Elf32_Rela >( offset, info, addend );
}
else {
generic_add_entry< Elf64_Rela >( offset, info, addend );
}
}
//------------------------------------------------------------------------------
void
add_entry( Elf64_Addr offset, Elf_Word symbol, unsigned char type,
Elf_Sxword addend )
{
Elf_Xword info;
if ( elf_file.get_class() == ELFCLASS32 ) {
info = ELF32_R_INFO( (Elf_Xword)symbol, type );
}
else {
info = ELF64_R_INFO( (Elf_Xword)symbol, type );
}
add_entry( offset, info, addend );
}
//------------------------------------------------------------------------------
void
add_entry( string_section_accessor str_writer,
const char* str,
symbol_section_accessor sym_writer,
Elf64_Addr value,
Elf_Word size,
unsigned char sym_info,
unsigned char other,
Elf_Half shndx,
Elf64_Addr offset,
unsigned char type )
{
Elf_Word str_index = str_writer.add_string( str );
Elf_Word sym_index = sym_writer.add_symbol( str_index, value, size,
sym_info, other, shndx );
add_entry( offset, sym_index, type );
}
//------------------------------------------------------------------------------
private:
//------------------------------------------------------------------------------
Elf_Half
get_symbol_table_index() const
{
return (Elf_Half)relocation_section->get_link();
}
//------------------------------------------------------------------------------
template< class T >
void
generic_get_entry_rel( Elf_Xword index,
Elf64_Addr& offset,
Elf_Word& symbol,
Elf_Word& type,
Elf_Sxword& addend ) const
{
const endianess_convertor& convertor = elf_file.get_convertor();
const T* pEntry = reinterpret_cast<const T*>(
relocation_section->get_data() +
index * relocation_section->get_entry_size() );
offset = convertor( pEntry->r_offset );
Elf_Xword tmp = convertor( pEntry->r_info );
symbol = get_sym_and_type<T>::get_r_sym( tmp );
type = get_sym_and_type<T>::get_r_type( tmp );
addend = 0;
}
//------------------------------------------------------------------------------
template< class T >
void
generic_get_entry_rela( Elf_Xword index,
Elf64_Addr& offset,
Elf_Word& symbol,
Elf_Word& type,
Elf_Sxword& addend ) const
{
const endianess_convertor& convertor = elf_file.get_convertor();
const T* pEntry = reinterpret_cast<const T*>(
relocation_section->get_data() +
index * relocation_section->get_entry_size() );
offset = convertor( pEntry->r_offset );
Elf_Xword tmp = convertor( pEntry->r_info );
symbol = get_sym_and_type<T>::get_r_sym( tmp );
type = get_sym_and_type<T>::get_r_type( tmp );
addend = convertor( pEntry->r_addend );
}
//------------------------------------------------------------------------------
template< class T >
void
generic_add_entry( Elf64_Addr offset, Elf_Xword info )
{
const endianess_convertor& convertor = elf_file.get_convertor();
T entry;
entry.r_offset = offset;
entry.r_info = info;
entry.r_offset = convertor( entry.r_offset );
entry.r_info = convertor( entry.r_info );
relocation_section->append_data( reinterpret_cast<char*>( &entry ), sizeof( entry ) );
}
//------------------------------------------------------------------------------
template< class T >
void
generic_add_entry( Elf64_Addr offset, Elf_Xword info, Elf_Sxword addend )
{
const endianess_convertor& convertor = elf_file.get_convertor();
T entry;
entry.r_offset = offset;
entry.r_info = info;
entry.r_addend = addend;
entry.r_offset = convertor( entry.r_offset );
entry.r_info = convertor( entry.r_info );
entry.r_addend = convertor( entry.r_addend );
relocation_section->append_data( reinterpret_cast<char*>( &entry ), sizeof( entry ) );
}
//------------------------------------------------------------------------------
private:
const elfio& elf_file;
S* relocation_section;
};
using relocation_section_accessor = relocation_section_accessor_template<section>;
using const_relocation_section_accessor = relocation_section_accessor_template<const section>;
} // namespace ELFIO
#endif // ELFIO_RELOCATION_HPP

View File

@ -1,314 +0,0 @@
/*
Copyright (C) 2001-2015 by Serge Lamikhov-Center
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef ELFIO_SECTION_HPP
#define ELFIO_SECTION_HPP
#include <string>
#include <iostream>
namespace ELFIO {
class section
{
friend class elfio;
public:
virtual ~section() {};
ELFIO_GET_ACCESS_DECL ( Elf_Half, index );
ELFIO_GET_SET_ACCESS_DECL( std::string, name );
ELFIO_GET_SET_ACCESS_DECL( Elf_Word, type );
ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, flags );
ELFIO_GET_SET_ACCESS_DECL( Elf_Word, info );
ELFIO_GET_SET_ACCESS_DECL( Elf_Word, link );
ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, addr_align );
ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, entry_size );
ELFIO_GET_SET_ACCESS_DECL( Elf64_Addr, address );
ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, size );
ELFIO_GET_SET_ACCESS_DECL( Elf_Word, name_string_offset );
ELFIO_GET_ACCESS_DECL ( Elf64_Off, offset );
size_t stream_size;
size_t get_stream_size() const
{
return stream_size;
}
void set_stream_size(size_t value)
{
stream_size = value;
}
virtual const char* get_data() const = 0;
virtual void set_data( const char* pData, Elf_Word size ) = 0;
virtual void set_data( const std::string& data ) = 0;
virtual void append_data( const char* pData, Elf_Word size ) = 0;
virtual void append_data( const std::string& data ) = 0;
protected:
ELFIO_SET_ACCESS_DECL( Elf64_Off, offset );
ELFIO_SET_ACCESS_DECL( Elf_Half, index );
virtual void load( std::istream& stream,
std::streampos header_offset ) = 0;
virtual void save( std::ostream& stream,
std::streampos header_offset,
std::streampos data_offset ) = 0;
virtual bool is_address_initialized() const = 0;
};
template< class T >
class section_impl : public section
{
public:
//------------------------------------------------------------------------------
section_impl( const endianess_convertor* convertor_ ) : convertor( convertor_ )
{
std::fill_n( reinterpret_cast<char*>( &header ), sizeof( header ), '\0' );
is_address_set = false;
data = 0;
data_size = 0;
}
//------------------------------------------------------------------------------
~section_impl()
{
delete [] data;
}
//------------------------------------------------------------------------------
// Section info functions
ELFIO_GET_SET_ACCESS( Elf_Word, type, header.sh_type );
ELFIO_GET_SET_ACCESS( Elf_Xword, flags, header.sh_flags );
ELFIO_GET_SET_ACCESS( Elf_Xword, size, header.sh_size );
ELFIO_GET_SET_ACCESS( Elf_Word, link, header.sh_link );
ELFIO_GET_SET_ACCESS( Elf_Word, info, header.sh_info );
ELFIO_GET_SET_ACCESS( Elf_Xword, addr_align, header.sh_addralign );
ELFIO_GET_SET_ACCESS( Elf_Xword, entry_size, header.sh_entsize );
ELFIO_GET_SET_ACCESS( Elf_Word, name_string_offset, header.sh_name );
ELFIO_GET_ACCESS ( Elf64_Addr, address, header.sh_addr );
//------------------------------------------------------------------------------
Elf_Half
get_index() const
{
return index;
}
//------------------------------------------------------------------------------
std::string
get_name() const
{
return name;
}
//------------------------------------------------------------------------------
void
set_name( std::string name_ )
{
name = name_;
}
//------------------------------------------------------------------------------
void
set_address( Elf64_Addr value )
{
header.sh_addr = value;
header.sh_addr = (*convertor)( header.sh_addr );
is_address_set = true;
}
//------------------------------------------------------------------------------
bool
is_address_initialized() const
{
return is_address_set;
}
//------------------------------------------------------------------------------
const char*
get_data() const
{
return data;
}
//------------------------------------------------------------------------------
void
set_data( const char* raw_data, Elf_Word size )
{
if ( get_type() != SHT_NOBITS ) {
delete [] data;
try {
data = new char[size];
} catch (const std::bad_alloc&) {
data = 0;
data_size = 0;
size = 0;
}
if ( 0 != data && 0 != raw_data ) {
data_size = size;
std::copy( raw_data, raw_data + size, data );
}
}
set_size( size );
}
//------------------------------------------------------------------------------
void
set_data( const std::string& str_data )
{
return set_data( str_data.c_str(), (Elf_Word)str_data.size() );
}
//------------------------------------------------------------------------------
void
append_data( const char* raw_data, Elf_Word size )
{
if ( get_type() != SHT_NOBITS ) {
if ( get_size() + size < data_size ) {
std::copy( raw_data, raw_data + size, data + get_size() );
}
else {
data_size = 2*( data_size + size);
char* new_data;
try {
new_data = new char[data_size];
} catch (const std::bad_alloc&) {
new_data = 0;
size = 0;
}
if ( 0 != new_data ) {
std::copy( data, data + get_size(), new_data );
std::copy( raw_data, raw_data + size, new_data + get_size() );
delete [] data;
data = new_data;
}
}
set_size( get_size() + size );
}
}
//------------------------------------------------------------------------------
void
append_data( const std::string& str_data )
{
return append_data( str_data.c_str(), (Elf_Word)str_data.size() );
}
//------------------------------------------------------------------------------
protected:
//------------------------------------------------------------------------------
ELFIO_GET_SET_ACCESS( Elf64_Off, offset, header.sh_offset );
//------------------------------------------------------------------------------
void
set_index( Elf_Half value )
{
index = value;
}
//------------------------------------------------------------------------------
void
load( std::istream& stream,
std::streampos header_offset )
{
std::fill_n( reinterpret_cast<char*>( &header ), sizeof( header ), '\0' );
stream.seekg ( 0, stream.end );
set_stream_size ( stream.tellg() );
stream.seekg( header_offset );
stream.read( reinterpret_cast<char*>( &header ), sizeof( header ) );
Elf_Xword size = get_size();
if ( 0 == data && SHT_NULL != get_type() && SHT_NOBITS != get_type() && size < get_stream_size()) {
try {
data = new char[size + 1];
} catch (const std::bad_alloc&) {
data = 0;
data_size = 0;
}
if ( ( 0 != size ) && ( 0 != data ) ) {
stream.seekg( (*convertor)( header.sh_offset ) );
stream.read( data, size );
data[size] = 0; // Ensure data is ended with 0 to avoid oob read
data_size = size;
}
}
}
//------------------------------------------------------------------------------
void
save( std::ostream& stream,
std::streampos header_offset,
std::streampos data_offset )
{
if ( 0 != get_index() ) {
header.sh_offset = data_offset;
header.sh_offset = (*convertor)( header.sh_offset );
}
save_header( stream, header_offset );
if ( get_type() != SHT_NOBITS && get_type() != SHT_NULL &&
get_size() != 0 && data != 0 ) {
save_data( stream, data_offset );
}
}
//------------------------------------------------------------------------------
private:
//------------------------------------------------------------------------------
void
save_header( std::ostream& stream,
std::streampos header_offset ) const
{
stream.seekp( header_offset );
stream.write( reinterpret_cast<const char*>( &header ), sizeof( header ) );
}
//------------------------------------------------------------------------------
void
save_data( std::ostream& stream,
std::streampos data_offset ) const
{
stream.seekp( data_offset );
stream.write( get_data(), get_size() );
}
//------------------------------------------------------------------------------
private:
T header;
Elf_Half index;
std::string name;
char* data;
Elf_Word data_size;
const endianess_convertor* convertor;
bool is_address_set;
};
} // namespace ELFIO
#endif // ELFIO_SECTION_HPP

View File

@ -1,246 +0,0 @@
/*
Copyright (C) 2001-2015 by Serge Lamikhov-Center
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef ELFIO_SEGMENT_HPP
#define ELFIO_SEGMENT_HPP
#include <iostream>
#include <vector>
namespace ELFIO {
class segment
{
friend class elfio;
public:
virtual ~segment() {};
ELFIO_GET_ACCESS_DECL ( Elf_Half, index );
ELFIO_GET_SET_ACCESS_DECL( Elf_Word, type );
ELFIO_GET_SET_ACCESS_DECL( Elf_Word, flags );
ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, align );
ELFIO_GET_SET_ACCESS_DECL( Elf64_Addr, virtual_address );
ELFIO_GET_SET_ACCESS_DECL( Elf64_Addr, physical_address );
ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, file_size );
ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, memory_size );
ELFIO_GET_ACCESS_DECL( Elf64_Off, offset );
virtual const char* get_data() const = 0;
virtual Elf_Half add_section_index( Elf_Half index, Elf_Xword addr_align ) = 0;
virtual Elf_Half get_sections_num() const = 0;
virtual Elf_Half get_section_index_at( Elf_Half num ) const = 0;
virtual bool is_offset_initialized() const = 0;
protected:
ELFIO_SET_ACCESS_DECL( Elf64_Off, offset );
ELFIO_SET_ACCESS_DECL( Elf_Half, index );
virtual const std::vector<Elf_Half>& get_sections() const = 0;
virtual void load( std::istream& stream, std::streampos header_offset ) = 0;
virtual void save( std::ostream& stream, std::streampos header_offset,
std::streampos data_offset ) = 0;
};
//------------------------------------------------------------------------------
template< class T >
class segment_impl : public segment
{
public:
//------------------------------------------------------------------------------
segment_impl( endianess_convertor* convertor_ ) :
stream_size( 0 ), index( 0 ), data( 0 ), convertor( convertor_ )
{
is_offset_set = false;
std::fill_n( reinterpret_cast<char*>( &ph ), sizeof( ph ), '\0' );
}
//------------------------------------------------------------------------------
virtual ~segment_impl()
{
delete [] data;
}
//------------------------------------------------------------------------------
// Section info functions
ELFIO_GET_SET_ACCESS( Elf_Word, type, ph.p_type );
ELFIO_GET_SET_ACCESS( Elf_Word, flags, ph.p_flags );
ELFIO_GET_SET_ACCESS( Elf_Xword, align, ph.p_align );
ELFIO_GET_SET_ACCESS( Elf64_Addr, virtual_address, ph.p_vaddr );
ELFIO_GET_SET_ACCESS( Elf64_Addr, physical_address, ph.p_paddr );
ELFIO_GET_SET_ACCESS( Elf_Xword, file_size, ph.p_filesz );
ELFIO_GET_SET_ACCESS( Elf_Xword, memory_size, ph.p_memsz );
ELFIO_GET_ACCESS( Elf64_Off, offset, ph.p_offset );
size_t stream_size;
//------------------------------------------------------------------------------
size_t
get_stream_size() const
{
return stream_size;
}
//------------------------------------------------------------------------------
void
set_stream_size(size_t value)
{
stream_size = value;
}
//------------------------------------------------------------------------------
Elf_Half
get_index() const
{
return index;
}
//------------------------------------------------------------------------------
const char*
get_data() const
{
return data;
}
//------------------------------------------------------------------------------
Elf_Half
add_section_index( Elf_Half sec_index, Elf_Xword addr_align )
{
sections.push_back( sec_index );
if ( addr_align > get_align() ) {
set_align( addr_align );
}
return (Elf_Half)sections.size();
}
//------------------------------------------------------------------------------
Elf_Half
get_sections_num() const
{
return (Elf_Half)sections.size();
}
//------------------------------------------------------------------------------
Elf_Half
get_section_index_at( Elf_Half num ) const
{
if ( num < sections.size() ) {
return sections[num];
}
return Elf_Half(-1);
}
//------------------------------------------------------------------------------
protected:
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void
set_offset( Elf64_Off value )
{
ph.p_offset = value;
ph.p_offset = (*convertor)( ph.p_offset );
is_offset_set = true;
}
//------------------------------------------------------------------------------
bool
is_offset_initialized() const
{
return is_offset_set;
}
//------------------------------------------------------------------------------
const std::vector<Elf_Half>&
get_sections() const
{
return sections;
}
//------------------------------------------------------------------------------
void
set_index( Elf_Half value )
{
index = value;
}
//------------------------------------------------------------------------------
void
load( std::istream& stream,
std::streampos header_offset )
{
stream.seekg ( 0, stream.end );
set_stream_size ( stream.tellg() );
stream.seekg( header_offset );
stream.read( reinterpret_cast<char*>( &ph ), sizeof( ph ) );
is_offset_set = true;
if ( PT_NULL != get_type() && 0 != get_file_size() ) {
stream.seekg( (*convertor)( ph.p_offset ) );
Elf_Xword size = get_file_size();
if ( size > get_stream_size() ) {
data = 0;
}
else {
try {
data = new char[size + 1];
} catch (const std::bad_alloc&) {
data = 0;
}
if ( 0 != data ) {
stream.read( data, size );
data[size] = 0;
}
}
}
}
//------------------------------------------------------------------------------
void save( std::ostream& stream,
std::streampos header_offset,
std::streampos data_offset )
{
ph.p_offset = data_offset;
ph.p_offset = (*convertor)(ph.p_offset);
stream.seekp( header_offset );
stream.write( reinterpret_cast<const char*>( &ph ), sizeof( ph ) );
}
//------------------------------------------------------------------------------
private:
T ph;
Elf_Half index;
char* data;
std::vector<Elf_Half> sections;
endianess_convertor* convertor;
bool is_offset_set;
};
} // namespace ELFIO
#endif // ELFIO_SEGMENT_HPP

View File

@ -1,100 +0,0 @@
/*
Copyright (C) 2001-2015 by Serge Lamikhov-Center
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef ELFIO_STRINGS_HPP
#define ELFIO_STRINGS_HPP
#include <cstdlib>
#include <cstring>
#include <string>
namespace ELFIO {
//------------------------------------------------------------------------------
template< class S >
class string_section_accessor_template
{
public:
//------------------------------------------------------------------------------
string_section_accessor_template( S* section_ ) :
string_section( section_ )
{
}
//------------------------------------------------------------------------------
const char*
get_string( Elf_Word index ) const
{
if ( string_section ) {
if ( index < string_section->get_size() ) {
const char* data = string_section->get_data();
if ( 0 != data ) {
return data + index;
}
}
}
return 0;
}
//------------------------------------------------------------------------------
Elf_Word
add_string( const char* str )
{
Elf_Word current_position = 0;
if (string_section) {
// Strings are addeded to the end of the current section data
current_position = (Elf_Word)string_section->get_size();
if ( current_position == 0 ) {
char empty_string = '\0';
string_section->append_data( &empty_string, 1 );
current_position++;
}
string_section->append_data( str, (Elf_Word)std::strlen( str ) + 1 );
}
return current_position;
}
//------------------------------------------------------------------------------
Elf_Word
add_string( const std::string& str )
{
return add_string( str.c_str() );
}
//------------------------------------------------------------------------------
private:
S* string_section;
};
using string_section_accessor = string_section_accessor_template<section>;
using const_string_section_accessor = string_section_accessor_template<const section>;
} // namespace ELFIO
#endif // ELFIO_STRINGS_HPP

View File

@ -1,282 +0,0 @@
/*
Copyright (C) 2001-2015 by Serge Lamikhov-Center
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef ELFIO_SYMBOLS_HPP
#define ELFIO_SYMBOLS_HPP
namespace ELFIO {
//------------------------------------------------------------------------------
template< class S >
class symbol_section_accessor_template
{
public:
//------------------------------------------------------------------------------
symbol_section_accessor_template( const elfio& elf_file_, S* symbol_section_ ) :
elf_file( elf_file_ ),
symbol_section( symbol_section_ )
{
find_hash_section();
}
//------------------------------------------------------------------------------
Elf_Xword
get_symbols_num() const
{
Elf_Xword nRet = 0;
if ( 0 != symbol_section->get_entry_size() ) {
nRet = symbol_section->get_size() / symbol_section->get_entry_size();
}
return nRet;
}
//------------------------------------------------------------------------------
bool
get_symbol( Elf_Xword index,
std::string& name,
Elf64_Addr& value,
Elf_Xword& size,
unsigned char& bind,
unsigned char& type,
Elf_Half& section_index,
unsigned char& other ) const
{
bool ret = false;
if ( elf_file.get_class() == ELFCLASS32 ) {
ret = generic_get_symbol<Elf32_Sym>( index, name, value, size, bind,
type, section_index, other );
}
else {
ret = generic_get_symbol<Elf64_Sym>( index, name, value, size, bind,
type, section_index, other );
}
return ret;
}
//------------------------------------------------------------------------------
bool
get_symbol( const std::string& name,
Elf64_Addr& value,
Elf_Xword& size,
unsigned char& bind,
unsigned char& type,
Elf_Half& section_index,
unsigned char& other ) const
{
bool ret = false;
if ( 0 != get_hash_table_index() ) {
Elf_Word nbucket = *(const Elf_Word*)hash_section->get_data();
Elf_Word nchain = *(const Elf_Word*)( hash_section->get_data() +
sizeof( Elf_Word ) );
Elf_Word val = elf_hash( (const unsigned char*)name.c_str() );
Elf_Word y = *(const Elf_Word*)( hash_section->get_data() +
( 2 + val % nbucket ) * sizeof( Elf_Word ) );
std::string str;
get_symbol( y, str, value, size, bind, type, section_index, other );
while ( str != name && STN_UNDEF != y && y < nchain ) {
y = *(const Elf_Word*)( hash_section->get_data() +
( 2 + nbucket + y ) * sizeof( Elf_Word ) );
get_symbol( y, str, value, size, bind, type, section_index, other );
}
if ( str == name ) {
ret = true;
}
}
return ret;
}
//------------------------------------------------------------------------------
Elf_Word
add_symbol( Elf_Word name, Elf64_Addr value, Elf_Xword size,
unsigned char info, unsigned char other,
Elf_Half shndx )
{
Elf_Word nRet;
if ( symbol_section->get_size() == 0 ) {
if ( elf_file.get_class() == ELFCLASS32 ) {
nRet = generic_add_symbol<Elf32_Sym>( 0, 0, 0, 0, 0, 0 );
}
else {
nRet = generic_add_symbol<Elf64_Sym>( 0, 0, 0, 0, 0, 0 );
}
}
if ( elf_file.get_class() == ELFCLASS32 ) {
nRet = generic_add_symbol<Elf32_Sym>( name, value, size, info, other,
shndx );
}
else {
nRet = generic_add_symbol<Elf64_Sym>( name, value, size, info, other,
shndx );
}
return nRet;
}
//------------------------------------------------------------------------------
Elf_Word
add_symbol( Elf_Word name, Elf64_Addr value, Elf_Xword size,
unsigned char bind, unsigned char type, unsigned char other,
Elf_Half shndx )
{
return add_symbol( name, value, size, ELF_ST_INFO( bind, type ), other, shndx );
}
//------------------------------------------------------------------------------
Elf_Word
add_symbol( string_section_accessor& pStrWriter, const char* str,
Elf64_Addr value, Elf_Xword size,
unsigned char info, unsigned char other,
Elf_Half shndx )
{
Elf_Word index = pStrWriter.add_string( str );
return add_symbol( index, value, size, info, other, shndx );
}
//------------------------------------------------------------------------------
Elf_Word
add_symbol( string_section_accessor& pStrWriter, const char* str,
Elf64_Addr value, Elf_Xword size,
unsigned char bind, unsigned char type, unsigned char other,
Elf_Half shndx )
{
return add_symbol( pStrWriter, str, value, size, ELF_ST_INFO( bind, type ), other, shndx );
}
//------------------------------------------------------------------------------
private:
//------------------------------------------------------------------------------
void
find_hash_section()
{
hash_section = 0;
hash_section_index = 0;
Elf_Half nSecNo = elf_file.sections.size();
for ( Elf_Half i = 0; i < nSecNo && 0 == hash_section_index; ++i ) {
const section* sec = elf_file.sections[i];
if ( sec->get_link() == symbol_section->get_index() ) {
hash_section = sec;
hash_section_index = i;
}
}
}
//------------------------------------------------------------------------------
Elf_Half
get_string_table_index() const
{
return (Elf_Half)symbol_section->get_link();
}
//------------------------------------------------------------------------------
Elf_Half
get_hash_table_index() const
{
return hash_section_index;
}
//------------------------------------------------------------------------------
template< class T >
bool
generic_get_symbol( Elf_Xword index,
std::string& name, Elf64_Addr& value,
Elf_Xword& size,
unsigned char& bind, unsigned char& type,
Elf_Half& section_index,
unsigned char& other ) const
{
bool ret = false;
if ( index < get_symbols_num() ) {
const T* pSym = reinterpret_cast<const T*>(
symbol_section->get_data() +
index * symbol_section->get_entry_size() );
const endianess_convertor& convertor = elf_file.get_convertor();
section* string_section = elf_file.sections[get_string_table_index()];
string_section_accessor str_reader( string_section );
const char* pStr = str_reader.get_string( convertor( pSym->st_name ) );
if ( 0 != pStr ) {
name = pStr;
}
value = convertor( pSym->st_value );
size = convertor( pSym->st_size );
bind = ELF_ST_BIND( pSym->st_info );
type = ELF_ST_TYPE( pSym->st_info );
section_index = convertor( pSym->st_shndx );
other = pSym->st_other;
ret = true;
}
return ret;
}
//------------------------------------------------------------------------------
template< class T >
Elf_Word
generic_add_symbol( Elf_Word name, Elf64_Addr value, Elf_Xword size,
unsigned char info, unsigned char other,
Elf_Half shndx )
{
const endianess_convertor& convertor = elf_file.get_convertor();
T entry;
entry.st_name = convertor( name );
entry.st_value = value;
entry.st_value = convertor( entry.st_value );
entry.st_size = size;
entry.st_size = convertor( entry.st_size );
entry.st_info = convertor( info );
entry.st_other = convertor( other );
entry.st_shndx = convertor( shndx );
symbol_section->append_data( reinterpret_cast<char*>( &entry ),
sizeof( entry ) );
Elf_Word nRet = symbol_section->get_size() / sizeof( entry ) - 1;
return nRet;
}
//------------------------------------------------------------------------------
private:
const elfio& elf_file;
S* symbol_section;
Elf_Half hash_section_index;
const section* hash_section;
};
using symbol_section_accessor = symbol_section_accessor_template<section>;
using const_symbol_section_accessor = symbol_section_accessor_template<const section>;
} // namespace ELFIO
#endif // ELFIO_SYMBOLS_HPP

View File

@ -1,209 +0,0 @@
/*
Copyright (C) 2001-2015 by Serge Lamikhov-Center
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef ELFIO_UTILS_HPP
#define ELFIO_UTILS_HPP
#define ELFIO_GET_ACCESS( TYPE, NAME, FIELD ) \
TYPE get_##NAME() const \
{ \
return (*convertor)( FIELD ); \
}
#define ELFIO_SET_ACCESS( TYPE, NAME, FIELD ) \
void set_##NAME( TYPE value ) \
{ \
FIELD = value; \
FIELD = (*convertor)( FIELD ); \
}
#define ELFIO_GET_SET_ACCESS( TYPE, NAME, FIELD ) \
TYPE get_##NAME() const \
{ \
return (*convertor)( FIELD ); \
} \
void set_##NAME( TYPE value ) \
{ \
FIELD = value; \
FIELD = (*convertor)( FIELD ); \
}
#define ELFIO_GET_ACCESS_DECL( TYPE, NAME ) \
virtual TYPE get_##NAME() const = 0
#define ELFIO_SET_ACCESS_DECL( TYPE, NAME ) \
virtual void set_##NAME( TYPE value ) = 0
#define ELFIO_GET_SET_ACCESS_DECL( TYPE, NAME ) \
virtual TYPE get_##NAME() const = 0; \
virtual void set_##NAME( TYPE value ) = 0
namespace ELFIO {
//------------------------------------------------------------------------------
class endianess_convertor {
public:
//------------------------------------------------------------------------------
endianess_convertor()
{
need_conversion = false;
}
//------------------------------------------------------------------------------
void
setup( unsigned char elf_file_encoding )
{
need_conversion = ( elf_file_encoding != get_host_encoding() );
}
//------------------------------------------------------------------------------
uint64_t
operator()( uint64_t value ) const
{
if ( !need_conversion ) {
return value;
}
value =
( ( value & 0x00000000000000FFull ) << 56 ) |
( ( value & 0x000000000000FF00ull ) << 40 ) |
( ( value & 0x0000000000FF0000ull ) << 24 ) |
( ( value & 0x00000000FF000000ull ) << 8 ) |
( ( value & 0x000000FF00000000ull ) >> 8 ) |
( ( value & 0x0000FF0000000000ull ) >> 24 ) |
( ( value & 0x00FF000000000000ull ) >> 40 ) |
( ( value & 0xFF00000000000000ull ) >> 56 );
return value;
}
//------------------------------------------------------------------------------
int64_t
operator()( int64_t value ) const
{
if ( !need_conversion ) {
return value;
}
return (int64_t)(*this)( (uint64_t)value );
}
//------------------------------------------------------------------------------
uint32_t
operator()( uint32_t value ) const
{
if ( !need_conversion ) {
return value;
}
value =
( ( value & 0x000000FF ) << 24 ) |
( ( value & 0x0000FF00 ) << 8 ) |
( ( value & 0x00FF0000 ) >> 8 ) |
( ( value & 0xFF000000 ) >> 24 );
return value;
}
//------------------------------------------------------------------------------
int32_t
operator()( int32_t value ) const
{
if ( !need_conversion ) {
return value;
}
return (int32_t)(*this)( (uint32_t)value );
}
//------------------------------------------------------------------------------
uint16_t
operator()( uint16_t value ) const
{
if ( !need_conversion ) {
return value;
}
value =
( ( value & 0x00FF ) << 8 ) |
( ( value & 0xFF00 ) >> 8 );
return value;
}
//------------------------------------------------------------------------------
int16_t
operator()( int16_t value ) const
{
if ( !need_conversion ) {
return value;
}
return (int16_t)(*this)( (uint16_t)value );
}
//------------------------------------------------------------------------------
int8_t
operator()( int8_t value ) const
{
return value;
}
//------------------------------------------------------------------------------
uint8_t
operator()( uint8_t value ) const
{
return value;
}
//------------------------------------------------------------------------------
private:
//------------------------------------------------------------------------------
unsigned char
get_host_encoding() const
{
static const int tmp = 1;
if ( 1 == *(const char*)&tmp ) {
return ELFDATA2LSB;
}
else {
return ELFDATA2MSB;
}
}
//------------------------------------------------------------------------------
private:
bool need_conversion;
};
//------------------------------------------------------------------------------
inline
uint32_t
elf_hash( const unsigned char *name )
{
uint32_t h = 0, g;
while ( *name ) {
h = (h << 4) + *name++;
g = h & 0xf0000000;
if ( g != 0 )
h ^= g >> 24;
h &= ~g;
}
return h;
}
} // namespace ELFIO
#endif // ELFIO_UTILS_HPP

View File

@ -77,8 +77,8 @@ void Ship::CollisionHeaderFactoryV0::ParseFileBinary(std::shared_ptr<BinaryReade
for (uint32_t i = 0; i < collisionHeader->surfaceTypesCount; i++) {
SurfaceType surfaceType;
surfaceType.data[1] = reader->ReadUInt32();
surfaceType.data[0] = reader->ReadUInt32();
surfaceType.data[1] = reader->ReadUInt32();
collisionHeader->surfaceTypes.push_back(surfaceType);
}

View File

@ -52,13 +52,12 @@ std::shared_ptr<Ship::File> ResourceMgr_LoadFile(const char* path) {
// Forward Declaration of function declared in OTRGlobals.cpp
std::shared_ptr<Ship::Resource> GetResourceByNameHandlingMQ(const char* path);
bool Scene_CommandSpawnList(PlayState* play, Ship::SceneCommand* cmd)
{
bool Scene_CommandSpawnList(PlayState* play, Ship::SceneCommand* cmd) {
// Ship::SetStartPositionList* cmdStartPos = std::static_pointer_cast<Ship::SetStartPositionList>(cmd);
Ship::SetStartPositionList* cmdStartPos = (Ship::SetStartPositionList*)cmd;
ActorEntry* entries = (ActorEntry*)cmdStartPos->GetPointer();
play->linkActorEntry = &entries[play->setupEntranceList[play->curSpawn].spawn];;
play->linkActorEntry = &entries[play->setupEntranceList[play->curSpawn].spawn];
play->linkAgeOnLoad = ((void)0, gSaveContext.linkAge);
s16 linkObjectId = gLinkObjectIds[((void)0, gSaveContext.linkAge)];
@ -77,16 +76,14 @@ bool Scene_CommandActorList(PlayState* play, Ship::SceneCommand* cmd) {
return false;
}
bool Scene_CommandUnused2(PlayState* play, Ship::SceneCommand* cmd)
{
bool Scene_CommandUnused2(PlayState* play, Ship::SceneCommand* cmd) {
// OTRTODO: Do we need to implement this?
//play->unk_11DFC = SEGMENTED_TO_VIRTUAL(cmd->unused02.segment);
// play->unk_11DFC = SEGMENTED_TO_VIRTUAL(cmd->unused02.segment);
return false;
}
bool Scene_CommandCollisionHeader(PlayState* play, Ship::SceneCommand* cmd)
{
bool Scene_CommandCollisionHeader(PlayState* play, Ship::SceneCommand* cmd) {
// Ship::SetCollisionHeader* cmdCol = std::static_pointer_cast<Ship::SetCollisionHeader>(cmd);
Ship::SetCollisionHeader* cmdCol = (Ship::SetCollisionHeader*)cmd;
BgCheck_Allocate(&play->colCtx, play, (CollisionHeader*)cmdCol->GetPointer());
@ -94,8 +91,7 @@ bool Scene_CommandCollisionHeader(PlayState* play, Ship::SceneCommand* cmd)
return false;
}
bool Scene_CommandRoomList(PlayState* play, Ship::SceneCommand* cmd)
{
bool Scene_CommandRoomList(PlayState* play, Ship::SceneCommand* cmd) {
// Ship::SetRoomList* cmdRoomList = std::static_pointer_cast<Ship::SetRoomList>(cmd);
Ship::SetRoomList* cmdRoomList = (Ship::SetRoomList*)cmd;
@ -105,8 +101,7 @@ bool Scene_CommandRoomList(PlayState* play, Ship::SceneCommand* cmd)
return false;
}
bool Scene_CommandEntranceList(PlayState* play, Ship::SceneCommand* cmd)
{
bool Scene_CommandEntranceList(PlayState* play, Ship::SceneCommand* cmd) {
// Ship::SetEntranceList* otrEntrance = std::static_pointer_cast<Ship::SetEntranceList>(cmd);
Ship::SetEntranceList* otrEntrance = (Ship::SetEntranceList*)cmd;
play->setupEntranceList = (EntranceEntry*)otrEntrance->GetPointer();
@ -114,8 +109,7 @@ bool Scene_CommandEntranceList(PlayState* play, Ship::SceneCommand* cmd)
return false;
}
bool Scene_CommandSpecialFiles(PlayState* play, Ship::SceneCommand* cmd)
{
bool Scene_CommandSpecialFiles(PlayState* play, Ship::SceneCommand* cmd) {
// Ship::SetSpecialObjects* specialCmd = std::static_pointer_cast<Ship::SetSpecialObjects>(cmd);
Ship::SetSpecialObjects* specialCmd = (Ship::SetSpecialObjects*)cmd;
@ -124,15 +118,15 @@ bool Scene_CommandSpecialFiles(PlayState* play, Ship::SceneCommand* cmd)
}
if (specialCmd->specialObjects.elfMessage != 0) {
auto res = (Ship::Blob*)OTRPlay_LoadFile(play, sNaviMsgFiles[specialCmd->specialObjects.elfMessage - 1].fileName);
auto res =
(Ship::Blob*)OTRPlay_LoadFile(play, sNaviMsgFiles[specialCmd->specialObjects.elfMessage - 1].fileName);
play->cUpElfMsgs = (ElfMessage*)res->Data.data();
}
return false;
}
bool Scene_CommandRoomBehavior(PlayState* play, Ship::SceneCommand* cmd)
{
bool Scene_CommandRoomBehavior(PlayState* play, Ship::SceneCommand* cmd) {
// Ship::SetRoomBehavior* cmdRoom = std::static_pointer_cast<Ship::SetRoomBehavior>(cmd);
Ship::SetRoomBehavior* cmdRoom = (Ship::SetRoomBehavior*)cmd;
@ -144,8 +138,7 @@ bool Scene_CommandRoomBehavior(PlayState* play, Ship::SceneCommand* cmd)
return false;
}
bool Scene_CommandMeshHeader(PlayState* play, Ship::SceneCommand* cmd)
{
bool Scene_CommandMeshHeader(PlayState* play, Ship::SceneCommand* cmd) {
// Ship::SetMesh* otrMesh = static_pointer_cast<Ship::SetMesh>(cmd);
Ship::SetMesh* otrMesh = (Ship::SetMesh*)cmd;
play->roomCtx.curRoom.meshHeader = (MeshHeader*)otrMesh->GetPointer();
@ -153,10 +146,9 @@ bool Scene_CommandMeshHeader(PlayState* play, Ship::SceneCommand* cmd)
return false;
}
extern "C" void* func_800982FC(ObjectContext * objectCtx, s32 bankIndex, s16 objectId);
extern "C" void* func_800982FC(ObjectContext* objectCtx, s32 bankIndex, s16 objectId);
bool Scene_CommandObjectList(PlayState* play, Ship::SceneCommand* cmd)
{
bool Scene_CommandObjectList(PlayState* play, Ship::SceneCommand* cmd) {
// Ship::SetObjectList* cmdObj = static_pointer_cast<Ship::SetObjectList>(cmd);
Ship::SetObjectList* cmdObj = (Ship::SetObjectList*)cmd;
@ -166,12 +158,12 @@ bool Scene_CommandObjectList(PlayState* play, Ship::SceneCommand* cmd)
ObjectStatus* status;
ObjectStatus* status2;
ObjectStatus* firstStatus;
//s16* objectEntry = SEGMENTED_TO_VIRTUAL(cmd->objectList.segment);
// s16* objectEntry = SEGMENTED_TO_VIRTUAL(cmd->objectList.segment);
s16* objectEntry = (s16*)cmdObj->GetPointer();
void* nextPtr;
k = 0;
//i = play->objectCtx.unk_09;
// i = play->objectCtx.unk_09;
i = 0;
firstStatus = &play->objectCtx.status[0];
status = &play->objectCtx.status[i];
@ -218,21 +210,18 @@ bool Scene_CommandObjectList(PlayState* play, Ship::SceneCommand* cmd)
return false;
}
bool Scene_CommandLightList(PlayState* play, Ship::SceneCommand* cmd)
{
bool Scene_CommandLightList(PlayState* play, Ship::SceneCommand* cmd) {
// Ship::SetLightList* cmdLight = static_pointer_cast<Ship::SetLightList>(cmd);
Ship::SetLightList* cmdLight = (Ship::SetLightList*)cmd;
for (size_t i = 0; i < cmdLight->lightList.size(); i++)
{
for (size_t i = 0; i < cmdLight->lightList.size(); i++) {
LightContext_InsertLight(play, &play->lightCtx, (LightInfo*)&cmdLight->lightList[i]);
}
return false;
}
bool Scene_CommandPathList(PlayState* play, Ship::SceneCommand* cmd)
{
bool Scene_CommandPathList(PlayState* play, Ship::SceneCommand* cmd) {
// Ship::SetPathways* cmdPath = static_pointer_cast<Ship::SetPathways>(cmd);
Ship::SetPathways* cmdPath = (Ship::SetPathways*)cmd;
play->setupPathList = (Path*)cmdPath->paths[0]->GetPointer();
@ -250,20 +239,18 @@ bool Scene_CommandTransitionActorList(PlayState* play, Ship::SceneCommand* cmd)
return false;
}
//void TransitionActor_InitContext(GameState* state, TransitionActorContext* transiActorCtx) {
// void TransitionActor_InitContext(GameState* state, TransitionActorContext* transiActorCtx) {
// transiActorCtx->numActors = 0;
//}
bool Scene_CommandLightSettingsList(PlayState* play, Ship::SceneCommand* cmd)
{
bool Scene_CommandLightSettingsList(PlayState* play, Ship::SceneCommand* cmd) {
play->envCtx.lightSettingsList = (EnvLightSettings*)cmd->GetPointer();
return false;
}
// Scene Command 0x11: Skybox Settings
bool Scene_CommandSkyboxSettings(PlayState* play, Ship::SceneCommand* cmd)
{
bool Scene_CommandSkyboxSettings(PlayState* play, Ship::SceneCommand* cmd) {
// Ship::SetSkyboxSettings* cmdSky = static_pointer_cast<Ship::SetSkyboxSettings>(cmd);
Ship::SetSkyboxSettings* cmdSky = (Ship::SetSkyboxSettings*)cmd;
@ -274,8 +261,7 @@ bool Scene_CommandSkyboxSettings(PlayState* play, Ship::SceneCommand* cmd)
return false;
}
bool Scene_CommandSkyboxDisables(PlayState* play, Ship::SceneCommand* cmd)
{
bool Scene_CommandSkyboxDisables(PlayState* play, Ship::SceneCommand* cmd) {
// Ship::SetSkyboxModifier* cmdSky = static_pointer_cast<Ship::SetSkyboxModifier>(cmd);
Ship::SetSkyboxModifier* cmdSky = (Ship::SetSkyboxModifier*)cmd;
@ -285,8 +271,7 @@ bool Scene_CommandSkyboxDisables(PlayState* play, Ship::SceneCommand* cmd)
return false;
}
bool Scene_CommandTimeSettings(PlayState* play, Ship::SceneCommand* cmd)
{
bool Scene_CommandTimeSettings(PlayState* play, Ship::SceneCommand* cmd) {
// Ship::SetTimeSettings* cmdTime = static_pointer_cast<Ship::SetTimeSettings>(cmd);
Ship::SetTimeSettings* cmdTime = (Ship::SetTimeSettings*)cmd;
@ -297,8 +282,7 @@ bool Scene_CommandTimeSettings(PlayState* play, Ship::SceneCommand* cmd)
if (cmdTime->settings.timeIncrement != 0xFF) {
play->envCtx.timeIncrement = cmdTime->settings.timeIncrement;
}
else {
} else {
play->envCtx.timeIncrement = 0;
}
@ -315,14 +299,11 @@ bool Scene_CommandTimeSettings(PlayState* play, Ship::SceneCommand* cmd)
gSaveContext.skyboxTime = ((void)0, gSaveContext.dayTime);
if ((gSaveContext.skyboxTime >= 0x2AAC) && (gSaveContext.skyboxTime < 0x4555)) {
gSaveContext.skyboxTime = 0x3556;
}
else if ((gSaveContext.skyboxTime >= 0x4555) && (gSaveContext.skyboxTime < 0x5556)) {
} else if ((gSaveContext.skyboxTime >= 0x4555) && (gSaveContext.skyboxTime < 0x5556)) {
gSaveContext.skyboxTime = 0x5556;
}
else if ((gSaveContext.skyboxTime >= 0xAAAB) && (gSaveContext.skyboxTime < 0xB556)) {
} else if ((gSaveContext.skyboxTime >= 0xAAAB) && (gSaveContext.skyboxTime < 0xB556)) {
gSaveContext.skyboxTime = 0xB556;
}
else if ((gSaveContext.skyboxTime >= 0xC001) && (gSaveContext.skyboxTime < 0xCAAC)) {
} else if ((gSaveContext.skyboxTime >= 0xC001) && (gSaveContext.skyboxTime < 0xCAAC)) {
gSaveContext.skyboxTime = 0xCAAC;
}
}
@ -343,8 +324,7 @@ bool Scene_CommandWindSettings(PlayState* play, Ship::SceneCommand* cmd) {
return false;
}
bool Scene_CommandExitList(PlayState* play, Ship::SceneCommand* cmd)
{
bool Scene_CommandExitList(PlayState* play, Ship::SceneCommand* cmd) {
play->setupExitList = (s16*)cmd->GetPointer();
return false;
@ -368,8 +348,7 @@ bool Scene_CommandSoundSettings(PlayState* play, Ship::SceneCommand* cmd) {
return false;
}
bool Scene_CommandEchoSettings(PlayState* play, Ship::SceneCommand* cmd)
{
bool Scene_CommandEchoSettings(PlayState* play, Ship::SceneCommand* cmd) {
// Ship::SetEchoSettings* cmdEcho = static_pointer_cast<Ship::SetEchoSettings>(cmd);
Ship::SetEchoSettings* cmdEcho = (Ship::SetEchoSettings*)cmd;
@ -378,41 +357,36 @@ bool Scene_CommandEchoSettings(PlayState* play, Ship::SceneCommand* cmd)
return false;
}
bool Scene_CommandAlternateHeaderList(PlayState* play, Ship::SceneCommand* cmd)
{
bool Scene_CommandAlternateHeaderList(PlayState* play, Ship::SceneCommand* cmd) {
// Ship::SetAlternateHeaders* cmdHeaders = static_pointer_cast<Ship::SetAlternateHeaders>(cmd);
Ship::SetAlternateHeaders* cmdHeaders = (Ship::SetAlternateHeaders*)cmd;
//s32 pad;
//SceneCmd* altHeader;
// s32 pad;
// SceneCmd* altHeader;
//osSyncPrintf("\n[ZU]sceneset age =[%X]", ((void)0, gSaveContext.linkAge));
//osSyncPrintf("\n[ZU]sceneset time =[%X]", ((void)0, gSaveContext.cutsceneIndex));
//osSyncPrintf("\n[ZU]sceneset counter=[%X]", ((void)0, gSaveContext.sceneSetupIndex));
// osSyncPrintf("\n[ZU]sceneset age =[%X]", ((void)0, gSaveContext.linkAge));
// osSyncPrintf("\n[ZU]sceneset time =[%X]", ((void)0, gSaveContext.cutsceneIndex));
// osSyncPrintf("\n[ZU]sceneset counter=[%X]", ((void)0, gSaveContext.sceneSetupIndex));
if (gSaveContext.sceneSetupIndex != 0)
{
Ship::Scene* desiredHeader = std::static_pointer_cast<Ship::Scene>(cmdHeaders->headers[gSaveContext.sceneSetupIndex - 1]).get();
if (gSaveContext.sceneSetupIndex != 0) {
Ship::Scene* desiredHeader =
std::static_pointer_cast<Ship::Scene>(cmdHeaders->headers[gSaveContext.sceneSetupIndex - 1]).get();
if (desiredHeader != nullptr)
{
if (desiredHeader != nullptr) {
OTRScene_ExecuteCommands(play, desiredHeader);
return true;
}
else
{
} else {
// "Coughh! There is no specified dataaaaa!"
osSyncPrintf("\nげぼはっ! 指定されたデータがないでええっす!");
if (gSaveContext.sceneSetupIndex == 3)
{
Ship::Scene* desiredHeader = std::static_pointer_cast<Ship::Scene>(cmdHeaders->headers[gSaveContext.sceneSetupIndex - 2]).get();
if (gSaveContext.sceneSetupIndex == 3) {
Ship::Scene* desiredHeader =
std::static_pointer_cast<Ship::Scene>(cmdHeaders->headers[gSaveContext.sceneSetupIndex - 2]).get();
// "Using adult day data there!"
osSyncPrintf("\nそこで、大人の昼データを使用するでええっす!!");
if (desiredHeader != nullptr)
{
if (desiredHeader != nullptr) {
OTRScene_ExecuteCommands(play, desiredHeader);
return true;
}
@ -422,20 +396,18 @@ bool Scene_CommandAlternateHeaderList(PlayState* play, Ship::SceneCommand* cmd)
return false;
}
bool Scene_CommandCutsceneData(PlayState* play, Ship::SceneCommand* cmd)
{
bool Scene_CommandCutsceneData(PlayState* play, Ship::SceneCommand* cmd) {
// Ship::SetCutscenes* cmdCS = std::static_pointer_cast<Ship::SetCutscenes>(cmd);
Ship::SetCutscenes* cmdCS = (Ship::SetCutscenes*)cmd;
play->csCtx.segment = cmdCS->cutscene->commands.data();
//osSyncPrintf("\ngame_play->demo_play.data=[%x]", play->csCtx.segment);
// osSyncPrintf("\ngame_play->demo_play.data=[%x]", play->csCtx.segment);
return false;
}
// Camera & World Map Area
bool Scene_CommandMiscSettings(PlayState* play, Ship::SceneCommand* cmd)
{
bool Scene_CommandMiscSettings(PlayState* play, Ship::SceneCommand* cmd) {
// Ship::SetCameraSettings* cmdCam = std::static_pointer_cast<Ship::SetCameraSettings>(cmd);
Ship::SetCameraSettings* cmdCam = (Ship::SetCameraSettings*)cmd;
@ -459,8 +431,7 @@ bool Scene_CommandMiscSettings(PlayState* play, Ship::SceneCommand* cmd)
return false;
}
bool (*sceneCommands[])(PlayState*, Ship::SceneCommand*) =
{
bool (*sceneCommands[])(PlayState*, Ship::SceneCommand*) = {
Scene_CommandSpawnList, // SCENE_CMD_ID_SPAWN_LIST
Scene_CommandActorList, // SCENE_CMD_ID_ACTOR_LIST
Scene_CommandUnused2, // SCENE_CMD_ID_UNUSED_2
@ -489,20 +460,17 @@ bool (*sceneCommands[])(PlayState*, Ship::SceneCommand*) =
Scene_CommandMiscSettings, // SCENE_CMD_ID_MISC_SETTINGS
};
s32 OTRScene_ExecuteCommands(PlayState* play, Ship::Scene* scene)
{
s32 OTRScene_ExecuteCommands(PlayState* play, Ship::Scene* scene) {
Ship::SceneCommandID cmdCode;
for (int i = 0; i < scene->commands.size(); i++)
{
for (int i = 0; i < scene->commands.size(); i++) {
auto sceneCmd = scene->commands[i];
if (sceneCmd == nullptr) // UH OH
continue;
cmdCode = sceneCmd->cmdId;
//osSyncPrintf("*** Scene_Word = { code=%d, data1=%02x, data2=%04x } ***\n", cmdCode, sceneCmd->base.data1, sceneCmd->base.data2);
// osSyncPrintf("*** Scene_Word = { code=%d, data1=%02x, data2=%04x } ***\n", cmdCode, sceneCmd->base.data1, sceneCmd->base.data2);
if ((int)cmdCode == 0x14) {
break;
@ -511,23 +479,21 @@ s32 OTRScene_ExecuteCommands(PlayState* play, Ship::Scene* scene)
if ((int)cmdCode <= 0x19) {
if (sceneCommands[(int)cmdCode](play, sceneCmd.get()))
break;
}
else {
} else {
osSyncPrintf(VT_FGCOL(RED));
osSyncPrintf("code の値が異常です\n"); // "code variable is abnormal"
osSyncPrintf(VT_RST);
}
//sceneCmd++;
// sceneCmd++;
}
return 0;
}
extern "C" s32 OTRfunc_800973FC(PlayState* play, RoomContext* roomCtx) {
if (roomCtx->status == 1) {
//if (!osRecvMesg(&roomCtx->loadQueue, NULL, OS_MESG_NOBLOCK)) {
if (1)
{
// if (!osRecvMesg(&roomCtx->loadQueue, NULL, OS_MESG_NOBLOCK)) {
if (1) {
roomCtx->status = 0;
roomCtx->curRoom.segment = roomCtx->unk_34;
gSegments[3] = VIRTUAL_TO_PHYSICAL(roomCtx->unk_34);
@ -560,13 +526,15 @@ extern "C" s32 OTRfunc_8009728C(PlayState* play, RoomContext* roomCtx, s32 roomN
return 0; // UH OH
size = play->roomList[roomNum].vromEnd - play->roomList[roomNum].vromStart;
roomCtx->unk_34 = (void*)ALIGN16((uintptr_t)roomCtx->bufPtrs[roomCtx->unk_30] - ((size + 8) * roomCtx->unk_30 + 7));
roomCtx->unk_34 =
(void*)ALIGN16((uintptr_t)roomCtx->bufPtrs[roomCtx->unk_30] - ((size + 8) * roomCtx->unk_30 + 7));
osCreateMesgQueue(&roomCtx->loadQueue, &roomCtx->loadMsg, 1);
//DmaMgr_SendRequest2(&roomCtx->dmaRequest, roomCtx->unk_34, play->roomList[roomNum].vromStart, size, 0,
// DmaMgr_SendRequest2(&roomCtx->dmaRequest, roomCtx->unk_34, play->roomList[roomNum].vromStart, size, 0,
//&roomCtx->loadQueue, NULL, __FILE__, __LINE__);
auto roomData = std::static_pointer_cast<Ship::Scene>(GetResourceByNameHandlingMQ(play->roomList[roomNum].fileName));
auto roomData =
std::static_pointer_cast<Ship::Scene>(GetResourceByNameHandlingMQ(play->roomList[roomNum].fileName));
roomCtx->status = 1;
roomCtx->roomToLoad = roomData.get();