BattleDataInstaller.cpp 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787
  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_].get();
  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. bool found = false;
  404. for (int m = 0; m < spell_models_.size(); m ++){
  405. if (spell_models_[m].id == id){
  406. spell_models_[m].p.push_back(p_name);
  407. found = true;
  408. break;
  409. }
  410. }
  411. if (found == false){
  412. SpellModel model;
  413. model.id = id;
  414. model.p.push_back(p_name);
  415. spell_models_.push_back(model);
  416. }
  417. }
  418. if (ext == "tex"){
  419. // Texture files. They can be shared among various spells, so just convert them and don't
  420. // add them to a particular model.
  421. magic_lgp_files_[next_model_to_process_].WriteFile(output_dir_ + "temp/spell_models/" + fname);
  422. TexFile tex(output_dir_ + "temp/spell_models/" + fname);
  423. std::string path = data_dir_ + "models/battle/attacks/" + id + ".png";
  424. // Many of these tex files are wrong and dummied out in the OG, so try/catch.
  425. try{
  426. tex.SavePng(path);
  427. }
  428. catch(const std::exception& e){
  429. std::cerr << "[WARNING] Error converting texture " << (output_dir_ + "temp/spell_models/" + fname)
  430. << " to png: " << e.what() << std::endl;
  431. }
  432. }
  433. if (ext == "a00"){
  434. // Animation file.
  435. magic_lgp_files_[next_model_to_process_].WriteFile(output_dir_ + "temp/spell_models/" + fname);
  436. bool found = false;
  437. for (int m = 0; m < spell_models_.size(); m ++){
  438. if (spell_models_[m].id == id){
  439. spell_models_[m].anim = fname;
  440. found = true;
  441. break;
  442. }
  443. }
  444. if (found == false){
  445. SpellModel model;
  446. model.id = id;
  447. model.anim = fname;
  448. spell_models_.push_back(model);
  449. }
  450. }
  451. // TODO: b files? a files? s files?
  452. next_model_to_process_ ++;
  453. return next_model_to_process_;
  454. }
  455. namespace{
  456. /**
  457. * Files of magic.lgp (without extension) with the animations of the limit breaks of each model of the party.
  458. * The animation files have the format of the animations of the models, with 8 animations for the skeleton of
  459. * the character (the animations 44 to 51 of the model, which are empty in battle.lgp) and 8 for its weapon.
  460. * The files are in the order of the techniques of the character (limit level 1 first and second, level 2, ...):
  461. * the table that ff7.exe uses to load them (at 0x7b7b58) has them in groups of 7 by character.
  462. */
  463. const std::map<std::string, std::vector<std::string>>& LimitAnimationFiles(){
  464. static const std::vector<std::string> cloud = {"blaver", "kyou", "limcl2", "limcl6", "limcl3", "limcl7", "limcl4"};
  465. static const std::vector<std::string> barret = {"hvshot", "limbr5", "limbr2", "limbr6", "limbr3", "limbr7", "limbr4"};
  466. static const std::map<std::string, std::vector<std::string>> files = {
  467. {"rt", cloud}, {"si", cloud},
  468. {"ru", {"limfast"}}, // Tifa.
  469. {"rv", {"iyash", "limea5", "limea2", "limea6", "limea3", "kodo", "limea4"}}, // Aerith.
  470. {"rw", {"limsled", "limrd5", "limsled", "limrd6", "limrd3", "limrd7", "limrd4"}}, // Red XIII.
  471. {"rx", {"limyf1", "limyf5", "limyf2", "limyf6", "limyf3", "limyf7", "limyf4"}}, // Yuffie.
  472. {"ry", {"dice"}}, // Cait Sith.
  473. {"rz", {"limcd1", "limcd5", "limcd2", "limcd6", "limcd3", "limcd7", "limcd4"}}, // Cid.
  474. {"sb", barret}, {"sc", barret}, {"sd", barret}, {"se", barret},
  475. };
  476. return files;
  477. }
  478. }
  479. unsigned int BattleDataInstaller::ConvertBattleModelsInit(){
  480. next_model_to_convert_ = 0;
  481. // The animations of the limit breaks are in magic.lgp. Take the ones of the party to the folder of the battle
  482. // models, so they are converted with them.
  483. try{
  484. std::set<std::string> wanted;
  485. for (const auto& entry : LimitAnimationFiles()){
  486. for (const std::string& tag : entry.second) wanted.insert(tag + ".a00");
  487. }
  488. File magic_lgp_file(*disk_image_.filePath("data/battle/magic.lgp"));
  489. VGears::LGPArchive magic_lgp(*disk_image_.filePath("data/battle/magic.lgp"), "LGP");
  490. magic_lgp.open(*disk_image_.filePath("data/battle/magic.lgp"), true);
  491. magic_lgp.load();
  492. VGears::LGPArchive::FileList file_list = magic_lgp.GetFiles();
  493. for (int i = 0; i < file_list.size(); i ++){
  494. VGears::LGPArchive::FileEntry f = file_list.at(i);
  495. std::string name = f.file_name;
  496. std::transform(name.begin(), name.end(), name.begin(), ::tolower);
  497. if (wanted.count(name) == 0) continue;
  498. if (f.data_offset + f.data_size > magic_lgp_file.GetFileSize()) continue;
  499. File limit_file(&magic_lgp_file, f.data_offset, f.data_size);
  500. limit_file.WriteFile(output_dir_ + "temp/battle_models/limit_" + name);
  501. }
  502. }
  503. catch (const std::exception& ex){
  504. std::cerr << "[ERROR] Exception reading the limit animations: " << ex.what() << std::endl;
  505. }
  506. return battle_models_.size();
  507. }
  508. unsigned int BattleDataInstaller::ConvertSpellModelsInit(){
  509. next_model_to_convert_ = 0;
  510. return spell_models_.size();
  511. }
  512. unsigned int BattleDataInstaller::ConvertBattleModel(){
  513. if (next_model_to_convert_ >= battle_models_.size()) return battle_models_.size();
  514. BattleModel model = battle_models_[next_model_to_convert_];
  515. try{
  516. std::string path = "";
  517. FF7Data::BattleModelInfo info = FF7Data::GetBattleModelInfo(model.id);
  518. if (info.is_player) path += "characters/";
  519. else if (info.is_scene) path += "scenes/";
  520. else path += "enemies/";
  521. if (info.is_scene){
  522. DecompileSceneModelHrc(
  523. File(output_dir_ + "temp/battle_models/" + model.hrc + "bin"), model,
  524. output_dir_ + "temp/battle_models/" + model.id + "_" + info.name_normal + ".hrc",
  525. model.id + "_" + info.name_normal
  526. );
  527. }
  528. else{
  529. DecompileBattleModelHrc(
  530. File(output_dir_ + "temp/battle_models/" + model.hrc + "bin"), model,
  531. output_dir_ + "temp/battle_models/" + model.id + "_" + info.name_normal + ".hrc",
  532. model.id + "_" + info.name_normal
  533. );
  534. }
  535. GenerateRsdFiles(model, output_dir_ + "temp/battle_models/");
  536. if ("" != model.anim){ // Skip for non-animated, ie battle backgrounds
  537. DaFile da(File(output_dir_ + "temp/battle_models/" + model.anim));
  538. std::vector<std::string> a_files = da.GenerateAFiles(model.id, output_dir_ + "temp/battle_models/");
  539. for (std::string file_name : a_files) model.a.push_back(file_name);
  540. }
  541. // Limit breaks of the party: their animations are in files of magic.lgp. Each one is added to the model with
  542. // the names <model>_<file>_00 to _07, which replace the empty animations 44 to 51 for that limit.
  543. if (info.is_player){
  544. auto limits = LimitAnimationFiles().find(model.id);
  545. if (limits != LimitAnimationFiles().end()){
  546. std::set<std::string> converted;
  547. for (const std::string& tag : limits->second){
  548. if (!converted.insert(tag).second) continue;
  549. std::string limit_path = output_dir_ + "temp/battle_models/limit_" + tag + ".a00";
  550. if (!std::ifstream(limit_path).good()) continue;
  551. try{
  552. File limit_file(limit_path);
  553. DaFile limit_da(limit_file);
  554. std::vector<std::string> limit_files = limit_da.GenerateAFiles(
  555. model.id + "_" + tag, output_dir_ + "temp/battle_models/"
  556. );
  557. for (const std::string& file_name : limit_files){
  558. // Only the animations of the skeleton (0 to 7), not the ones of the weapon.
  559. size_t dot = file_name.find_last_of('.');
  560. int number = std::atoi(file_name.substr(dot - 2, 2).c_str());
  561. if (number < 8) model.a.push_back(file_name);
  562. }
  563. }
  564. catch (const std::exception& ex){
  565. std::cerr << "[ERROR] Exception reading the limit animation " << tag << ": " << ex.what() << std::endl;
  566. }
  567. }
  568. }
  569. }
  570. if ("" != model.script){ // Skip non scripted models
  571. // Only the models of the party have the 74 scripts (the limits are the ones from 60 up). The other
  572. // ones (enemies and the rest of the models with scripts) have 32.
  573. AbFile ab(File(output_dir_ + "temp/battle_models/" + model.script), !info.is_player);
  574. ab.GenerateScripts(model.id + "_" + info.name_normal, data_dir_ + "scripts/battle_models/");
  575. if (!info.is_scene && "" != model.hrc){
  576. WriteModelCamera(
  577. File(output_dir_ + "temp/battle_models/" + model.script),
  578. File(output_dir_ + "temp/battle_models/" + model.hrc + "bin"),
  579. model.id + "_" + info.name_normal
  580. );
  581. }
  582. }
  583. // Playable characters hold their weapons in battle (but Red XIII, who has none). Each one is a
  584. // polygon file by itself, named <id>c<k..z>, so make a model for each with a single bone.
  585. std::vector<std::pair<std::string, std::string>> weapons; // Polygon file, mesh name.
  586. if (info.is_player && model.id != "rw"){
  587. for (std::string p : model.p){
  588. if (p.length() < 4 || p[2] != 'c' || p[3] < 'k' || p[3] > 'z') continue;
  589. char number[8];
  590. std::snprintf(number, sizeof(number), "%02d", p[3] - 'k');
  591. const std::string weapon_name = model.id + "_" + info.name_normal + "_weapon_" + number;
  592. std::ofstream hrc(output_dir_ + "temp/battle_models/" + weapon_name + ".hrc");
  593. hrc << ":HEADER_BLOCK 2\n:SKELETON " << weapon_name << "\n:BONES 1\n\nbone0\nroot\n0.000000\n1 "
  594. << p.substr(0, 4) << "\n\n";
  595. hrc.close();
  596. weapons.push_back(std::make_pair(p, weapon_name));
  597. }
  598. }
  599. // Reload the resources for the newly created hrc and rsd.
  600. // TODO: Could this be done with res_mgr_->declareResource() ? Probably faster
  601. res_mgr_->removeResourceLocation(output_dir_ + "temp/battle_models/", "FFVII");
  602. res_mgr_->addResourceLocation(output_dir_ + "temp/battle_models/", "FileSystem", "FFVII", true, true);
  603. Ogre::ResourcePtr hrc = VGears::HRCFileManager::GetSingleton().load(
  604. model.id + "_" + info.name_normal + ".hrc", "FFVII"
  605. );
  606. Ogre::String base_name;
  607. VGears::StringUtil::splitBase(model.hrc, base_name);
  608. auto mesh_name = model.id + "_" + info.name_normal + ".mesh";
  609. Ogre::MeshPtr mesh(Ogre::MeshManager::getSingleton().load(mesh_name, "FFVII"));
  610. Ogre::SkeletonPtr skeleton(mesh->getSkeleton());
  611. for (std::string anim : model.a){
  612. VGears::AFileManager &afl_mgr(VGears::AFileManager::GetSingleton());
  613. Ogre::String a_base_name;
  614. VGears::StringUtil::splitBase(anim, a_base_name);
  615. VGears::AFilePtr a = afl_mgr.load(a_base_name + ".a", "FFVII").staticCast<VGears::AFile>();
  616. // Convert the FF7 name to a more readable name set in the meta data.
  617. VGears::StringUtil::splitBase(anim, base_name);
  618. a->AddTo(skeleton, VGears::NameLookup::Animation(base_name));
  619. }
  620. ExportMesh(path, mesh);
  621. for (const auto& weapon : weapons){
  622. try{
  623. VGears::HRCFileManager::GetSingleton().load(weapon.second + ".hrc", "FFVII");
  624. Ogre::MeshPtr weapon_mesh(Ogre::MeshManager::getSingleton().load(weapon.second + ".mesh", "FFVII"));
  625. ExportMesh(path, weapon_mesh);
  626. }
  627. catch (const Ogre::Exception& ex){
  628. std::cerr << "[ERROR] Ogre exception converting weapon " << weapon.second << ": " << ex.what() << std::endl;
  629. }
  630. }
  631. }
  632. catch (const Ogre::Exception& ex){
  633. std::cerr << "[ERROR] Ogre exception converting battle model " << model.hrc <<": " << ex.what() << std::endl;
  634. }
  635. catch (const std::exception& ex){
  636. std::cerr << "[ERROR] Exception converting battle model " << model.hrc << ": " << ex.what() << std::endl;
  637. }
  638. next_model_to_convert_ ++;
  639. return next_model_to_convert_;
  640. }
  641. unsigned int BattleDataInstaller::ConvertSpellModel(){
  642. if (next_model_to_convert_ >= spell_models_.size()) return spell_models_.size();
  643. SpellModel model = spell_models_[next_model_to_convert_];
  644. try{
  645. std::string path = "attacks/";
  646. FF7Data::SpellModelInfo info = FF7Data::GetSpellModelInfo(model.id);
  647. // Decompile the .hrc file (if any)
  648. if (model.hrc != ""){
  649. DecompileSpellModelHrc(
  650. File(output_dir_ + "temp/spell_models/" + model.hrc), model,
  651. output_dir_ + "temp/spell_models/" + info.name_normal + ".hrc", model.id
  652. );
  653. model.hrc = info.name_normal + ".hrc";
  654. }
  655. GenerateRsdFiles(model, output_dir_ + "temp/spell_models/");
  656. // Decompile the .a00 file (if any) into a .a file.
  657. if ("" != model.anim){ // Skip for non-animated.
  658. DaFile da(File(output_dir_ + "temp/spell_models/" + model.anim));
  659. std::vector<std::string> a_files = da.GenerateAFiles(model.id, output_dir_ + "temp/spell_models/");
  660. for (std::string file_name : a_files) model.a.push_back(file_name);
  661. }
  662. // Reload the resources for the newly created hrc and rsd.
  663. // TODO: Could this be done with res_mgr_->declareResource() ? Probably faster
  664. res_mgr_->removeResourceLocation(output_dir_ + "temp/spell_models/", "FFVII");
  665. res_mgr_->addResourceLocation(output_dir_ + "temp/spell_models/", "FileSystem", "FFVII", true, true);
  666. // Export meshes thet have an .hrc skeleton.
  667. if (model.hrc != ""){
  668. Ogre::ResourcePtr hrc = VGears::HRCFileManager::GetSingleton().load(model.id + ".hrc", "FFVII");
  669. Ogre::String base_name;
  670. VGears::StringUtil::splitBase(model.hrc, base_name);
  671. auto mesh_name = model.id + ".mesh";
  672. Ogre::MeshPtr mesh(Ogre::MeshManager::getSingleton().load(mesh_name, "FFVII"));
  673. Ogre::SkeletonPtr skeleton(mesh->getSkeleton());
  674. for (std::string anim : model.a){
  675. VGears::AFileManager &afl_mgr(VGears::AFileManager::GetSingleton());
  676. Ogre::String a_base_name;
  677. VGears::StringUtil::splitBase(anim, a_base_name);
  678. VGears::AFilePtr a = afl_mgr.load(a_base_name + ".a", "FFVII").staticCast<VGears::AFile>();
  679. // Convert the FF7 name to a more readable name set in the meta data.
  680. VGears::StringUtil::splitBase(anim, base_name);
  681. a->AddTo(skeleton, VGears::NameLookup::Animation(base_name));
  682. }
  683. ExportMesh(path, mesh);
  684. }
  685. }
  686. catch (const Ogre::Exception& ex){
  687. std::cerr << "[ERROR] Ogre exception converting spell model " << model.hrc <<": " << ex.what() << std::endl;
  688. }
  689. catch (const std::exception& ex){
  690. std::cerr << "[ERROR] Exception converting spell model " << model.hrc << ": " << ex.what() << std::endl;
  691. }
  692. next_model_to_convert_ ++;
  693. return next_model_to_convert_;
  694. }
  695. namespace{
  696. /**
  697. * Makes a name that is safe to use in files and Ogre resources: lower case letters, numbers and
  698. * underscores.
  699. */
  700. std::string EffectSafeName(std::string name){
  701. for (char& c : name){
  702. c = std::tolower(static_cast<unsigned char>(c));
  703. if (!std::isalnum(static_cast<unsigned char>(c)) && c != '_') c = '_';
  704. }
  705. return name;
  706. }
  707. /**
  708. * Gets the name without the extension, in lower case.
  709. */
  710. std::string EffectStem(const std::string& file_name){
  711. std::string stem = file_name.substr(0, file_name.find_last_of('.'));
  712. std::transform(stem.begin(), stem.end(), stem.begin(), [](unsigned char c){return std::tolower(c);});
  713. return stem;
  714. }
  715. /**
  716. * Gets the name of a texture in a rsd file, without the extension, in lower case.
  717. */
  718. std::string EffectRsdValue(const std::string& line){
  719. size_t equal = line.find('=');
  720. if (equal == std::string::npos) return "";
  721. std::string value = line.substr(equal + 1);
  722. while (!value.empty() && std::isspace(static_cast<unsigned char>(value.back()))) value.pop_back();
  723. while (!value.empty() && std::isspace(static_cast<unsigned char>(value.front()))) value.erase(0, 1);
  724. return EffectStem(value);
  725. }
  726. }
  727. unsigned int BattleDataInstaller::InitializeEffectModels(){
  728. effect_models_.clear();
  729. next_effect_to_convert_ = 0;
  730. const std::string dir = output_dir_ + "temp/effects/";
  731. // Index the files by folder and name.
  732. std::map<std::pair<std::string, std::string>, size_t> index;
  733. for (size_t f = 0; f < magic_lgp_files_.size(); f ++){
  734. std::string name = magic_lgp_file_names_[f];
  735. std::transform(name.begin(), name.end(), name.begin(), [](unsigned char c){return std::tolower(c);});
  736. index[{magic_lgp_file_folders_[f], name}] = f;
  737. }
  738. // Folder key: the effect folder, "common" for the root.
  739. auto key_of = [](const std::string& folder){
  740. if (folder.empty()) return std::string("common");
  741. std::string key = folder;
  742. const std::string prefix = "ff7/data/battle/";
  743. if (key.compare(0, prefix.size(), prefix) == 0) key = key.substr(prefix.size());
  744. return EffectSafeName(key);
  745. };
  746. // Finds a file in the folder of the model, or in the archive root.
  747. auto find = [&](const std::string& folder, const std::string& name, std::string& found_folder){
  748. auto it = index.find({folder, name});
  749. if (it != index.end()){found_folder = folder; return it->second;}
  750. it = index.find({"", name});
  751. if (it != index.end()){found_folder = ""; return it->second;}
  752. return static_cast<size_t>(-1);
  753. };
  754. // The folders that have each file, for the textures of the models of the root.
  755. std::map<std::string, std::vector<std::string>> texture_folders;
  756. for (const auto& entry : index) if (!entry.first.first.empty()) texture_folders[entry.first.second].push_back(entry.first.first);
  757. std::set<std::string> written;
  758. auto write = [&](size_t f, const std::string& name){
  759. if (written.insert(name).second) magic_lgp_files_[f].WriteFile(dir + name);
  760. };
  761. for (size_t f = 0; f < magic_lgp_files_.size(); f ++){
  762. std::string rsd_name = magic_lgp_file_names_[f];
  763. if (rsd_name.size() < 4 || EffectSafeName(rsd_name.substr(rsd_name.size() - 4)) != "_rsd") continue;
  764. const std::string& folder = magic_lgp_file_folders_[f];
  765. // Parse the rsd.
  766. File& rsd_file = magic_lgp_files_[f];
  767. rsd_file.SetOffset(0);
  768. std::string content;
  769. for (size_t b = 0; b < rsd_file.GetFileSize(); b ++) content += static_cast<char>(rsd_file.readU8());
  770. std::string ply;
  771. std::vector<std::string> tex;
  772. std::istringstream lines(content);
  773. std::string line;
  774. while (std::getline(lines, line)){
  775. std::string upper = line;
  776. std::transform(upper.begin(), upper.end(), upper.begin(), [](unsigned char c){return std::toupper(c);});
  777. if (upper.compare(0, 4, "PLY=") == 0) ply = EffectRsdValue(line);
  778. else if (upper.compare(0, 4, "TEX[") == 0) tex.push_back(EffectRsdValue(line));
  779. }
  780. if (ply.empty()) continue;
  781. std::string p_folder;
  782. size_t p_index = find(folder, ply + ".p", p_folder);
  783. if (p_index == static_cast<size_t>(-1)) continue;
  784. const std::string p_name = key_of(p_folder) + "_" + EffectSafeName(ply) + ".p";
  785. write(p_index, p_name);
  786. const std::string stem = EffectSafeName(EffectStem(rsd_name));
  787. // Tells if a texture is in a folder, or in the archive root.
  788. const auto has_texture = [&](const std::string& texture_folder, const std::string& t){
  789. std::string found;
  790. return find(texture_folder, t + ".tex", found) != static_cast<size_t>(-1);
  791. };
  792. // Writes a model with the textures of a folder. The textures keep their place in the list, so the
  793. // polygons get the texture they use even if one is missing.
  794. const auto add_model = [&](const std::string& name, const std::string& texture_folder){
  795. EffectModel model;
  796. model.name = name;
  797. std::string rsd = "@RSD940102\nPLY=" + p_name.substr(0, p_name.size() - 2) + ".PLY\n";
  798. rsd += "MAT=" + model.name + ".MAT\nGRP=" + model.name + ".GRP\n";
  799. std::vector<std::string> tex_names;
  800. for (const std::string& t : tex){
  801. std::string t_folder;
  802. const size_t t_index = find(texture_folder, t + ".tex", t_folder);
  803. if (t_index == static_cast<size_t>(-1)){
  804. std::cerr << "[WARNING] The texture " << t << " of the effect model " << model.name
  805. << " is not in magic.lgp." << std::endl;
  806. tex_names.push_back(key_of(texture_folder) + "_" + EffectSafeName(t) + ".tex");
  807. continue;
  808. }
  809. const std::string t_name = key_of(t_folder) + "_" + EffectSafeName(t) + ".tex";
  810. write(t_index, t_name);
  811. tex_names.push_back(t_name);
  812. }
  813. rsd += "NTEX=" + std::to_string(tex_names.size()) + "\n";
  814. for (size_t t = 0; t < tex_names.size(); t ++){
  815. rsd += "TEX[" + std::to_string(t) + "]=" + tex_names[t].substr(0, tex_names[t].size() - 4) + ".TIM\n";
  816. }
  817. model.textures = tex_names;
  818. std::ofstream(dir + model.name + ".rsd") << rsd;
  819. // A model with a single bone, with the mesh.
  820. std::ofstream(dir + model.name + ".hrc")
  821. << ":HEADER_BLOCK 2\n:SKELETON " << model.name << "\n:BONES 1\n\nbone0\nroot\n0.000000\n1 "
  822. << model.name << "\n\n";
  823. effect_models_.push_back(model);
  824. };
  825. bool complete = true;
  826. for (const std::string& t : tex) complete = complete && has_texture(folder, t);
  827. // The models of the archive root are shared by several effects, and each effect has its own version of
  828. // their textures in its folder (exp_1.tex is in five, all different). There is a model for each folder
  829. // that has all of them, named after the folder like the models of the folders.
  830. std::vector<std::string> variants;
  831. if (!complete && folder.empty()){
  832. std::set<std::string> candidates;
  833. for (const std::string& t : tex){
  834. const auto found = texture_folders.find(t + ".tex");
  835. if (found != texture_folders.end()) candidates.insert(found->second.begin(), found->second.end());
  836. }
  837. for (const std::string& candidate : candidates){
  838. bool all = true;
  839. for (const std::string& t : tex) all = all && has_texture(candidate, t);
  840. if (all) variants.push_back(candidate);
  841. }
  842. }
  843. if (variants.empty()) add_model(key_of(folder) + "_" + stem, folder);
  844. else for (const std::string& variant : variants) add_model(key_of(variant) + "_" + stem, variant);
  845. }
  846. res_mgr_->removeResourceLocation(dir, "FFVII");
  847. res_mgr_->addResourceLocation(dir, "FileSystem", "FFVII", true, true);
  848. return effect_models_.size();
  849. }
  850. unsigned int BattleDataInstaller::ConvertEffectModel(){
  851. if (next_effect_to_convert_ >= effect_models_.size()) return effect_models_.size();
  852. EffectModel& model = effect_models_[next_effect_to_convert_];
  853. try{
  854. VGears::HRCFileManager::GetSingleton().load(model.name + ".hrc", "FFVII");
  855. Ogre::MeshPtr mesh(Ogre::MeshManager::getSingleton().load(model.name + ".mesh", "FFVII"));
  856. ExportMesh("effects/", mesh);
  857. for (const std::string& texture : model.textures){
  858. const std::string path = data_dir_ + "models/battle/effects/"
  859. + texture.substr(0, texture.size() - 4) + ".png";
  860. if (boost::filesystem::exists(path)) continue;
  861. // A texture that is not in magic.lgp is already reported.
  862. if (!boost::filesystem::exists(output_dir_ + "temp/effects/" + texture)) continue;
  863. try{
  864. TexFile tex(output_dir_ + "temp/effects/" + texture);
  865. tex.SavePng(path);
  866. }
  867. catch (const std::exception& ex){
  868. // Many of the original textures are dummies.
  869. std::cerr << "[WARNING] Error converting effect texture " << texture << ": " << ex.what() << std::endl;
  870. }
  871. }
  872. model.converted = true;
  873. }
  874. catch (const Ogre::Exception& ex){
  875. std::cerr << "[WARNING] Could not convert effect model " << model.name << ": " << ex.what() << std::endl;
  876. }
  877. catch (const std::exception& ex){
  878. std::cerr << "[WARNING] Could not convert effect model " << model.name << ": " << ex.what() << std::endl;
  879. }
  880. next_effect_to_convert_ ++;
  881. return next_effect_to_convert_;
  882. }
  883. void BattleDataInstaller::WriteEffectModels(){
  884. std::ofstream file(data_dir_ + "gamedata/effects.lua");
  885. file << "-- Meshes of the battle effects, extracted from magic.lgp. Names are the folder of the effect\n"
  886. << "-- and the original file, for example magic_faira_1. Meshes are in models/battle/effects.\n"
  887. << "Game.EffectModels = {\n";
  888. for (const EffectModel& model : effect_models_){
  889. if (model.converted) file << " \"" << model.name << "\",\n";
  890. }
  891. file << "}\n";
  892. WriteEffectSprites();
  893. WriteEffectCameras();
  894. WriteEffectMeshes();
  895. WriteBattleCameras();
  896. }
  897. void BattleDataInstaller::WriteBattleCameras(){
  898. // The scripts of the cameras of the battles (see BattleCameraScripts.h).
  899. std::map<int, BattleCameraScripts::Set> sets;
  900. for (int i = 0; i < 3; ++ i){
  901. const std::string name = "data/battle/camdat" + std::to_string(i) + ".bin";
  902. auto path = const_cast<DiskImage&>(disk_image_).filePath(name);
  903. BattleCameraScripts::Set set;
  904. if (path != nullptr && BattleCameraScripts::ReadFile(*path, set)) sets[i] = set;
  905. else std::cerr << "[WARNING] Can't read " << name << "." << std::endl;
  906. }
  907. std::ofstream file(data_dir_ + "gamedata/battle_cameras.lua");
  908. BattleCameraScripts::WriteLua(file, sets);
  909. // The ones of the start of the battles are in the executable.
  910. BattleCameraScripts::Set intro;
  911. auto exe_path = const_cast<DiskImage&>(disk_image_).filePath("ff7.exe");
  912. if (exe_path != nullptr && BattleCameraScripts::ReadIntro(*exe_path, intro)){
  913. BattleCameraScripts::WriteIntroLua(file, intro);
  914. }
  915. else std::cerr << "[WARNING] Can't read the cameras of the start of the battles from ff7.exe." << std::endl;
  916. }
  917. void BattleDataInstaller::WriteEffectMeshes(){
  918. // The meshes of the effects that are in the data of ff7.exe, like the ground of Ifrit and the
  919. // mountain of Ramuh (see ExeEffectMeshes.h). Names are the address of the block in the executable.
  920. std::map<uint32_t, ExeEffectMeshes::Mesh> meshes;
  921. auto exe_path = const_cast<DiskImage&>(disk_image_).filePath("ff7.exe");
  922. if (exe_path == nullptr || !ExeEffectMeshes::Extract(*exe_path, meshes)){
  923. std::cerr << "[WARNING] Can't read the meshes of the effects from ff7.exe." << std::endl;
  924. }
  925. std::ofstream file(data_dir_ + "gamedata/effect_meshes.lua");
  926. ExeEffectMeshes::WriteLua(file, meshes);
  927. }
  928. void BattleDataInstaller::WriteEffectCameras(){
  929. // The scripts of the cameras are in the data of ff7.exe, and are found from the code that
  930. // uses them. Names are the address of the script in memory.
  931. std::map<uint32_t, std::vector<int16_t>> scripts;
  932. auto exe_path = const_cast<DiskImage&>(disk_image_).filePath("ff7.exe");
  933. if (exe_path == nullptr || !ExeEffectCameras::Extract(*exe_path, scripts)){
  934. std::cerr << "[WARNING] Can't read the camera scripts of the effects from ff7.exe." << std::endl;
  935. }
  936. std::ofstream file(data_dir_ + "gamedata/effect_cameras.lua");
  937. file << "-- Camera scripts of the battle effects, read from ff7.exe. Game.EffectCameras[name] is a list\n"
  938. << "-- of 16 bit words, with the address of the script in the executable as the name (like\n"
  939. << "-- 0x8ae268). See scripts/battle/effect_camera.lua for the format.\n"
  940. << "Game.EffectCameras = Game.EffectCameras or {}\n";
  941. for (const auto& script : scripts){
  942. file << "Game.EffectCameras[\"0x" << std::hex << script.first << std::dec << "\"] = {";
  943. for (size_t i = 0; i < script.second.size(); ++ i){
  944. if (i % 16 == 0) file << "\n ";
  945. file << script.second[i] << ", ";
  946. }
  947. file << "\n}\n";
  948. }
  949. }
  950. void BattleDataInstaller::WriteEffectSprites(){
  951. // The sprite files (.s) are lists of frames, and every frame a list of quads of a sprite sheet (see
  952. // the layout below). They are written twice: all the quads one after the other (the first format,
  953. // used by the Cure effect) and the frames with their quads (effect_animations.lua).
  954. // Textures are converted too, with the name of the effect folder as a prefix (common_ for the
  955. // archive root), to images/battle_fx, so they can be used as images of sprites.
  956. const std::string key_prefix = "ff7/data/battle/";
  957. auto key_of = [&](std::string folder){
  958. if (folder.empty()) return std::string("common");
  959. if (folder.compare(0, key_prefix.size(), key_prefix) == 0) folder = folder.substr(key_prefix.size());
  960. return EffectSafeName(folder);
  961. };
  962. std::ofstream file(data_dir_ + "gamedata/effect_sprites.lua");
  963. file << "-- Frames of the sprite files of magic.lgp. Game.EffectSprites[name] is a list of frames with\n"
  964. << "-- the position (u, v) and size (w, h) in the texture, in pixels, the offset to draw it\n"
  965. << "-- (ox, oy) and the flags. The names are the folder and the file, like common_iyashi.\n"
  966. << "-- Textures are in images/battle_fx, like common_iyashi00.png.\n"
  967. << "Game.EffectSprites = Game.EffectSprites or {}\n";
  968. // (The list has the quads of all the frames in order, with the position of the corner as ox, oy.)
  969. std::ofstream animations(data_dir_ + "gamedata/effect_animations.lua");
  970. animations << "-- Frames of the sprite files (.SPT) of magic.lgp. Game.EffectAnimations[name] is a list of frames and\n"
  971. << "-- every frame a list of quads: {x, y, u, v, w, h}, with the position of the corner and the size of the\n"
  972. << "-- quad in units of 8 of the effect, and the place in the texture in pixels. The names are the folder\n"
  973. << "-- and the file, like common_houden_2.\n"
  974. << "Game.EffectAnimations = Game.EffectAnimations or {}\n";
  975. const std::string dir = output_dir_ + "temp/effects/";
  976. boost::filesystem::create_directories(data_dir_ + "images/battle_fx/");
  977. for (size_t f = 0; f < magic_lgp_files_.size(); f ++){
  978. const std::string& name = magic_lgp_file_names_[f];
  979. if (name.size() < 3) continue;
  980. std::string ext = name.substr(name.find_last_of('.') + 1);
  981. std::transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char c){return std::tolower(c);});
  982. const std::string key = key_of(magic_lgp_file_folders_[f]);
  983. if (ext == "tex"){
  984. const std::string stem = EffectSafeName(EffectStem(name));
  985. const std::string path = data_dir_ + "images/battle_fx/" + key + "_" + stem + ".png";
  986. if (boost::filesystem::exists(path)) continue;
  987. try{
  988. magic_lgp_files_[f].WriteFile(dir + key + "_" + stem + ".tex");
  989. TexFile tex(dir + key + "_" + stem + ".tex");
  990. tex.SavePng(path);
  991. }
  992. catch (const std::exception& ex){
  993. // Many of the original textures are dummies.
  994. }
  995. }
  996. else if (ext == "s"){
  997. File& sprite_file = magic_lgp_files_[f];
  998. const size_t size = sprite_file.GetFileSize();
  999. if (size < 8) continue;
  1000. sprite_file.SetOffset(0);
  1001. std::vector<unsigned char> bytes(size);
  1002. for (size_t b = 0; b < size; b ++) bytes[b] = sprite_file.readU8();
  1003. // Only the files with the header of sprite lists.
  1004. if (bytes[0] != 0x23 || bytes[1] != 0x20) continue;
  1005. // After the header (the two characters, and the number of frames as a 32 bit value, at 4)
  1006. // there are the frames. Each one has two 16 bit values, the second is the number of quads,
  1007. // and then 20 bytes for every quad: flags (4 bytes), the position of the corner (x and y,
  1008. // 16 bits), the place in the texture (u and v, 16 bits), 4 more bytes, and the width
  1009. // (8 bits, twice) and the height (8 bits, twice). Positions and sizes are in units of 8 of
  1010. // the effect. Layout found in the code that draws them (0x598a7a), and all the files of
  1011. // magic.lgp end exactly where their last frame ends.
  1012. struct Quad{int x, y, u, v, w, h;};
  1013. std::vector<std::vector<Quad>> frames;
  1014. const uint32_t frame_count = bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (static_cast<uint32_t>(bytes[7]) << 24);
  1015. size_t p = 8;
  1016. bool valid = true;
  1017. for (uint32_t fr = 0; fr < frame_count && valid; ++ fr){
  1018. if (p + 4 > size){valid = false; break;}
  1019. const int count = static_cast<int16_t>(bytes[p + 2] | (bytes[p + 3] << 8));
  1020. p += 4;
  1021. if (count < 0 || p + static_cast<size_t>(count) * 20 > size){valid = false; break;}
  1022. std::vector<Quad> quads;
  1023. for (int q = 0; q < count; ++ q, p += 20){
  1024. Quad quad;
  1025. quad.x = static_cast<int16_t>(bytes[p + 4] | (bytes[p + 5] << 8));
  1026. quad.y = static_cast<int16_t>(bytes[p + 6] | (bytes[p + 7] << 8));
  1027. quad.u = static_cast<int16_t>(bytes[p + 8] | (bytes[p + 9] << 8));
  1028. quad.v = static_cast<int16_t>(bytes[p + 10] | (bytes[p + 11] << 8));
  1029. quad.w = bytes[p + 16];
  1030. quad.h = bytes[p + 18];
  1031. quads.push_back(quad);
  1032. }
  1033. frames.push_back(quads);
  1034. }
  1035. if (!valid || p != size || frames.empty()) continue;
  1036. const std::string sprite_name = key + "_" + EffectSafeName(EffectStem(name));
  1037. // All the quads one after the other, for the effects that pick them by number.
  1038. file << "Game.EffectSprites[\"" << sprite_name << "\"] = {\n";
  1039. for (const std::vector<Quad>& quads : frames){
  1040. for (const Quad& quad : quads){
  1041. file << " {u = " << quad.u << ", v = " << quad.v << ", w = " << quad.w << ", h = " << quad.h
  1042. << ", ox = " << quad.x << ", oy = " << quad.y << "},\n";
  1043. }
  1044. }
  1045. file << "}\n";
  1046. // The frames, with their quads.
  1047. animations << "Game.EffectAnimations[\"" << sprite_name << "\"] = {\n";
  1048. for (const std::vector<Quad>& quads : frames){
  1049. animations << " {";
  1050. for (size_t q = 0; q < quads.size(); ++ q){
  1051. animations << (q > 0 ? ", " : "") << "{" << quads[q].x << ", " << quads[q].y << ", " << quads[q].u << ", "
  1052. << quads[q].v << ", " << quads[q].w << ", " << quads[q].h << "}";
  1053. }
  1054. animations << "},\n";
  1055. }
  1056. animations << "}\n";
  1057. }
  1058. }
  1059. }
  1060. void BattleDataInstaller::WriteEnemies(){
  1061. for (Enemy enemy : enemies_){
  1062. TiXmlDocument xml;
  1063. std::unique_ptr<TiXmlElement> container(new TiXmlElement("enemy"));
  1064. container->SetAttribute("id", enemy.id);
  1065. container->SetAttribute("model", enemy.model);
  1066. container->SetAttribute("name", enemy.name);
  1067. container->SetAttribute("level", enemy.level);
  1068. container->SetAttribute("exp", enemy.exp);
  1069. container->SetAttribute("ap", enemy.ap);
  1070. container->SetAttribute("money", enemy.money);
  1071. container->SetAttribute("morph", enemy.morph);
  1072. container->SetDoubleAttribute("back_damage", enemy.back_damage);
  1073. std::unique_ptr<TiXmlElement> stats(new TiXmlElement("stats"));
  1074. std::unique_ptr<TiXmlElement> stat_str(new TiXmlElement("stat"));
  1075. stat_str->SetAttribute("id", "str");
  1076. stat_str->SetAttribute("value", enemy.str);
  1077. stats->LinkEndChild(stat_str.release());
  1078. std::unique_ptr<TiXmlElement> stat_mag(new TiXmlElement("stat"));
  1079. stat_mag->SetAttribute("id", "mag");
  1080. stat_mag->SetAttribute("value", enemy.mag);
  1081. stats->LinkEndChild(stat_mag.release());
  1082. std::unique_ptr<TiXmlElement> stat_def(new TiXmlElement("stat"));
  1083. stat_def->SetAttribute("id", "def");
  1084. stat_def->SetAttribute("value", enemy.def);
  1085. stats->LinkEndChild(stat_def.release());
  1086. std::unique_ptr<TiXmlElement> stat_mdef(new TiXmlElement("stat"));
  1087. stat_mdef->SetAttribute("id", "mdef");
  1088. stat_mdef->SetAttribute("value", enemy.mdef);
  1089. stats->LinkEndChild(stat_mdef.release());
  1090. std::unique_ptr<TiXmlElement> stat_spd(new TiXmlElement("stat"));
  1091. stat_spd->SetAttribute("id", "spd");
  1092. stat_spd->SetAttribute("value", enemy.spd);
  1093. stats->LinkEndChild(stat_spd.release());
  1094. std::unique_ptr<TiXmlElement> stat_lck(new TiXmlElement("stat"));
  1095. stat_lck->SetAttribute("id", "lck");
  1096. stat_lck->SetAttribute("value", enemy.lck);
  1097. stats->LinkEndChild(stat_lck.release());
  1098. std::unique_ptr<TiXmlElement> stat_eva(new TiXmlElement("stat"));
  1099. stat_eva->SetAttribute("id", "eva");
  1100. stat_eva->SetAttribute("value", enemy.eva);
  1101. stats->LinkEndChild(stat_eva.release());
  1102. std::unique_ptr<TiXmlElement> stat_hp(new TiXmlElement("stat"));
  1103. stat_hp->SetAttribute("id", "hp");
  1104. stat_hp->SetAttribute("value", enemy.hp);
  1105. stats->LinkEndChild(stat_hp.release());
  1106. std::unique_ptr<TiXmlElement> stat_mp(new TiXmlElement("stat"));
  1107. stat_mp->SetAttribute("id", "mp");
  1108. stat_mp->SetAttribute("value", enemy.mp);
  1109. stats->LinkEndChild(stat_mp.release());
  1110. container->LinkEndChild(stats.release());
  1111. std::unique_ptr<TiXmlElement> elements(new TiXmlElement("elements"));
  1112. for (Enemy::Element element : enemy.elements){
  1113. std::unique_ptr<TiXmlElement> xml_element(new TiXmlElement("element"));
  1114. xml_element->SetAttribute("id", element.id);
  1115. xml_element->SetDoubleAttribute("factor", element.factor);
  1116. elements->LinkEndChild(xml_element.release());
  1117. }
  1118. container->LinkEndChild(elements.release());
  1119. std::unique_ptr<TiXmlElement> immunities(new TiXmlElement("immunities"));
  1120. for (Enemy::Immunity immunity : enemy.immunities){
  1121. std::unique_ptr<TiXmlElement> xml_immunity(new TiXmlElement("immunity"));
  1122. xml_immunity->SetAttribute("status", immunity.status);
  1123. xml_immunity->SetDoubleAttribute("rate", immunity.rate);
  1124. immunities->LinkEndChild(xml_immunity.release());
  1125. }
  1126. container->LinkEndChild(immunities.release());
  1127. std::unique_ptr<TiXmlElement> attacks(new TiXmlElement("attacks"));
  1128. for (Enemy::Attack attack : enemy.attacks){
  1129. std::unique_ptr<TiXmlElement> xml_attack(new TiXmlElement("attack"));
  1130. xml_attack->SetAttribute("id", attack.id);
  1131. xml_attack->SetAttribute("animation", attack.animation);
  1132. xml_attack->SetAttribute("camera", attack.camera);
  1133. attacks->LinkEndChild(xml_attack.release());
  1134. }
  1135. container->LinkEndChild(attacks.release());
  1136. std::unique_ptr<TiXmlElement> manip_attacks(new TiXmlElement("manipulate"));
  1137. manip_attacks->SetAttribute("manipulable", enemy.manipulate_attacks.size() > 0 ? 1 : 0);
  1138. for (u16 attack : enemy.manipulate_attacks){
  1139. std::unique_ptr<TiXmlElement> xml_manip_attack(new TiXmlElement("attack"));
  1140. xml_manip_attack->SetAttribute("id", attack);
  1141. manip_attacks->LinkEndChild(xml_manip_attack.release());
  1142. }
  1143. container->LinkEndChild(manip_attacks.release());
  1144. std::unique_ptr<TiXmlElement> steals(new TiXmlElement("steal"));
  1145. for (Enemy::Item item : enemy.steal){
  1146. std::unique_ptr<TiXmlElement> xml_steal(new TiXmlElement("item"));
  1147. xml_steal->SetAttribute("id", item.id);
  1148. xml_steal->SetDoubleAttribute("rate", item.rate);
  1149. steals->LinkEndChild(xml_steal.release());
  1150. }
  1151. container->LinkEndChild(steals.release());
  1152. std::unique_ptr<TiXmlElement> drops(new TiXmlElement("drop"));
  1153. for (Enemy::Item item : enemy.drop){
  1154. std::unique_ptr<TiXmlElement> xml_drop(new TiXmlElement("item"));
  1155. xml_drop->SetAttribute("id", item.id);
  1156. xml_drop->SetDoubleAttribute("rate", item.rate);
  1157. drops->LinkEndChild(xml_drop.release());
  1158. }
  1159. container->LinkEndChild(drops.release());
  1160. std::unique_ptr<TiXmlElement> animations(new TiXmlElement("animations"));
  1161. for (unsigned int animation : enemy.animations){
  1162. std::unique_ptr<TiXmlElement> xml_animation(new TiXmlElement("animation"));
  1163. xml_animation->SetAttribute("id", animation);
  1164. animations->LinkEndChild(xml_animation.release());
  1165. }
  1166. container->LinkEndChild(animations.release());
  1167. // AI scripts, as hexadecimal bytecode.
  1168. {
  1169. static const char* AI_SLOT_NAMES[16] = {
  1170. "init", "main", "counter_general", "counter_death", "counter_physical", "counter_magic",
  1171. "battle_end", "pre_turn", "event_1", "event_2", "event_3", "event_4", "event_5",
  1172. "event_6", "event_7", "event_8"
  1173. };
  1174. std::unique_ptr<TiXmlElement> ai(new TiXmlElement("ai"));
  1175. for (size_t slot = 0; slot < enemy.ai_scripts.size() && slot < 16; slot ++){
  1176. if (enemy.ai_scripts[slot].empty()) continue;
  1177. std::string hex;
  1178. char digits[3];
  1179. for (u8 byte : enemy.ai_scripts[slot]){
  1180. snprintf(digits, sizeof(digits), "%02x", byte);
  1181. hex += digits;
  1182. }
  1183. std::unique_ptr<TiXmlElement> xml_script(new TiXmlElement("script"));
  1184. xml_script->SetAttribute("slot", static_cast<int>(slot));
  1185. xml_script->SetAttribute("name", AI_SLOT_NAMES[slot]);
  1186. xml_script->SetAttribute("data", hex);
  1187. ai->LinkEndChild(xml_script.release());
  1188. }
  1189. container->LinkEndChild(ai.release());
  1190. }
  1191. xml.LinkEndChild(container.release());
  1192. std::string file_name = BuildEnemyFileName(enemy);
  1193. xml.SaveFile(data_dir_ + file_name);
  1194. enemy_map_[enemy.id] = file_name;
  1195. }
  1196. }
  1197. void BattleDataInstaller::WriteAttacks(){
  1198. for (Attack attack : attacks_){
  1199. TiXmlDocument xml;
  1200. std::unique_ptr<TiXmlElement> container(new TiXmlElement("Attack"));
  1201. container->SetAttribute("id", attack.id);
  1202. container->SetAttribute("name", attack.name);
  1203. container->SetAttribute("mp", attack.mp);
  1204. container->SetAttribute("reflectable", attack.reflectable);
  1205. std::unique_ptr<TiXmlElement> damage(new TiXmlElement("Damage"));
  1206. std::unique_ptr<TiXmlElement> damage_power(new TiXmlElement("Parameter"));
  1207. damage_power->SetAttribute("id", "power");
  1208. damage_power->SetAttribute("value", attack.damage.power);
  1209. damage->LinkEndChild(damage_power.release());
  1210. std::unique_ptr<TiXmlElement> damage_formula(new TiXmlElement("Parameter"));
  1211. damage_formula->SetAttribute("id", "formula");
  1212. damage_formula->SetAttribute("value", attack.damage.formula);
  1213. damage->LinkEndChild(damage_formula.release());
  1214. std::unique_ptr<TiXmlElement> damage_modifier(new TiXmlElement("Parameter"));
  1215. damage_modifier->SetAttribute("id", "modifier");
  1216. damage_modifier->SetAttribute("value", attack.damage.modifier);
  1217. damage->LinkEndChild(damage_modifier.release());
  1218. std::unique_ptr<TiXmlElement> damage_acc(new TiXmlElement("Parameter"));
  1219. damage_acc->SetAttribute("id", "accuracy");
  1220. // Accuracy is a fraction between 0 and 1, it can't be written as an integer.
  1221. damage_acc->SetDoubleAttribute("value", attack.damage.accuracy);
  1222. damage->LinkEndChild(damage_acc.release());
  1223. std::unique_ptr<TiXmlElement> damage_darkness(new TiXmlElement("Parameter"));
  1224. damage_darkness->SetAttribute("id", "affected_by_darkness");
  1225. damage_darkness->SetAttribute("value", attack.damage.affected_by_darkness);
  1226. damage->LinkEndChild(damage_darkness.release());
  1227. std::unique_ptr<TiXmlElement> damage_restore(new TiXmlElement("Parameter"));
  1228. damage_restore->SetAttribute("id", "restore");
  1229. damage_restore->SetAttribute("value", static_cast<int>(attack.damage.restore));
  1230. damage->LinkEndChild(damage_restore.release());
  1231. std::unique_ptr<TiXmlElement> damage_mp(new TiXmlElement("Parameter"));
  1232. damage_mp->SetAttribute("id", "damage_mp");
  1233. damage_mp->SetAttribute("value", attack.damage.damage_mp);
  1234. damage->LinkEndChild(damage_mp.release());
  1235. std::unique_ptr<TiXmlElement> damage_drain_hp(new TiXmlElement("Parameter"));
  1236. damage_drain_hp->SetAttribute("id", "drain_hp");
  1237. damage_drain_hp->SetAttribute("value", attack.damage.drain_hp);
  1238. damage->LinkEndChild(damage_drain_hp.release());
  1239. std::unique_ptr<TiXmlElement> damage_drain_mp(new TiXmlElement("Parameter"));
  1240. damage_drain_mp->SetAttribute("id", "drain_mp");
  1241. damage_drain_mp->SetAttribute("value", attack.damage.drain_mp);
  1242. damage->LinkEndChild(damage_drain_mp.release());
  1243. std::unique_ptr<TiXmlElement> damage_ignore(new TiXmlElement("Parameter"));
  1244. damage_ignore->SetAttribute("id", "ignore_status_defense");
  1245. damage_ignore->SetAttribute("value", attack.damage.ignore_status_defense);
  1246. damage->LinkEndChild(damage_ignore.release());
  1247. std::unique_ptr<TiXmlElement> damage_critical(new TiXmlElement("Parameter"));
  1248. damage_critical->SetAttribute("id", "always_critical");
  1249. damage_critical->SetAttribute("value", attack.damage.critical);
  1250. damage->LinkEndChild(damage_critical.release());
  1251. container->LinkEndChild(damage.release());
  1252. std::unique_ptr<TiXmlElement> target_opts(new TiXmlElement("Target"));
  1253. std::unique_ptr<TiXmlElement> target_se(new TiXmlElement("Parameter"));
  1254. target_se->SetAttribute("id", "selection_enabled");
  1255. target_se->SetAttribute("value", attack.target.selection_enabled);
  1256. target_opts->LinkEndChild(target_se.release());
  1257. std::unique_ptr<TiXmlElement> target_de(new TiXmlElement("Parameter"));
  1258. target_de->SetAttribute("id", "default_enemy");
  1259. target_de->SetAttribute("value", attack.target.default_enemy);
  1260. target_opts->LinkEndChild(target_de.release());
  1261. std::unique_ptr<TiXmlElement> target_dm(new TiXmlElement("Parameter"));
  1262. target_dm->SetAttribute("id", "default_multiple");
  1263. target_dm->SetAttribute("value", attack.target.default_multiple);
  1264. target_opts->LinkEndChild(target_dm.release());
  1265. std::unique_ptr<TiXmlElement> target_tm(new TiXmlElement("Parameter"));
  1266. target_tm->SetAttribute("id", "toggle_multiple");
  1267. target_tm->SetAttribute("value", attack.target.toggle_multiple);
  1268. target_opts->LinkEndChild(target_tm.release());
  1269. std::unique_ptr<TiXmlElement> target_fr(new TiXmlElement("Parameter"));
  1270. target_fr->SetAttribute("id", "fixed_row");
  1271. target_fr->SetAttribute("value", attack.target.fixed_row);
  1272. target_opts->LinkEndChild(target_fr.release());
  1273. std::unique_ptr<TiXmlElement> target_sr(new TiXmlElement("Parameter"));
  1274. target_sr->SetAttribute("id", "short_range");
  1275. target_sr->SetAttribute("value", attack.target.short_range);
  1276. target_opts->LinkEndChild(target_sr.release());
  1277. std::unique_ptr<TiXmlElement> target_ar(new TiXmlElement("Parameter"));
  1278. target_ar->SetAttribute("id", "all_rows");
  1279. target_ar->SetAttribute("value", attack.target.all_rows);
  1280. target_opts->LinkEndChild(target_ar.release());
  1281. std::unique_ptr<TiXmlElement> target_rd(new TiXmlElement("Parameter"));
  1282. target_rd->SetAttribute("id", "random");
  1283. target_rd->SetAttribute("value", attack.target.random);
  1284. target_opts->LinkEndChild(target_rd.release());
  1285. std::unique_ptr<TiXmlElement> target_od(new TiXmlElement("Parameter"));
  1286. target_od->SetAttribute("id", "only_for_dead");
  1287. target_od->SetAttribute("value", attack.target.only_for_dead);
  1288. target_opts->LinkEndChild(target_od.release());
  1289. std::unique_ptr<TiXmlElement> target_nr(new TiXmlElement("Parameter"));
  1290. target_nr->SetAttribute("id", "no_retarget");
  1291. target_nr->SetAttribute("value", attack.target.no_re_target);
  1292. target_opts->LinkEndChild(target_nr.release());
  1293. container->LinkEndChild(target_opts.release());
  1294. std::unique_ptr<TiXmlElement> effects(new TiXmlElement("Effects"));
  1295. for (Attack::StatusEffect effect : attack.status_effects){
  1296. std::unique_ptr<TiXmlElement> xml_effect(new TiXmlElement("Effect"));
  1297. xml_effect->SetAttribute("id", effect.id);
  1298. xml_effect->SetDoubleAttribute("chance", effect.chance);
  1299. xml_effect->SetAttribute("mode", GameData::STATUS_EFFECT_MODE::to_string(effect.type));
  1300. effects->LinkEndChild(xml_effect.release());
  1301. }
  1302. container->LinkEndChild(effects.release());
  1303. std::unique_ptr<TiXmlElement> elements(new TiXmlElement("Elements"));
  1304. for (unsigned int element : attack.elements){
  1305. std::unique_ptr<TiXmlElement> xml_element(new TiXmlElement("Element"));
  1306. xml_element->SetAttribute("id", element);
  1307. elements->LinkEndChild(xml_element.release());
  1308. }
  1309. container->LinkEndChild(elements.release());
  1310. std::unique_ptr<TiXmlElement> anim(new TiXmlElement("Animation"));
  1311. std::unique_ptr<TiXmlElement> anim_e(new TiXmlElement("Parameter"));
  1312. anim_e->SetAttribute("id", "effect");
  1313. anim_e->SetAttribute("value", attack.animation.effect);
  1314. anim->LinkEndChild(anim_e.release());
  1315. std::unique_ptr<TiXmlElement> anim_ie(new TiXmlElement("Parameter"));
  1316. anim_ie->SetAttribute("id", "impact_effect");
  1317. anim_ie->SetAttribute("value", attack.animation.impact_effect);
  1318. anim->LinkEndChild(anim_ie.release());
  1319. std::unique_ptr<TiXmlElement> anim_s(new TiXmlElement("Parameter"));
  1320. anim_s->SetAttribute("id", "sound");
  1321. anim_s->SetAttribute("value", attack.animation.sound);
  1322. anim->LinkEndChild(anim_s.release());
  1323. std::unique_ptr<TiXmlElement> anim_ha(new TiXmlElement("Parameter"));
  1324. anim_ha->SetAttribute("id", "hurt_anim");
  1325. anim_ha->SetAttribute("value", attack.animation.hurt_anim);
  1326. anim->LinkEndChild(anim_ha.release());
  1327. std::unique_ptr<TiXmlElement> anim_c(new TiXmlElement("Parameter"));
  1328. anim_c->SetAttribute("id", "camera_single");
  1329. anim_c->SetAttribute("value", attack.animation.camera_single);
  1330. anim->LinkEndChild(anim_c.release());
  1331. std::unique_ptr<TiXmlElement> anim_cm(new TiXmlElement("Parameter"));
  1332. anim_cm->SetAttribute("id", "camera_multiple");
  1333. anim_cm->SetAttribute("value", attack.animation.camera_multiple);
  1334. anim->LinkEndChild(anim_cm.release());
  1335. container->LinkEndChild(anim.release());
  1336. xml.LinkEndChild(container.release());
  1337. std::string file_name = BuildAttackFileName(attack);
  1338. xml.SaveFile(data_dir_ + file_name);
  1339. attack_map_[attack.id] = file_name;
  1340. }
  1341. // Index of the attack files by ID, as file names include the attack name.
  1342. TiXmlDocument index;
  1343. std::unique_ptr<TiXmlElement> attacks(new TiXmlElement("attacks"));
  1344. for (const auto& entry : attack_map_){
  1345. std::unique_ptr<TiXmlElement> xml_attack(new TiXmlElement("attack"));
  1346. xml_attack->SetAttribute("id", entry.first);
  1347. // The file name in the map has the gamedata/attack/ path.
  1348. xml_attack->SetAttribute("file", entry.second.substr(entry.second.find_last_of('/') + 1));
  1349. attacks->LinkEndChild(xml_attack.release());
  1350. }
  1351. index.LinkEndChild(attacks.release());
  1352. index.SaveFile(data_dir_ + "gamedata/attack/_index.xml");
  1353. }
  1354. void BattleDataInstaller::WriteFormations(){
  1355. for (Formation formation : formations_){
  1356. TiXmlDocument xml;
  1357. std::unique_ptr<TiXmlElement> container(new TiXmlElement("formation"));
  1358. container->SetAttribute("id", formation.id);
  1359. container->SetAttribute("next", formation.next_formation);
  1360. container->SetDoubleAttribute("escape_difficulty", formation.escape_counter);
  1361. container->SetAttribute("escapable", formation.escapable);
  1362. container->SetAttribute("skip_victory_pose", formation.skip_victory_pose);
  1363. container->SetAttribute("skip_spoils", formation.skip_spoils);
  1364. container->SetAttribute("skip_victory_pose", formation.skip_victory_pose);
  1365. container->SetAttribute("preemptive_disabled", formation.preemptive_disabled);
  1366. container->SetAttribute("layout", static_cast<int>(formation.layout));
  1367. std::unique_ptr<TiXmlElement> location(new TiXmlElement("location"));
  1368. location->SetAttribute("id", formation.location);
  1369. location->SetAttribute("name", formation.location_name);
  1370. container->LinkEndChild(location.release());
  1371. std::unique_ptr<TiXmlElement> enemies(new TiXmlElement("enemies"));
  1372. for (Formation::Enemy enemy : formation.enemies){
  1373. std::unique_ptr<TiXmlElement> enemy_xml(new TiXmlElement("enemy"));
  1374. enemy_xml->SetAttribute("id", enemy.id);
  1375. enemy_xml->SetAttribute("x", enemy.x);
  1376. enemy_xml->SetAttribute("y", enemy.y);
  1377. enemy_xml->SetAttribute("z", enemy.z);
  1378. enemy_xml->SetAttribute("row", enemy.row);
  1379. std::string cover = "";
  1380. for (int c = 0; c < 5; c ++) cover += enemy.cover[c];
  1381. enemy_xml->SetAttribute("cover", cover);
  1382. enemy_xml->SetAttribute("visible", enemy.visible);
  1383. enemy_xml->SetAttribute("direction", enemy.direction);
  1384. enemy_xml->SetAttribute("targeteable", enemy.targeteable);
  1385. enemy_xml->SetAttribute("main_script_active", enemy.main_script_active);
  1386. enemies->LinkEndChild(enemy_xml.release());
  1387. }
  1388. container->LinkEndChild(enemies.release());
  1389. std::unique_ptr<TiXmlElement> cameras(new TiXmlElement("camera"));
  1390. cameras->SetAttribute("initial", formation.initial_camera_position);
  1391. cameras->SetAttribute("intro", formation.intro_camera);
  1392. int c = 0;
  1393. for (Formation::Camera camera : formation.camera_positions){
  1394. std::unique_ptr<TiXmlElement> camera_xml(new TiXmlElement("position"));
  1395. camera_xml->SetAttribute("id", c);
  1396. camera_xml->SetDoubleAttribute("x", camera.x);
  1397. camera_xml->SetDoubleAttribute("y", camera.y);
  1398. camera_xml->SetDoubleAttribute("z", camera.z);
  1399. camera_xml->SetDoubleAttribute("direction_x", camera.d_x);
  1400. camera_xml->SetDoubleAttribute("direction_y", camera.d_y);
  1401. camera_xml->SetDoubleAttribute("direction_z", camera.d_z);
  1402. cameras->LinkEndChild(camera_xml.release());
  1403. c ++;
  1404. }
  1405. container->LinkEndChild(cameras.release());
  1406. std::unique_ptr<TiXmlElement> arena(new TiXmlElement("arena"));
  1407. arena->SetAttribute("is_arena", formation.is_arena_battle);
  1408. for (int next : formation.next_arena_formation_candidates){
  1409. std::unique_ptr<TiXmlElement> next_xml(new TiXmlElement("next_candidate"));
  1410. next_xml->SetAttribute("id", next);
  1411. arena->LinkEndChild(next_xml.release());
  1412. }
  1413. container->LinkEndChild(arena.release());
  1414. xml.LinkEndChild(container.release());
  1415. std::string file_name = std::to_string(formation.id);
  1416. while (file_name.length() < 4) file_name = "0" + file_name;
  1417. file_name = "gamedata/formation/" + file_name + ".xml";
  1418. xml.SaveFile(data_dir_ + file_name);
  1419. formation_map_[formation.id] = file_name;
  1420. }
  1421. }
  1422. void BattleDataInstaller::WriteCharacterData(){
  1423. TiXmlDocument xml;
  1424. std::unique_ptr<TiXmlElement> container(new TiXmlElement("characters"));
  1425. for (CharacterData data : character_data_){
  1426. std::unique_ptr<TiXmlElement> xml_character(new TiXmlElement("character"));
  1427. xml_character->SetAttribute("id", data.id);
  1428. for (CharacterModel model : data.models){
  1429. std::unique_ptr<TiXmlElement> xml_model(new TiXmlElement("model"));
  1430. xml_model->SetAttribute("name", model.name);
  1431. xml_model->SetAttribute("file", model.model);
  1432. xml_character->LinkEndChild(xml_model.release());
  1433. }
  1434. container->LinkEndChild(xml_character.release());
  1435. }
  1436. xml.LinkEndChild(container.release());
  1437. xml.SaveFile(data_dir_ + "models/battle/characters.xml");
  1438. }
  1439. void BattleDataInstaller::WriteSceneData(){
  1440. TiXmlDocument xml;
  1441. std::unique_ptr<TiXmlElement> container(new TiXmlElement("scenes"));
  1442. for (SceneModel data : scene_data_){
  1443. std::unique_ptr<TiXmlElement> xml_scene(new TiXmlElement("scene"));
  1444. xml_scene->SetAttribute("id", data.id);
  1445. xml_scene->SetAttribute("file", data.model);
  1446. xml_scene->SetAttribute("description", data.description);
  1447. container->LinkEndChild(xml_scene.release());
  1448. }
  1449. xml.LinkEndChild(container.release());
  1450. xml.SaveFile(data_dir_ + "models/battle/scenes.xml");
  1451. }
  1452. std::string BattleDataInstaller::BuildEnemyFileName(Enemy enemy){
  1453. std::string file_name = "gamedata/enemy/";
  1454. std::string id = std::to_string(enemy.id);
  1455. while (id.size() < 4) id = "0" + id;
  1456. file_name += id + ".xml";
  1457. return file_name;
  1458. }
  1459. std::string BattleDataInstaller::BuildAttackFileName(Attack attack){
  1460. std::string file_name = "gamedata/attack/";
  1461. std::string id = std::to_string(attack.id);
  1462. while (id.size() < 4) id = "0" + id;
  1463. file_name += (id + "_");
  1464. for (int n = 0; n < attack.name.size(); n ++){
  1465. if (
  1466. (attack.name[n] >= '0' && attack.name[n] <= '9')
  1467. || (attack.name[n] >= 'a' && attack.name[n] <= 'z')
  1468. || (attack.name[n] >= 'A' && attack.name[n] <= 'Z')
  1469. ) file_name += attack.name[n];
  1470. }
  1471. file_name += ".xml";
  1472. return file_name;
  1473. }
  1474. std::unique_ptr<File> BattleDataInstaller::ExtractGZipScene(const File& file){
  1475. std::vector<u8> compressed(file.GetFileSize());
  1476. if (!compressed.empty()) file.GetFileBuffer(compressed.data(), 0, compressed.size());
  1477. std::vector<u8> out;
  1478. std::string error;
  1479. if (compressed.empty() || !BinGZipFile::Inflate(compressed.data(), compressed.size(), out, error) || out.empty()){
  1480. std::cout << "Warning: " << (error.empty() ? "empty data" : error) << " in file " << file.GetFileName() << std::endl;
  1481. return nullptr;
  1482. }
  1483. return std::make_unique<File>(out.data(), 0, static_cast<u32>(out.size()));
  1484. }
  1485. void BattleDataInstaller::ExportMesh(const std::string outdir, const Ogre::MeshPtr &mesh){
  1486. VGears::String base_mesh_name;
  1487. VGears::StringUtil::splitFull(mesh->getName(), base_mesh_name);
  1488. MakeMaterialsUnique(mesh, outdir + base_mesh_name);
  1489. // A model without geometry (enemy 15, Eye, has only a skeleton and animations) has no bounds, and Ogre
  1490. // doesn't export a mesh without them. It is exported as an empty mesh at the origin.
  1491. // Ogre also wants a radius that is not 0, so the bounds are a tiny box.
  1492. if (mesh->getBounds().isNull() || mesh->getBoundingSphereRadius() <= 0){
  1493. mesh->_setBounds(Ogre::AxisAlignedBox(Ogre::Vector3(-0.01f), Ogre::Vector3(0.01f)), false);
  1494. mesh->_setBoundingSphereRadius(0.02f);
  1495. }
  1496. Ogre::MeshSerializer mesh_serializer;
  1497. Ogre::SkeletonPtr skeleton(mesh->getSkeleton());
  1498. Ogre::SkeletonSerializer skeleton_serializer;
  1499. skeleton_serializer.exportSkeleton(
  1500. skeleton.get(), data_dir_ + "models/battle/" + outdir + base_mesh_name + ".skeleton"
  1501. );
  1502. mesh->setSkeletonName(outdir + base_mesh_name + ".skeleton");
  1503. mesh_serializer.exportMesh(mesh.get(), data_dir_ + "models/battle/" + outdir + mesh->getName());
  1504. Ogre::MaterialSerializer mat_ser;
  1505. bool queued = false;
  1506. std::set<std::string> textures;
  1507. Ogre::Mesh::SubMeshList sub_meshes = mesh->getSubMeshes();
  1508. for (Ogre::SubMesh* sub_mesh : sub_meshes){
  1509. Ogre::MaterialPtr mat(Ogre::MaterialManager::getSingleton().getByName(sub_mesh->getMaterialName()));
  1510. if (mat == nullptr) continue;
  1511. for (size_t techs = 0; techs < mat->getNumTechniques(); techs ++){
  1512. Ogre::Technique* tech = mat->getTechnique(techs);
  1513. if (tech == nullptr) continue;
  1514. for (size_t pass_num = 0; pass_num < tech->getNumPasses(); pass_num ++){
  1515. Ogre::Pass* pass = tech->getPass(pass_num);
  1516. if (pass == nullptr) continue;
  1517. for (
  1518. size_t texture_unit_num = 0; texture_unit_num < pass->getNumTextureUnitStates(); texture_unit_num ++
  1519. ){
  1520. Ogre::TextureUnitState* unit = pass->getTextureUnitState(texture_unit_num);
  1521. if (unit && unit->getTextureName().empty() == false){
  1522. // Ensure the output material script references png files, no tex files.
  1523. Ogre::String base_name;
  1524. VGears::StringUtil::splitBase(unit->getTextureName(), base_name);
  1525. unit->setTextureName(outdir + base_name + ".png");
  1526. textures.insert(unit->getTextureName());
  1527. }
  1528. }
  1529. }
  1530. }
  1531. if (std::count(battle_materials_.begin(), battle_materials_.end(), sub_mesh->getMaterialName()) == 0){
  1532. mat_ser.queueForExport(mat);
  1533. queued = true;
  1534. battle_materials_.push_back(sub_mesh->getMaterialName());
  1535. }
  1536. }
  1537. // Ogre throws if there is nothing to export (a mesh without geometry, or whose materials are already exported).
  1538. if (queued)
  1539. mat_ser.exportQueued(data_dir_ + "models/battle/" + outdir + base_mesh_name + VGears::EXT_MATERIAL);
  1540. }
  1541. void BattleDataInstaller::GenerateRsdFiles(BattleModel model, std::string path){
  1542. std::sort(model.tex.begin(), model.tex.end());
  1543. // For each p file, generate a rsd file.
  1544. for (std::string p : model.p){
  1545. std::string base_name = p.substr(0, 4);
  1546. std::string content = "@RSD940102\n";
  1547. content += "PLY=" + base_name + ".PLY\n";
  1548. content += "MAT=" + base_name + ".MAT\n";
  1549. content += "GRP=" + base_name + ".GRP\n";
  1550. content += "NTEX=" + std::to_string(model.tex.size()) + "\n";
  1551. for (int t = 0; t < model.tex.size(); t ++) content += "TEX[" + std::to_string(t) + "]=" + model.tex[t] + "\n";
  1552. content += "\n";
  1553. std::ofstream out(path + base_name + ".rsd");
  1554. out << content;
  1555. out.close();
  1556. }
  1557. }
  1558. void BattleDataInstaller::GenerateRsdFiles(SpellModel model, std::string path){
  1559. //std::sort(model.tex.begin(), model.tex.end());
  1560. // For each p file, generate a rsd file.
  1561. for (std::string p : model.p){
  1562. std::string base_name = p.substr(0, p.length() - 2);
  1563. std::string content = "@RSD940102\n";
  1564. content += "PLY=" + base_name + ".PLY\n";
  1565. content += "MAT=" + base_name + ".MAT\n";
  1566. content += "GRP=" + base_name + ".GRP\n";
  1567. content += "NTEX=0\n";
  1568. //for (int t = 0; t < model.tex.size(); t ++)
  1569. // content += "TEX[" + std::to_string(t) + "]=" + model.tex[t] + "\n";
  1570. content += "\n";
  1571. std::ofstream out(path + base_name + ".rsd");
  1572. out << content;
  1573. out.close();
  1574. }
  1575. }
  1576. void BattleDataInstaller::WriteModelCamera(
  1577. File script, File skeleton, const std::string& model_name
  1578. ){
  1579. // The scripts of a model start with a header of 0x68 bytes, that ff7.exe copies to the data the
  1580. // cameras use (0x42b6a0): 16 points of the model at 0x12, the factors of the size at 0x44, two
  1581. // views of the model (a camera position and a point to look at) at 0x4C and the height of the point
  1582. // the camera looks at, at 0x64.
  1583. if (script.GetFileSize() < 0x68 || skeleton.GetFileSize() < 16) return;
  1584. skeleton.SetOffset(12);
  1585. const unsigned int bones = skeleton.readU32LE();
  1586. if (bones == 0 || skeleton.GetFileSize() < 16 + bones * 12) return;
  1587. std::ofstream file(data_dir_ + "scripts/battle_models/" + model_name + "_camera.lua");
  1588. if (!file) return;
  1589. file << "-- Data of the model for the cameras of the battles. A point is the end of the bone with the\n"
  1590. << "-- number of the point minus one (0 is the root).\n"
  1591. << "BattleModelCameras = BattleModelCameras or {}\n"
  1592. << "BattleModelCameras[\"" << model_name << "\"] = {\n points = {";
  1593. script.SetOffset(0x12);
  1594. for (int i = 0; i < 16; i ++) file << static_cast<int>(script.readU8()) << ", ";
  1595. file << "},\n size = {";
  1596. script.SetOffset(0x44);
  1597. for (int i = 0; i < 3; i ++) file << static_cast<int>(static_cast<int16_t>(script.readU16LE())) << ", ";
  1598. // The two views, one after the other.
  1599. script.SetOffset(0x4C);
  1600. file << "},\n views = {";
  1601. for (int v = 0; v < 2; v ++){
  1602. for (int p = 0; p < 2; p ++){
  1603. file << (p == 0 ? "{pos = {" : "look = {");
  1604. for (int i = 0; i < 3; i ++) file << static_cast<int>(static_cast<int16_t>(script.readU16LE())) << ", ";
  1605. file << (p == 0 ? "}, " : "}}, ");
  1606. }
  1607. }
  1608. script.SetOffset(0x64);
  1609. file << "},\n look_height = " << static_cast<int>(static_cast<int16_t>(script.readU16LE()))
  1610. << ",\n lengths = {";
  1611. // The bones are the last data of the skeleton: parent, length (negative) and polygons.
  1612. skeleton.SetOffset(skeleton.GetFileSize() - bones * 12);
  1613. for (unsigned int b = 0; b < bones; b ++){
  1614. skeleton.readU32LE();
  1615. const u32 raw = skeleton.readU32LE();
  1616. float length = 0.0f;
  1617. std::memcpy(&length, &raw, sizeof(length));
  1618. skeleton.readU32LE();
  1619. file << "[" << b << "] = " << -length << ", ";
  1620. }
  1621. file << "},\n}\n";
  1622. }
  1623. void BattleDataInstaller::DecompileBattleModelHrc(
  1624. File compiled, BattleModel model, std::string path, std::string skeleton_name
  1625. ){
  1626. compiled.SetOffset(0);
  1627. compiled.readU32LE();
  1628. compiled.readU32LE();
  1629. compiled.readU32LE();
  1630. std::sort(model.p.begin(), model.p.end());
  1631. std::string decompiled(":HEADER_BLOCK 2\n:SKELETON " + skeleton_name + "\n");
  1632. int bones = compiled.readU32LE();
  1633. compiled.SetOffset(compiled.GetFileSize() - (bones * 12));
  1634. decompiled += ":BONES " + std::to_string(bones) + "\n\n";
  1635. int p_file_index = 0;
  1636. for (int b = 0; b < bones; b ++){
  1637. decompiled += "bone" + std::to_string(b) + "\n";
  1638. int parent = compiled.readU32LE();
  1639. if (parent == 0xFFFFFFFF) decompiled += "root\n";
  1640. else decompiled += "bone" + std::to_string(parent) + "\n";
  1641. union {
  1642. float f;
  1643. unsigned long ul;
  1644. unsigned char b[4];
  1645. } u;
  1646. u.b[0] = compiled.readU8();
  1647. u.b[1] = compiled.readU8();
  1648. u.b[2] = compiled.readU8();
  1649. u.b[3] = compiled.readU8();
  1650. decompiled += std::to_string(u.f * -1) + "\n";
  1651. int offset = compiled.readU32LE();
  1652. if (offset == 0) decompiled += "0\n\n";
  1653. else {
  1654. decompiled += std::to_string(offset) + " ";
  1655. if (p_file_index < model.p.size()) decompiled += model.p[p_file_index].substr(0, 4);
  1656. p_file_index ++;
  1657. decompiled += "\n\n";
  1658. }
  1659. }
  1660. std::ofstream out(path);
  1661. out << decompiled;
  1662. out.close();
  1663. }
  1664. void BattleDataInstaller::DecompileSpellModelHrc(
  1665. File compiled, SpellModel model, std::string path, std::string skeleton_name
  1666. ){
  1667. compiled.SetOffset(0);
  1668. compiled.readU32LE();
  1669. compiled.readU32LE();
  1670. compiled.readU32LE();
  1671. std::sort(model.p.begin(), model.p.end());
  1672. std::string decompiled(":HEADER_BLOCK 2\n:SKELETON " + skeleton_name + "\n");
  1673. int bones = compiled.readU32LE();
  1674. compiled.SetOffset(compiled.GetFileSize() - (bones * 12));
  1675. decompiled += ":BONES " + std::to_string(bones) + "\n\n";
  1676. int p_index = 0;
  1677. for (int b = 0; b < bones; b ++){
  1678. decompiled += "bone" + std::to_string(b) + "\n";
  1679. int parent = compiled.readU32LE();
  1680. if (parent == 0xFFFFFFFF) decompiled += "root\n";
  1681. else decompiled += "bone" + std::to_string(parent) + "\n";
  1682. union {
  1683. float f;
  1684. unsigned long ul;
  1685. unsigned char b[4];
  1686. } u;
  1687. u.b[0] = compiled.readU8();
  1688. u.b[1] = compiled.readU8();
  1689. u.b[2] = compiled.readU8();
  1690. u.b[3] = compiled.readU8();
  1691. decompiled += std::to_string(u.f * -1) + "\n";
  1692. int offset = compiled.readU32LE();
  1693. if (offset == 0) decompiled += "0\n\n";
  1694. else {
  1695. decompiled += std::to_string(offset) + " ";
  1696. if (p_index < model.p.size()) decompiled += model.p[p_index].substr(0, model.p[p_index].length() - 2);
  1697. p_index ++;
  1698. decompiled += "\n\n";
  1699. }
  1700. }
  1701. std::ofstream out(path);
  1702. out << decompiled;
  1703. out.close();
  1704. }
  1705. void BattleDataInstaller::DecompileSceneModelHrc(
  1706. File compiled, BattleModel model, std::string path, std::string skeleton_name
  1707. ){
  1708. compiled.SetOffset(0);
  1709. compiled.readU32LE(); // Skip 4 bytes
  1710. compiled.readU32LE(); // Skip 4 bytes
  1711. compiled.readU32LE(); // Skip 4 bytes
  1712. compiled.readU32LE(); // Supposed to be the number of bones, but for scenes is always 0.
  1713. std::sort(model.p.begin(), model.p.end());
  1714. std::string decompiled(":HEADER_BLOCK 2\n:SKELETON " + skeleton_name + "\n");
  1715. int bones = model.p.size();
  1716. decompiled += ":BONES " + std::to_string(bones) + "\n\n";
  1717. int p_file_index = 0;
  1718. for (int b = 0; b < bones; b ++){
  1719. decompiled += "bone" + std::to_string(b) + "\n";
  1720. if (b == 0) decompiled += "root\n";
  1721. else decompiled += ("bone" + std::to_string(b - 1) + "\n");
  1722. // The pieces share the coordinates of the scene. A length would move each one along the depth, away
  1723. // from the previous one.
  1724. decompiled += "0.000000\n";
  1725. decompiled += "1 " + model.p[b].substr(0, 4) + "\n\n";
  1726. }
  1727. std::ofstream out(path);
  1728. out << decompiled;
  1729. out.close();
  1730. }