Nessuna descrizione

project.cpp 60KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590
  1. #include "asm.h"
  2. #include "project.h"
  3. #include "tile.h"
  4. #include "tileset.h"
  5. #include "metatile.h"
  6. #include "event.h"
  7. #include <QDebug>
  8. #include <QDir>
  9. #include <QFile>
  10. #include <QTextStream>
  11. #include <QStandardItem>
  12. #include <QMessageBox>
  13. #include <QRegularExpression>
  14. Project::Project()
  15. {
  16. groupNames = new QStringList;
  17. map_groups = new QMap<QString, int>;
  18. groupedMapNames = new QList<QStringList*>;
  19. mapNames = new QStringList;
  20. map_cache = new QMap<QString, Map*>;
  21. mapConstantsToMapNames = new QMap<QString, QString>;
  22. mapNamesToMapConstants = new QMap<QString, QString>;
  23. mapAttributesTable = new QMap<int, QString>;
  24. mapAttributes = new QMap<QString, QMap<QString, QString>*>;
  25. tileset_cache = new QMap<QString, Tileset*>;
  26. }
  27. QString Project::getProjectTitle() {
  28. if (!root.isNull()) {
  29. return root.section('/', -1);
  30. } else {
  31. return QString();
  32. }
  33. }
  34. Map* Project::loadMap(QString map_name) {
  35. // New maps are saved to actual files yet, so we need to fetch their data from the map_cache.
  36. Map *map;
  37. if (map_cache->contains(map_name) && !map_cache->value(map_name)->isPersistedToFile) {
  38. map = map_cache->value(map_name);
  39. } else {
  40. map = new Map;
  41. map->setName(map_name);
  42. }
  43. readMapHeader(map);
  44. readMapAttributes(map);
  45. getTilesets(map);
  46. loadBlockdata(map);
  47. loadMapBorder(map);
  48. readMapEvents(map);
  49. loadMapConnections(map);
  50. map->commit();
  51. map->history.save();
  52. map_cache->insert(map_name, map);
  53. return map;
  54. }
  55. void Project::loadMapConnections(Map *map) {
  56. if (!map->isPersistedToFile) {
  57. return;
  58. }
  59. map->connections.clear();
  60. if (!map->connections_label.isNull()) {
  61. QString path = root + QString("/data/maps/%1/connections.inc").arg(map->name);
  62. QString text = readTextFile(path);
  63. if (!text.isNull()) {
  64. QList<QStringList> *commands = parse(text);
  65. QStringList *list = getLabelValues(commands, map->connections_label);
  66. //// Avoid using this value. It ought to be generated instead.
  67. //int num_connections = list->value(0).toInt(nullptr, 0);
  68. QString connections_list_label = list->value(1);
  69. QList<QStringList> *connections = getLabelMacros(commands, connections_list_label);
  70. for (QStringList command : *connections) {
  71. QString macro = command.value(0);
  72. if (macro == "connection") {
  73. Connection *connection = new Connection;
  74. connection->direction = command.value(1);
  75. connection->offset = command.value(2);
  76. QString mapConstant = command.value(3);
  77. if (mapConstantsToMapNames->contains(mapConstant)) {
  78. connection->map_name = mapConstantsToMapNames->value(mapConstant);
  79. map->connections.append(connection);
  80. } else {
  81. qDebug() << QString("Failed to find connected map for map constant '%1'").arg(mapConstant);
  82. }
  83. }
  84. }
  85. }
  86. }
  87. }
  88. void Project::setNewMapConnections(Map *map) {
  89. map->connections.clear();
  90. }
  91. QList<QStringList>* Project::getLabelMacros(QList<QStringList> *list, QString label) {
  92. bool in_label = false;
  93. QList<QStringList> *new_list = new QList<QStringList>;
  94. for (int i = 0; i < list->length(); i++) {
  95. QStringList params = list->value(i);
  96. QString macro = params.value(0);
  97. if (macro == ".label") {
  98. if (params.value(1) == label) {
  99. in_label = true;
  100. } else if (in_label) {
  101. // If nothing has been read yet, assume the label
  102. // we're looking for is in a stack of labels.
  103. if (new_list->length() > 0) {
  104. break;
  105. }
  106. }
  107. } else if (in_label) {
  108. new_list->append(params);
  109. }
  110. }
  111. return new_list;
  112. }
  113. // For if you don't care about filtering by macro,
  114. // and just want all values associated with some label.
  115. QStringList* Project::getLabelValues(QList<QStringList> *list, QString label) {
  116. list = getLabelMacros(list, label);
  117. QStringList *values = new QStringList;
  118. for (int i = 0; i < list->length(); i++) {
  119. QStringList params = list->value(i);
  120. QString macro = params.value(0);
  121. // Ignore .align
  122. if (macro == ".align") {
  123. continue;
  124. }
  125. for (int j = 1; j < params.length(); j++) {
  126. values->append(params.value(j));
  127. }
  128. }
  129. return values;
  130. }
  131. void Project::readMapHeader(Map* map) {
  132. if (!map->isPersistedToFile) {
  133. return;
  134. }
  135. QString label = map->name;
  136. Asm *parser = new Asm;
  137. QString header_text = readTextFile(root + "/data/maps/" + label + "/header.inc");
  138. if (header_text.isNull()) {
  139. return;
  140. }
  141. QStringList *header = getLabelValues(parser->parse(header_text), label);
  142. map->attributes_label = header->value(0);
  143. map->events_label = header->value(1);
  144. map->scripts_label = header->value(2);
  145. map->connections_label = header->value(3);
  146. map->song = header->value(4);
  147. map->index = header->value(5);
  148. map->location = header->value(6);
  149. map->visibility = header->value(7);
  150. map->weather = header->value(8);
  151. map->type = header->value(9);
  152. map->unknown = header->value(10);
  153. map->show_location = header->value(11);
  154. map->battle_scene = header->value(12);
  155. }
  156. void Project::setNewMapHeader(Map* map, int mapIndex) {
  157. map->attributes_label = QString("%1_MapAttributes").arg(map->name);
  158. map->events_label = QString("%1_MapEvents").arg(map->name);;
  159. map->scripts_label = QString("%1_MapScripts").arg(map->name);;
  160. map->connections_label = "0x0";
  161. map->song = "BGM_DAN02";
  162. map->index = QString("%1").arg(mapIndex);
  163. map->location = "0";
  164. map->visibility = "0";
  165. map->weather = "2";
  166. map->type = "1";
  167. map->unknown = "0";
  168. map->show_location = "1";
  169. map->battle_scene = "0";
  170. }
  171. void Project::saveMapHeader(Map *map) {
  172. QString label = map->name;
  173. QString header_path = root + "/data/maps/" + label + "/header.inc";
  174. QString text = "";
  175. text += QString("%1::\n").arg(label);
  176. text += QString("\t.4byte %1\n").arg(map->attributes_label);
  177. text += QString("\t.4byte %1\n").arg(map->events_label);
  178. text += QString("\t.4byte %1\n").arg(map->scripts_label);
  179. text += QString("\t.4byte %1\n").arg(map->connections_label);
  180. text += QString("\t.2byte %1\n").arg(map->song);
  181. text += QString("\t.2byte %1\n").arg(map->index);
  182. text += QString("\t.byte %1\n").arg(map->location);
  183. text += QString("\t.byte %1\n").arg(map->visibility);
  184. text += QString("\t.byte %1\n").arg(map->weather);
  185. text += QString("\t.byte %1\n").arg(map->type);
  186. text += QString("\t.2byte %1\n").arg(map->unknown);
  187. text += QString("\t.byte %1\n").arg(map->show_location);
  188. text += QString("\t.byte %1\n").arg(map->battle_scene);
  189. saveTextFile(header_path, text);
  190. }
  191. void Project::readMapAttributesTable() {
  192. int curMapIndex = 1;
  193. QString attributesText = readTextFile(getMapAttributesTableFilepath());
  194. QList<QStringList>* values = parse(attributesText);
  195. bool inAttributePointers = false;
  196. for (int i = 0; i < values->length(); i++) {
  197. QStringList params = values->value(i);
  198. QString macro = params.value(0);
  199. if (macro == ".label") {
  200. if (inAttributePointers) {
  201. break;
  202. }
  203. if (params.value(1) == "gMapAttributes") {
  204. inAttributePointers = true;
  205. }
  206. } else if (macro == ".4byte" && inAttributePointers) {
  207. QString mapName = params.value(1);
  208. if (!mapName.contains("UnknownMapAttributes")) {
  209. // Strip off "_MapAttributes" from the label if it's a real map label.
  210. mapName = mapName.remove(mapName.length() - 14, 14);
  211. }
  212. mapAttributesTable->insert(curMapIndex, mapName);
  213. curMapIndex++;
  214. }
  215. }
  216. }
  217. void Project::saveMapAttributesTable() {
  218. QString text = "";
  219. text += QString("\t.align 2\n");
  220. text += QString("gMapAttributes::\n");
  221. for (int i = 0; i < mapAttributesTable->count(); i++) {
  222. int mapIndex = i + 1;
  223. QString mapName = mapAttributesTable->value(mapIndex);
  224. if (!mapName.contains("UnknownMapAttributes")) {
  225. text += QString("\t.4byte %1_MapAttributes\n").arg(mapName);
  226. } else {
  227. text += QString("\t.4byte %1\n").arg(mapName);
  228. }
  229. }
  230. saveTextFile(getMapAttributesTableFilepath(), text);
  231. }
  232. QString Project::getMapAttributesTableFilepath() {
  233. return QString("%1/data/maps/attributes_table.inc").arg(root);
  234. }
  235. void Project::readMapAttributes(Map* map) {
  236. if (!map->isPersistedToFile) {
  237. return;
  238. }
  239. Asm *parser = new Asm;
  240. QString assets_text = readTextFile(getMapAssetsFilepath());
  241. if (assets_text.isNull()) {
  242. return;
  243. }
  244. QStringList *attributes = getLabelValues(parser->parse(assets_text), map->attributes_label);
  245. map->width = attributes->value(0);
  246. map->height = attributes->value(1);
  247. map->border_label = attributes->value(2);
  248. map->blockdata_label = attributes->value(3);
  249. map->tileset_primary_label = attributes->value(4);
  250. map->tileset_secondary_label = attributes->value(5);
  251. }
  252. void Project::readAllMapAttributes() {
  253. mapAttributes->clear();
  254. Asm *parser = new Asm;
  255. QString assets_text = readTextFile(getMapAssetsFilepath());
  256. if (assets_text.isNull()) {
  257. return;
  258. }
  259. QList<QStringList> *commands = parser->parse(assets_text);
  260. // Assume the _assets.inc file is grouped consistently in the order of:
  261. // 1. <map_name>_MapBorder
  262. // 2. <map_name>_MapBlockdata
  263. // 3. <map_name>_MapAttributes
  264. int i = 0;
  265. while (i < commands->length()) {
  266. // Read MapBorder assets.
  267. QStringList borderParams = commands->value(i++);
  268. bool isUnknownMapBorder = borderParams.value(1).startsWith("UnknownMapBorder_");
  269. if (borderParams.value(0) != ".label" || (!borderParams.value(1).endsWith("_MapBorder") && !isUnknownMapBorder)) {
  270. qDebug() << QString("Expected MapBorder label, but found %1").arg(borderParams.value(1));
  271. continue;
  272. }
  273. QString borderLabel = borderParams.value(1);
  274. QString mapName;
  275. if (!isUnknownMapBorder) {
  276. mapName = borderLabel.remove(borderLabel.length() - 10, 10);
  277. } else {
  278. // Unknown map name has to match the MapAttributes label.
  279. mapName = borderLabel.replace("Border", "Attributes");
  280. }
  281. QMap<QString, QString>* attrs = new QMap<QString, QString>;
  282. mapAttributes->insert(mapName, attrs);
  283. attrs->insert("border_label", borderParams.value(1));
  284. borderParams = commands->value(i++);
  285. attrs->insert("border_filepath", borderParams.value(1).replace("\"", ""));
  286. // Read MapBlockData assets.
  287. QStringList blockDataParams = commands->value(i++);
  288. bool isUnknownMapBlockdata = blockDataParams.value(1).startsWith("UnknownMapBlockdata_");
  289. if (blockDataParams.value(0) != ".label" || (!blockDataParams.value(1).endsWith("_MapBlockdata") && !isUnknownMapBlockdata)) {
  290. qDebug() << QString("Expected MapBlockdata label, but found %1").arg(blockDataParams.value(1));
  291. continue;
  292. }
  293. QString blockDataLabel = blockDataParams.value(1);
  294. attrs->insert("blockdata_label", blockDataLabel);
  295. blockDataParams = commands->value(i++);
  296. attrs->insert("blockdata_filepath", blockDataParams.value(1).replace("\"", ""));
  297. // Read MapAttributes assets.
  298. i++; // skip .align
  299. // Maps can share MapAttributes, so gather a list of them.
  300. QStringList attributeMapLabels;
  301. QStringList attributesParams;
  302. QStringList* sharedAttrMaps = new QStringList;
  303. while (i < commands->length()) {
  304. attributesParams = commands->value(i);
  305. if (attributesParams.value(0) != ".label") {
  306. break;
  307. }
  308. QString attrLabel = attributesParams.value(1);
  309. attributeMapLabels.append(attrLabel);
  310. sharedAttrMaps->append(attrLabel);
  311. i++;
  312. }
  313. // Apply the map attributes to each of the shared maps.
  314. QString attrWidth = commands->value(i++).value(1);
  315. QString attrHeight = commands->value(i++).value(1);
  316. QString attrBorderLabel = commands->value(i++).value(1);
  317. QString attrBlockdataLabel = commands->value(i++).value(1);
  318. QString attrTilesetPrimary = commands->value(i++).value(1);
  319. QString attrTilesetSecondary = commands->value(i++).value(1);
  320. for (QString attributeMapLabel: attributeMapLabels) {
  321. QString altMapName = attributeMapLabel;
  322. if (!altMapName.startsWith("UnknownMapAttributes_")) {
  323. altMapName.remove(altMapName.length() - 14, 14);
  324. }
  325. if (!mapAttributes->contains(altMapName)) {
  326. mapAttributes->insert(altMapName, new QMap<QString, QString>);
  327. }
  328. mapAttributes->value(altMapName)->insert("attributes_label", attributeMapLabel);
  329. mapAttributes->value(altMapName)->insert("width", attrWidth);
  330. mapAttributes->value(altMapName)->insert("height", attrHeight);
  331. mapAttributes->value(altMapName)->insert("border_label", attrBorderLabel);
  332. mapAttributes->value(altMapName)->insert("blockdata_label", attrBlockdataLabel);
  333. mapAttributes->value(altMapName)->insert("tileset_primary", attrTilesetPrimary);
  334. mapAttributes->value(altMapName)->insert("tileset_secondary", attrTilesetSecondary);
  335. if (sharedAttrMaps->length() > 1) {
  336. mapAttributes->value(altMapName)->insert("shared_attr_maps", sharedAttrMaps->join(":"));
  337. }
  338. }
  339. }
  340. }
  341. void Project::saveAllMapAttributes() {
  342. QString text = "";
  343. for (int i = 0; i < mapAttributesTable->count(); i++) {
  344. int mapIndex = i + 1;
  345. QString mapName = mapAttributesTable->value(mapIndex);
  346. QMap<QString, QString>* attrs = mapAttributes->value(mapName);
  347. // Find the map attributes object that contains the border data.
  348. QMap<QString, QString>* attrsWithBorder;
  349. if (attrs->contains("border_filepath")) {
  350. attrsWithBorder = attrs;
  351. } else {
  352. QStringList labels = attrs->value("shared_attr_maps").split(":");
  353. for (QString label : labels) {
  354. label.remove(label.length() - 14, 14);
  355. if (mapAttributes->contains(label) && mapAttributes->value(label)->contains("border_filepath")) {
  356. attrsWithBorder = mapAttributes->value(label);
  357. break;
  358. }
  359. }
  360. }
  361. if (attrsWithBorder != nullptr) {
  362. text += QString("%1::\n").arg(attrsWithBorder->value("border_label"));
  363. text += QString("\t.incbin \"%1\"\n").arg(attrsWithBorder->value("border_filepath"));
  364. text += QString("\n");
  365. }
  366. // Find the map attributes object that contains the blockdata.
  367. QMap<QString, QString>* attrsWithBlockdata;
  368. if (attrs->contains("blockdata_filepath")) {
  369. attrsWithBlockdata = attrs;
  370. } else {
  371. QStringList labels = attrs->value("shared_attr_maps").split(":");
  372. for (QString label : labels) {
  373. label.remove(label.length() - 14, 14);
  374. if (mapAttributes->contains(label) && mapAttributes->value(label)->contains("blockdata_filepath")) {
  375. attrsWithBlockdata = mapAttributes->value(label);
  376. break;
  377. }
  378. }
  379. }
  380. if (attrsWithBlockdata != nullptr) {
  381. text += QString("%1::\n").arg(attrsWithBlockdata->value("blockdata_label"));
  382. text += QString("\t.incbin \"%1\"\n").arg(attrsWithBorder->value("blockdata_filepath"));
  383. text += QString("\n");
  384. }
  385. text += QString("\t.align 2\n");
  386. if (attrs->contains("shared_attr_maps")) {
  387. QStringList labels = attrs->value("shared_attr_maps").split(":");
  388. for (QString label : labels) {
  389. text += QString("%1::\n").arg(label);
  390. }
  391. } else {
  392. text += QString("%1::\n").arg(attrs->value("attributes_label"));
  393. }
  394. text += QString("\t.4byte %1\n").arg(attrs->value("width"));
  395. text += QString("\t.4byte %1\n").arg(attrs->value("height"));
  396. text += QString("\t.4byte %1\n").arg(attrs->value("border_label"));
  397. text += QString("\t.4byte %1\n").arg(attrs->value("blockdata_label"));
  398. text += QString("\t.4byte %1\n").arg(attrs->value("tileset_primary"));
  399. text += QString("\t.4byte %1\n").arg(attrs->value("tileset_secondary"));
  400. text += QString("\n");
  401. }
  402. saveTextFile(getMapAssetsFilepath(), text);
  403. }
  404. QString Project::getMapAssetsFilepath() {
  405. return root + "/data/maps/_assets.inc";
  406. }
  407. void Project::setNewMapAttributes(Map* map) {
  408. map->width = "20";
  409. map->height = "20";
  410. map->border_label = QString("%1_MapBorder").arg(map->name);
  411. map->blockdata_label = QString("%1_MapBlockdata").arg(map->name);
  412. map->tileset_primary_label = "gTileset_General";
  413. map->tileset_secondary_label = "gTileset_Petalburg";
  414. // Insert new entry into the global map attributes.
  415. QMap<QString, QString>* attrs = new QMap<QString, QString>;
  416. attrs->insert("border_label", QString("%1_MapBorder").arg(map->name));
  417. attrs->insert("border_filepath", QString("data/maps/%1/border.bin").arg(map->name));
  418. attrs->insert("blockdata_label", QString("%1_MapBlockdata").arg(map->name));
  419. attrs->insert("blockdata_filepath", QString("data/maps/%1/map.bin").arg(map->name));
  420. attrs->insert("attributes_label", QString("%1_MapAttributes").arg(map->name));
  421. attrs->insert("width", map->width);
  422. attrs->insert("height", map->height);
  423. attrs->insert("tileset_primary", map->tileset_primary_label);
  424. attrs->insert("tileset_secondary", map->tileset_secondary_label);
  425. mapAttributes->insert(map->name, attrs);
  426. }
  427. void Project::getTilesets(Map* map) {
  428. map->tileset_primary = getTileset(map->tileset_primary_label);
  429. map->tileset_secondary = getTileset(map->tileset_secondary_label);
  430. }
  431. Tileset* Project::loadTileset(QString label) {
  432. Asm *parser = new Asm;
  433. QString headers_text = readTextFile(root + "/data/tilesets/headers.inc");
  434. QStringList *values = getLabelValues(parser->parse(headers_text), label);
  435. Tileset *tileset = new Tileset;
  436. tileset->name = label;
  437. tileset->is_compressed = values->value(0);
  438. tileset->is_secondary = values->value(1);
  439. tileset->padding = values->value(2);
  440. tileset->tiles_label = values->value(3);
  441. tileset->palettes_label = values->value(4);
  442. tileset->metatiles_label = values->value(5);
  443. tileset->metatile_attrs_label = values->value(6);
  444. tileset->callback_label = values->value(7);
  445. loadTilesetAssets(tileset);
  446. tileset_cache->insert(label, tileset);
  447. return tileset;
  448. }
  449. QString Project::getBlockdataPath(Map* map) {
  450. QString text = readTextFile(getMapAssetsFilepath());
  451. QStringList *values = getLabelValues(parse(text), map->blockdata_label);
  452. QString path;
  453. if (!values->isEmpty()) {
  454. path = root + "/" + values->value(0).section('"', 1, 1);
  455. } else {
  456. path = root + "/data/maps/" + map->name + "/map.bin";
  457. }
  458. return path;
  459. }
  460. QString Project::getMapBorderPath(Map *map) {
  461. QString text = readTextFile(getMapAssetsFilepath());
  462. QStringList *values = getLabelValues(parse(text), map->border_label);
  463. QString path;
  464. if (!values->isEmpty()) {
  465. path = root + "/" + values->value(0).section('"', 1, 1);
  466. } else {
  467. path = root + "/data/maps/" + map->name + "/border.bin";
  468. }
  469. return path;
  470. }
  471. void Project::loadBlockdata(Map* map) {
  472. if (!map->isPersistedToFile) {
  473. return;
  474. }
  475. QString path = getBlockdataPath(map);
  476. map->blockdata = readBlockdata(path);
  477. }
  478. void Project::setNewMapBlockdata(Map* map) {
  479. Blockdata *blockdata = new Blockdata;
  480. for (int i = 0; i < map->getWidth() * map->getHeight(); i++) {
  481. blockdata->addBlock(qint16(0x3001));
  482. }
  483. map->blockdata = blockdata;
  484. }
  485. void Project::loadMapBorder(Map *map) {
  486. if (!map->isPersistedToFile) {
  487. return;
  488. }
  489. QString path = getMapBorderPath(map);
  490. map->border = readBlockdata(path);
  491. }
  492. void Project::setNewMapBorder(Map *map) {
  493. Blockdata *blockdata = new Blockdata;
  494. blockdata->addBlock(qint16(0x01D4));
  495. blockdata->addBlock(qint16(0x01D5));
  496. blockdata->addBlock(qint16(0x01DC));
  497. blockdata->addBlock(qint16(0x01DD));
  498. map->border = blockdata;
  499. }
  500. void Project::saveMapBorder(Map *map) {
  501. QString path = getMapBorderPath(map);
  502. writeBlockdata(path, map->border);
  503. }
  504. void Project::saveBlockdata(Map* map) {
  505. QString path = getBlockdataPath(map);
  506. writeBlockdata(path, map->blockdata);
  507. map->history.save();
  508. }
  509. void Project::writeBlockdata(QString path, Blockdata *blockdata) {
  510. QFile file(path);
  511. if (file.open(QIODevice::WriteOnly)) {
  512. QByteArray data = blockdata->serialize();
  513. file.write(data);
  514. }
  515. }
  516. void Project::saveAllMaps() {
  517. QList<QString> keys = map_cache->keys();
  518. for (int i = 0; i < keys.length(); i++) {
  519. QString key = keys.value(i);
  520. Map* map = map_cache->value(key);
  521. saveMap(map);
  522. }
  523. }
  524. void Project::saveMap(Map *map) {
  525. // Create/Modify a few collateral files for brand new maps.
  526. if (!map->isPersistedToFile) {
  527. QString newMapDataDir = QString(root + "/data/maps/%1").arg(map->name);
  528. if (!QDir::root().mkdir(newMapDataDir)) {
  529. qDebug() << "Error: failed to create directory for new map. " << newMapDataDir;
  530. }
  531. // Create file data/scripts/maps/<map_name>.inc
  532. QString text = QString("%1_MapScripts::\n\t.byte 0\n").arg(map->name);
  533. saveTextFile(root + "/data/scripts/maps/" + map->name + ".inc", text);
  534. // Create file data/text/maps/<map_name>.inc
  535. saveTextFile(root + "/data/text/maps/" + map->name + ".inc", "\n");
  536. // Simply append to data/event_scripts.s.
  537. // TODO: In the future, this file needs more structure to allow for proper parsing.
  538. text = QString("\n\t.include \"data/scripts/maps/%1.inc\"\n").arg(map->name);
  539. text += QString("\t.include \"data/text/maps/%1.inc\"\n").arg(map->name);
  540. appendTextFile(root + "/data/event_scripts.s", text);
  541. // Simply append to data/map_events.s.
  542. text = QString("\n\t.include \"data/maps/events/%1.inc\"\n").arg(map->name);
  543. appendTextFile(root + "/data/map_events.s", text);
  544. // Simply append to data/maps/headers.inc.
  545. text = QString("\t.include \"data/maps/%1/header.inc\"\n").arg(map->name);
  546. appendTextFile(root + "/data/maps/headers.inc", text);
  547. }
  548. saveMapBorder(map);
  549. saveMapHeader(map);
  550. saveBlockdata(map);
  551. saveMapEvents(map);
  552. }
  553. void Project::saveAllDataStructures() {
  554. saveMapAttributesTable();
  555. saveAllMapAttributes();
  556. // TODO: saveMapGroupsTable();
  557. }
  558. void Project::loadTilesetAssets(Tileset* tileset) {
  559. Asm* parser = new Asm;
  560. QString category = (tileset->is_secondary == "TRUE") ? "secondary" : "primary";
  561. if (tileset->name.isNull()) {
  562. return;
  563. }
  564. QString dir_path = root + "/data/tilesets/" + category + "/" + tileset->name.replace("gTileset_", "").toLower();
  565. QString graphics_text = readTextFile(root + "/data/tilesets/graphics.inc");
  566. QList<QStringList> *graphics = parser->parse(graphics_text);
  567. QStringList *tiles_values = getLabelValues(graphics, tileset->tiles_label);
  568. QStringList *palettes_values = getLabelValues(graphics, tileset->palettes_label);
  569. QString tiles_path;
  570. if (!tiles_values->isEmpty()) {
  571. tiles_path = root + "/" + tiles_values->value(0).section('"', 1, 1);
  572. } else {
  573. tiles_path = dir_path + "/tiles.4bpp";
  574. if (tileset->is_compressed == "TRUE") {
  575. tiles_path += ".lz";
  576. }
  577. }
  578. QStringList *palette_paths = new QStringList;
  579. if (!palettes_values->isEmpty()) {
  580. for (int i = 0; i < palettes_values->length(); i++) {
  581. QString value = palettes_values->value(i);
  582. palette_paths->append(root + "/" + value.section('"', 1, 1));
  583. }
  584. } else {
  585. QString palettes_dir_path = dir_path + "/palettes";
  586. for (int i = 0; i < 16; i++) {
  587. palette_paths->append(palettes_dir_path + "/" + QString("%1").arg(i, 2, 10, QLatin1Char('0')) + ".gbapal");
  588. }
  589. }
  590. QString metatiles_path;
  591. QString metatile_attrs_path;
  592. QString metatiles_text = readTextFile(root + "/data/tilesets/metatiles.inc");
  593. QList<QStringList> *metatiles_macros = parser->parse(metatiles_text);
  594. QStringList *metatiles_values = getLabelValues(metatiles_macros, tileset->metatiles_label);
  595. if (!metatiles_values->isEmpty()) {
  596. metatiles_path = root + "/" + metatiles_values->value(0).section('"', 1, 1);
  597. } else {
  598. metatiles_path = dir_path + "/metatiles.bin";
  599. }
  600. QStringList *metatile_attrs_values = getLabelValues(metatiles_macros, tileset->metatile_attrs_label);
  601. if (!metatile_attrs_values->isEmpty()) {
  602. metatile_attrs_path = root + "/" + metatile_attrs_values->value(0).section('"', 1, 1);
  603. } else {
  604. metatile_attrs_path = dir_path + "/metatile_attributes.bin";
  605. }
  606. // tiles
  607. tiles_path = fixGraphicPath(tiles_path);
  608. QImage *image = new QImage(tiles_path);
  609. //image->setColor(0, qRgb(0xff, 0, 0)); // debug
  610. QList<QImage> *tiles = new QList<QImage>;
  611. int w = 8;
  612. int h = 8;
  613. for (int y = 0; y < image->height(); y += h)
  614. for (int x = 0; x < image->width(); x += w) {
  615. QImage tile = image->copy(x, y, w, h);
  616. tiles->append(tile);
  617. }
  618. tileset->tiles = tiles;
  619. // metatiles
  620. //qDebug() << metatiles_path;
  621. QFile metatiles_file(metatiles_path);
  622. if (metatiles_file.open(QIODevice::ReadOnly)) {
  623. QByteArray data = metatiles_file.readAll();
  624. int num_metatiles = data.length() / 16;
  625. int num_layers = 2;
  626. QList<Metatile*> *metatiles = new QList<Metatile*>;
  627. for (int i = 0; i < num_metatiles; i++) {
  628. Metatile *metatile = new Metatile;
  629. int index = i * (2 * 4 * num_layers);
  630. for (int j = 0; j < 4 * num_layers; j++) {
  631. uint16_t word = data[index++] & 0xff;
  632. word += (data[index++] & 0xff) << 8;
  633. Tile tile;
  634. tile.tile = word & 0x3ff;
  635. tile.xflip = (word >> 10) & 1;
  636. tile.yflip = (word >> 11) & 1;
  637. tile.palette = (word >> 12) & 0xf;
  638. metatile->tiles->append(tile);
  639. }
  640. metatiles->append(metatile);
  641. }
  642. tileset->metatiles = metatiles;
  643. } else {
  644. tileset->metatiles = new QList<Metatile*>;
  645. qDebug() << QString("Could not open '%1'").arg(metatiles_path);
  646. }
  647. QFile attrs_file(metatile_attrs_path);
  648. //qDebug() << metatile_attrs_path;
  649. if (attrs_file.open(QIODevice::ReadOnly)) {
  650. QByteArray data = attrs_file.readAll();
  651. int num_metatiles = data.length() / 2;
  652. for (int i = 0; i < num_metatiles; i++) {
  653. uint16_t word = data[i*2] & 0xff;
  654. word += (data[i*2 + 1] & 0xff) << 8;
  655. tileset->metatiles->value(i)->attr = word;
  656. }
  657. } else {
  658. qDebug() << QString("Could not open '%1'").arg(metatile_attrs_path);
  659. }
  660. // palettes
  661. QList<QList<QRgb>> *palettes = new QList<QList<QRgb>>;
  662. for (int i = 0; i < palette_paths->length(); i++) {
  663. QString path = palette_paths->value(i);
  664. // the palettes are not compressed. this should never happen. it's only a precaution.
  665. path = path.replace(QRegExp("\\.lz$"), "");
  666. // TODO default to .pal (JASC-PAL)
  667. // just use .gbapal for now
  668. QFile file(path);
  669. QList<QRgb> palette;
  670. if (file.open(QIODevice::ReadOnly)) {
  671. QByteArray data = file.readAll();
  672. for (int j = 0; j < 16; j++) {
  673. uint16_t word = data[j*2] & 0xff;
  674. word += (data[j*2 + 1] & 0xff) << 8;
  675. int red = word & 0x1f;
  676. int green = (word >> 5) & 0x1f;
  677. int blue = (word >> 10) & 0x1f;
  678. QRgb color = qRgb(red * 8, green * 8, blue * 8);
  679. palette.prepend(color);
  680. }
  681. } else {
  682. for (int j = 0; j < 16; j++) {
  683. palette.append(qRgb(j * 16, j * 16, j * 16));
  684. }
  685. qDebug() << QString("Could not open '%1'").arg(path);
  686. }
  687. //qDebug() << path;
  688. palettes->append(palette);
  689. }
  690. tileset->palettes = palettes;
  691. }
  692. Blockdata* Project::readBlockdata(QString path) {
  693. Blockdata *blockdata = new Blockdata;
  694. //qDebug() << path;
  695. QFile file(path);
  696. if (file.open(QIODevice::ReadOnly)) {
  697. QByteArray data = file.readAll();
  698. for (int i = 0; (i + 1) < data.length(); i += 2) {
  699. uint16_t word = (data[i] & 0xff) + ((data[i + 1] & 0xff) << 8);
  700. blockdata->addBlock(word);
  701. }
  702. }
  703. return blockdata;
  704. }
  705. Map* Project::getMap(QString map_name) {
  706. if (map_cache->contains(map_name)) {
  707. return map_cache->value(map_name);
  708. } else {
  709. Map *map = loadMap(map_name);
  710. return map;
  711. }
  712. }
  713. Tileset* Project::getTileset(QString label) {
  714. if (tileset_cache->contains(label)) {
  715. return tileset_cache->value(label);
  716. } else {
  717. Tileset *tileset = loadTileset(label);
  718. return tileset;
  719. }
  720. }
  721. QString Project::readTextFile(QString path) {
  722. QFile file(path);
  723. if (!file.open(QIODevice::ReadOnly)) {
  724. //QMessageBox::information(0, "Error", QString("Could not open '%1': ").arg(path) + file.errorString());
  725. qDebug() << QString("Could not open '%1': ").arg(path) + file.errorString();
  726. return QString();
  727. }
  728. QTextStream in(&file);
  729. QString text = "";
  730. while (!in.atEnd()) {
  731. text += in.readLine() + "\n";
  732. }
  733. return text;
  734. }
  735. void Project::saveTextFile(QString path, QString text) {
  736. QFile file(path);
  737. if (file.open(QIODevice::WriteOnly)) {
  738. file.write(text.toUtf8());
  739. } else {
  740. qDebug() << QString("Could not open '%1' for writing: ").arg(path) + file.errorString();
  741. }
  742. }
  743. void Project::appendTextFile(QString path, QString text) {
  744. QFile file(path);
  745. if (file.open(QIODevice::Append)) {
  746. file.write(text.toUtf8());
  747. } else {
  748. qDebug() << QString("Could not open '%1' for appending: ").arg(path) + file.errorString();
  749. }
  750. }
  751. void Project::readMapGroups() {
  752. QString text = readTextFile(root + "/data/maps/_groups.inc");
  753. if (text.isNull()) {
  754. return;
  755. }
  756. Asm *parser = new Asm;
  757. QList<QStringList> *commands = parser->parse(text);
  758. bool in_group_pointers = false;
  759. QStringList *groups = new QStringList;
  760. for (int i = 0; i < commands->length(); i++) {
  761. QStringList params = commands->value(i);
  762. QString macro = params.value(0);
  763. if (macro == ".label") {
  764. if (in_group_pointers) {
  765. break;
  766. }
  767. if (params.value(1) == "gMapGroups") {
  768. in_group_pointers = true;
  769. }
  770. } else if (macro == ".4byte") {
  771. if (in_group_pointers) {
  772. for (int j = 1; j < params.length(); j++) {
  773. groups->append(params.value(j));
  774. }
  775. }
  776. }
  777. }
  778. QList<QStringList*> *groupedMaps = new QList<QStringList*>;
  779. for (int i = 0; i < groups->length(); i++) {
  780. QStringList *list = new QStringList;
  781. groupedMaps->append(list);
  782. }
  783. QStringList *maps = new QStringList;
  784. int group = -1;
  785. for (int i = 0; i < commands->length(); i++) {
  786. QStringList params = commands->value(i);
  787. QString macro = params.value(0);
  788. if (macro == ".label") {
  789. group = groups->indexOf(params.value(1));
  790. } else if (macro == ".4byte") {
  791. if (group != -1) {
  792. for (int j = 1; j < params.length(); j++) {
  793. QString mapName = params.value(j);
  794. QStringList *list = groupedMaps->value(group);
  795. list->append(mapName);
  796. maps->append(mapName);
  797. map_groups->insert(mapName, group);
  798. // Build the mapping and reverse mapping between map constants and map names.
  799. QString mapConstant = Map::mapConstantFromName(mapName);
  800. mapConstantsToMapNames->insert(mapConstant, mapName);
  801. mapNamesToMapConstants->insert(mapName, mapConstant);
  802. }
  803. }
  804. }
  805. }
  806. groupNames = groups;
  807. groupedMapNames = groupedMaps;
  808. mapNames = maps;
  809. }
  810. void Project::addNewMapToGroup(QString mapName, int groupNum) {
  811. int mapIndex = mapAttributesTable->count() + 1;
  812. mapAttributesTable->insert(mapIndex, mapName);
  813. // Setup new map in memory, but don't write to file until map is actually saved later.
  814. mapNames->append(mapName);
  815. map_groups->insert(mapName, groupNum);
  816. groupedMapNames->value(groupNum)->append(mapName);
  817. Map *map = new Map;
  818. map->isPersistedToFile = false;
  819. map->setName(mapName);
  820. setNewMapHeader(map, mapIndex);
  821. setNewMapAttributes(map);
  822. getTilesets(map);
  823. setNewMapBlockdata(map);
  824. setNewMapBorder(map);
  825. setNewMapEvents(map);
  826. setNewMapConnections(map);
  827. map->commit();
  828. map->history.save();
  829. map_cache->insert(mapName, map);
  830. // QString dataDir = QString("%1/data/").arg(root);
  831. // QString dataMapsDir = QString("%1maps/").arg(dataDir);
  832. // QString newMapDataDir = QString("%1%2/").arg(dataMapsDir).arg(mapName);
  833. // // 1. Create directory data/maps/<map_name>/
  834. // if (!QDir::root().mkdir(newMapDataDir)) {
  835. // qDebug() << "Error: failed to create directory for new map. " << newMapDataDir;
  836. // return;
  837. // }
  838. // // 2. Create file data/maps/<map_name>/border.bin
  839. // QFile borderFile(newMapDataDir + "border.bin");
  840. // borderFile.open(QIODevice::WriteOnly);
  841. // QDataStream borderStream(&borderFile);
  842. // borderStream.setByteOrder(QDataStream::LittleEndian);
  843. // borderStream << qint16(0x01D4) << qint16(0x01D5) << qint16(0x01DC) << qint16(0x01DD);
  844. // borderFile.close();
  845. // // 3. Create file data/maps/<map_name>/header.inc
  846. // QFile headerFile(newMapDataDir + "header.inc");
  847. // headerFile.open(QIODevice::WriteOnly);
  848. // QTextStream headerStream(&headerFile);
  849. // headerStream << mapName << "::" << endl
  850. // << "\t.4byte " << mapName << "_MapAttributes" << endl
  851. // << "\t.4byte " << mapName << "_MapEvents" << endl
  852. // << "\t.4byte " << mapName << "_MapScripts" << endl
  853. // << "\t.4byte 0x0" << endl
  854. // << "\t.2byte BGM_DAN02" << endl
  855. // << "\t.2byte " << mapIndex << endl
  856. // << "\t.byte 0" << endl
  857. // << "\t.byte 0" << endl
  858. // << "\t.byte 11" << endl
  859. // << "\t.byte 4" << endl
  860. // << "\t.2byte 0" << endl
  861. // << "\t.byte 1" << endl
  862. // << "\t.byte 0" << endl;
  863. // headerFile.close();
  864. // // 4. Create file data/maps/<map_name>/map.bin
  865. // QFile mapFile(newMapDataDir + "map.bin");
  866. // mapFile.open(QIODevice::WriteOnly);
  867. // QDataStream mapStream(&mapFile);
  868. // mapStream.setByteOrder(QDataStream::LittleEndian);
  869. // for (int i = 0; i < 20 * 20; i++) {
  870. // mapStream << qint16(0x3001);
  871. // }
  872. // mapFile.close();
  873. // // 5. Create file data/maps/events/<map_name>.inc
  874. // QFile eventsFile(dataMapsDir + "events/" + mapName + ".inc");
  875. // eventsFile.open(QIODevice::WriteOnly);
  876. // QTextStream eventsStream(&eventsFile);
  877. // eventsStream << mapName << "_MapEvents::" << endl
  878. // << "\tmap_events 0x0, 0x0, 0x0, 0x0" << endl;
  879. // eventsFile.close();
  880. // // 6. Create file data/scripts/maps/<map_name>.inc
  881. // QFile scriptsFile(dataDir + "scripts/maps/" + mapName + ".inc");
  882. // scriptsFile.open(QIODevice::WriteOnly);
  883. // QTextStream scriptsStream(&scriptsFile);
  884. // scriptsStream << mapName << "_MapScripts::" << endl
  885. // << "\t.byte 0" << endl;
  886. // scriptsFile.close();
  887. // // 7. Create file data/text/maps/<map_name>.inc
  888. // QFile textFile(dataDir + "text/maps/" + mapName + ".inc");
  889. // textFile.open(QIODevice::WriteOnly);
  890. // QTextStream textStream(&textFile);
  891. // textStream << endl;
  892. // textFile.close();
  893. // // 8. Modify data/event_scripts.s:
  894. // QFile eventScriptsFile(dataDir + "event_scripts.s");
  895. // eventScriptsFile.open(QIODevice::Append);
  896. // QTextStream eventScriptsStream(&eventScriptsFile);
  897. // eventScriptsStream << endl
  898. // << "\t.include \"data/scripts/maps/" << mapName << ".inc\"" << endl
  899. // << "\t.include \"data/text/maps/" << mapName << ".inc\"" << endl;
  900. // eventScriptsFile.close();
  901. // // 9. Modify data/map_events.s:
  902. // QFile mapEventsFile(dataDir + "map_events.s");
  903. // mapEventsFile.open(QIODevice::Append);
  904. // QTextStream mapEventsStream(&mapEventsFile);
  905. // mapEventsStream << endl
  906. // << "\t.include \"data/maps/events/" << mapName << ".inc\"" << endl;
  907. // mapEventsFile.close();
  908. // // 10. Modify data/maps/_assets.inc
  909. // QFile assetsFile(dataMapsDir + "_assets.inc");
  910. // assetsFile.open(QIODevice::Append);
  911. // QTextStream assetsStream(&assetsFile);
  912. // assetsStream << endl
  913. // << mapName << "_MapBorder::" << endl
  914. // << "\t.incbin \"data/maps/" << mapName << "/border.bin\"" << endl
  915. // << endl
  916. // << mapName << "_MapBlockdata::" << endl
  917. // << "\t.incbin \"data/maps/" << mapName << "/map.bin\"" << endl
  918. // << endl
  919. // << "\t.align 2" << endl
  920. // << mapName << "_MapAttributes::" << endl
  921. // << "\t.4byte 0x14" << endl
  922. // << "\t.4byte 0x14" << endl
  923. // << "\t.4byte " << mapName << "_MapBorder" << endl
  924. // << "\t.4byte " << mapName << "_MapBlockdata" << endl
  925. // << "\t.4byte gTileset_General" << endl
  926. // << "\t.4byte gTileset_Pacifidlog" << endl
  927. // << endl;
  928. // assetsFile.close();
  929. // // 11. Modify data/maps/_groups.inc
  930. // // TODO:
  931. // // 12. Modify data/maps/attributes_table.inc
  932. // QFile attributesFile(dataMapsDir + "attributes_table.inc");
  933. // attributesFile.open(QIODevice::Append);
  934. // QTextStream attributesStream(&attributesFile);
  935. // attributesStream << endl
  936. // << "\t.4byte " << mapName << "_MapAttributes" << endl;
  937. // attributesFile.close();
  938. // // 13. Modify data/maps/headers.inc
  939. // QFile headersFile(dataMapsDir + "headers.inc");
  940. // headersFile.open(QIODevice::Append);
  941. // QTextStream headersStream(&headersFile);
  942. // headersStream << endl
  943. // << "\t.include \"data/maps/" << mapName << "/header.inc\"" << endl;
  944. // headersFile.close();
  945. }
  946. QString Project::getNewMapName() {
  947. // Ensure default name doesn't already exist.
  948. int i = 0;
  949. QString newMapName;
  950. do {
  951. newMapName = QString("NewMap%1").arg(++i);
  952. } while (mapNames->contains(newMapName));
  953. return newMapName;
  954. }
  955. QList<QStringList>* Project::parse(QString text) {
  956. Asm *parser = new Asm;
  957. return parser->parse(text);
  958. }
  959. QStringList Project::getLocations() {
  960. // TODO
  961. QStringList names;
  962. for (int i = 0; i < 88; i++) {
  963. names.append(QString("%1").arg(i));
  964. }
  965. return names;
  966. }
  967. QStringList Project::getVisibilities() {
  968. // TODO
  969. QStringList names;
  970. for (int i = 0; i < 16; i++) {
  971. names.append(QString("%1").arg(i));
  972. }
  973. return names;
  974. }
  975. QStringList Project::getWeathers() {
  976. // TODO
  977. QStringList names;
  978. for (int i = 0; i < 16; i++) {
  979. names.append(QString("%1").arg(i));
  980. }
  981. return names;
  982. }
  983. QStringList Project::getMapTypes() {
  984. // TODO
  985. QStringList names;
  986. for (int i = 0; i < 16; i++) {
  987. names.append(QString("%1").arg(i));
  988. }
  989. return names;
  990. }
  991. QStringList Project::getBattleScenes() {
  992. // TODO
  993. QStringList names;
  994. for (int i = 0; i < 16; i++) {
  995. names.append(QString("%1").arg(i));
  996. }
  997. return names;
  998. }
  999. QStringList Project::getSongNames() {
  1000. QStringList names;
  1001. QString text = readTextFile(root + "/include/constants/songs.h");
  1002. if (!text.isNull()) {
  1003. QStringList songDefinePrefixes;
  1004. songDefinePrefixes << "SE_" << "BGM_";
  1005. QMap<QString, int> songDefines = readCDefines(text, songDefinePrefixes);
  1006. names = songDefines.keys();
  1007. }
  1008. return names;
  1009. }
  1010. QString Project::getSongName(int songNumber) {
  1011. QStringList names;
  1012. QString text = readTextFile(root + "/include/constants/songs.h");
  1013. if (!text.isNull()) {
  1014. QStringList songDefinePrefixes;
  1015. songDefinePrefixes << "SE_" << "BGM_";
  1016. QMap<QString, int> songDefines = readCDefines(text, songDefinePrefixes);
  1017. // Loop through song defines, and fine the one with the matching song number.
  1018. QMap<QString, int>::iterator iter = songDefines.begin();
  1019. while (iter != songDefines.end()) {
  1020. if (iter.value() == songNumber) {
  1021. return iter.key();
  1022. }
  1023. iter++;
  1024. }
  1025. }
  1026. return "";
  1027. }
  1028. QMap<QString, int> Project::getMapObjGfxConstants() {
  1029. QMap<QString, int> constants;
  1030. QString text = readTextFile(root + "/include/constants/map_objects.h");
  1031. if (!text.isNull()) {
  1032. QStringList mapObjGfxPrefixes;
  1033. mapObjGfxPrefixes << "MAP_OBJ_GFX_";
  1034. constants = readCDefines(text, mapObjGfxPrefixes);
  1035. }
  1036. return constants;
  1037. }
  1038. QString Project::fixGraphicPath(QString path) {
  1039. path = path.replace(QRegExp("\\.lz$"), "");
  1040. path = path.replace(QRegExp("\\.[1248]bpp$"), ".png");
  1041. return path;
  1042. }
  1043. void Project::loadObjectPixmaps(QList<Event*> objects) {
  1044. bool needs_update = false;
  1045. for (Event *object : objects) {
  1046. if (object->pixmap.isNull()) {
  1047. needs_update = true;
  1048. break;
  1049. }
  1050. }
  1051. if (!needs_update) {
  1052. return;
  1053. }
  1054. QMap<QString, int> constants = getMapObjGfxConstants();
  1055. QString pointers_text = readTextFile(root + "/src/data/field_map_obj/map_object_graphics_info_pointers.h");
  1056. QString info_text = readTextFile(root + "/src/data/field_map_obj/map_object_graphics_info.h");
  1057. QString pic_text = readTextFile(root + "/src/data/field_map_obj/map_object_pic_tables.h");
  1058. QString assets_text = readTextFile(root + "/src/field/field_map_obj.c");
  1059. QStringList pointers = readCArray(pointers_text, "gMapObjectGraphicsInfoPointers");
  1060. for (Event *object : objects) {
  1061. if (!object->pixmap.isNull()) {
  1062. continue;
  1063. }
  1064. QString event_type = object->get("event_type");
  1065. if (event_type == "object") {
  1066. object->pixmap = QPixmap(":/images/Entities_16x16.png").copy(0, 0, 16, 16);
  1067. } else if (event_type == "warp") {
  1068. object->pixmap = QPixmap(":/images/Entities_16x16.png").copy(16, 0, 16, 16);
  1069. } else if (event_type == "trap" || event_type == "trap_weather") {
  1070. object->pixmap = QPixmap(":/images/Entities_16x16.png").copy(32, 0, 16, 16);
  1071. } else if (event_type == "sign" || event_type == "event_hidden_item" || event_type == "event_secret_base") {
  1072. object->pixmap = QPixmap(":/images/Entities_16x16.png").copy(48, 0, 16, 16);
  1073. }
  1074. if (event_type == "object") {
  1075. int sprite_id = constants.value(object->get("sprite"));
  1076. QString info_label = pointers.value(sprite_id).replace("&", "");
  1077. QString pic_label = readCArray(info_text, info_label).value(14);
  1078. QString gfx_label = readCArray(pic_text, pic_label).value(0);
  1079. gfx_label = gfx_label.section(QRegExp("[\\(\\)]"), 1, 1);
  1080. QString path = readCIncbin(assets_text, gfx_label);
  1081. if (!path.isNull()) {
  1082. path = fixGraphicPath(path);
  1083. QPixmap pixmap(root + "/" + path);
  1084. if (!pixmap.isNull()) {
  1085. object->pixmap = pixmap;
  1086. }
  1087. }
  1088. }
  1089. }
  1090. }
  1091. void Project::saveMapEvents(Map *map) {
  1092. QString path = root + QString("/data/maps/events/%1.inc").arg(map->name);
  1093. QString text = "";
  1094. if (map->events["object"].length() > 0) {
  1095. text += QString("%1::\n").arg(map->object_events_label);
  1096. for (int i = 0; i < map->events["object"].length(); i++) {
  1097. Event *object_event = map->events["object"].value(i);
  1098. int radius_x = object_event->getInt("radius_x");
  1099. int radius_y = object_event->getInt("radius_y");
  1100. QString radius = QString("%1").arg((radius_x & 0xf) + ((radius_y & 0xf) << 4));
  1101. uint16_t x = object_event->getInt("x");
  1102. uint16_t y = object_event->getInt("y");
  1103. text += QString("\tobject_event %1").arg(i + 1);
  1104. text += QString(", %1").arg(object_event->get("sprite"));
  1105. text += QString(", %1").arg(object_event->get("replacement"));
  1106. text += QString(", %1").arg(x & 0xff);
  1107. text += QString(", %1").arg((x >> 8) & 0xff);
  1108. text += QString(", %1").arg(y & 0xff);
  1109. text += QString(", %1").arg((y >> 8) & 0xff);
  1110. text += QString(", %1").arg(object_event->get("elevation"));
  1111. text += QString(", %1").arg(object_event->get("behavior"));
  1112. text += QString(", %1").arg(radius);
  1113. text += QString(", 0");
  1114. text += QString(", %1").arg(object_event->get("property"));
  1115. text += QString(", 0");
  1116. text += QString(", %1").arg(object_event->get("sight_radius"));
  1117. text += QString(", 0");
  1118. text += QString(", %1").arg(object_event->get("script_label"));
  1119. text += QString(", %1").arg(object_event->get("event_flag"));
  1120. text += QString(", 0");
  1121. text += QString(", 0");
  1122. text += "\n";
  1123. }
  1124. text += "\n";
  1125. }
  1126. if (map->events["warp"].length() > 0) {
  1127. text += QString("%1::\n").arg(map->warps_label);
  1128. for (Event *warp : map->events["warp"]) {
  1129. text += QString("\twarp_def %1").arg(warp->get("x"));
  1130. text += QString(", %1").arg(warp->get("y"));
  1131. text += QString(", %1").arg(warp->get("elevation"));
  1132. text += QString(", %1").arg(warp->get("destination_warp"));
  1133. text += QString(", %1").arg(mapNamesToMapConstants->value(warp->get("destination_map_name")));
  1134. text += "\n";
  1135. }
  1136. text += "\n";
  1137. }
  1138. if (map->events["trap"].length() + map->events["trap_weather"].length() > 0) {
  1139. text += QString("%1::\n").arg(map->coord_events_label);
  1140. for (Event *coords : map->events["trap"]) {
  1141. text += QString("\tcoord_event %1").arg(coords->get("x"));
  1142. text += QString(", %1").arg(coords->get("y"));
  1143. text += QString(", %1").arg(coords->get("elevation"));
  1144. text += QString(", 0");
  1145. text += QString(", %1").arg(coords->get("coord_unknown1"));
  1146. text += QString(", %1").arg(coords->get("coord_unknown2"));
  1147. text += QString(", 0");
  1148. text += QString(", %1").arg(coords->get("script_label"));
  1149. text += "\n";
  1150. }
  1151. for (Event *coords : map->events["trap_weather"]) {
  1152. text += QString("\tcoord_weather_event %1").arg(coords->get("x"));
  1153. text += QString(", %1").arg(coords->get("y"));
  1154. text += QString(", %1").arg(coords->get("elevation"));
  1155. text += QString(", %1").arg(coords->get("weather"));
  1156. text += "\n";
  1157. }
  1158. text += "\n";
  1159. }
  1160. if (map->events["sign"].length() +
  1161. map->events["event_hidden_item"].length() +
  1162. map->events["event_secret_base"].length() > 0)
  1163. {
  1164. text += QString("%1::\n").arg(map->bg_events_label);
  1165. for (Event *sign : map->events["sign"]) {
  1166. text += QString("\tbg_event %1").arg(sign->get("x"));
  1167. text += QString(", %1").arg(sign->get("y"));
  1168. text += QString(", %1").arg(sign->get("elevation"));
  1169. text += QString(", %1").arg(sign->get("type"));
  1170. text += QString(", 0");
  1171. text += QString(", %1").arg(sign->get("script_label"));
  1172. text += "\n";
  1173. }
  1174. for (Event *item : map->events["event_hidden_item"]) {
  1175. text += QString("\tbg_hidden_item_event %1").arg(item->get("x"));
  1176. text += QString(", %1").arg(item->get("y"));
  1177. text += QString(", %1").arg(item->get("elevation"));
  1178. text += QString(", %1").arg(item->get("item"));
  1179. text += QString(", %1").arg(item->get("flag"));
  1180. text += "\n";
  1181. }
  1182. for (Event *item : map->events["event_secret_base"]) {
  1183. text += QString("\tbg_secret_base_event %1").arg(item->get("x"));
  1184. text += QString(", %1").arg(item->get("y"));
  1185. text += QString(", %1").arg(item->get("elevation"));
  1186. text += QString(", %1").arg(item->get("secret_base_map"));
  1187. text += "\n";
  1188. }
  1189. text += "\n";
  1190. }
  1191. text += QString("%1::\n").arg(map->events_label);
  1192. text += QString("\tmap_events %1, %2, %3, %4\n")
  1193. .arg(map->object_events_label)
  1194. .arg(map->warps_label)
  1195. .arg(map->coord_events_label)
  1196. .arg(map->bg_events_label);
  1197. saveTextFile(path, text);
  1198. }
  1199. void Project::readMapEvents(Map *map) {
  1200. if (!map->isPersistedToFile) {
  1201. return;
  1202. }
  1203. // lazy
  1204. QString path = root + QString("/data/maps/events/%1.inc").arg(map->name);
  1205. QString text = readTextFile(path);
  1206. if (text.isNull()) {
  1207. return;
  1208. }
  1209. QStringList *labels = getLabelValues(parse(text), map->events_label);
  1210. map->object_events_label = labels->value(0);
  1211. map->warps_label = labels->value(1);
  1212. map->coord_events_label = labels->value(2);
  1213. map->bg_events_label = labels->value(3);
  1214. QList<QStringList> *object_events = getLabelMacros(parse(text), map->object_events_label);
  1215. map->events["object"].clear();
  1216. for (QStringList command : *object_events) {
  1217. if (command.value(0) == "object_event") {
  1218. Event *object = new Event;
  1219. object->put("map_name", map->name);
  1220. // This macro is not fixed as of writing, but it should take fewer args.
  1221. bool old_macro = false;
  1222. if (command.length() >= 20) {
  1223. command.removeAt(19);
  1224. command.removeAt(18);
  1225. command.removeAt(15);
  1226. command.removeAt(13);
  1227. command.removeAt(11);
  1228. command.removeAt(1); // id. not 0, but is just the index in the list of objects
  1229. old_macro = true;
  1230. }
  1231. int i = 1;
  1232. object->put("sprite", command.value(i++));
  1233. object->put("replacement", command.value(i++));
  1234. int16_t x = command.value(i++).toInt(nullptr, 0) | (command.value(i++).toInt(nullptr, 0) << 8);
  1235. int16_t y = command.value(i++).toInt(nullptr, 0) | (command.value(i++).toInt(nullptr, 0) << 8);
  1236. object->put("x", x);
  1237. object->put("y", y);
  1238. object->put("elevation", command.value(i++));
  1239. object->put("behavior", command.value(i++));
  1240. if (old_macro) {
  1241. int radius = command.value(i++).toInt(nullptr, 0);
  1242. object->put("radius_x", radius & 0xf);
  1243. object->put("radius_y", (radius >> 4) & 0xf);
  1244. } else {
  1245. object->put("radius_x", command.value(i++));
  1246. object->put("radius_y", command.value(i++));
  1247. }
  1248. object->put("property", command.value(i++));
  1249. object->put("sight_radius", command.value(i++));
  1250. object->put("script_label", command.value(i++));
  1251. object->put("event_flag", command.value(i++));
  1252. object->put("event_type", "object");
  1253. map->events["object"].append(object);
  1254. }
  1255. }
  1256. QList<QStringList> *warps = getLabelMacros(parse(text), map->warps_label);
  1257. map->events["warp"].clear();
  1258. for (QStringList command : *warps) {
  1259. if (command.value(0) == "warp_def") {
  1260. Event *warp = new Event;
  1261. warp->put("map_name", map->name);
  1262. int i = 1;
  1263. warp->put("x", command.value(i++));
  1264. warp->put("y", command.value(i++));
  1265. warp->put("elevation", command.value(i++));
  1266. warp->put("destination_warp", command.value(i++));
  1267. // Ensure the warp destination map constant is valid before adding it to the warps.
  1268. QString mapConstant = command.value(i++);
  1269. if (mapConstantsToMapNames->contains(mapConstant)) {
  1270. warp->put("destination_map_name", mapConstantsToMapNames->value(mapConstant));
  1271. warp->put("event_type", "warp");
  1272. map->events["warp"].append(warp);
  1273. } else {
  1274. qDebug() << QString("Destination map constant '%1' is invalid for warp").arg(mapConstant);
  1275. }
  1276. }
  1277. }
  1278. QList<QStringList> *coords = getLabelMacros(parse(text), map->coord_events_label);
  1279. map->events["trap"].clear();
  1280. map->events["trap_weather"].clear();
  1281. for (QStringList command : *coords) {
  1282. if (command.value(0) == "coord_event") {
  1283. Event *coord = new Event;
  1284. coord->put("map_name", map->name);
  1285. bool old_macro = false;
  1286. if (command.length() >= 9) {
  1287. command.removeAt(7);
  1288. command.removeAt(4);
  1289. old_macro = true;
  1290. }
  1291. int i = 1;
  1292. coord->put("x", command.value(i++));
  1293. coord->put("y", command.value(i++));
  1294. coord->put("elevation", command.value(i++));
  1295. coord->put("coord_unknown1", command.value(i++));
  1296. coord->put("coord_unknown2", command.value(i++));
  1297. coord->put("script_label", command.value(i++));
  1298. //coord_unknown3
  1299. //coord_unknown4
  1300. coord->put("event_type", "trap");
  1301. map->events["trap"].append(coord);
  1302. } else if (command.value(0) == "coord_weather_event") {
  1303. Event *coord = new Event;
  1304. coord->put("map_name", map->name);
  1305. int i = 1;
  1306. coord->put("x", command.value(i++));
  1307. coord->put("y", command.value(i++));
  1308. coord->put("elevation", command.value(i++));
  1309. coord->put("weather", command.value(i++));
  1310. coord->put("event_type", "trap_weather");
  1311. map->events["trap_weather"].append(coord);
  1312. }
  1313. }
  1314. QList<QStringList> *bgs = getLabelMacros(parse(text), map->bg_events_label);
  1315. map->events["sign"].clear();
  1316. map->events["event_hidden_item"].clear();
  1317. map->events["event_secret_base"].clear();
  1318. for (QStringList command : *bgs) {
  1319. if (command.value(0) == "bg_event") {
  1320. Event *bg = new Event;
  1321. bg->put("map_name", map->name);
  1322. int i = 1;
  1323. bg->put("x", command.value(i++));
  1324. bg->put("y", command.value(i++));
  1325. bg->put("elevation", command.value(i++));
  1326. bg->put("type", command.value(i++));
  1327. i++;
  1328. bg->put("script_label", command.value(i++));
  1329. //sign_unknown7
  1330. bg->put("event_type", "sign");
  1331. map->events["sign"].append(bg);
  1332. } else if (command.value(0) == "bg_hidden_item_event") {
  1333. Event *bg = new Event;
  1334. bg->put("map_name", map->name);
  1335. int i = 1;
  1336. bg->put("x", command.value(i++));
  1337. bg->put("y", command.value(i++));
  1338. bg->put("elevation", command.value(i++));
  1339. bg->put("item", command.value(i++));
  1340. bg->put("flag", command.value(i++));
  1341. bg->put("event_type", "event_hidden_item");
  1342. map->events["event_hidden_item"].append(bg);
  1343. } else if (command.value(0) == "bg_secret_base_event") {
  1344. Event *bg = new Event;
  1345. bg->put("map_name", map->name);
  1346. int i = 1;
  1347. bg->put("x", command.value(i++));
  1348. bg->put("y", command.value(i++));
  1349. bg->put("elevation", command.value(i++));
  1350. bg->put("secret_base_map", command.value(i++));
  1351. bg->put("event_type", "event_secret_base");
  1352. map->events["event_secret_base"].append(bg);
  1353. }
  1354. }
  1355. }
  1356. void Project::setNewMapEvents(Map *map) {
  1357. map->object_events_label = "0x0";
  1358. map->warps_label = "0x0";
  1359. map->coord_events_label = "0x0";
  1360. map->bg_events_label = "0x0";
  1361. map->events["object"].clear();
  1362. map->events["warp"].clear();
  1363. map->events["trap"].clear();
  1364. map->events["trap_weather"].clear();
  1365. map->events["sign"].clear();
  1366. map->events["event_hidden_item"].clear();
  1367. map->events["event_secret_base"].clear();
  1368. }
  1369. QStringList Project::readCArray(QString text, QString label) {
  1370. QStringList list;
  1371. if (label.isNull()) {
  1372. return list;
  1373. }
  1374. QRegExp *re = new QRegExp(QString("\\b%1\\b\\s*\\[?\\s*\\]?\\s*=\\s*\\{([^\\}]*)\\}").arg(label));
  1375. int pos = re->indexIn(text);
  1376. if (pos != -1) {
  1377. QString body = re->cap(1);
  1378. body = body.replace(QRegExp("\\s*"), "");
  1379. list = body.split(',');
  1380. /*
  1381. QRegExp *inner = new QRegExp("&?\\b([A-Za-z0-9_\\(\\)]*)\\b,");
  1382. int pos = 0;
  1383. while ((pos = inner->indexIn(body, pos)) != -1) {
  1384. list << inner->cap(1);
  1385. pos += inner->matchedLength();
  1386. }
  1387. */
  1388. }
  1389. return list;
  1390. }
  1391. QString Project::readCIncbin(QString text, QString label) {
  1392. QString path;
  1393. if (label.isNull()) {
  1394. return path;
  1395. }
  1396. QRegExp *re = new QRegExp(QString(
  1397. "\\b%1\\b"
  1398. "\\s*\\[?\\s*\\]?\\s*=\\s*"
  1399. "INCBIN_[US][0-9][0-9]?"
  1400. "\\(\"([^\"]*)\"\\)").arg(label));
  1401. int pos = re->indexIn(text);
  1402. if (pos != -1) {
  1403. path = re->cap(1);
  1404. }
  1405. return path;
  1406. }
  1407. QMap<QString, int> Project::readCDefines(QString text, QStringList prefixes) {
  1408. QMap<QString, int> defines;
  1409. QString combinedPrefixes = "[" + prefixes.join('|') + "]";
  1410. QRegularExpression re(QString("#define\\s+(?<defineName>%1\\w+)\\s(?<defineValue>\\w+)").arg(combinedPrefixes));
  1411. QRegularExpressionMatchIterator iter = re.globalMatch(text);
  1412. while (iter.hasNext()) {
  1413. QRegularExpressionMatch match = iter.next();
  1414. QString name = match.captured("defineName");
  1415. QString value = match.captured("defineValue");
  1416. bool valid;
  1417. int parsedValue = value.startsWith("0x") ? value.toInt(&valid, 16) : value.toInt(&valid, 10);
  1418. if (valid) {
  1419. if (!defines.contains(name)) {
  1420. defines.insert(name, parsedValue);
  1421. } else {
  1422. qDebug() << QString("Define '%1' is defined multiple times'").arg(name);
  1423. }
  1424. } else {
  1425. qDebug() << QString("Failed to parse define '%1' value '%2' as base 10 or hexadecimal value").arg(name, value);
  1426. }
  1427. }
  1428. return defines;
  1429. }