BattleDataInstaller.cpp 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806
  1. /*
  2. * V-Gears
  3. * Copyright (C) 2022 V-Gears Team
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #include <iostream>
  19. #include <fstream>
  20. #include <sstream>
  21. #include <map>
  22. #include <set>
  23. #include <cctype>
  24. #include <cstdio>
  25. #include <cstring>
  26. #include <cstdlib>
  27. #include <algorithm>
  28. #include <zlib.h>
  29. #include <tinyxml.h>
  30. #include <boost/filesystem.hpp>
  31. #include <OgreMesh.h>
  32. #include "BattleDataInstaller.h"
  33. #include "BattleCameraScripts.h"
  34. #include "ExeEffectCameras.h"
  35. #include "ExeEffectMeshes.h"
  36. #include "ModelMaterials.h"
  37. #include "TexFile.h"
  38. #include "data/VGearsHRCFileManager.h"
  39. #include "data/VGearsAFileManager.h"
  40. #include "data/AbFile.h"
  41. #include "data/DaFile.h"
  42. #include "data/FF7Data.h"
  43. #include "common/VGearsStringUtil.h"
  44. #include "common/FinalFantasy7/FF7NameLookup.h"
  45. BattleDataInstaller::BattleDataInstaller(
  46. const DiskImage& disk_image, const std::string output_dir, Ogre::ResourceGroupManager* res_mgr
  47. ):
  48. disk_image_(disk_image), output_dir_(output_dir), data_dir_(output_dir + "data/"),
  49. scene_bin_(*const_cast<DiskImage&>(disk_image).filePath("data/battle/scene.bin")), total_scenes_(0), next_scene_(0),
  50. res_mgr_(res_mgr)
  51. {}
  52. BattleDataInstaller::~BattleDataInstaller(){}
  53. unsigned int BattleDataInstaller::InitializeScenes(){
  54. next_scene_ = 0;
  55. scenes_.clear();
  56. enemies_.clear();
  57. attacks_.clear();
  58. scenes_uncompressed_.clear();
  59. total_scenes_ = 0;
  60. // scene.bin is a sequence of 0x2000 bytes blocks (33 in the original game). Each block starts
  61. // with up to 16 pointers (in 4-byte units) to gzipped scenes, terminated by 0xFFFFFFFF. A scene
  62. // ends where the next one starts, or at the end of the block. There are 256 scenes in total.
  63. // Scene indexes are positional: every slot must be kept, even if it can't be extracted,
  64. // because battle IDs (scene * 4 + setup) are derived from them.
  65. const u32 block_size = 0x2000;
  66. const u32 blocks = scene_bin_.GetFileSize() / block_size;
  67. for (u32 i = 0; i < blocks; i ++){
  68. File scene_bin_block(&scene_bin_, i * block_size, block_size);
  69. u32 offsets[16];
  70. u32 count = 0;
  71. for (; count < 16; count ++){
  72. scene_bin_block.SetOffset(4 * count);
  73. u32 pointer = scene_bin_block.readU32LE();
  74. if (pointer == 0xFFFFFFFF || pointer * 4 >= block_size) break;
  75. offsets[count] = pointer * 4;
  76. }
  77. for (u32 o = 0; o < count; o ++){
  78. u32 start_offset = offsets[o];
  79. u32 end_offset = (o + 1 < count) ? offsets[o + 1] : block_size;
  80. if (end_offset <= start_offset) end_offset = block_size;
  81. File scene_bin_fragment(&scene_bin_block, start_offset, end_offset - start_offset);
  82. // NULL if it can't be extracted. Kept to preserve scene indexes.
  83. scenes_uncompressed_.push_back(ExtractGZipScene(scene_bin_fragment));
  84. total_scenes_ ++;
  85. }
  86. }
  87. return total_scenes_;
  88. }
  89. unsigned int BattleDataInstaller::InitializeBattleModels(){
  90. next_model_to_process_ = 0;
  91. next_model_to_convert_ = 0;
  92. battle_lgp_files_.clear();
  93. battle_lgp_file_names_.clear();
  94. battle_models_.clear();
  95. // Open battle.lgp
  96. File battle_lgp_file(*disk_image_.filePath("data/battle/battle.lgp"));
  97. // Also, open it as a LGP archive.
  98. VGears::LGPArchive battle_lgp(*disk_image_.filePath("data/battle/battle.lgp"), "LGP");
  99. battle_lgp.open(*disk_image_.filePath("data/battle/battle.lgp"), true);
  100. battle_lgp.load();
  101. VGears::LGPArchive::FileList file_list = battle_lgp.GetFiles();
  102. for (int i = 0; i < file_list.size(); i ++){
  103. VGears::LGPArchive::FileEntry f = file_list.at(i);
  104. if (f.data_offset + f.data_size <= battle_lgp_file.GetFileSize()){
  105. File b_lgp_file(&battle_lgp_file, f.data_offset, f.data_size);
  106. battle_lgp_files_.push_back(b_lgp_file);
  107. battle_lgp_file_names_.push_back(f.file_name);
  108. }
  109. }
  110. return battle_lgp_files_.size();
  111. }
  112. unsigned int BattleDataInstaller::InitializeSpellModels(){
  113. next_model_to_process_ = 0;
  114. next_model_to_convert_ = 0;
  115. battle_lgp_files_.clear();
  116. battle_lgp_file_names_.clear();
  117. battle_models_.clear();
  118. magic_lgp_files_.clear();
  119. magic_lgp_file_names_.clear();
  120. magic_lgp_file_folders_.clear();
  121. // Open magic.lgp
  122. File magic_lgp_file(*disk_image_.filePath("data/battle/magic.lgp"));
  123. // Also, open it as a LGP archive.
  124. VGears::LGPArchive magic_lgp(*disk_image_.filePath("data/battle/magic.lgp"), "LGP");
  125. magic_lgp.open(*disk_image_.filePath("data/battle/magic.lgp"), true);
  126. magic_lgp.load();
  127. VGears::LGPArchive::FileList file_list = magic_lgp.GetFiles();
  128. for (int i = 0; i < file_list.size(); i ++){
  129. VGears::LGPArchive::FileEntry f = file_list.at(i);
  130. if (f.data_offset + f.data_size <= magic_lgp_file.GetFileSize()){
  131. File m_lgp_file(&magic_lgp_file, f.data_offset, f.data_size);
  132. magic_lgp_files_.push_back(m_lgp_file);
  133. magic_lgp_file_names_.push_back(f.file_name);
  134. magic_lgp_file_folders_.push_back(f.folder);
  135. }
  136. }
  137. return magic_lgp_files_.size();
  138. }
  139. unsigned int BattleDataInstaller::ProcessScene(){
  140. if (next_scene_ >= scenes_uncompressed_.size()) return total_scenes_;
  141. File* scene_file = scenes_uncompressed_[next_scene_];
  142. if (scene_file == NULL){
  143. // Keep battle IDs stable: an unreadable scene still takes its 4 battle slots.
  144. std::cout << "Warning: scene " << next_scene_ << " could not be extracted." << std::endl;
  145. for (int f = 0; f < 4; f ++){
  146. Formation empty;
  147. empty.id = next_scene_ * 4 + f;
  148. formations_.push_back(empty);
  149. }
  150. next_scene_ ++;
  151. return next_scene_;
  152. }
  153. BattleSceneFile scene(next_scene_, *scene_file);
  154. scenes_.push_back(scene);
  155. // Add new enemies to the list.
  156. std::vector<Enemy> enemies = scene.GetEnemies();
  157. for (int e = 0; e < enemies.size(); e ++){
  158. if (std::any_of(
  159. enemies_.begin(), enemies_.end(), [&](const Enemy& existing){ return existing.id == enemies[e].id; }
  160. )) continue;
  161. enemies_.push_back(enemies[e]);
  162. }
  163. // Add new attacks to the list.
  164. std::vector<Attack> attacks = scene.GetAttacks();
  165. for (int a = 0; a < attacks.size(); a ++){
  166. if (std::any_of(
  167. attacks_.begin(), attacks_.end(), [&](const Attack& existing){ return existing.id == attacks[a].id; }
  168. )) continue;
  169. attacks_.push_back(attacks[a]);
  170. }
  171. // Battle ID = scene index * 4 + setup index, as referenced by field scripts and encounters.
  172. std::vector<Formation> formations = scene.GetFormations();
  173. for (int f = 0; f < formations.size(); f ++){
  174. formations[f].id = next_scene_ * 4 + f;
  175. formations_.push_back(formations[f]);
  176. }
  177. next_scene_ ++;
  178. return next_scene_;
  179. }
  180. unsigned int BattleDataInstaller::ProcessBattleModel(){
  181. if (next_model_to_process_ >= battle_lgp_files_.size()) return battle_lgp_files_.size();
  182. // TODO: Do something with the files.
  183. // A little explanation. Each file has a 4 letter name, for example: 1234
  184. // 12 is the model identifier.
  185. // 34 if the type of file:
  186. // - aa: Skeleton file (.hrc)
  187. // - ab: Animation scripts
  188. // - ac - al: Textures (.tex)
  189. // - am - cz: Polygon files (.p)
  190. // - da: Animations (.anim)
  191. std::string id = battle_lgp_file_names_[next_model_to_process_].substr(0, 2);
  192. /*if (id != "rt"){ // TODO DEBUG REMOVE
  193. next_model_to_process_ ++;
  194. return next_model_to_process_;
  195. }*/
  196. std::string type = battle_lgp_file_names_[next_model_to_process_].substr(2, 2);
  197. FF7Data::BattleModelInfo info = FF7Data::GetBattleModelInfo(id);
  198. if (type == "aa"){
  199. // HRC file.
  200. battle_lgp_files_[next_model_to_process_].WriteFile(
  201. output_dir_ + "temp/battle_models/"
  202. + battle_lgp_file_names_[next_model_to_process_] + ".hrcbin"
  203. );
  204. bool found = false;
  205. for (int m = 0; m < battle_models_.size(); m ++){
  206. if (battle_models_[m].id == id){
  207. battle_models_[m].hrc = battle_lgp_file_names_[next_model_to_process_] + ".hrc";
  208. found = true;
  209. break;
  210. }
  211. }
  212. if (found == false){
  213. BattleModel model;
  214. model.id = id;
  215. model.hrc = battle_lgp_file_names_[next_model_to_process_] + ".hrc";
  216. battle_models_.push_back(model);
  217. }
  218. }
  219. else if (type == "ab"){
  220. battle_lgp_files_[next_model_to_process_].WriteFile(
  221. output_dir_ + "temp/battle_models/"
  222. + battle_lgp_file_names_[next_model_to_process_] + ".script"
  223. );
  224. auto model_it = std::find_if(
  225. battle_models_.begin(), battle_models_.end(),
  226. [&](const BattleModel& model){ return model.id == id; }
  227. );
  228. if (model_it != battle_models_.end()){
  229. model_it->script = battle_lgp_file_names_[next_model_to_process_] + ".script";
  230. }
  231. else{
  232. BattleModel model;
  233. model.id = id;
  234. model.script = battle_lgp_file_names_[next_model_to_process_] + ".script";
  235. battle_models_.push_back(model);
  236. }
  237. }
  238. else if (type == "da"){
  239. // .da Animation file.
  240. battle_lgp_files_[next_model_to_process_].WriteFile(
  241. output_dir_ + "temp/battle_models/" + battle_lgp_file_names_[next_model_to_process_] + ".anim"
  242. );
  243. bool found = false;
  244. for (int m = 0; m < battle_models_.size(); m ++){
  245. if (battle_models_[m].id == id){
  246. battle_models_[m].anim = battle_lgp_file_names_[next_model_to_process_] + ".anim";
  247. found = true;
  248. break;
  249. }
  250. }
  251. if (found == false){
  252. BattleModel model;
  253. model.id = id;
  254. model.anim = battle_lgp_file_names_[next_model_to_process_] + ".anim";
  255. battle_models_.push_back(model);
  256. }
  257. }
  258. else if (
  259. type == "ac" || type == "ad" || type == "ae" || type == "af" || type == "ag"
  260. || type == "ah"|| type == "ai" || type == "aj" || type == "ak" || type == "al"
  261. ){
  262. // .tex texture files. Save directly to their directory.
  263. battle_lgp_files_[next_model_to_process_].WriteFile(
  264. output_dir_ + "temp/battle_models/" + battle_lgp_file_names_[next_model_to_process_] + ".tex"
  265. );
  266. TexFile tex(battle_lgp_files_[next_model_to_process_]);
  267. std::string path = data_dir_ + "models/battle/";
  268. if (info.is_player){
  269. path += "characters/";
  270. // Add or update on character_data_
  271. bool found = false;
  272. for (auto data: character_data_){
  273. if (data.id == info.numeric_id){
  274. // Check if the model already exists for this character
  275. bool model_found = false;
  276. for (auto mod: data.models){
  277. if (mod.model == info.alphanumeric_id + "_" + info.name_normal + ".mesh"){
  278. model_found = true;
  279. break;
  280. }
  281. }
  282. if (model_found) break;
  283. CharacterModel model;
  284. model.name = info.name;
  285. model.model = info.alphanumeric_id + "_" + info.name_normal + ".mesh";
  286. data.models.push_back(model);
  287. character_data_.push_back(data);
  288. found = true;
  289. break;
  290. }
  291. }
  292. if (!found){
  293. CharacterData character_data;
  294. character_data.id = info.numeric_id;
  295. CharacterModel model;
  296. model.name = info.name;
  297. model.model = info.alphanumeric_id + "_" + info.name_normal + ".mesh";
  298. character_data.models.push_back(model);
  299. character_data_.push_back(character_data);
  300. }
  301. }
  302. else if (info.is_scene){
  303. SceneModel scene_data;
  304. scene_data.id = info.numeric_id;
  305. scene_data.model = info.alphanumeric_id + "_" + info.name_normal + ".mesh";
  306. scene_data.description = info.name;
  307. // Every texture of a scene model reaches this point, but the map needs one entry.
  308. if (std::none_of(scene_data_.begin(), scene_data_.end(), [&](const SceneModel& s){
  309. return s.id == scene_data.id && s.model == scene_data.model;
  310. })) scene_data_.push_back(scene_data);
  311. path += "scenes/";
  312. }
  313. else path += "enemies/";
  314. path += (id + type + "_" + info.name_normal + ".png");
  315. tex.SavePng(path);
  316. res_mgr_->declareResource(
  317. id + type + "_" + info.name_normal + ".png", "Texture", "FFVIITextures"
  318. );
  319. bool found = false;
  320. for (int m = 0; m < battle_models_.size(); m ++){
  321. if (battle_models_[m].id == id){
  322. battle_models_[m].tex.push_back(id + type+ "_" + info.name_normal + ".png");
  323. found = true;
  324. break;
  325. }
  326. }
  327. if (found == false){
  328. BattleModel model;
  329. model.id = id;
  330. model.tex.push_back(id + type + "_" + info.name_normal + ".png");
  331. battle_models_.push_back(model);
  332. }
  333. }
  334. else{
  335. // .p polygon file.
  336. battle_lgp_files_[next_model_to_process_].WriteFile(
  337. output_dir_ + "temp/battle_models/" + battle_lgp_file_names_[next_model_to_process_] + ".p"
  338. );
  339. bool found = false;
  340. for (int m = 0; m < battle_models_.size(); m ++){
  341. if (battle_models_[m].id == id){
  342. battle_models_[m].p.push_back(battle_lgp_file_names_[next_model_to_process_] + ".p");
  343. found = true;
  344. break;
  345. }
  346. }
  347. if (found == false){
  348. BattleModel model;
  349. model.id = id;
  350. model.p.push_back(battle_lgp_file_names_[next_model_to_process_] + ".p");
  351. battle_models_.push_back(model);
  352. }
  353. }
  354. next_model_to_process_ ++;
  355. return next_model_to_process_;
  356. }
  357. unsigned int BattleDataInstaller::ProcessSpellModel(){
  358. if (next_model_to_process_ >= magic_lgp_files_.size()) return magic_lgp_files_.size();
  359. // TODO: Do something with the files.
  360. // A little explanation. There are no patterns on file names, and there are multiple extensions.
  361. // - d: Skeleton file, similar to aa from battle models.
  362. // - b: Unknown.
  363. // - p*: Polygon files, for each bone.
  364. // - tex: Texture files, TIM format.
  365. // - rsd: Resource files
  366. // - s: Unknown.
  367. // - a00: Animation files, similar to da from battle models.
  368. //std::cout << "SPELL MODEL FILE: " << magic_lgp_file_names_[next_model_to_process_] << std::endl;
  369. std::string fname = magic_lgp_file_names_[next_model_to_process_];
  370. std::string id = fname.substr(0, fname.find_last_of("."));
  371. std::string ext = fname.substr(fname.find_last_of(".") + 1);
  372. FF7Data::SpellModelInfo info = FF7Data::GetSpellModelInfo(id);
  373. //magic_lgp_files_[next_model_to_process_].WriteFile(output_dir_ + "temp/spell_models/" + fname);
  374. if (ext == "d"){
  375. // Skeleton file.
  376. magic_lgp_files_[next_model_to_process_].WriteFile(output_dir_ + "temp/spell_models/" + fname);
  377. bool found = false;
  378. for (int m = 0; m < spell_models_.size(); m ++){
  379. if (spell_models_[m].id == id){
  380. spell_models_[m].hrc = fname;
  381. found = true;
  382. break;
  383. }
  384. }
  385. if (found == false){
  386. SpellModel model;
  387. model.id = id;
  388. model.hrc = fname;
  389. spell_models_.push_back(model);
  390. }
  391. }
  392. else if (ext.at(0) == 'p'){
  393. // Bone file.
  394. // If the extension is just ".p", use the file name.
  395. std::string p_name;
  396. if (ext == "p") p_name = fname;
  397. // If the extension is ".pXX", save it with altered name.
  398. else p_name =
  399. fname.substr(0, fname.length() - 4) + "_" + fname.substr(fname.length() - 2, 2) + ".p";
  400. magic_lgp_files_[next_model_to_process_].WriteFile(
  401. output_dir_ + "temp/spell_models/" + p_name
  402. );
  403. std::cout << "[BONE RENAMED] " << fname << " --> " << p_name << std::endl;
  404. bool found = false;
  405. for (int m = 0; m < spell_models_.size(); m ++){
  406. if (spell_models_[m].id == id){
  407. spell_models_[m].p.push_back(p_name);
  408. found = true;
  409. break;
  410. }
  411. }
  412. if (found == false){
  413. SpellModel model;
  414. model.id = id;
  415. model.p.push_back(p_name);
  416. spell_models_.push_back(model);
  417. }
  418. }
  419. if (ext == "tex"){
  420. // Texture files. They can be shared among various spells, so just convert them and don't
  421. // add them to a particular model.
  422. magic_lgp_files_[next_model_to_process_].WriteFile(output_dir_ + "temp/spell_models/" + fname);
  423. TexFile tex(output_dir_ + "temp/spell_models/" + fname);
  424. std::string path = data_dir_ + "models/battle/attacks/" + id + ".png";
  425. // Many of these tex files are wrong and dummied out in the OG, so try/catch.
  426. try{
  427. tex.SavePng(path);
  428. }
  429. catch(const std::exception& e){
  430. std::cerr << "[WARNING] Error converting texture " << (output_dir_ + "temp/spell_models/" + fname)
  431. << " to png: " << e.what() << std::endl;
  432. }
  433. }
  434. if (ext == "a00"){
  435. // Animation file.
  436. magic_lgp_files_[next_model_to_process_].WriteFile(output_dir_ + "temp/spell_models/" + fname);
  437. bool found = false;
  438. for (int m = 0; m < spell_models_.size(); m ++){
  439. if (spell_models_[m].id == id){
  440. spell_models_[m].anim = fname;
  441. found = true;
  442. break;
  443. }
  444. }
  445. if (found == false){
  446. SpellModel model;
  447. model.id = id;
  448. model.anim = fname;
  449. spell_models_.push_back(model);
  450. }
  451. }
  452. // TODO: b files? a files? s files?
  453. next_model_to_process_ ++;
  454. return next_model_to_process_;
  455. }
  456. namespace{
  457. /**
  458. * Files of magic.lgp (without extension) with the animations of the limit breaks of each model of the party.
  459. * The animation files have the format of the animations of the models, with 8 animations for the skeleton of
  460. * the character (the animations 44 to 51 of the model, which are empty in battle.lgp) and 8 for its weapon.
  461. * The files are in the order of the techniques of the character (limit level 1 first and second, level 2, ...):
  462. * the table that ff7.exe uses to load them (at 0x7b7b58) has them in groups of 7 by character.
  463. */
  464. const std::map<std::string, std::vector<std::string>>& LimitAnimationFiles(){
  465. static const std::vector<std::string> cloud = {"blaver", "kyou", "limcl2", "limcl6", "limcl3", "limcl7", "limcl4"};
  466. static const std::vector<std::string> barret = {"hvshot", "limbr5", "limbr2", "limbr6", "limbr3", "limbr7", "limbr4"};
  467. static const std::map<std::string, std::vector<std::string>> files = {
  468. {"rt", cloud}, {"si", cloud},
  469. {"ru", {"limfast"}}, // Tifa.
  470. {"rv", {"iyash", "limea5", "limea2", "limea6", "limea3", "kodo", "limea4"}}, // Aerith.
  471. {"rw", {"limsled", "limrd5", "limsled", "limrd6", "limrd3", "limrd7", "limrd4"}}, // Red XIII.
  472. {"rx", {"limyf1", "limyf5", "limyf2", "limyf6", "limyf3", "limyf7", "limyf4"}}, // Yuffie.
  473. {"ry", {"dice"}}, // Cait Sith.
  474. {"rz", {"limcd1", "limcd5", "limcd2", "limcd6", "limcd3", "limcd7", "limcd4"}}, // Cid.
  475. {"sb", barret}, {"sc", barret}, {"sd", barret}, {"se", barret},
  476. };
  477. return files;
  478. }
  479. }
  480. unsigned int BattleDataInstaller::ConvertBattleModelsInit(){
  481. next_model_to_convert_ = 0;
  482. // The animations of the limit breaks are in magic.lgp. Take the ones of the party to the folder of the battle
  483. // models, so they are converted with them.
  484. try{
  485. std::set<std::string> wanted;
  486. for (const auto& entry : LimitAnimationFiles()){
  487. for (const std::string& tag : entry.second) wanted.insert(tag + ".a00");
  488. }
  489. File magic_lgp_file(*disk_image_.filePath("data/battle/magic.lgp"));
  490. VGears::LGPArchive magic_lgp(*disk_image_.filePath("data/battle/magic.lgp"), "LGP");
  491. magic_lgp.open(*disk_image_.filePath("data/battle/magic.lgp"), true);
  492. magic_lgp.load();
  493. VGears::LGPArchive::FileList file_list = magic_lgp.GetFiles();
  494. for (int i = 0; i < file_list.size(); i ++){
  495. VGears::LGPArchive::FileEntry f = file_list.at(i);
  496. std::string name = f.file_name;
  497. std::transform(name.begin(), name.end(), name.begin(), ::tolower);
  498. if (wanted.count(name) == 0) continue;
  499. if (f.data_offset + f.data_size > magic_lgp_file.GetFileSize()) continue;
  500. File limit_file(&magic_lgp_file, f.data_offset, f.data_size);
  501. limit_file.WriteFile(output_dir_ + "temp/battle_models/limit_" + name);
  502. }
  503. }
  504. catch (const std::exception& ex){
  505. std::cerr << "[ERROR] Exception reading the limit animations: " << ex.what() << std::endl;
  506. }
  507. return battle_models_.size();
  508. }
  509. unsigned int BattleDataInstaller::ConvertSpellModelsInit(){
  510. next_model_to_convert_ = 0;
  511. return spell_models_.size();
  512. }
  513. unsigned int BattleDataInstaller::ConvertBattleModel(){
  514. if (next_model_to_convert_ >= battle_models_.size()) return battle_models_.size();
  515. BattleModel model = battle_models_[next_model_to_convert_];
  516. try{
  517. std::string path = "";
  518. FF7Data::BattleModelInfo info = FF7Data::GetBattleModelInfo(model.id);
  519. if (info.is_player) path += "characters/";
  520. else if (info.is_scene) path += "scenes/";
  521. else path += "enemies/";
  522. if (info.is_scene){
  523. DecompileSceneModelHrc(
  524. File(output_dir_ + "temp/battle_models/" + model.hrc + "bin"), model,
  525. output_dir_ + "temp/battle_models/" + model.id + "_" + info.name_normal + ".hrc",
  526. model.id + "_" + info.name_normal
  527. );
  528. }
  529. else{
  530. DecompileBattleModelHrc(
  531. File(output_dir_ + "temp/battle_models/" + model.hrc + "bin"), model,
  532. output_dir_ + "temp/battle_models/" + model.id + "_" + info.name_normal + ".hrc",
  533. model.id + "_" + info.name_normal
  534. );
  535. }
  536. GenerateRsdFiles(model, output_dir_ + "temp/battle_models/");
  537. if ("" != model.anim){ // Skip for non-animated, ie battle backgrounds
  538. DaFile da(File(output_dir_ + "temp/battle_models/" + model.anim));
  539. std::vector<std::string> a_files = da.GenerateAFiles(model.id, output_dir_ + "temp/battle_models/");
  540. for (std::string file_name : a_files) model.a.push_back(file_name);
  541. }
  542. // Limit breaks of the party: their animations are in files of magic.lgp. Each one is added to the model with
  543. // the names <model>_<file>_00 to _07, which replace the empty animations 44 to 51 for that limit.
  544. if (info.is_player){
  545. auto limits = LimitAnimationFiles().find(model.id);
  546. if (limits != LimitAnimationFiles().end()){
  547. std::set<std::string> converted;
  548. for (const std::string& tag : limits->second){
  549. if (!converted.insert(tag).second) continue;
  550. std::string limit_path = output_dir_ + "temp/battle_models/limit_" + tag + ".a00";
  551. if (!std::ifstream(limit_path).good()) continue;
  552. try{
  553. File limit_file(limit_path);
  554. DaFile limit_da(limit_file);
  555. std::vector<std::string> limit_files = limit_da.GenerateAFiles(
  556. model.id + "_" + tag, output_dir_ + "temp/battle_models/"
  557. );
  558. for (const std::string& file_name : limit_files){
  559. // Only the animations of the skeleton (0 to 7), not the ones of the weapon.
  560. size_t dot = file_name.find_last_of('.');
  561. int number = std::atoi(file_name.substr(dot - 2, 2).c_str());
  562. if (number < 8) model.a.push_back(file_name);
  563. }
  564. }
  565. catch (const std::exception& ex){
  566. std::cerr << "[ERROR] Exception reading the limit animation " << tag << ": " << ex.what() << std::endl;
  567. }
  568. }
  569. }
  570. }
  571. if ("" != model.script){ // Skip non scripted models
  572. // Only the models of the party have the 74 scripts (the limits are the ones from 60 up). The other
  573. // ones (enemies and the rest of the models with scripts) have 32.
  574. AbFile ab(File(output_dir_ + "temp/battle_models/" + model.script), !info.is_player);
  575. ab.GenerateScripts(model.id + "_" + info.name_normal, data_dir_ + "scripts/battle_models/");
  576. if (!info.is_scene && "" != model.hrc){
  577. WriteModelCamera(
  578. File(output_dir_ + "temp/battle_models/" + model.script),
  579. File(output_dir_ + "temp/battle_models/" + model.hrc + "bin"),
  580. model.id + "_" + info.name_normal
  581. );
  582. }
  583. }
  584. // Playable characters hold their weapons in battle (but Red XIII, who has none). Each one is a
  585. // polygon file by itself, named <id>c<k..z>, so make a model for each with a single bone.
  586. std::vector<std::pair<std::string, std::string>> weapons; // Polygon file, mesh name.
  587. if (info.is_player && model.id != "rw"){
  588. for (std::string p : model.p){
  589. if (p.length() < 4 || p[2] != 'c' || p[3] < 'k' || p[3] > 'z') continue;
  590. char number[8];
  591. std::snprintf(number, sizeof(number), "%02d", p[3] - 'k');
  592. const std::string weapon_name = model.id + "_" + info.name_normal + "_weapon_" + number;
  593. std::ofstream hrc(output_dir_ + "temp/battle_models/" + weapon_name + ".hrc");
  594. hrc << ":HEADER_BLOCK 2\n:SKELETON " << weapon_name << "\n:BONES 1\n\nbone0\nroot\n0.000000\n1 "
  595. << p.substr(0, 4) << "\n\n";
  596. hrc.close();
  597. weapons.push_back(std::make_pair(p, weapon_name));
  598. }
  599. }
  600. // Reload the resources for the newly created hrc and rsd.
  601. // TODO: Could this be done with res_mgr_->declareResource() ? Probably faster
  602. res_mgr_->removeResourceLocation(output_dir_ + "temp/battle_models/", "FFVII");
  603. res_mgr_->addResourceLocation(output_dir_ + "temp/battle_models/", "FileSystem", "FFVII", true, true);
  604. Ogre::ResourcePtr hrc = VGears::HRCFileManager::GetSingleton().load(
  605. model.id + "_" + info.name_normal + ".hrc", "FFVII"
  606. );
  607. Ogre::String base_name;
  608. VGears::StringUtil::splitBase(model.hrc, base_name);
  609. auto mesh_name = model.id + "_" + info.name_normal + ".mesh";
  610. Ogre::MeshPtr mesh(Ogre::MeshManager::getSingleton().load(mesh_name, "FFVII"));
  611. Ogre::SkeletonPtr skeleton(mesh->getSkeleton());
  612. for (std::string anim : model.a){
  613. VGears::AFileManager &afl_mgr(VGears::AFileManager::GetSingleton());
  614. Ogre::String a_base_name;
  615. VGears::StringUtil::splitBase(anim, a_base_name);
  616. VGears::AFilePtr a = afl_mgr.load(a_base_name + ".a", "FFVII").staticCast<VGears::AFile>();
  617. // Convert the FF7 name to a more readable name set in the meta data.
  618. VGears::StringUtil::splitBase(anim, base_name);
  619. a->AddTo(skeleton, VGears::NameLookup::Animation(base_name));
  620. }
  621. ExportMesh(path, mesh);
  622. for (const auto& weapon : weapons){
  623. try{
  624. VGears::HRCFileManager::GetSingleton().load(weapon.second + ".hrc", "FFVII");
  625. Ogre::MeshPtr weapon_mesh(Ogre::MeshManager::getSingleton().load(weapon.second + ".mesh", "FFVII"));
  626. ExportMesh(path, weapon_mesh);
  627. }
  628. catch (const Ogre::Exception& ex){
  629. std::cerr << "[ERROR] Ogre exception converting weapon " << weapon.second << ": " << ex.what() << std::endl;
  630. }
  631. }
  632. }
  633. catch (const Ogre::Exception& ex){
  634. std::cerr << "[ERROR] Ogre exception converting battle model " << model.hrc <<": " << ex.what() << std::endl;
  635. }
  636. catch (const std::exception& ex){
  637. std::cerr << "[ERROR] Exception converting battle model " << model.hrc << ": " << ex.what() << std::endl;
  638. }
  639. next_model_to_convert_ ++;
  640. return next_model_to_convert_;
  641. }
  642. unsigned int BattleDataInstaller::ConvertSpellModel(){
  643. if (next_model_to_convert_ >= spell_models_.size()) return spell_models_.size();
  644. SpellModel model = spell_models_[next_model_to_convert_];
  645. try{
  646. std::string path = "attacks/";
  647. FF7Data::SpellModelInfo info = FF7Data::GetSpellModelInfo(model.id);
  648. // Decompile the .hrc file (if any)
  649. if (model.hrc != ""){
  650. std::cout << "[DECOMPILE] " << output_dir_ + "temp/spell_models/" + model.hrc << std::endl;
  651. DecompileSpellModelHrc(
  652. File(output_dir_ + "temp/spell_models/" + model.hrc), model,
  653. output_dir_ + "temp/spell_models/" + info.name_normal + ".hrc", model.id
  654. );
  655. model.hrc = info.name_normal + ".hrc";
  656. std::cout << " TO: " << (output_dir_ + "temp/spell_models/" + info.name_normal + ".hrc") << std::endl;
  657. }
  658. GenerateRsdFiles(model, output_dir_ + "temp/spell_models/");
  659. // Decompile the .a00 file (if any) into a .a file.
  660. if ("" != model.anim){ // Skip for non-animated.
  661. DaFile da(File(output_dir_ + "temp/spell_models/" + model.anim));
  662. std::vector<std::string> a_files = da.GenerateAFiles(model.id, output_dir_ + "temp/spell_models/");
  663. for (std::string file_name : a_files) model.a.push_back(file_name);
  664. }
  665. // Reload the resources for the newly created hrc and rsd.
  666. // TODO: Could this be done with res_mgr_->declareResource() ? Probably faster
  667. res_mgr_->removeResourceLocation(output_dir_ + "temp/spell_models/", "FFVII");
  668. res_mgr_->addResourceLocation(output_dir_ + "temp/spell_models/", "FileSystem", "FFVII", true, true);
  669. // Export meshes thet have an .hrc skeleton.
  670. if (model.hrc != ""){
  671. std::cout << "[EXPORT MESH] " << model.hrc << std::endl;
  672. Ogre::ResourcePtr hrc = VGears::HRCFileManager::GetSingleton().load(model.id + ".hrc", "FFVII");
  673. Ogre::String base_name;
  674. VGears::StringUtil::splitBase(model.hrc, base_name);
  675. auto mesh_name = model.id + ".mesh";
  676. Ogre::MeshPtr mesh(Ogre::MeshManager::getSingleton().load(mesh_name, "FFVII"));
  677. Ogre::SkeletonPtr skeleton(mesh->getSkeleton());
  678. for (std::string anim : model.a){
  679. VGears::AFileManager &afl_mgr(VGears::AFileManager::GetSingleton());
  680. Ogre::String a_base_name;
  681. VGears::StringUtil::splitBase(anim, a_base_name);
  682. VGears::AFilePtr a = afl_mgr.load(a_base_name + ".a", "FFVII").staticCast<VGears::AFile>();
  683. // Convert the FF7 name to a more readable name set in the meta data.
  684. VGears::StringUtil::splitBase(anim, base_name);
  685. a->AddTo(skeleton, VGears::NameLookup::Animation(base_name));
  686. }
  687. ExportMesh(path, mesh);
  688. }
  689. }
  690. catch (const Ogre::Exception& ex){
  691. std::cerr << "[ERROR] Ogre exception converting spell model " << model.hrc <<": " << ex.what() << std::endl;
  692. }
  693. catch (const std::exception& ex){
  694. std::cerr << "[ERROR] Exception converting spell model " << model.hrc << ": " << ex.what() << std::endl;
  695. }
  696. next_model_to_convert_ ++;
  697. return next_model_to_convert_;
  698. }
  699. namespace{
  700. /**
  701. * Makes a name that is safe to use in files and Ogre resources: lower case letters, numbers and
  702. * underscores.
  703. */
  704. std::string EffectSafeName(std::string name){
  705. for (char& c : name){
  706. c = std::tolower(static_cast<unsigned char>(c));
  707. if (!std::isalnum(static_cast<unsigned char>(c)) && c != '_') c = '_';
  708. }
  709. return name;
  710. }
  711. /**
  712. * Gets the name without the extension, in lower case.
  713. */
  714. std::string EffectStem(const std::string& file_name){
  715. std::string stem = file_name.substr(0, file_name.find_last_of('.'));
  716. std::transform(stem.begin(), stem.end(), stem.begin(), [](unsigned char c){return std::tolower(c);});
  717. return stem;
  718. }
  719. /**
  720. * Gets the name of a texture in a rsd file, without the extension, in lower case.
  721. */
  722. std::string EffectRsdValue(const std::string& line){
  723. size_t equal = line.find('=');
  724. if (equal == std::string::npos) return "";
  725. std::string value = line.substr(equal + 1);
  726. while (!value.empty() && std::isspace(static_cast<unsigned char>(value.back()))) value.pop_back();
  727. while (!value.empty() && std::isspace(static_cast<unsigned char>(value.front()))) value.erase(0, 1);
  728. return EffectStem(value);
  729. }
  730. }
  731. unsigned int BattleDataInstaller::InitializeEffectModels(){
  732. effect_models_.clear();
  733. next_effect_to_convert_ = 0;
  734. const std::string dir = output_dir_ + "temp/effects/";
  735. // Index the files by folder and name.
  736. std::map<std::pair<std::string, std::string>, size_t> index;
  737. for (size_t f = 0; f < magic_lgp_files_.size(); f ++){
  738. std::string name = magic_lgp_file_names_[f];
  739. std::transform(name.begin(), name.end(), name.begin(), [](unsigned char c){return std::tolower(c);});
  740. index[{magic_lgp_file_folders_[f], name}] = f;
  741. }
  742. // Folder key: the effect folder, "common" for the root.
  743. auto key_of = [](const std::string& folder){
  744. if (folder.empty()) return std::string("common");
  745. std::string key = folder;
  746. const std::string prefix = "ff7/data/battle/";
  747. if (key.compare(0, prefix.size(), prefix) == 0) key = key.substr(prefix.size());
  748. return EffectSafeName(key);
  749. };
  750. // Finds a file in the folder of the model, or in the archive root.
  751. auto find = [&](const std::string& folder, const std::string& name, std::string& found_folder){
  752. auto it = index.find({folder, name});
  753. if (it != index.end()){found_folder = folder; return it->second;}
  754. it = index.find({"", name});
  755. if (it != index.end()){found_folder = ""; return it->second;}
  756. return static_cast<size_t>(-1);
  757. };
  758. std::set<std::string> written;
  759. auto write = [&](size_t f, const std::string& name){
  760. if (written.insert(name).second) magic_lgp_files_[f].WriteFile(dir + name);
  761. };
  762. for (size_t f = 0; f < magic_lgp_files_.size(); f ++){
  763. std::string rsd_name = magic_lgp_file_names_[f];
  764. if (rsd_name.size() < 4 || EffectSafeName(rsd_name.substr(rsd_name.size() - 4)) != "_rsd") continue;
  765. const std::string& folder = magic_lgp_file_folders_[f];
  766. // Parse the rsd.
  767. File& rsd_file = magic_lgp_files_[f];
  768. rsd_file.SetOffset(0);
  769. std::string content;
  770. for (size_t b = 0; b < rsd_file.GetFileSize(); b ++) content += static_cast<char>(rsd_file.readU8());
  771. std::string ply;
  772. std::vector<std::string> tex;
  773. std::istringstream lines(content);
  774. std::string line;
  775. while (std::getline(lines, line)){
  776. std::string upper = line;
  777. std::transform(upper.begin(), upper.end(), upper.begin(), [](unsigned char c){return std::toupper(c);});
  778. if (upper.compare(0, 4, "PLY=") == 0) ply = EffectRsdValue(line);
  779. else if (upper.compare(0, 4, "TEX[") == 0) tex.push_back(EffectRsdValue(line));
  780. }
  781. if (ply.empty()) continue;
  782. std::string p_folder;
  783. size_t p_index = find(folder, ply + ".p", p_folder);
  784. if (p_index == static_cast<size_t>(-1)) continue;
  785. const std::string key = key_of(folder);
  786. EffectModel model;
  787. model.name = key + "_" + EffectSafeName(EffectStem(rsd_name));
  788. const std::string p_name = key_of(p_folder) + "_" + EffectSafeName(ply) + ".p";
  789. write(p_index, p_name);
  790. std::string rsd = "@RSD940102\nPLY=" + p_name.substr(0, p_name.size() - 2) + ".PLY\n";
  791. rsd += "MAT=" + model.name + ".MAT\nGRP=" + model.name + ".GRP\n";
  792. std::vector<std::string> tex_names;
  793. for (const std::string& t : tex){
  794. std::string t_folder;
  795. size_t t_index = find(folder, t + ".tex", t_folder);
  796. if (t_index == static_cast<size_t>(-1)) continue;
  797. const std::string t_name = key_of(t_folder) + "_" + EffectSafeName(t) + ".tex";
  798. write(t_index, t_name);
  799. tex_names.push_back(t_name);
  800. }
  801. rsd += "NTEX=" + std::to_string(tex_names.size()) + "\n";
  802. for (size_t t = 0; t < tex_names.size(); t ++){
  803. rsd += "TEX[" + std::to_string(t) + "]=" + tex_names[t].substr(0, tex_names[t].size() - 4) + ".TIM\n";
  804. }
  805. model.textures = tex_names;
  806. std::ofstream(dir + model.name + ".rsd") << rsd;
  807. // A model with a single bone, with the mesh.
  808. std::ofstream(dir + model.name + ".hrc")
  809. << ":HEADER_BLOCK 2\n:SKELETON " << model.name << "\n:BONES 1\n\nbone0\nroot\n0.000000\n1 "
  810. << model.name << "\n\n";
  811. effect_models_.push_back(model);
  812. }
  813. res_mgr_->removeResourceLocation(dir, "FFVII");
  814. res_mgr_->addResourceLocation(dir, "FileSystem", "FFVII", true, true);
  815. return effect_models_.size();
  816. }
  817. unsigned int BattleDataInstaller::ConvertEffectModel(){
  818. if (next_effect_to_convert_ >= effect_models_.size()) return effect_models_.size();
  819. EffectModel& model = effect_models_[next_effect_to_convert_];
  820. try{
  821. VGears::HRCFileManager::GetSingleton().load(model.name + ".hrc", "FFVII");
  822. Ogre::MeshPtr mesh(Ogre::MeshManager::getSingleton().load(model.name + ".mesh", "FFVII"));
  823. ExportMesh("effects/", mesh);
  824. for (const std::string& texture : model.textures){
  825. const std::string path = data_dir_ + "models/battle/effects/"
  826. + texture.substr(0, texture.size() - 4) + ".png";
  827. if (boost::filesystem::exists(path)) continue;
  828. try{
  829. TexFile tex(output_dir_ + "temp/effects/" + texture);
  830. tex.SavePng(path);
  831. }
  832. catch (const std::exception& ex){
  833. // Many of the original textures are dummies.
  834. std::cerr << "[WARNING] Error converting effect texture " << texture << ": " << ex.what() << std::endl;
  835. }
  836. }
  837. model.converted = true;
  838. }
  839. catch (const Ogre::Exception& ex){
  840. std::cerr << "[WARNING] Could not convert effect model " << model.name << ": " << ex.what() << std::endl;
  841. }
  842. catch (const std::exception& ex){
  843. std::cerr << "[WARNING] Could not convert effect model " << model.name << ": " << ex.what() << std::endl;
  844. }
  845. next_effect_to_convert_ ++;
  846. return next_effect_to_convert_;
  847. }
  848. void BattleDataInstaller::WriteEffectModels(){
  849. std::ofstream file(data_dir_ + "gamedata/effects.lua");
  850. file << "-- Meshes of the battle effects, extracted from magic.lgp. Names are the folder of the effect\n"
  851. << "-- and the original file, for example magic_faira_1. Meshes are in models/battle/effects.\n"
  852. << "Game.EffectModels = {\n";
  853. for (const EffectModel& model : effect_models_){
  854. if (model.converted) file << " \"" << model.name << "\",\n";
  855. }
  856. file << "}\n";
  857. WriteEffectSprites();
  858. WriteEffectCameras();
  859. WriteEffectMeshes();
  860. WriteBattleCameras();
  861. }
  862. void BattleDataInstaller::WriteBattleCameras(){
  863. // The scripts of the cameras of the battles (see BattleCameraScripts.h).
  864. std::map<int, BattleCameraScripts::Set> sets;
  865. for (int i = 0; i < 3; ++ i){
  866. const std::string name = "data/battle/camdat" + std::to_string(i) + ".bin";
  867. auto path = const_cast<DiskImage&>(disk_image_).filePath(name);
  868. BattleCameraScripts::Set set;
  869. if (path != nullptr && BattleCameraScripts::ReadFile(*path, set)) sets[i] = set;
  870. else std::cerr << "[WARNING] Can't read " << name << "." << std::endl;
  871. }
  872. std::ofstream file(data_dir_ + "gamedata/battle_cameras.lua");
  873. BattleCameraScripts::WriteLua(file, sets);
  874. // The ones of the start of the battles are in the executable.
  875. BattleCameraScripts::Set intro;
  876. auto exe_path = const_cast<DiskImage&>(disk_image_).filePath("ff7.exe");
  877. if (exe_path != nullptr && BattleCameraScripts::ReadIntro(*exe_path, intro)){
  878. BattleCameraScripts::WriteIntroLua(file, intro);
  879. }
  880. else std::cerr << "[WARNING] Can't read the cameras of the start of the battles from ff7.exe." << std::endl;
  881. }
  882. void BattleDataInstaller::WriteEffectMeshes(){
  883. // The meshes of the effects that are in the data of ff7.exe, like the ground of Ifrit and the
  884. // mountain of Ramuh (see ExeEffectMeshes.h). Names are the address of the block in the executable.
  885. std::map<uint32_t, ExeEffectMeshes::Mesh> meshes;
  886. auto exe_path = const_cast<DiskImage&>(disk_image_).filePath("ff7.exe");
  887. if (exe_path == nullptr || !ExeEffectMeshes::Extract(*exe_path, meshes)){
  888. std::cerr << "[WARNING] Can't read the meshes of the effects from ff7.exe." << std::endl;
  889. }
  890. std::ofstream file(data_dir_ + "gamedata/effect_meshes.lua");
  891. ExeEffectMeshes::WriteLua(file, meshes);
  892. }
  893. void BattleDataInstaller::WriteEffectCameras(){
  894. // The scripts of the cameras are in the data of ff7.exe, and are found from the code that
  895. // uses them. Names are the address of the script in memory.
  896. std::map<uint32_t, std::vector<int16_t>> scripts;
  897. auto exe_path = const_cast<DiskImage&>(disk_image_).filePath("ff7.exe");
  898. if (exe_path == nullptr || !ExeEffectCameras::Extract(*exe_path, scripts)){
  899. std::cerr << "[WARNING] Can't read the camera scripts of the effects from ff7.exe." << std::endl;
  900. }
  901. std::ofstream file(data_dir_ + "gamedata/effect_cameras.lua");
  902. file << "-- Camera scripts of the battle effects, read from ff7.exe. Game.EffectCameras[name] is a list\n"
  903. << "-- of 16 bit words, with the address of the script in the executable as the name (like\n"
  904. << "-- 0x8ae268). See scripts/battle/effect_camera.lua for the format.\n"
  905. << "Game.EffectCameras = Game.EffectCameras or {}\n";
  906. for (const auto& script : scripts){
  907. file << "Game.EffectCameras[\"0x" << std::hex << script.first << std::dec << "\"] = {";
  908. for (size_t i = 0; i < script.second.size(); ++ i){
  909. if (i % 16 == 0) file << "\n ";
  910. file << script.second[i] << ", ";
  911. }
  912. file << "\n}\n";
  913. }
  914. }
  915. void BattleDataInstaller::WriteEffectSprites(){
  916. // The sprite files (.s) are lists of frames, and every frame a list of quads of a sprite sheet (see
  917. // the layout below). They are written twice: all the quads one after the other (the first format,
  918. // used by the Cure effect) and the frames with their quads (effect_animations.lua).
  919. // Textures are converted too, with the name of the effect folder as a prefix (common_ for the
  920. // archive root), to images/battle_fx, so they can be used as images of sprites.
  921. const std::string key_prefix = "ff7/data/battle/";
  922. auto key_of = [&](std::string folder){
  923. if (folder.empty()) return std::string("common");
  924. if (folder.compare(0, key_prefix.size(), key_prefix) == 0) folder = folder.substr(key_prefix.size());
  925. return EffectSafeName(folder);
  926. };
  927. std::ofstream file(data_dir_ + "gamedata/effect_sprites.lua");
  928. file << "-- Frames of the sprite files of magic.lgp. Game.EffectSprites[name] is a list of frames with\n"
  929. << "-- the position (u, v) and size (w, h) in the texture, in pixels, the offset to draw it\n"
  930. << "-- (ox, oy) and the flags. The names are the folder and the file, like common_iyashi.\n"
  931. << "-- Textures are in images/battle_fx, like common_iyashi00.png.\n"
  932. << "Game.EffectSprites = Game.EffectSprites or {}\n";
  933. // (The list has the quads of all the frames in order, with the position of the corner as ox, oy.)
  934. std::ofstream animations(data_dir_ + "gamedata/effect_animations.lua");
  935. animations << "-- Frames of the sprite files (.SPT) of magic.lgp. Game.EffectAnimations[name] is a list of frames and\n"
  936. << "-- every frame a list of quads: {x, y, u, v, w, h}, with the position of the corner and the size of the\n"
  937. << "-- quad in units of 8 of the effect, and the place in the texture in pixels. The names are the folder\n"
  938. << "-- and the file, like common_houden_2.\n"
  939. << "Game.EffectAnimations = Game.EffectAnimations or {}\n";
  940. const std::string dir = output_dir_ + "temp/effects/";
  941. boost::filesystem::create_directories(data_dir_ + "images/battle_fx/");
  942. for (size_t f = 0; f < magic_lgp_files_.size(); f ++){
  943. const std::string& name = magic_lgp_file_names_[f];
  944. if (name.size() < 3) continue;
  945. std::string ext = name.substr(name.find_last_of('.') + 1);
  946. std::transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char c){return std::tolower(c);});
  947. const std::string key = key_of(magic_lgp_file_folders_[f]);
  948. if (ext == "tex"){
  949. const std::string stem = EffectSafeName(EffectStem(name));
  950. const std::string path = data_dir_ + "images/battle_fx/" + key + "_" + stem + ".png";
  951. if (boost::filesystem::exists(path)) continue;
  952. try{
  953. magic_lgp_files_[f].WriteFile(dir + key + "_" + stem + ".tex");
  954. TexFile tex(dir + key + "_" + stem + ".tex");
  955. tex.SavePng(path);
  956. }
  957. catch (const std::exception& ex){
  958. // Many of the original textures are dummies.
  959. }
  960. }
  961. else if (ext == "s"){
  962. File& sprite_file = magic_lgp_files_[f];
  963. const size_t size = sprite_file.GetFileSize();
  964. if (size < 8) continue;
  965. sprite_file.SetOffset(0);
  966. std::vector<unsigned char> bytes(size);
  967. for (size_t b = 0; b < size; b ++) bytes[b] = sprite_file.readU8();
  968. // Only the files with the header of sprite lists.
  969. if (bytes[0] != 0x23 || bytes[1] != 0x20) continue;
  970. // After the header (the two characters, and the number of frames as a 32 bit value, at 4)
  971. // there are the frames. Each one has two 16 bit values, the second is the number of quads,
  972. // and then 20 bytes for every quad: flags (4 bytes), the position of the corner (x and y,
  973. // 16 bits), the place in the texture (u and v, 16 bits), 4 more bytes, and the width
  974. // (8 bits, twice) and the height (8 bits, twice). Positions and sizes are in units of 8 of
  975. // the effect. Layout found in the code that draws them (0x598a7a), and all the files of
  976. // magic.lgp end exactly where their last frame ends.
  977. struct Quad{int x, y, u, v, w, h;};
  978. std::vector<std::vector<Quad>> frames;
  979. const uint32_t frame_count = bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (static_cast<uint32_t>(bytes[7]) << 24);
  980. size_t p = 8;
  981. bool valid = true;
  982. for (uint32_t fr = 0; fr < frame_count && valid; ++ fr){
  983. if (p + 4 > size){valid = false; break;}
  984. const int count = static_cast<int16_t>(bytes[p + 2] | (bytes[p + 3] << 8));
  985. p += 4;
  986. if (count < 0 || p + static_cast<size_t>(count) * 20 > size){valid = false; break;}
  987. std::vector<Quad> quads;
  988. for (int q = 0; q < count; ++ q, p += 20){
  989. Quad quad;
  990. quad.x = static_cast<int16_t>(bytes[p + 4] | (bytes[p + 5] << 8));
  991. quad.y = static_cast<int16_t>(bytes[p + 6] | (bytes[p + 7] << 8));
  992. quad.u = static_cast<int16_t>(bytes[p + 8] | (bytes[p + 9] << 8));
  993. quad.v = static_cast<int16_t>(bytes[p + 10] | (bytes[p + 11] << 8));
  994. quad.w = bytes[p + 16];
  995. quad.h = bytes[p + 18];
  996. quads.push_back(quad);
  997. }
  998. frames.push_back(quads);
  999. }
  1000. if (!valid || p != size || frames.empty()) continue;
  1001. const std::string sprite_name = key + "_" + EffectSafeName(EffectStem(name));
  1002. // All the quads one after the other, for the effects that pick them by number.
  1003. file << "Game.EffectSprites[\"" << sprite_name << "\"] = {\n";
  1004. for (const std::vector<Quad>& quads : frames){
  1005. for (const Quad& quad : quads){
  1006. file << " {u = " << quad.u << ", v = " << quad.v << ", w = " << quad.w << ", h = " << quad.h
  1007. << ", ox = " << quad.x << ", oy = " << quad.y << "},\n";
  1008. }
  1009. }
  1010. file << "}\n";
  1011. // The frames, with their quads.
  1012. animations << "Game.EffectAnimations[\"" << sprite_name << "\"] = {\n";
  1013. for (const std::vector<Quad>& quads : frames){
  1014. animations << " {";
  1015. for (size_t q = 0; q < quads.size(); ++ q){
  1016. animations << (q > 0 ? ", " : "") << "{" << quads[q].x << ", " << quads[q].y << ", " << quads[q].u << ", "
  1017. << quads[q].v << ", " << quads[q].w << ", " << quads[q].h << "}";
  1018. }
  1019. animations << "},\n";
  1020. }
  1021. animations << "}\n";
  1022. }
  1023. }
  1024. }
  1025. void BattleDataInstaller::WriteEnemies(){
  1026. for (Enemy enemy : enemies_){
  1027. TiXmlDocument xml;
  1028. std::unique_ptr<TiXmlElement> container(new TiXmlElement("enemy"));
  1029. container->SetAttribute("id", enemy.id);
  1030. container->SetAttribute("model", enemy.model);
  1031. container->SetAttribute("name", enemy.name);
  1032. container->SetAttribute("level", enemy.level);
  1033. container->SetAttribute("exp", enemy.exp);
  1034. container->SetAttribute("ap", enemy.ap);
  1035. container->SetAttribute("money", enemy.money);
  1036. container->SetAttribute("morph", enemy.morph);
  1037. container->SetDoubleAttribute("back_damage", enemy.back_damage);
  1038. std::unique_ptr<TiXmlElement> stats(new TiXmlElement("stats"));
  1039. std::unique_ptr<TiXmlElement> stat_str(new TiXmlElement("stat"));
  1040. stat_str->SetAttribute("id", "str");
  1041. stat_str->SetAttribute("value", enemy.str);
  1042. stats->LinkEndChild(stat_str.release());
  1043. std::unique_ptr<TiXmlElement> stat_mag(new TiXmlElement("stat"));
  1044. stat_mag->SetAttribute("id", "mag");
  1045. stat_mag->SetAttribute("value", enemy.mag);
  1046. stats->LinkEndChild(stat_mag.release());
  1047. std::unique_ptr<TiXmlElement> stat_def(new TiXmlElement("stat"));
  1048. stat_def->SetAttribute("id", "def");
  1049. stat_def->SetAttribute("value", enemy.def);
  1050. stats->LinkEndChild(stat_def.release());
  1051. std::unique_ptr<TiXmlElement> stat_mdef(new TiXmlElement("stat"));
  1052. stat_mdef->SetAttribute("id", "mdef");
  1053. stat_mdef->SetAttribute("value", enemy.mdef);
  1054. stats->LinkEndChild(stat_mdef.release());
  1055. std::unique_ptr<TiXmlElement> stat_spd(new TiXmlElement("stat"));
  1056. stat_spd->SetAttribute("id", "spd");
  1057. stat_spd->SetAttribute("value", enemy.spd);
  1058. stats->LinkEndChild(stat_spd.release());
  1059. std::unique_ptr<TiXmlElement> stat_lck(new TiXmlElement("stat"));
  1060. stat_lck->SetAttribute("id", "lck");
  1061. stat_lck->SetAttribute("value", enemy.lck);
  1062. stats->LinkEndChild(stat_lck.release());
  1063. std::unique_ptr<TiXmlElement> stat_eva(new TiXmlElement("stat"));
  1064. stat_eva->SetAttribute("id", "eva");
  1065. stat_eva->SetAttribute("value", enemy.eva);
  1066. stats->LinkEndChild(stat_eva.release());
  1067. std::unique_ptr<TiXmlElement> stat_hp(new TiXmlElement("stat"));
  1068. stat_hp->SetAttribute("id", "hp");
  1069. stat_hp->SetAttribute("value", enemy.hp);
  1070. stats->LinkEndChild(stat_hp.release());
  1071. std::unique_ptr<TiXmlElement> stat_mp(new TiXmlElement("stat"));
  1072. stat_mp->SetAttribute("id", "mp");
  1073. stat_mp->SetAttribute("value", enemy.mp);
  1074. stats->LinkEndChild(stat_mp.release());
  1075. container->LinkEndChild(stats.release());
  1076. std::unique_ptr<TiXmlElement> elements(new TiXmlElement("elements"));
  1077. for (Enemy::Element element : enemy.elements){
  1078. std::unique_ptr<TiXmlElement> xml_element(new TiXmlElement("element"));
  1079. xml_element->SetAttribute("id", element.id);
  1080. xml_element->SetDoubleAttribute("factor", element.factor);
  1081. elements->LinkEndChild(xml_element.release());
  1082. }
  1083. container->LinkEndChild(elements.release());
  1084. std::unique_ptr<TiXmlElement> immunities(new TiXmlElement("immunities"));
  1085. for (Enemy::Immunity immunity : enemy.immunities){
  1086. std::unique_ptr<TiXmlElement> xml_immunity(new TiXmlElement("immunity"));
  1087. xml_immunity->SetAttribute("status", immunity.status);
  1088. xml_immunity->SetDoubleAttribute("rate", immunity.rate);
  1089. immunities->LinkEndChild(xml_immunity.release());
  1090. }
  1091. container->LinkEndChild(immunities.release());
  1092. std::unique_ptr<TiXmlElement> attacks(new TiXmlElement("attacks"));
  1093. for (Enemy::Attack attack : enemy.attacks){
  1094. std::unique_ptr<TiXmlElement> xml_attack(new TiXmlElement("attack"));
  1095. xml_attack->SetAttribute("id", attack.id);
  1096. xml_attack->SetAttribute("animation", attack.animation);
  1097. xml_attack->SetAttribute("camera", attack.camera);
  1098. attacks->LinkEndChild(xml_attack.release());
  1099. }
  1100. container->LinkEndChild(attacks.release());
  1101. std::unique_ptr<TiXmlElement> manip_attacks(new TiXmlElement("manipulate"));
  1102. manip_attacks->SetAttribute("manipulable", enemy.manipulate_attacks.size() > 0 ? 1 : 0);
  1103. for (u16 attack : enemy.manipulate_attacks){
  1104. std::unique_ptr<TiXmlElement> xml_manip_attack(new TiXmlElement("attack"));
  1105. xml_manip_attack->SetAttribute("id", attack);
  1106. manip_attacks->LinkEndChild(xml_manip_attack.release());
  1107. }
  1108. container->LinkEndChild(manip_attacks.release());
  1109. std::unique_ptr<TiXmlElement> steals(new TiXmlElement("steal"));
  1110. for (Enemy::Item item : enemy.steal){
  1111. std::unique_ptr<TiXmlElement> xml_steal(new TiXmlElement("item"));
  1112. xml_steal->SetAttribute("id", item.id);
  1113. xml_steal->SetDoubleAttribute("rate", item.rate);
  1114. steals->LinkEndChild(xml_steal.release());
  1115. }
  1116. container->LinkEndChild(steals.release());
  1117. std::unique_ptr<TiXmlElement> drops(new TiXmlElement("drop"));
  1118. for (Enemy::Item item : enemy.drop){
  1119. std::unique_ptr<TiXmlElement> xml_drop(new TiXmlElement("item"));
  1120. xml_drop->SetAttribute("id", item.id);
  1121. xml_drop->SetDoubleAttribute("rate", item.rate);
  1122. drops->LinkEndChild(xml_drop.release());
  1123. }
  1124. container->LinkEndChild(drops.release());
  1125. std::unique_ptr<TiXmlElement> animations(new TiXmlElement("animations"));
  1126. for (unsigned int animation : enemy.animations){
  1127. std::unique_ptr<TiXmlElement> xml_animation(new TiXmlElement("animation"));
  1128. xml_animation->SetAttribute("id", animation);
  1129. animations->LinkEndChild(xml_animation.release());
  1130. }
  1131. container->LinkEndChild(animations.release());
  1132. // AI scripts, as hexadecimal bytecode.
  1133. {
  1134. static const char* AI_SLOT_NAMES[16] = {
  1135. "init", "main", "counter_general", "counter_death", "counter_physical", "counter_magic",
  1136. "battle_end", "pre_turn", "event_1", "event_2", "event_3", "event_4", "event_5",
  1137. "event_6", "event_7", "event_8"
  1138. };
  1139. std::unique_ptr<TiXmlElement> ai(new TiXmlElement("ai"));
  1140. for (size_t slot = 0; slot < enemy.ai_scripts.size() && slot < 16; slot ++){
  1141. if (enemy.ai_scripts[slot].empty()) continue;
  1142. std::string hex;
  1143. char digits[3];
  1144. for (u8 byte : enemy.ai_scripts[slot]){
  1145. snprintf(digits, sizeof(digits), "%02x", byte);
  1146. hex += digits;
  1147. }
  1148. std::unique_ptr<TiXmlElement> xml_script(new TiXmlElement("script"));
  1149. xml_script->SetAttribute("slot", static_cast<int>(slot));
  1150. xml_script->SetAttribute("name", AI_SLOT_NAMES[slot]);
  1151. xml_script->SetAttribute("data", hex);
  1152. ai->LinkEndChild(xml_script.release());
  1153. }
  1154. container->LinkEndChild(ai.release());
  1155. }
  1156. xml.LinkEndChild(container.release());
  1157. std::string file_name = BuildEnemyFileName(enemy);
  1158. xml.SaveFile(data_dir_ + file_name);
  1159. enemy_map_[enemy.id] = file_name;
  1160. }
  1161. }
  1162. void BattleDataInstaller::WriteAttacks(){
  1163. for (Attack attack : attacks_){
  1164. TiXmlDocument xml;
  1165. std::unique_ptr<TiXmlElement> container(new TiXmlElement("Attack"));
  1166. container->SetAttribute("id", attack.id);
  1167. container->SetAttribute("name", attack.name);
  1168. container->SetAttribute("mp", attack.mp);
  1169. container->SetAttribute("reflectable", attack.reflectable);
  1170. std::unique_ptr<TiXmlElement> damage(new TiXmlElement("Damage"));
  1171. std::unique_ptr<TiXmlElement> damage_power(new TiXmlElement("Parameter"));
  1172. damage_power->SetAttribute("id", "power");
  1173. damage_power->SetAttribute("value", attack.damage.power);
  1174. damage->LinkEndChild(damage_power.release());
  1175. std::unique_ptr<TiXmlElement> damage_formula(new TiXmlElement("Parameter"));
  1176. damage_formula->SetAttribute("id", "formula");
  1177. damage_formula->SetAttribute("value", attack.damage.formula);
  1178. damage->LinkEndChild(damage_formula.release());
  1179. std::unique_ptr<TiXmlElement> damage_modifier(new TiXmlElement("Parameter"));
  1180. damage_modifier->SetAttribute("id", "modifier");
  1181. damage_modifier->SetAttribute("value", attack.damage.modifier);
  1182. damage->LinkEndChild(damage_modifier.release());
  1183. std::unique_ptr<TiXmlElement> damage_acc(new TiXmlElement("Parameter"));
  1184. damage_acc->SetAttribute("id", "accuracy");
  1185. // Accuracy is a fraction between 0 and 1, it can't be written as an integer.
  1186. damage_acc->SetDoubleAttribute("value", attack.damage.accuracy);
  1187. damage->LinkEndChild(damage_acc.release());
  1188. std::unique_ptr<TiXmlElement> damage_darkness(new TiXmlElement("Parameter"));
  1189. damage_darkness->SetAttribute("id", "affected_by_darkness");
  1190. damage_darkness->SetAttribute("value", attack.damage.affected_by_darkness);
  1191. damage->LinkEndChild(damage_darkness.release());
  1192. std::unique_ptr<TiXmlElement> damage_restore(new TiXmlElement("Parameter"));
  1193. damage_restore->SetAttribute("id", "restore");
  1194. damage_restore->SetAttribute("value", static_cast<int>(attack.damage.restore));
  1195. damage->LinkEndChild(damage_restore.release());
  1196. std::unique_ptr<TiXmlElement> damage_mp(new TiXmlElement("Parameter"));
  1197. damage_mp->SetAttribute("id", "damage_mp");
  1198. damage_mp->SetAttribute("value", attack.damage.damage_mp);
  1199. damage->LinkEndChild(damage_mp.release());
  1200. std::unique_ptr<TiXmlElement> damage_drain_hp(new TiXmlElement("Parameter"));
  1201. damage_drain_hp->SetAttribute("id", "drain_hp");
  1202. damage_drain_hp->SetAttribute("value", attack.damage.drain_hp);
  1203. damage->LinkEndChild(damage_drain_hp.release());
  1204. std::unique_ptr<TiXmlElement> damage_drain_mp(new TiXmlElement("Parameter"));
  1205. damage_drain_mp->SetAttribute("id", "drain_mp");
  1206. damage_drain_mp->SetAttribute("value", attack.damage.drain_mp);
  1207. damage->LinkEndChild(damage_drain_mp.release());
  1208. std::unique_ptr<TiXmlElement> damage_ignore(new TiXmlElement("Parameter"));
  1209. damage_ignore->SetAttribute("id", "ignore_status_defense");
  1210. damage_ignore->SetAttribute("value", attack.damage.ignore_status_defense);
  1211. damage->LinkEndChild(damage_ignore.release());
  1212. std::unique_ptr<TiXmlElement> damage_critical(new TiXmlElement("Parameter"));
  1213. damage_critical->SetAttribute("id", "always_critical");
  1214. damage_critical->SetAttribute("value", attack.damage.critical);
  1215. damage->LinkEndChild(damage_critical.release());
  1216. container->LinkEndChild(damage.release());
  1217. std::unique_ptr<TiXmlElement> target_opts(new TiXmlElement("Target"));
  1218. std::unique_ptr<TiXmlElement> target_se(new TiXmlElement("Parameter"));
  1219. target_se->SetAttribute("id", "selection_enabled");
  1220. target_se->SetAttribute("value", attack.target.selection_enabled);
  1221. target_opts->LinkEndChild(target_se.release());
  1222. std::unique_ptr<TiXmlElement> target_de(new TiXmlElement("Parameter"));
  1223. target_de->SetAttribute("id", "default_enemy");
  1224. target_de->SetAttribute("value", attack.target.default_enemy);
  1225. target_opts->LinkEndChild(target_de.release());
  1226. std::unique_ptr<TiXmlElement> target_dm(new TiXmlElement("Parameter"));
  1227. target_dm->SetAttribute("id", "default_multiple");
  1228. target_dm->SetAttribute("value", attack.target.default_multiple);
  1229. target_opts->LinkEndChild(target_dm.release());
  1230. std::unique_ptr<TiXmlElement> target_tm(new TiXmlElement("Parameter"));
  1231. target_tm->SetAttribute("id", "toggle_multiple");
  1232. target_tm->SetAttribute("value", attack.target.toggle_multiple);
  1233. target_opts->LinkEndChild(target_tm.release());
  1234. std::unique_ptr<TiXmlElement> target_fr(new TiXmlElement("Parameter"));
  1235. target_fr->SetAttribute("id", "fixed_row");
  1236. target_fr->SetAttribute("value", attack.target.fixed_row);
  1237. target_opts->LinkEndChild(target_fr.release());
  1238. std::unique_ptr<TiXmlElement> target_sr(new TiXmlElement("Parameter"));
  1239. target_sr->SetAttribute("id", "short_range");
  1240. target_sr->SetAttribute("value", attack.target.short_range);
  1241. target_opts->LinkEndChild(target_sr.release());
  1242. std::unique_ptr<TiXmlElement> target_ar(new TiXmlElement("Parameter"));
  1243. target_ar->SetAttribute("id", "all_rows");
  1244. target_ar->SetAttribute("value", attack.target.all_rows);
  1245. target_opts->LinkEndChild(target_ar.release());
  1246. std::unique_ptr<TiXmlElement> target_rd(new TiXmlElement("Parameter"));
  1247. target_rd->SetAttribute("id", "random");
  1248. target_rd->SetAttribute("value", attack.target.random);
  1249. target_opts->LinkEndChild(target_rd.release());
  1250. std::unique_ptr<TiXmlElement> target_od(new TiXmlElement("Parameter"));
  1251. target_od->SetAttribute("id", "only_for_dead");
  1252. target_od->SetAttribute("value", attack.target.only_for_dead);
  1253. target_opts->LinkEndChild(target_od.release());
  1254. std::unique_ptr<TiXmlElement> target_nr(new TiXmlElement("Parameter"));
  1255. target_nr->SetAttribute("id", "no_retarget");
  1256. target_nr->SetAttribute("value", attack.target.no_re_target);
  1257. target_opts->LinkEndChild(target_nr.release());
  1258. container->LinkEndChild(target_opts.release());
  1259. std::unique_ptr<TiXmlElement> effects(new TiXmlElement("Effects"));
  1260. for (Attack::StatusEffect effect : attack.status_effects){
  1261. std::unique_ptr<TiXmlElement> xml_effect(new TiXmlElement("Effect"));
  1262. xml_effect->SetAttribute("id", effect.id);
  1263. xml_effect->SetDoubleAttribute("chance", effect.chance);
  1264. xml_effect->SetAttribute("mode", GameData::STATUS_EFFECT_MODE::to_string(effect.type));
  1265. effects->LinkEndChild(xml_effect.release());
  1266. }
  1267. container->LinkEndChild(effects.release());
  1268. std::unique_ptr<TiXmlElement> elements(new TiXmlElement("Elements"));
  1269. for (unsigned int element : attack.elements){
  1270. std::unique_ptr<TiXmlElement> xml_element(new TiXmlElement("Element"));
  1271. xml_element->SetAttribute("id", element);
  1272. elements->LinkEndChild(xml_element.release());
  1273. }
  1274. container->LinkEndChild(elements.release());
  1275. std::unique_ptr<TiXmlElement> anim(new TiXmlElement("Animation"));
  1276. std::unique_ptr<TiXmlElement> anim_e(new TiXmlElement("Parameter"));
  1277. anim_e->SetAttribute("id", "effect");
  1278. anim_e->SetAttribute("value", attack.animation.effect);
  1279. anim->LinkEndChild(anim_e.release());
  1280. std::unique_ptr<TiXmlElement> anim_ie(new TiXmlElement("Parameter"));
  1281. anim_ie->SetAttribute("id", "impact_effect");
  1282. anim_ie->SetAttribute("value", attack.animation.impact_effect);
  1283. anim->LinkEndChild(anim_ie.release());
  1284. std::unique_ptr<TiXmlElement> anim_s(new TiXmlElement("Parameter"));
  1285. anim_s->SetAttribute("id", "sound");
  1286. anim_s->SetAttribute("value", attack.animation.sound);
  1287. anim->LinkEndChild(anim_s.release());
  1288. std::unique_ptr<TiXmlElement> anim_ha(new TiXmlElement("Parameter"));
  1289. anim_ha->SetAttribute("id", "hurt_anim");
  1290. anim_ha->SetAttribute("value", attack.animation.hurt_anim);
  1291. anim->LinkEndChild(anim_ha.release());
  1292. std::unique_ptr<TiXmlElement> anim_c(new TiXmlElement("Parameter"));
  1293. anim_c->SetAttribute("id", "camera_single");
  1294. anim_c->SetAttribute("value", attack.animation.camera_single);
  1295. anim->LinkEndChild(anim_c.release());
  1296. std::unique_ptr<TiXmlElement> anim_cm(new TiXmlElement("Parameter"));
  1297. anim_cm->SetAttribute("id", "camera_multiple");
  1298. anim_cm->SetAttribute("value", attack.animation.camera_multiple);
  1299. anim->LinkEndChild(anim_cm.release());
  1300. container->LinkEndChild(anim.release());
  1301. xml.LinkEndChild(container.release());
  1302. std::string file_name = BuildAttackFileName(attack);
  1303. xml.SaveFile(data_dir_ + file_name);
  1304. attack_map_[attack.id] = file_name;
  1305. }
  1306. // Index of the attack files by ID, as file names include the attack name.
  1307. TiXmlDocument index;
  1308. std::unique_ptr<TiXmlElement> attacks(new TiXmlElement("attacks"));
  1309. for (const auto& entry : attack_map_){
  1310. std::unique_ptr<TiXmlElement> xml_attack(new TiXmlElement("attack"));
  1311. xml_attack->SetAttribute("id", entry.first);
  1312. // The file name in the map has the gamedata/attack/ path.
  1313. xml_attack->SetAttribute("file", entry.second.substr(entry.second.find_last_of('/') + 1));
  1314. attacks->LinkEndChild(xml_attack.release());
  1315. }
  1316. index.LinkEndChild(attacks.release());
  1317. index.SaveFile(data_dir_ + "gamedata/attack/_index.xml");
  1318. }
  1319. void BattleDataInstaller::WriteFormations(){
  1320. for (Formation formation : formations_){
  1321. TiXmlDocument xml;
  1322. std::unique_ptr<TiXmlElement> container(new TiXmlElement("formation"));
  1323. container->SetAttribute("id", formation.id);
  1324. container->SetAttribute("next", formation.next_formation);
  1325. container->SetDoubleAttribute("escape_difficulty", formation.escape_counter);
  1326. container->SetAttribute("escapable", formation.escapable);
  1327. container->SetAttribute("skip_victory_pose", formation.skip_victory_pose);
  1328. container->SetAttribute("skip_spoils", formation.skip_spoils);
  1329. container->SetAttribute("skip_victory_pose", formation.skip_victory_pose);
  1330. container->SetAttribute("preemptive_disabled", formation.preemptive_disabled);
  1331. container->SetAttribute("layout", static_cast<int>(formation.layout));
  1332. std::unique_ptr<TiXmlElement> location(new TiXmlElement("location"));
  1333. location->SetAttribute("id", formation.location);
  1334. location->SetAttribute("name", formation.location_name);
  1335. container->LinkEndChild(location.release());
  1336. std::unique_ptr<TiXmlElement> enemies(new TiXmlElement("enemies"));
  1337. for (Formation::Enemy enemy : formation.enemies){
  1338. std::unique_ptr<TiXmlElement> enemy_xml(new TiXmlElement("enemy"));
  1339. enemy_xml->SetAttribute("id", enemy.id);
  1340. enemy_xml->SetAttribute("x", enemy.x);
  1341. enemy_xml->SetAttribute("y", enemy.y);
  1342. enemy_xml->SetAttribute("z", enemy.z);
  1343. enemy_xml->SetAttribute("row", enemy.row);
  1344. std::string cover = "";
  1345. for (int c = 0; c < 5; c ++) cover += enemy.cover[c];
  1346. enemy_xml->SetAttribute("cover", cover);
  1347. enemy_xml->SetAttribute("visible", enemy.visible);
  1348. enemy_xml->SetAttribute("direction", enemy.direction);
  1349. enemy_xml->SetAttribute("targeteable", enemy.targeteable);
  1350. enemy_xml->SetAttribute("main_script_active", enemy.main_script_active);
  1351. enemies->LinkEndChild(enemy_xml.release());
  1352. }
  1353. container->LinkEndChild(enemies.release());
  1354. std::unique_ptr<TiXmlElement> cameras(new TiXmlElement("camera"));
  1355. cameras->SetAttribute("initial", formation.initial_camera_position);
  1356. cameras->SetAttribute("intro", formation.intro_camera);
  1357. int c = 0;
  1358. for (Formation::Camera camera : formation.camera_positions){
  1359. std::unique_ptr<TiXmlElement> camera_xml(new TiXmlElement("position"));
  1360. camera_xml->SetAttribute("id", c);
  1361. camera_xml->SetDoubleAttribute("x", camera.x);
  1362. camera_xml->SetDoubleAttribute("y", camera.y);
  1363. camera_xml->SetDoubleAttribute("z", camera.z);
  1364. camera_xml->SetDoubleAttribute("direction_x", camera.d_x);
  1365. camera_xml->SetDoubleAttribute("direction_y", camera.d_y);
  1366. camera_xml->SetDoubleAttribute("direction_z", camera.d_z);
  1367. cameras->LinkEndChild(camera_xml.release());
  1368. c ++;
  1369. }
  1370. container->LinkEndChild(cameras.release());
  1371. std::unique_ptr<TiXmlElement> arena(new TiXmlElement("arena"));
  1372. arena->SetAttribute("is_arena", formation.is_arena_battle);
  1373. for (int next : formation.next_arena_formation_candidates){
  1374. std::unique_ptr<TiXmlElement> next_xml(new TiXmlElement("next_candidate"));
  1375. next_xml->SetAttribute("id", next);
  1376. arena->LinkEndChild(next_xml.release());
  1377. }
  1378. container->LinkEndChild(arena.release());
  1379. xml.LinkEndChild(container.release());
  1380. std::string file_name = std::to_string(formation.id);
  1381. while (file_name.length() < 4) file_name = "0" + file_name;
  1382. file_name = "gamedata/formation/" + file_name + ".xml";
  1383. xml.SaveFile(data_dir_ + file_name);
  1384. formation_map_[formation.id] = file_name;
  1385. }
  1386. }
  1387. void BattleDataInstaller::WriteCharacterData(){
  1388. TiXmlDocument xml;
  1389. std::unique_ptr<TiXmlElement> container(new TiXmlElement("characters"));
  1390. for (CharacterData data : character_data_){
  1391. std::unique_ptr<TiXmlElement> xml_character(new TiXmlElement("character"));
  1392. xml_character->SetAttribute("id", data.id);
  1393. for (CharacterModel model : data.models){
  1394. std::unique_ptr<TiXmlElement> xml_model(new TiXmlElement("model"));
  1395. xml_model->SetAttribute("name", model.name);
  1396. xml_model->SetAttribute("file", model.model);
  1397. xml_character->LinkEndChild(xml_model.release());
  1398. }
  1399. container->LinkEndChild(xml_character.release());
  1400. }
  1401. xml.LinkEndChild(container.release());
  1402. xml.SaveFile(data_dir_ + "models/battle/characters.xml");
  1403. }
  1404. void BattleDataInstaller::WriteSceneData(){
  1405. TiXmlDocument xml;
  1406. std::unique_ptr<TiXmlElement> container(new TiXmlElement("scenes"));
  1407. for (SceneModel data : scene_data_){
  1408. std::unique_ptr<TiXmlElement> xml_scene(new TiXmlElement("scene"));
  1409. xml_scene->SetAttribute("id", data.id);
  1410. xml_scene->SetAttribute("file", data.model);
  1411. xml_scene->SetAttribute("description", data.description);
  1412. container->LinkEndChild(xml_scene.release());
  1413. }
  1414. xml.LinkEndChild(container.release());
  1415. xml.SaveFile(data_dir_ + "models/battle/scenes.xml");
  1416. }
  1417. std::string BattleDataInstaller::BuildEnemyFileName(Enemy enemy){
  1418. std::string file_name = "gamedata/enemy/";
  1419. std::string id = std::to_string(enemy.id);
  1420. while (id.size() < 4) id = "0" + id;
  1421. file_name += id + ".xml";
  1422. return file_name;
  1423. }
  1424. std::string BattleDataInstaller::BuildAttackFileName(Attack attack){
  1425. std::string file_name = "gamedata/attack/";
  1426. std::string id = std::to_string(attack.id);
  1427. while (id.size() < 4) id = "0" + id;
  1428. file_name += (id + "_");
  1429. for (int n = 0; n < attack.name.size(); n ++){
  1430. if (
  1431. (attack.name[n] >= '0' && attack.name[n] <= '9')
  1432. || (attack.name[n] >= 'a' && attack.name[n] <= 'z')
  1433. || (attack.name[n] >= 'A' && attack.name[n] <= 'Z')
  1434. ) file_name += attack.name[n];
  1435. }
  1436. file_name += ".xml";
  1437. return file_name;
  1438. }
  1439. File* BattleDataInstaller::ExtractGZipScene(File file){
  1440. u32 offset = 0;
  1441. u8* file_buffer = static_cast<u8*>(malloc(file.GetFileSize()));
  1442. file.GetFileBuffer(file_buffer, 0, file.GetFileSize());
  1443. u32 extract_size = 256 * 1024;
  1444. u8* extract_buffer = static_cast<u8*>(malloc(extract_size));
  1445. int ret;
  1446. z_stream strm;
  1447. strm.zalloc = Z_NULL; // Used to allocate the internal state.
  1448. strm.zfree = Z_NULL; // Used to free the internal state.
  1449. strm.opaque = Z_NULL; // Private data object passed to zalloc and zfree.
  1450. strm.next_in = file_buffer + offset; //Next input byte.
  1451. strm.avail_in = file.GetFileSize() - offset; // Number of bytes available at next_in.
  1452. strm.next_out = extract_buffer; // Next output byte should be put there.
  1453. strm.avail_out = extract_size; // Remaining free space at next_out.
  1454. ret = inflateInit2(&strm, 15 + 32);
  1455. if (ret != Z_OK){
  1456. switch (ret){
  1457. case Z_MEM_ERROR:
  1458. inflateEnd(&strm);
  1459. std::cout << "Warning: inflateInit2 - Z_MEM_ERROR in file " << file.GetFileName() << std::endl;
  1460. break;
  1461. case Z_STREAM_ERROR:
  1462. inflateEnd(&strm);
  1463. std::cout << "Warning: inflateInit2 - Z_STREAM_ERROR in file " << file.GetFileName() << std::endl;
  1464. break;
  1465. default:
  1466. inflateEnd(&strm);
  1467. std::cout << "Warning: inflateInit2 - unknown error in file " << file.GetFileName() << std::endl;
  1468. }
  1469. return NULL;
  1470. }
  1471. do{
  1472. if (strm.next_out == NULL){
  1473. inflateEnd(&strm);
  1474. std::cout << "Warning: strm.next_out == NULL in file " << file.GetFileName() << std::endl;
  1475. return NULL;
  1476. }
  1477. ret = inflate(&strm, Z_NO_FLUSH);
  1478. assert(ret != Z_STREAM_ERROR);
  1479. switch (ret){
  1480. case Z_NEED_DICT:
  1481. inflateEnd(&strm);
  1482. std::cout << "Warning: inflate - Z_NEED_DICT in file " << file.GetFileName() << std::endl;
  1483. return NULL;
  1484. case Z_DATA_ERROR:
  1485. inflateEnd(&strm);
  1486. std::cout << "Warning: inflate - Z_DATA_ERROR in file " << file.GetFileName() << std::endl;
  1487. return NULL;
  1488. case Z_MEM_ERROR:
  1489. inflateEnd(&strm);
  1490. std::cout << "Warning: inflate - Z_MEM_ERROR in file " << file.GetFileName() << std::endl;
  1491. return NULL;
  1492. }
  1493. if (ret != Z_STREAM_END){
  1494. extract_buffer = static_cast<u8*>(realloc(extract_buffer, extract_size * 2));
  1495. if (extract_buffer == NULL){
  1496. inflateEnd(&strm);
  1497. //std::cout << "Warning: extract_buffer == NULL in file "
  1498. // << file.GetFileName() << std::endl;
  1499. return NULL;
  1500. }
  1501. strm.next_out = static_cast<u8*>(extract_buffer + extract_size);
  1502. strm.avail_out = extract_size;
  1503. extract_size *= 2;
  1504. }
  1505. } while (ret != Z_STREAM_END);
  1506. extract_size = extract_size - strm.avail_out;
  1507. (void)inflateEnd(&strm);
  1508. if (ret != Z_STREAM_END){
  1509. std::cout << "Warning: ret != Z_STREAM_END in file " << file.GetFileName() << std::endl;
  1510. return NULL;
  1511. }
  1512. File* out_file = new File(extract_buffer, 0, extract_size);
  1513. return out_file;
  1514. }
  1515. void BattleDataInstaller::ExportMesh(const std::string outdir, const Ogre::MeshPtr &mesh){
  1516. VGears::String base_mesh_name;
  1517. VGears::StringUtil::splitFull(mesh->getName(), base_mesh_name);
  1518. MakeMaterialsUnique(mesh, outdir + base_mesh_name);
  1519. Ogre::MeshSerializer mesh_serializer;
  1520. Ogre::SkeletonPtr skeleton(mesh->getSkeleton());
  1521. Ogre::SkeletonSerializer skeleton_serializer;
  1522. skeleton_serializer.exportSkeleton(
  1523. skeleton.get(), data_dir_ + "models/battle/" + outdir + base_mesh_name + ".skeleton"
  1524. );
  1525. mesh->setSkeletonName(outdir + base_mesh_name + ".skeleton");
  1526. mesh_serializer.exportMesh(mesh.get(), data_dir_ + "models/battle/" + outdir + mesh->getName());
  1527. Ogre::MaterialSerializer mat_ser;
  1528. std::set<std::string> textures;
  1529. Ogre::Mesh::SubMeshList sub_meshes = mesh->getSubMeshes();
  1530. for (Ogre::SubMesh* sub_mesh : sub_meshes){
  1531. Ogre::MaterialPtr mat(Ogre::MaterialManager::getSingleton().getByName(sub_mesh->getMaterialName()));
  1532. if (mat == nullptr) continue;
  1533. for (size_t techs = 0; techs < mat->getNumTechniques(); techs ++){
  1534. Ogre::Technique* tech = mat->getTechnique(techs);
  1535. if (tech == nullptr) continue;
  1536. for (size_t pass_num = 0; pass_num < tech->getNumPasses(); pass_num ++){
  1537. Ogre::Pass* pass = tech->getPass(pass_num);
  1538. if (pass == nullptr) continue;
  1539. for (
  1540. size_t texture_unit_num = 0; texture_unit_num < pass->getNumTextureUnitStates(); texture_unit_num ++
  1541. ){
  1542. Ogre::TextureUnitState* unit = pass->getTextureUnitState(texture_unit_num);
  1543. if (unit && unit->getTextureName().empty() == false){
  1544. // Ensure the output material script references png files, no tex files.
  1545. Ogre::String base_name;
  1546. VGears::StringUtil::splitBase(unit->getTextureName(), base_name);
  1547. unit->setTextureName(outdir + base_name + ".png");
  1548. textures.insert(unit->getTextureName());
  1549. }
  1550. }
  1551. }
  1552. }
  1553. if (std::count(battle_materials_.begin(), battle_materials_.end(), sub_mesh->getMaterialName()) == 0){
  1554. mat_ser.queueForExport(mat);
  1555. battle_materials_.push_back(sub_mesh->getMaterialName());
  1556. }
  1557. }
  1558. mat_ser.exportQueued(data_dir_ + "models/battle/" + outdir + base_mesh_name + VGears::EXT_MATERIAL);
  1559. }
  1560. void BattleDataInstaller::GenerateRsdFiles(BattleModel model, std::string path){
  1561. std::sort(model.tex.begin(), model.tex.end());
  1562. // For each p file, generate a rsd file.
  1563. for (std::string p : model.p){
  1564. std::string base_name = p.substr(0, 4);
  1565. std::string content = "@RSD940102\n";
  1566. content += "PLY=" + base_name + ".PLY\n";
  1567. content += "MAT=" + base_name + ".MAT\n";
  1568. content += "GRP=" + base_name + ".GRP\n";
  1569. content += "NTEX=" + std::to_string(model.tex.size()) + "\n";
  1570. for (int t = 0; t < model.tex.size(); t ++) content += "TEX[" + std::to_string(t) + "]=" + model.tex[t] + "\n";
  1571. content += "\n";
  1572. std::ofstream out(path + base_name + ".rsd");
  1573. out << content;
  1574. out.close();
  1575. }
  1576. }
  1577. void BattleDataInstaller::GenerateRsdFiles(SpellModel model, std::string path){
  1578. //std::sort(model.tex.begin(), model.tex.end());
  1579. // For each p file, generate a rsd file.
  1580. for (std::string p : model.p){
  1581. std::string base_name = p.substr(0, p.length() - 2);
  1582. std::string content = "@RSD940102\n";
  1583. content += "PLY=" + base_name + ".PLY\n";
  1584. content += "MAT=" + base_name + ".MAT\n";
  1585. content += "GRP=" + base_name + ".GRP\n";
  1586. content += "NTEX=0\n";
  1587. //for (int t = 0; t < model.tex.size(); t ++)
  1588. // content += "TEX[" + std::to_string(t) + "]=" + model.tex[t] + "\n";
  1589. content += "\n";
  1590. std::ofstream out(path + base_name + ".rsd");
  1591. out << content;
  1592. out.close();
  1593. }
  1594. }
  1595. void BattleDataInstaller::WriteModelCamera(
  1596. File script, File skeleton, const std::string& model_name
  1597. ){
  1598. // The scripts of a model start with a header of 0x68 bytes, that ff7.exe copies to the data the
  1599. // cameras use (0x42b6a0): 16 points of the model at 0x12, the factors of the size at 0x44, two
  1600. // views of the model (a camera position and a point to look at) at 0x4C and the height of the point
  1601. // the camera looks at, at 0x64.
  1602. if (script.GetFileSize() < 0x68 || skeleton.GetFileSize() < 16) return;
  1603. skeleton.SetOffset(12);
  1604. const unsigned int bones = skeleton.readU32LE();
  1605. if (bones == 0 || skeleton.GetFileSize() < 16 + bones * 12) return;
  1606. std::ofstream file(data_dir_ + "scripts/battle_models/" + model_name + "_camera.lua");
  1607. if (!file) return;
  1608. file << "-- Data of the model for the cameras of the battles. A point is the end of the bone with the\n"
  1609. << "-- number of the point minus one (0 is the root).\n"
  1610. << "BattleModelCameras = BattleModelCameras or {}\n"
  1611. << "BattleModelCameras[\"" << model_name << "\"] = {\n points = {";
  1612. script.SetOffset(0x12);
  1613. for (int i = 0; i < 16; i ++) file << static_cast<int>(script.readU8()) << ", ";
  1614. file << "},\n size = {";
  1615. script.SetOffset(0x44);
  1616. for (int i = 0; i < 3; i ++) file << static_cast<int>(static_cast<int16_t>(script.readU16LE())) << ", ";
  1617. // The two views, one after the other.
  1618. script.SetOffset(0x4C);
  1619. file << "},\n views = {";
  1620. for (int v = 0; v < 2; v ++){
  1621. for (int p = 0; p < 2; p ++){
  1622. file << (p == 0 ? "{pos = {" : "look = {");
  1623. for (int i = 0; i < 3; i ++) file << static_cast<int>(static_cast<int16_t>(script.readU16LE())) << ", ";
  1624. file << (p == 0 ? "}, " : "}}, ");
  1625. }
  1626. }
  1627. script.SetOffset(0x64);
  1628. file << "},\n look_height = " << static_cast<int>(static_cast<int16_t>(script.readU16LE()))
  1629. << ",\n lengths = {";
  1630. // The bones are the last data of the skeleton: parent, length (negative) and polygons.
  1631. skeleton.SetOffset(skeleton.GetFileSize() - bones * 12);
  1632. for (unsigned int b = 0; b < bones; b ++){
  1633. skeleton.readU32LE();
  1634. const u32 raw = skeleton.readU32LE();
  1635. float length = 0.0f;
  1636. std::memcpy(&length, &raw, sizeof(length));
  1637. skeleton.readU32LE();
  1638. file << "[" << b << "] = " << -length << ", ";
  1639. }
  1640. file << "},\n}\n";
  1641. }
  1642. void BattleDataInstaller::DecompileBattleModelHrc(
  1643. File compiled, BattleModel model, std::string path, std::string skeleton_name
  1644. ){
  1645. compiled.SetOffset(0);
  1646. compiled.readU32LE();
  1647. compiled.readU32LE();
  1648. compiled.readU32LE();
  1649. std::sort(model.p.begin(), model.p.end());
  1650. std::string decompiled(":HEADER_BLOCK 2\n:SKELETON " + skeleton_name + "\n");
  1651. int bones = compiled.readU32LE();
  1652. compiled.SetOffset(compiled.GetFileSize() - (bones * 12));
  1653. decompiled += ":BONES " + std::to_string(bones) + "\n\n";
  1654. int p_file_index = 0;
  1655. for (int b = 0; b < bones; b ++){
  1656. decompiled += "bone" + std::to_string(b) + "\n";
  1657. int parent = compiled.readU32LE();
  1658. if (parent == 0xFFFFFFFF) decompiled += "root\n";
  1659. else decompiled += "bone" + std::to_string(parent) + "\n";
  1660. union {
  1661. float f;
  1662. unsigned long ul;
  1663. unsigned char b[4];
  1664. } u;
  1665. u.b[0] = compiled.readU8();
  1666. u.b[1] = compiled.readU8();
  1667. u.b[2] = compiled.readU8();
  1668. u.b[3] = compiled.readU8();
  1669. decompiled += std::to_string(u.f * -1) + "\n";
  1670. int offset = compiled.readU32LE();
  1671. if (offset == 0) decompiled += "0\n\n";
  1672. else {
  1673. decompiled += std::to_string(offset) + " ";
  1674. if (p_file_index < model.p.size()) decompiled += model.p[p_file_index].substr(0, 4);
  1675. p_file_index ++;
  1676. decompiled += "\n\n";
  1677. }
  1678. }
  1679. std::ofstream out(path);
  1680. out << decompiled;
  1681. out.close();
  1682. }
  1683. void BattleDataInstaller::DecompileSpellModelHrc(
  1684. File compiled, SpellModel model, std::string path, std::string skeleton_name
  1685. ){
  1686. compiled.SetOffset(0);
  1687. compiled.readU32LE();
  1688. compiled.readU32LE();
  1689. compiled.readU32LE();
  1690. std::sort(model.p.begin(), model.p.end());
  1691. std::string decompiled(":HEADER_BLOCK 2\n:SKELETON " + skeleton_name + "\n");
  1692. int bones = compiled.readU32LE();
  1693. compiled.SetOffset(compiled.GetFileSize() - (bones * 12));
  1694. decompiled += ":BONES " + std::to_string(bones) + "\n\n";
  1695. int p_index = 0;
  1696. for (int b = 0; b < bones; b ++){
  1697. decompiled += "bone" + std::to_string(b) + "\n";
  1698. int parent = compiled.readU32LE();
  1699. if (parent == 0xFFFFFFFF) decompiled += "root\n";
  1700. else decompiled += "bone" + std::to_string(parent) + "\n";
  1701. union {
  1702. float f;
  1703. unsigned long ul;
  1704. unsigned char b[4];
  1705. } u;
  1706. u.b[0] = compiled.readU8();
  1707. u.b[1] = compiled.readU8();
  1708. u.b[2] = compiled.readU8();
  1709. u.b[3] = compiled.readU8();
  1710. decompiled += std::to_string(u.f * -1) + "\n";
  1711. int offset = compiled.readU32LE();
  1712. if (offset == 0) decompiled += "0\n\n";
  1713. else {
  1714. decompiled += std::to_string(offset) + " ";
  1715. if (p_index < model.p.size()) decompiled += model.p[p_index].substr(0, model.p[p_index].length() - 2);
  1716. p_index ++;
  1717. decompiled += "\n\n";
  1718. }
  1719. }
  1720. std::ofstream out(path);
  1721. out << decompiled;
  1722. out.close();
  1723. }
  1724. void BattleDataInstaller::DecompileSceneModelHrc(
  1725. File compiled, BattleModel model, std::string path, std::string skeleton_name
  1726. ){
  1727. compiled.SetOffset(0);
  1728. compiled.readU32LE(); // Skip 4 bytes
  1729. compiled.readU32LE(); // Skip 4 bytes
  1730. compiled.readU32LE(); // Skip 4 bytes
  1731. compiled.readU32LE(); // Supposed to be the number of bones, but for scenes is always 0.
  1732. std::sort(model.p.begin(), model.p.end());
  1733. std::string decompiled(":HEADER_BLOCK 2\n:SKELETON " + skeleton_name + "\n");
  1734. int bones = model.p.size();
  1735. decompiled += ":BONES " + std::to_string(bones) + "\n\n";
  1736. int p_file_index = 0;
  1737. for (int b = 0; b < bones; b ++){
  1738. decompiled += "bone" + std::to_string(b) + "\n";
  1739. if (b == 0) decompiled += "root\n";
  1740. else decompiled += ("bone" + std::to_string(b - 1) + "\n");
  1741. // The pieces share the coordinates of the scene. A length would move each one along the depth, away
  1742. // from the previous one.
  1743. decompiled += "0.000000\n";
  1744. decompiled += "1 " + model.p[b].substr(0, 4) + "\n\n";
  1745. }
  1746. std::ofstream out(path);
  1747. out << decompiled;
  1748. out.close();
  1749. }