暂无描述

project.cpp 59KB

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