Нема описа

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518
  1. #include "parseutil.h"
  2. #include "project.h"
  3. #include "tile.h"
  4. #include "tileset.h"
  5. #include "event.h"
  6. #include <QDebug>
  7. #include <QDir>
  8. #include <QFile>
  9. #include <QTextStream>
  10. #include <QStandardItem>
  11. #include <QMessageBox>
  12. #include <QRegularExpression>
  13. Project::Project()
  14. {
  15. groupNames = new QStringList;
  16. map_groups = new QMap<QString, int>;
  17. mapNames = new QStringList;
  18. itemNames = new QStringList;
  19. flagNames = new QStringList;
  20. varNames = new QStringList;
  21. map_cache = new QMap<QString, Map*>;
  22. mapConstantsToMapNames = new QMap<QString, QString>;
  23. mapNamesToMapConstants = new QMap<QString, QString>;
  24. tileset_cache = new QMap<QString, Tileset*>;
  25. }
  26. QString Project::getProjectTitle() {
  27. if (!root.isNull()) {
  28. return root.section('/', -1);
  29. } else {
  30. return QString();
  31. }
  32. }
  33. Map* Project::loadMap(QString map_name) {
  34. Map *map;
  35. if (map_cache->contains(map_name)) {
  36. map = map_cache->value(map_name);
  37. // TODO: uncomment when undo/redo history is fully implemented for all actions.
  38. if (true/*map->hasUnsavedChanges()*/) {
  39. return map;
  40. }
  41. } else {
  42. map = new Map;
  43. map->setName(map_name);
  44. }
  45. readMapHeader(map);
  46. readMapLayout(map);
  47. readMapEvents(map);
  48. loadMapConnections(map);
  49. map->commit();
  50. map->history.save();
  51. map_cache->insert(map_name, map);
  52. return map;
  53. }
  54. void Project::loadMapConnections(Map *map) {
  55. if (!map->isPersistedToFile) {
  56. return;
  57. }
  58. map->connections.clear();
  59. map->connection_items.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 = parseAsm(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. if (macro == ".ifdef")
  125. continue;
  126. if (macro == ".ifndef")
  127. continue;
  128. for (int j = 1; j < params.length(); j++) {
  129. values->append(params.value(j));
  130. }
  131. }
  132. return values;
  133. }
  134. void Project::readMapHeader(Map* map) {
  135. if (!map->isPersistedToFile) {
  136. return;
  137. }
  138. QString label = map->name;
  139. ParseUtil *parser = new ParseUtil;
  140. QString header_text = readTextFile(root + "/data/maps/" + label + "/header.inc");
  141. if (header_text.isNull()) {
  142. return;
  143. }
  144. QStringList *header = getLabelValues(parser->parseAsm(header_text), label);
  145. map->layout_label = header->value(0);
  146. map->events_label = header->value(1);
  147. map->scripts_label = header->value(2);
  148. map->connections_label = header->value(3);
  149. map->song = header->value(4);
  150. map->layout_id = header->value(5);
  151. map->location = header->value(6);
  152. map->visibility = header->value(7);
  153. map->weather = header->value(8);
  154. map->type = header->value(9);
  155. map->unknown = header->value(10);
  156. map->show_location = header->value(11);
  157. map->battle_scene = header->value(12);
  158. }
  159. void Project::setNewMapHeader(Map* map, int mapIndex) {
  160. map->layout_label = QString("%1_Layout").arg(map->name);
  161. map->events_label = QString("%1_MapEvents").arg(map->name);;
  162. map->scripts_label = QString("%1_MapScripts").arg(map->name);;
  163. map->connections_label = "0x0";
  164. map->song = "MUS_DAN02";
  165. map->layout_id = QString("%1").arg(mapIndex);
  166. map->location = "0";
  167. map->visibility = "0";
  168. map->weather = "2";
  169. map->type = "1";
  170. map->unknown = "0";
  171. map->show_location = "1";
  172. map->battle_scene = "0";
  173. }
  174. void Project::saveMapHeader(Map *map) {
  175. QString label = map->name;
  176. QString header_path = root + "/data/maps/" + label + "/header.inc";
  177. QString text = "";
  178. text += QString("%1::\n").arg(label);
  179. text += QString("\t.4byte %1\n").arg(map->layout_label);
  180. text += QString("\t.4byte %1\n").arg(map->events_label);
  181. text += QString("\t.4byte %1\n").arg(map->scripts_label);
  182. if (map->connections.length() == 0) {
  183. map->connections_label = "0x0";
  184. } else {
  185. map->connections_label = QString("%1_MapConnections").arg(map->name);
  186. }
  187. text += QString("\t.4byte %1\n").arg(map->connections_label);
  188. text += QString("\t.2byte %1\n").arg(map->song);
  189. text += QString("\t.2byte %1\n").arg(map->layout_id);
  190. text += QString("\t.byte %1\n").arg(map->location);
  191. text += QString("\t.byte %1\n").arg(map->visibility);
  192. text += QString("\t.byte %1\n").arg(map->weather);
  193. text += QString("\t.byte %1\n").arg(map->type);
  194. text += QString("\t.2byte %1\n").arg(map->unknown);
  195. text += QString("\t.byte %1\n").arg(map->show_location);
  196. text += QString("\t.byte %1\n").arg(map->battle_scene);
  197. saveTextFile(header_path, text);
  198. }
  199. void Project::saveMapConnections(Map *map) {
  200. QString path = root + "/data/maps/" + map->name + "/connections.inc";
  201. if (map->connections.length() > 0) {
  202. QString text = "";
  203. QString connectionsListLabel = QString("%1_MapConnectionsList").arg(map->name);
  204. int numValidConnections = 0;
  205. text += QString("%1::\n").arg(connectionsListLabel);
  206. for (Connection* connection : map->connections) {
  207. if (mapNamesToMapConstants->contains(connection->map_name)) {
  208. text += QString("\tconnection %1, %2, %3\n")
  209. .arg(connection->direction)
  210. .arg(connection->offset)
  211. .arg(mapNamesToMapConstants->value(connection->map_name));
  212. numValidConnections++;
  213. } else {
  214. qDebug() << QString("Failed to write map connection. %1 not a valid map name").arg(connection->map_name);
  215. }
  216. }
  217. text += QString("\n");
  218. text += QString("%1::\n").arg(map->connections_label);
  219. text += QString("\t.4byte %1\n").arg(numValidConnections);
  220. text += QString("\t.4byte %1\n").arg(connectionsListLabel);
  221. saveTextFile(path, text);
  222. } else {
  223. deleteFile(path);
  224. }
  225. updateMapsWithConnections(map);
  226. }
  227. void Project::updateMapsWithConnections(Map *map) {
  228. if (map->connections.length() > 0) {
  229. if (!mapsWithConnections.contains(map->name)) {
  230. mapsWithConnections.append(map->name);
  231. }
  232. } else {
  233. if (mapsWithConnections.contains(map->name)) {
  234. mapsWithConnections.removeOne(map->name);
  235. }
  236. }
  237. }
  238. void Project::readMapLayoutsTable() {
  239. int curIndex = 1;
  240. QString layoutsText = readTextFile(getMapLayoutsTableFilepath());
  241. QList<QStringList>* values = parseAsm(layoutsText);
  242. bool inLayoutPointers = false;
  243. for (int i = 0; i < values->length(); i++) {
  244. QStringList params = values->value(i);
  245. QString macro = params.value(0);
  246. if (macro == ".label") {
  247. if (inLayoutPointers) {
  248. break;
  249. }
  250. if (params.value(1) == "gMapLayouts") {
  251. inLayoutPointers = true;
  252. }
  253. } else if (macro == ".4byte" && inLayoutPointers) {
  254. QString layoutName = params.value(1);
  255. mapLayoutsTable.append(layoutName);
  256. }
  257. }
  258. // Deep copy
  259. mapLayoutsTableMaster = mapLayoutsTable;
  260. mapLayoutsTableMaster.detach();
  261. }
  262. void Project::saveMapLayoutsTable() {
  263. QString text = "";
  264. text += QString("\t.align 2\n");
  265. text += QString("gMapLayouts::\n");
  266. for (QString layoutName : mapLayoutsTableMaster) {
  267. text += QString("\t.4byte %1\n").arg(layoutName);
  268. }
  269. saveTextFile(getMapLayoutsTableFilepath(), text);
  270. }
  271. QString Project::getMapLayoutsTableFilepath() {
  272. return QString("%1/data/layouts_table.inc").arg(root);
  273. }
  274. QStringList* Project::readLayoutValues(QString layoutLabel) {
  275. ParseUtil *parser = new ParseUtil;
  276. QString layoutText = readTextFile(getMapLayoutFilepath(layoutLabel));
  277. if (layoutText.isNull()) {
  278. return NULL;
  279. }
  280. QStringList *layoutValues = getLabelValues(parser->parseAsm(layoutText), layoutLabel);
  281. QString borderLabel = layoutValues->value(2);
  282. QString blockdataLabel = layoutValues->value(3);
  283. QStringList *borderValues = getLabelValues(parser->parseAsm(layoutText), borderLabel);
  284. QString borderPath = borderValues->value(0).replace("\"", "");
  285. layoutValues->append(borderPath);
  286. QStringList *blockdataValues = getLabelValues(parser->parseAsm(layoutText), blockdataLabel);
  287. QString blockdataPath = blockdataValues->value(0).replace("\"", "");
  288. layoutValues->append(blockdataPath);
  289. if (layoutValues->size() != 8) {
  290. qDebug() << "Error: Unexpected number of properties in layout '" << layoutLabel << "'";
  291. return NULL;
  292. }
  293. return layoutValues;
  294. }
  295. void Project::readMapLayout(Map* map) {
  296. if (!map->isPersistedToFile) {
  297. return;
  298. }
  299. MapLayout *layout;
  300. if (!mapLayouts.contains(map->layout_label)) {
  301. QStringList *layoutValues = readLayoutValues(map->layout->label);
  302. if (layoutValues == NULL) {
  303. return;
  304. }
  305. layout = new MapLayout();
  306. mapLayouts.insert(map->layout_label, layout);
  307. layout->name = MapLayout::getNameFromLabel(map->layout_label);
  308. layout->label = map->layout_label;
  309. layout->width = layoutValues->value(0);
  310. layout->height = layoutValues->value(1);
  311. layout->border_label = layoutValues->value(2);
  312. layout->blockdata_label = layoutValues->value(3);
  313. layout->tileset_primary_label = layoutValues->value(4);
  314. layout->tileset_secondary_label = layoutValues->value(5);
  315. layout->border_path = layoutValues->value(6);
  316. layout->blockdata_path = layoutValues->value(7);
  317. map->layout = layout;
  318. } else {
  319. map->layout = mapLayouts[map->layout_label];
  320. }
  321. getMapTilesets(map);
  322. loadBlockdata(map);
  323. loadMapBorder(map);
  324. }
  325. void Project::readAllMapLayouts() {
  326. mapLayouts.clear();
  327. for (int i = 0; i < mapLayoutsTable.size(); i++) {
  328. QString layoutLabel = mapLayoutsTable[i];
  329. QStringList *layoutValues = readLayoutValues(layoutLabel);
  330. if (layoutValues == NULL) {
  331. return;
  332. }
  333. MapLayout *layout = new MapLayout();
  334. layout->name = MapLayout::getNameFromLabel(layoutLabel);
  335. layout->label = layoutLabel;
  336. layout->index = i;
  337. layout->width = layoutValues->value(0);
  338. layout->height = layoutValues->value(1);
  339. layout->border_label = layoutValues->value(2);
  340. layout->blockdata_label = layoutValues->value(3);
  341. layout->tileset_primary_label = layoutValues->value(4);
  342. layout->tileset_secondary_label = layoutValues->value(5);
  343. layout->border_path = layoutValues->value(6);
  344. layout->blockdata_path = layoutValues->value(7);
  345. mapLayouts.insert(layoutLabel, layout);
  346. }
  347. // Deep copy
  348. mapLayoutsMaster = mapLayouts;
  349. mapLayoutsMaster.detach();
  350. }
  351. void Project::saveAllMapLayouts() {
  352. for (QString layoutName : mapLayoutsTableMaster) {
  353. MapLayout *layout = mapLayouts.value(layoutName);
  354. QString text = QString("%1::\n").arg(layout->border_label);
  355. text += QString("\t.incbin \"%1\"\n").arg(layout->border_path);
  356. text += QString("\n");
  357. text += QString("%1::\n").arg(layout->blockdata_label);
  358. text += QString("\t.incbin \"%1\"\n").arg(layout->blockdata_path);
  359. text += QString("\n");
  360. text += QString("\t.align 2\n");
  361. text += QString("%1::\n").arg(layoutName);
  362. text += QString("\t.4byte %1\n").arg(layout->width);
  363. text += QString("\t.4byte %1\n").arg(layout->height);
  364. text += QString("\t.4byte %1\n").arg(layout->border_label);
  365. text += QString("\t.4byte %1\n").arg(layout->blockdata_label);
  366. text += QString("\t.4byte %1\n").arg(layout->tileset_primary_label);
  367. text += QString("\t.4byte %1\n").arg(layout->tileset_secondary_label);
  368. text += QString("\n");
  369. saveTextFile(getMapLayoutFilepath(layout->label), text);
  370. }
  371. }
  372. QString Project::getMapLayoutFilepath(QString layoutLabel) {
  373. return QString("%1/data/layouts/%2/layout.inc").arg(root).arg(MapLayout::getNameFromLabel(layoutLabel));
  374. }
  375. void Project::setNewMapLayout(Map* map) {
  376. MapLayout *layout = new MapLayout();
  377. layout->label = QString("%1_Layout").arg(map->name);
  378. layout->name = MapLayout::getNameFromLabel(layout->label);
  379. layout->width = "20";
  380. layout->height = "20";
  381. layout->border_label = QString("%1_MapBorder").arg(map->name);
  382. layout->border_path = QString("data/layouts/%1/border.bin").arg(map->name);
  383. layout->blockdata_label = QString("%1_MapBlockdata").arg(map->name);
  384. layout->blockdata_path = QString("data/layouts/%1/map.bin").arg(map->name);
  385. layout->tileset_primary_label = "gTileset_General";
  386. layout->tileset_secondary_label = "gTileset_Petalburg";
  387. map->layout = layout;
  388. map->layout_label = layout->label;
  389. // Insert new entry into the global map layouts.
  390. mapLayouts.insert(layout->label, layout);
  391. mapLayoutsTable.append(layout->label);
  392. }
  393. void Project::saveMapGroupsTable() {
  394. QString text = "";
  395. int groupNum = 0;
  396. for (QStringList mapNames : groupedMapNames) {
  397. text += QString("\t.align 2\n");
  398. text += QString("gMapGroup%1::\n").arg(groupNum);
  399. for (QString mapName : mapNames) {
  400. text += QString("\t.4byte %1\n").arg(mapName);
  401. }
  402. text += QString("\n");
  403. groupNum++;
  404. }
  405. text += QString("\t.align 2\n");
  406. text += QString("gMapGroups::\n");
  407. for (int i = 0; i < groupNum; i++) {
  408. text += QString("\t.4byte gMapGroup%1\n").arg(i);
  409. }
  410. saveTextFile(root + "/data/maps/groups.inc", text);
  411. }
  412. void Project::saveMapConstantsHeader() {
  413. QString text = QString("#ifndef GUARD_CONSTANTS_MAPS_H\n");
  414. text += QString("#define GUARD_CONSTANTS_MAPS_H\n");
  415. text += QString("\n");
  416. int groupNum = 0;
  417. for (QStringList mapNames : groupedMapNames) {
  418. text += QString("// Map Group %1\n").arg(groupNum);
  419. int maxLength = 0;
  420. for (QString mapName : mapNames) {
  421. QString mapConstantName = mapNamesToMapConstants->value(mapName);
  422. if (mapConstantName.length() > maxLength)
  423. maxLength = mapConstantName.length();
  424. }
  425. int groupIndex = 0;
  426. for (QString mapName : mapNames) {
  427. QString mapConstantName = mapNamesToMapConstants->value(mapName);
  428. text += QString("#define %1%2(%3 | (%4 << 8))\n")
  429. .arg(mapConstantName)
  430. .arg(QString(" ").repeated(maxLength - mapConstantName.length() + 1))
  431. .arg(groupIndex)
  432. .arg(groupNum);
  433. groupIndex++;
  434. }
  435. text += QString("\n");
  436. groupNum++;
  437. }
  438. text += QString("\n");
  439. text += QString("#define MAP_NONE (0x7F | (0x7F << 8))\n");
  440. text += QString("#define MAP_UNDEFINED (0xFF | (0xFF << 8))\n\n\n");
  441. text += QString("#define MAP_GROUP(map) (MAP_##map >> 8)\n");
  442. text += QString("#define MAP_NUM(map) (MAP_##map & 0xFF)\n\n");
  443. text += QString("#endif // GUARD_CONSTANTS_MAPS_H\n");
  444. saveTextFile(root + "/include/constants/maps.h", text);
  445. }
  446. void Project::getMapTilesets(Map* map) {
  447. if (map->layout->has_unsaved_changes) {
  448. return;
  449. }
  450. map->layout->tileset_primary = getTileset(map->layout->tileset_primary_label);
  451. map->layout->tileset_secondary = getTileset(map->layout->tileset_secondary_label);
  452. }
  453. Tileset* Project::loadTileset(QString label) {
  454. ParseUtil *parser = new ParseUtil;
  455. QString headers_text = readTextFile(root + "/data/tilesets/headers.inc");
  456. QStringList *values = getLabelValues(parser->parseAsm(headers_text), label);
  457. Tileset *tileset = new Tileset;
  458. tileset->name = label;
  459. tileset->is_compressed = values->value(0);
  460. tileset->is_secondary = values->value(1);
  461. tileset->padding = values->value(2);
  462. tileset->tiles_label = values->value(3);
  463. tileset->palettes_label = values->value(4);
  464. tileset->metatiles_label = values->value(5);
  465. tileset->metatile_attrs_label = values->value(6);
  466. tileset->callback_label = values->value(7);
  467. loadTilesetAssets(tileset);
  468. tileset_cache->insert(label, tileset);
  469. return tileset;
  470. }
  471. void Project::loadBlockdata(Map* map) {
  472. if (!map->isPersistedToFile || map->layout->has_unsaved_changes) {
  473. return;
  474. }
  475. QString path = QString("%1/%2").arg(root).arg(map->layout->blockdata_path);
  476. map->layout->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->layout->blockdata = blockdata;
  484. }
  485. void Project::loadMapBorder(Map *map) {
  486. if (!map->isPersistedToFile || map->layout->has_unsaved_changes) {
  487. return;
  488. }
  489. QString path = QString("%1/%2").arg(root).arg(map->layout->border_path);
  490. map->layout->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->layout->border = blockdata;
  499. }
  500. void Project::saveMapBorder(Map *map) {
  501. QString path = QString("%1/%2").arg(root).arg(map->layout->border_path);
  502. writeBlockdata(path, map->layout->border);
  503. }
  504. void Project::saveBlockdata(Map* map) {
  505. QString path = QString("%1/%2").arg(root).arg(map->layout->blockdata_path);
  506. writeBlockdata(path, map->layout->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. } else {
  515. qDebug() << "Failed to open blockdata file for writing: '" << path << "'";
  516. }
  517. }
  518. void Project::saveAllMaps() {
  519. QList<QString> keys = map_cache->keys();
  520. for (int i = 0; i < keys.length(); i++) {
  521. QString key = keys.value(i);
  522. Map* map = map_cache->value(key);
  523. saveMap(map);
  524. }
  525. }
  526. void Project::saveMap(Map *map) {
  527. // Create/Modify a few collateral files for brand new maps.
  528. if (!map->isPersistedToFile) {
  529. QString newMapDataDir = QString(root + "/data/maps/%1").arg(map->name);
  530. if (!QDir::root().mkdir(newMapDataDir)) {
  531. qDebug() << "Error: failed to create directory for new map. " << newMapDataDir;
  532. }
  533. QString newLayoutDir = QString(root + "/data/layouts/%1").arg(map->name);
  534. if (!QDir::root().mkdir(newLayoutDir)) {
  535. qDebug() << "Error: failed to create directory for new layout. " << newLayoutDir;
  536. }
  537. // TODO: In the future, these files needs more structure to allow for proper parsing/saving.
  538. // Create file data/maps/<map_name>/scripts.inc
  539. QString text = QString("%1_MapScripts::\n\t.byte 0\n").arg(map->name);
  540. saveTextFile(root + "/data/maps/" + map->name + "/scripts.inc", text);
  541. // Create file data/maps/<map_name>/text.inc
  542. saveTextFile(root + "/data/maps/" + map->name + "/text.inc", "\n");
  543. // Simply append to data/event_scripts.s.
  544. text = QString("\n\t.include \"data/maps/%1/scripts.inc\"\n").arg(map->name);
  545. text += QString("\t.include \"data/maps/%1/text.inc\"\n").arg(map->name);
  546. appendTextFile(root + "/data/event_scripts.s", text);
  547. // Simply append to data/map_events.s.
  548. text = QString("\n\t.include \"data/maps/%1/events.inc\"\n").arg(map->name);
  549. appendTextFile(root + "/data/map_events.s", text);
  550. // Simply append to data/maps/headers.inc.
  551. text = QString("\t.include \"data/maps/%1/header.inc\"\n").arg(map->name);
  552. appendTextFile(root + "/data/maps/headers.inc", text);
  553. // Simply append to data/layouts.inc.
  554. text = QString("\t.include \"data/layouts/%1/layout.inc\"\n").arg(map->layout->name);
  555. appendTextFile(root + "/data/layouts.inc", text);
  556. }
  557. saveMapBorder(map);
  558. saveMapHeader(map);
  559. saveMapConnections(map);
  560. saveBlockdata(map);
  561. saveMapEvents(map);
  562. // Update global data structures with current map data.
  563. updateMapLayout(map);
  564. map->isPersistedToFile = true;
  565. map->layout->has_unsaved_changes = false;
  566. }
  567. void Project::updateMapLayout(Map* map) {
  568. if (!mapLayoutsTableMaster.contains(map->layout_label)) {
  569. mapLayoutsTableMaster.append(map->layout_label);
  570. }
  571. // Deep copy
  572. MapLayout *layout = mapLayouts.value(map->layout_label);
  573. MapLayout *newLayout = new MapLayout();
  574. *newLayout = *layout;
  575. mapLayoutsMaster.insert(map->layout_label, newLayout);
  576. }
  577. void Project::saveAllDataStructures() {
  578. saveMapLayoutsTable();
  579. saveAllMapLayouts();
  580. saveMapGroupsTable();
  581. saveMapConstantsHeader();
  582. saveMapsWithConnections();
  583. }
  584. void Project::loadTilesetAssets(Tileset* tileset) {
  585. ParseUtil* parser = new ParseUtil;
  586. QString category = (tileset->is_secondary == "TRUE") ? "secondary" : "primary";
  587. if (tileset->name.isNull()) {
  588. return;
  589. }
  590. QString dir_path = root + "/data/tilesets/" + category + "/" + tileset->name.replace("gTileset_", "").toLower();
  591. QString graphics_text = readTextFile(root + "/data/tilesets/graphics.inc");
  592. QList<QStringList> *graphics = parser->parseAsm(graphics_text);
  593. QStringList *tiles_values = getLabelValues(graphics, tileset->tiles_label);
  594. QStringList *palettes_values = getLabelValues(graphics, tileset->palettes_label);
  595. QString tiles_path;
  596. if (!tiles_values->isEmpty()) {
  597. tiles_path = root + "/" + tiles_values->value(0).section('"', 1, 1);
  598. } else {
  599. tiles_path = dir_path + "/tiles.4bpp";
  600. if (tileset->is_compressed == "TRUE") {
  601. tiles_path += ".lz";
  602. }
  603. }
  604. QStringList *palette_paths = new QStringList;
  605. if (!palettes_values->isEmpty()) {
  606. for (int i = 0; i < palettes_values->length(); i++) {
  607. QString value = palettes_values->value(i);
  608. palette_paths->append(root + "/" + value.section('"', 1, 1));
  609. }
  610. } else {
  611. QString palettes_dir_path = dir_path + "/palettes";
  612. for (int i = 0; i < 16; i++) {
  613. palette_paths->append(palettes_dir_path + "/" + QString("%1").arg(i, 2, 10, QLatin1Char('0')) + ".gbapal");
  614. }
  615. }
  616. QString metatiles_path;
  617. QString metatile_attrs_path;
  618. QString metatiles_text = readTextFile(root + "/data/tilesets/metatiles.inc");
  619. QList<QStringList> *metatiles_macros = parser->parseAsm(metatiles_text);
  620. QStringList *metatiles_values = getLabelValues(metatiles_macros, tileset->metatiles_label);
  621. if (!metatiles_values->isEmpty()) {
  622. metatiles_path = root + "/" + metatiles_values->value(0).section('"', 1, 1);
  623. } else {
  624. metatiles_path = dir_path + "/metatiles.bin";
  625. }
  626. QStringList *metatile_attrs_values = getLabelValues(metatiles_macros, tileset->metatile_attrs_label);
  627. if (!metatile_attrs_values->isEmpty()) {
  628. metatile_attrs_path = root + "/" + metatile_attrs_values->value(0).section('"', 1, 1);
  629. } else {
  630. metatile_attrs_path = dir_path + "/metatile_attributes.bin";
  631. }
  632. // tiles
  633. tiles_path = fixGraphicPath(tiles_path);
  634. QImage *image = new QImage(tiles_path);
  635. //image->setColor(0, qRgb(0xff, 0, 0)); // debug
  636. QList<QImage> *tiles = new QList<QImage>;
  637. int w = 8;
  638. int h = 8;
  639. for (int y = 0; y < image->height(); y += h)
  640. for (int x = 0; x < image->width(); x += w) {
  641. QImage tile = image->copy(x, y, w, h);
  642. tiles->append(tile);
  643. }
  644. tileset->tiles = tiles;
  645. // metatiles
  646. QFile metatiles_file(metatiles_path);
  647. if (metatiles_file.open(QIODevice::ReadOnly)) {
  648. QByteArray data = metatiles_file.readAll();
  649. int num_metatiles = data.length() / 16;
  650. int num_layers = 2;
  651. QList<Metatile*> *metatiles = new QList<Metatile*>;
  652. for (int i = 0; i < num_metatiles; i++) {
  653. Metatile *metatile = new Metatile;
  654. int index = i * (2 * 4 * num_layers);
  655. for (int j = 0; j < 4 * num_layers; j++) {
  656. uint16_t word = data[index++] & 0xff;
  657. word += (data[index++] & 0xff) << 8;
  658. Tile tile;
  659. tile.tile = word & 0x3ff;
  660. tile.xflip = (word >> 10) & 1;
  661. tile.yflip = (word >> 11) & 1;
  662. tile.palette = (word >> 12) & 0xf;
  663. metatile->tiles->append(tile);
  664. }
  665. metatiles->append(metatile);
  666. }
  667. tileset->metatiles = metatiles;
  668. } else {
  669. tileset->metatiles = new QList<Metatile*>;
  670. qDebug() << QString("Could not open '%1'").arg(metatiles_path);
  671. }
  672. QFile attrs_file(metatile_attrs_path);
  673. //qDebug() << metatile_attrs_path;
  674. if (attrs_file.open(QIODevice::ReadOnly)) {
  675. QByteArray data = attrs_file.readAll();
  676. int num_metatiles = data.length() / 2;
  677. for (int i = 0; i < num_metatiles; i++) {
  678. uint16_t word = data[i*2] & 0xff;
  679. word += (data[i*2 + 1] & 0xff) << 8;
  680. tileset->metatiles->value(i)->attr = word;
  681. }
  682. } else {
  683. qDebug() << QString("Could not open '%1'").arg(metatile_attrs_path);
  684. }
  685. // palettes
  686. QList<QList<QRgb>> *palettes = new QList<QList<QRgb>>;
  687. for (int i = 0; i < palette_paths->length(); i++) {
  688. QString path = palette_paths->value(i);
  689. // the palettes are not compressed. this should never happen. it's only a precaution.
  690. path = path.replace(QRegExp("\\.lz$"), "");
  691. // TODO default to .pal (JASC-PAL)
  692. // just use .gbapal for now
  693. QFile file(path);
  694. QList<QRgb> palette;
  695. if (file.open(QIODevice::ReadOnly)) {
  696. QByteArray data = file.readAll();
  697. for (int j = 0; j < 16; j++) {
  698. uint16_t word = data[j*2] & 0xff;
  699. word += (data[j*2 + 1] & 0xff) << 8;
  700. int red = word & 0x1f;
  701. int green = (word >> 5) & 0x1f;
  702. int blue = (word >> 10) & 0x1f;
  703. QRgb color = qRgb(red * 8, green * 8, blue * 8);
  704. palette.prepend(color);
  705. }
  706. } else {
  707. for (int j = 0; j < 16; j++) {
  708. palette.append(qRgb(j * 16, j * 16, j * 16));
  709. }
  710. qDebug() << QString("Could not open palette path '%1'").arg(path);
  711. }
  712. palettes->append(palette);
  713. }
  714. tileset->palettes = palettes;
  715. }
  716. Blockdata* Project::readBlockdata(QString path) {
  717. Blockdata *blockdata = new Blockdata;
  718. QFile file(path);
  719. if (file.open(QIODevice::ReadOnly)) {
  720. QByteArray data = file.readAll();
  721. for (int i = 0; (i + 1) < data.length(); i += 2) {
  722. uint16_t word = (data[i] & 0xff) + ((data[i + 1] & 0xff) << 8);
  723. blockdata->addBlock(word);
  724. }
  725. } else {
  726. qDebug() << "Failed to open blockdata path '" << path << "'";
  727. }
  728. return blockdata;
  729. }
  730. Map* Project::getMap(QString map_name) {
  731. if (map_cache->contains(map_name)) {
  732. return map_cache->value(map_name);
  733. } else {
  734. Map *map = loadMap(map_name);
  735. return map;
  736. }
  737. }
  738. Tileset* Project::getTileset(QString label) {
  739. if (tileset_cache->contains(label)) {
  740. return tileset_cache->value(label);
  741. } else {
  742. Tileset *tileset = loadTileset(label);
  743. return tileset;
  744. }
  745. }
  746. QString Project::readTextFile(QString path) {
  747. QFile file(path);
  748. if (!file.open(QIODevice::ReadOnly)) {
  749. //QMessageBox::information(0, "Error", QString("Could not open '%1': ").arg(path) + file.errorString());
  750. qDebug() << QString("Could not open '%1': ").arg(path) + file.errorString();
  751. return QString();
  752. }
  753. QTextStream in(&file);
  754. QString text = "";
  755. while (!in.atEnd()) {
  756. text += in.readLine() + "\n";
  757. }
  758. return text;
  759. }
  760. void Project::saveTextFile(QString path, QString text) {
  761. QFile file(path);
  762. if (file.open(QIODevice::WriteOnly)) {
  763. file.write(text.toUtf8());
  764. } else {
  765. qDebug() << QString("Could not open '%1' for writing: ").arg(path) + file.errorString();
  766. }
  767. }
  768. void Project::appendTextFile(QString path, QString text) {
  769. QFile file(path);
  770. if (file.open(QIODevice::Append)) {
  771. file.write(text.toUtf8());
  772. } else {
  773. qDebug() << QString("Could not open '%1' for appending: ").arg(path) + file.errorString();
  774. }
  775. }
  776. void Project::deleteFile(QString path) {
  777. QFile file(path);
  778. if (file.exists() && !file.remove()) {
  779. qDebug() << QString("Could not delete file '%1': ").arg(path) + file.errorString();
  780. }
  781. }
  782. void Project::readMapGroups() {
  783. QString text = readTextFile(root + "/data/maps/groups.inc");
  784. if (text.isNull()) {
  785. return;
  786. }
  787. ParseUtil *parser = new ParseUtil;
  788. QList<QStringList> *commands = parser->parseAsm(text);
  789. bool in_group_pointers = false;
  790. QStringList *groups = new QStringList;
  791. for (int i = 0; i < commands->length(); i++) {
  792. QStringList params = commands->value(i);
  793. QString macro = params.value(0);
  794. if (macro == ".label") {
  795. if (in_group_pointers) {
  796. break;
  797. }
  798. if (params.value(1) == "gMapGroups") {
  799. in_group_pointers = true;
  800. }
  801. } else if (macro == ".4byte") {
  802. if (in_group_pointers) {
  803. for (int j = 1; j < params.length(); j++) {
  804. groups->append(params.value(j));
  805. }
  806. }
  807. }
  808. }
  809. QList<QStringList> groupedMaps;
  810. for (int i = 0; i < groups->length(); i++) {
  811. groupedMaps.append(QStringList());
  812. }
  813. QStringList *maps = new QStringList;
  814. int group = -1;
  815. for (int i = 0; i < commands->length(); i++) {
  816. QStringList params = commands->value(i);
  817. QString macro = params.value(0);
  818. if (macro == ".label") {
  819. group = groups->indexOf(params.value(1));
  820. } else if (macro == ".4byte") {
  821. if (group != -1) {
  822. for (int j = 1; j < params.length(); j++) {
  823. QString mapName = params.value(j);
  824. groupedMaps[group].append(mapName);
  825. maps->append(mapName);
  826. map_groups->insert(mapName, group);
  827. // Build the mapping and reverse mapping between map constants and map names.
  828. QString mapConstant = Map::mapConstantFromName(mapName);
  829. mapConstantsToMapNames->insert(mapConstant, mapName);
  830. mapNamesToMapConstants->insert(mapName, mapConstant);
  831. }
  832. }
  833. }
  834. }
  835. groupNames = groups;
  836. groupedMapNames = groupedMaps;
  837. mapNames = maps;
  838. }
  839. Map* Project::addNewMapToGroup(QString mapName, int groupNum) {
  840. // Setup new map in memory, but don't write to file until map is actually saved later.
  841. mapNames->append(mapName);
  842. map_groups->insert(mapName, groupNum);
  843. groupedMapNames[groupNum].append(mapName);
  844. Map *map = new Map;
  845. map->isPersistedToFile = false;
  846. map->setName(mapName);
  847. mapConstantsToMapNames->insert(map->constantName, map->name);
  848. mapNamesToMapConstants->insert(map->name, map->constantName);
  849. setNewMapHeader(map, mapLayoutsTable.size() + 1);
  850. setNewMapLayout(map);
  851. getMapTilesets(map);
  852. setNewMapBlockdata(map);
  853. setNewMapBorder(map);
  854. setNewMapEvents(map);
  855. setNewMapConnections(map);
  856. map->commit();
  857. map->history.save();
  858. map_cache->insert(mapName, map);
  859. return map;
  860. }
  861. QString Project::getNewMapName() {
  862. // Ensure default name doesn't already exist.
  863. int i = 0;
  864. QString newMapName;
  865. do {
  866. newMapName = QString("NewMap%1").arg(++i);
  867. } while (mapNames->contains(newMapName));
  868. return newMapName;
  869. }
  870. QList<QStringList>* Project::parseAsm(QString text) {
  871. ParseUtil *parser = new ParseUtil;
  872. return parser->parseAsm(text);
  873. }
  874. QStringList Project::getLocations() {
  875. // TODO
  876. QStringList names;
  877. for (int i = 0; i < 88; i++) {
  878. names.append(QString("%1").arg(i));
  879. }
  880. return names;
  881. }
  882. QStringList Project::getVisibilities() {
  883. // TODO
  884. QStringList names;
  885. for (int i = 0; i < 16; i++) {
  886. names.append(QString("%1").arg(i));
  887. }
  888. return names;
  889. }
  890. QMap<QString, QStringList> Project::getTilesets() {
  891. QMap<QString, QStringList> allTilesets;
  892. QStringList primaryTilesets;
  893. QStringList secondaryTilesets;
  894. allTilesets.insert("primary", primaryTilesets);
  895. allTilesets.insert("secondary", secondaryTilesets);
  896. QString headers_text = readTextFile(root + "/data/tilesets/headers.inc");
  897. QList<QStringList>* commands = parseAsm(headers_text);
  898. int i = 0;
  899. while (i < commands->length()) {
  900. if (commands->at(i).length() != 2)
  901. continue;
  902. if (commands->at(i).at(0) == ".label") {
  903. QString tilesetLabel = commands->at(i).at(1);
  904. // Advance to command specifying whether or not it is a secondary tileset
  905. i += 2;
  906. if (commands->at(i).at(0) != ".byte") {
  907. qDebug() << "Unexpected command found for secondary tileset flag. Expected '.byte', but found: " << commands->at(i).at(0);
  908. continue;
  909. }
  910. QString secondaryTilesetValue = commands->at(i).at(1);
  911. if (secondaryTilesetValue != "TRUE" && secondaryTilesetValue != "FALSE" && secondaryTilesetValue != "0" && secondaryTilesetValue != "1") {
  912. qDebug() << "Unexpected secondary tileset flag found. Expected \"TRUE\", \"FALSE\", \"0\", or \"1\", but found: " << secondaryTilesetValue;
  913. continue;
  914. }
  915. bool isSecondaryTileset = (secondaryTilesetValue == "TRUE" || secondaryTilesetValue == "1");
  916. if (isSecondaryTileset)
  917. allTilesets["secondary"].append(tilesetLabel);
  918. else
  919. allTilesets["primary"].append(tilesetLabel);
  920. }
  921. i++;
  922. }
  923. return allTilesets;
  924. }
  925. QStringList Project::getWeathers() {
  926. // TODO
  927. QStringList names;
  928. for (int i = 0; i < 16; i++) {
  929. names.append(QString("%1").arg(i));
  930. }
  931. return names;
  932. }
  933. QStringList Project::getMapTypes() {
  934. // TODO
  935. QStringList names;
  936. for (int i = 0; i < 16; i++) {
  937. names.append(QString("%1").arg(i));
  938. }
  939. return names;
  940. }
  941. QStringList Project::getBattleScenes() {
  942. // TODO
  943. QStringList names;
  944. for (int i = 0; i < 16; i++) {
  945. names.append(QString("%1").arg(i));
  946. }
  947. return names;
  948. }
  949. void Project::readItemNames() {
  950. QString filepath = root + "/include/constants/items.h";
  951. QStringList prefixes = (QStringList() << "ITEM_");
  952. readCDefinesSorted(filepath, prefixes, itemNames);
  953. }
  954. void Project::readFlagNames() {
  955. QString filepath = root + "/include/constants/flags.h";
  956. QStringList prefixes = (QStringList() << "FLAG_");
  957. readCDefinesSorted(filepath, prefixes, flagNames);
  958. }
  959. void Project::readVarNames() {
  960. QString filepath = root + "/include/constants/vars.h";
  961. QStringList prefixes = (QStringList() << "VAR_");
  962. readCDefinesSorted(filepath, prefixes, varNames);
  963. }
  964. void Project::readCDefinesSorted(QString filepath, QStringList prefixes, QStringList* definesToSet) {
  965. QString text = readTextFile(filepath);
  966. if (!text.isNull()) {
  967. QMap<QString, int> defines = readCDefines(text, prefixes);
  968. // The defines should to be sorted by their underlying value, not alphabetically.
  969. // Reverse the map and read out the resulting keys in order.
  970. QMultiMap<int, QString> definesInverse;
  971. for (QString defineName : defines.keys()) {
  972. definesInverse.insert(defines[defineName], defineName);
  973. }
  974. *definesToSet = definesInverse.values();
  975. }
  976. }
  977. void Project::readMapsWithConnections() {
  978. QString path = root + "/data/maps/connections.inc";
  979. QString text = readTextFile(path);
  980. if (text.isNull()) {
  981. return;
  982. }
  983. mapsWithConnections.clear();
  984. QRegularExpression re("data\\/maps\\/(?<mapName>\\w+)\\/connections.inc");
  985. QList<QStringList>* includes = parseAsm(text);
  986. for (QStringList values : *includes) {
  987. if (values.length() != 2)
  988. continue;
  989. QRegularExpressionMatch match = re.match(values.value(1));
  990. if (match.hasMatch()) {
  991. QString mapName = match.captured("mapName");
  992. mapsWithConnections.append(mapName);
  993. }
  994. }
  995. }
  996. void Project::saveMapsWithConnections() {
  997. QString path = root + "/data/maps/connections.inc";
  998. QString text = "";
  999. for (QString mapName : mapsWithConnections) {
  1000. if (mapNamesToMapConstants->contains(mapName)) {
  1001. text += QString("\t.include \"data/maps/%1/connections.inc\"\n").arg(mapName);
  1002. } else {
  1003. qDebug() << QString("Failed to write connection include. %1 not a valid map name").arg(mapName);
  1004. }
  1005. }
  1006. saveTextFile(path, text);
  1007. }
  1008. QStringList Project::getSongNames() {
  1009. QStringList names;
  1010. QString text = readTextFile(root + "/include/constants/songs.h");
  1011. if (!text.isNull()) {
  1012. QStringList songDefinePrefixes;
  1013. songDefinePrefixes << "SE_" << "MUS_";
  1014. QMap<QString, int> songDefines = readCDefines(text, songDefinePrefixes);
  1015. names = songDefines.keys();
  1016. }
  1017. return names;
  1018. }
  1019. QMap<QString, int> Project::getEventObjGfxConstants() {
  1020. QMap<QString, int> constants;
  1021. QString text = readTextFile(root + "/include/constants/event_objects.h");
  1022. if (!text.isNull()) {
  1023. QStringList eventObjGfxPrefixes;
  1024. eventObjGfxPrefixes << "EVENT_OBJ_GFX_";
  1025. constants = readCDefines(text, eventObjGfxPrefixes);
  1026. }
  1027. return constants;
  1028. }
  1029. QString Project::fixGraphicPath(QString path) {
  1030. path = path.replace(QRegExp("\\.lz$"), "");
  1031. path = path.replace(QRegExp("\\.[1248]bpp$"), ".png");
  1032. return path;
  1033. }
  1034. void Project::loadEventPixmaps(QList<Event*> objects) {
  1035. bool needs_update = false;
  1036. for (Event *object : objects) {
  1037. if (object->pixmap.isNull()) {
  1038. needs_update = true;
  1039. break;
  1040. }
  1041. }
  1042. if (!needs_update) {
  1043. return;
  1044. }
  1045. QMap<QString, int> constants = getEventObjGfxConstants();
  1046. QString pointers_text = readTextFile(root + "/src/data/field_event_obj/event_object_graphics_info_pointers.h");
  1047. QString info_text = readTextFile(root + "/src/data/field_event_obj/event_object_graphics_info.h");
  1048. QString pic_text = readTextFile(root + "/src/data/field_event_obj/event_object_pic_tables.h");
  1049. QString assets_text = readTextFile(root + "/src/data/field_event_obj/event_object_graphics.h");
  1050. QStringList pointers = readCArray(pointers_text, "gEventObjectGraphicsInfoPointers");
  1051. for (Event *object : objects) {
  1052. if (!object->pixmap.isNull()) {
  1053. continue;
  1054. }
  1055. QString event_type = object->get("event_type");
  1056. if (event_type == EventType::Object) {
  1057. object->pixmap = QPixmap(":/images/Entities_16x16.png").copy(0, 0, 16, 16);
  1058. } else if (event_type == EventType::Warp) {
  1059. object->pixmap = QPixmap(":/images/Entities_16x16.png").copy(16, 0, 16, 16);
  1060. } else if (event_type == EventType::CoordScript || event_type == EventType::CoordWeather) {
  1061. object->pixmap = QPixmap(":/images/Entities_16x16.png").copy(32, 0, 16, 16);
  1062. } else if (event_type == EventType::Sign || event_type == EventType::HiddenItem || event_type == EventType::SecretBase) {
  1063. object->pixmap = QPixmap(":/images/Entities_16x16.png").copy(48, 0, 16, 16);
  1064. }
  1065. if (event_type == EventType::Object) {
  1066. int sprite_id = constants.value(object->get("sprite"));
  1067. QString info_label = pointers.value(sprite_id).replace("&", "");
  1068. QString pic_label = readCArray(info_text, info_label).value(14);
  1069. QString gfx_label = readCArray(pic_text, pic_label).value(0);
  1070. gfx_label = gfx_label.section(QRegExp("[\\(\\)]"), 1, 1);
  1071. QString path = readCIncbin(assets_text, gfx_label);
  1072. if (!path.isNull()) {
  1073. path = fixGraphicPath(path);
  1074. QPixmap pixmap(root + "/" + path);
  1075. if (!pixmap.isNull()) {
  1076. object->pixmap = pixmap;
  1077. }
  1078. }
  1079. }
  1080. }
  1081. }
  1082. void Project::saveMapEvents(Map *map) {
  1083. QString path = root + QString("/data/maps/%1/events.inc").arg(map->name);
  1084. QString text = "";
  1085. QString objectEventsLabel = "0x0";
  1086. QString warpEventsLabel = "0x0";
  1087. QString coordEventsLabel = "0x0";
  1088. QString bgEventsLabel = "0x0";
  1089. if (map->events["object_event_group"].length() > 0) {
  1090. objectEventsLabel = Map::objectEventsLabelFromName(map->name);
  1091. text += QString("%1::\n").arg(objectEventsLabel);
  1092. for (int i = 0; i < map->events["object_event_group"].length(); i++) {
  1093. Event *object_event = map->events["object_event_group"].value(i);
  1094. text += object_event->buildObjectEventMacro(i);
  1095. }
  1096. text += "\n";
  1097. }
  1098. if (map->events["warp_event_group"].length() > 0) {
  1099. warpEventsLabel = Map::warpEventsLabelFromName(map->name);
  1100. text += QString("%1::\n").arg(warpEventsLabel);
  1101. for (Event *warp : map->events["warp_event_group"]) {
  1102. text += warp->buildWarpEventMacro(mapNamesToMapConstants);
  1103. }
  1104. text += "\n";
  1105. }
  1106. if (map->events["coord_event_group"].length() > 0) {
  1107. coordEventsLabel = Map::coordEventsLabelFromName(map->name);
  1108. text += QString("%1::\n").arg(coordEventsLabel);
  1109. for (Event *event : map->events["coord_event_group"]) {
  1110. QString event_type = event->get("event_type");
  1111. if (event_type == EventType::CoordScript) {
  1112. text += event->buildCoordScriptEventMacro();
  1113. } else if (event_type == EventType::CoordWeather) {
  1114. text += event->buildCoordWeatherEventMacro();
  1115. }
  1116. }
  1117. text += "\n";
  1118. }
  1119. if (map->events["bg_event_group"].length() > 0)
  1120. {
  1121. bgEventsLabel = Map::bgEventsLabelFromName(map->name);
  1122. text += QString("%1::\n").arg(bgEventsLabel);
  1123. for (Event *event : map->events["bg_event_group"]) {
  1124. QString event_type = event->get("event_type");
  1125. if (event_type == EventType::Sign) {
  1126. text += event->buildSignEventMacro();
  1127. } else if (event_type == EventType::HiddenItem) {
  1128. text += event->buildHiddenItemEventMacro();
  1129. } else if (event_type == EventType::SecretBase) {
  1130. text += event->buildSecretBaseEventMacro();
  1131. }
  1132. }
  1133. text += "\n";
  1134. }
  1135. text += QString("%1::\n").arg(map->events_label);
  1136. text += QString("\tmap_events %1, %2, %3, %4\n")
  1137. .arg(objectEventsLabel)
  1138. .arg(warpEventsLabel)
  1139. .arg(coordEventsLabel)
  1140. .arg(bgEventsLabel);
  1141. saveTextFile(path, text);
  1142. }
  1143. void Project::readMapEvents(Map *map) {
  1144. if (!map->isPersistedToFile) {
  1145. return;
  1146. }
  1147. // lazy
  1148. QString path = root + QString("/data/maps/%1/events.inc").arg(map->name);
  1149. QString text = readTextFile(path);
  1150. if (text.isNull()) {
  1151. return;
  1152. }
  1153. QStringList *labels = getLabelValues(parseAsm(text), map->events_label);
  1154. QString objectEventsLabel = labels->value(0);
  1155. QString warpEventsLabel = labels->value(1);
  1156. QString coordEventsLabel = labels->value(2);
  1157. QString bgEventsLabel = labels->value(3);
  1158. QList<QStringList> *object_events = getLabelMacros(parseAsm(text), objectEventsLabel);
  1159. map->events["object_event_group"].clear();
  1160. for (QStringList command : *object_events) {
  1161. if (command.value(0) == "object_event") {
  1162. Event *object = new Event;
  1163. object->put("map_name", map->name);
  1164. int i = 2;
  1165. object->put("sprite", command.value(i++));
  1166. object->put("replacement", command.value(i++));
  1167. object->put("x", command.value(i++).toInt(nullptr, 0));
  1168. object->put("y", command.value(i++).toInt(nullptr, 0));
  1169. object->put("elevation", command.value(i++));
  1170. object->put("behavior", command.value(i++));
  1171. object->put("radius_x", command.value(i++).toInt(nullptr, 0));
  1172. object->put("radius_y", command.value(i++).toInt(nullptr, 0));
  1173. object->put("trainer_see_type", command.value(i++));
  1174. object->put("sight_radius_tree_id", command.value(i++));
  1175. object->put("script_label", command.value(i++));
  1176. object->put("event_flag", command.value(i++));
  1177. object->put("event_group_type", "object_event_group");
  1178. object->put("event_type", EventType::Object);
  1179. map->events["object_event_group"].append(object);
  1180. }
  1181. }
  1182. QList<QStringList> *warps = getLabelMacros(parseAsm(text), warpEventsLabel);
  1183. map->events["warp_event_group"].clear();
  1184. for (QStringList command : *warps) {
  1185. if (command.value(0) == "warp_def") {
  1186. Event *warp = new Event;
  1187. warp->put("map_name", map->name);
  1188. int i = 1;
  1189. warp->put("x", command.value(i++));
  1190. warp->put("y", command.value(i++));
  1191. warp->put("elevation", command.value(i++));
  1192. warp->put("destination_warp", command.value(i++));
  1193. // Ensure the warp destination map constant is valid before adding it to the warps.
  1194. QString mapConstant = command.value(i++);
  1195. if (mapConstantsToMapNames->contains(mapConstant)) {
  1196. warp->put("destination_map_name", mapConstantsToMapNames->value(mapConstant));
  1197. warp->put("event_group_type", "warp_event_group");
  1198. warp->put("event_type", EventType::Warp);
  1199. map->events["warp_event_group"].append(warp);
  1200. } else {
  1201. qDebug() << QString("Destination map constant '%1' is invalid for warp").arg(mapConstant);
  1202. }
  1203. }
  1204. }
  1205. QList<QStringList> *coords = getLabelMacros(parseAsm(text), coordEventsLabel);
  1206. map->events["coord_event_group"].clear();
  1207. for (QStringList command : *coords) {
  1208. if (command.value(0) == "coord_event") {
  1209. Event *coord = new Event;
  1210. coord->put("map_name", map->name);
  1211. bool old_macro = false;
  1212. if (command.length() >= 9) {
  1213. command.removeAt(7);
  1214. command.removeAt(4);
  1215. old_macro = true;
  1216. }
  1217. int i = 1;
  1218. coord->put("x", command.value(i++));
  1219. coord->put("y", command.value(i++));
  1220. coord->put("elevation", command.value(i++));
  1221. coord->put("script_var", command.value(i++));
  1222. coord->put("script_var_value", command.value(i++));
  1223. coord->put("script_label", command.value(i++));
  1224. //coord_unknown3
  1225. //coord_unknown4
  1226. coord->put("event_group_type", "coord_event_group");
  1227. coord->put("event_type", EventType::CoordScript);
  1228. map->events["coord_event_group"].append(coord);
  1229. } else if (command.value(0) == "coord_weather_event") {
  1230. Event *coord = new Event;
  1231. coord->put("map_name", map->name);
  1232. int i = 1;
  1233. coord->put("x", command.value(i++));
  1234. coord->put("y", command.value(i++));
  1235. coord->put("elevation", command.value(i++));
  1236. coord->put("weather", command.value(i++));
  1237. coord->put("event_group_type", "coord_event_group");
  1238. coord->put("event_type", EventType::CoordWeather);
  1239. map->events["coord_event_group"].append(coord);
  1240. }
  1241. }
  1242. QList<QStringList> *bgs = getLabelMacros(parseAsm(text), bgEventsLabel);
  1243. map->events["bg_event_group"].clear();
  1244. for (QStringList command : *bgs) {
  1245. if (command.value(0) == "bg_event") {
  1246. Event *bg = new Event;
  1247. bg->put("map_name", map->name);
  1248. int i = 1;
  1249. bg->put("x", command.value(i++));
  1250. bg->put("y", command.value(i++));
  1251. bg->put("elevation", command.value(i++));
  1252. bg->put("player_facing_direction", command.value(i++));
  1253. i++;
  1254. bg->put("script_label", command.value(i++));
  1255. //sign_unknown7
  1256. bg->put("event_group_type", "bg_event_group");
  1257. bg->put("event_type", EventType::Sign);
  1258. map->events["bg_event_group"].append(bg);
  1259. } else if (command.value(0) == "bg_hidden_item_event") {
  1260. Event *bg = new Event;
  1261. bg->put("map_name", map->name);
  1262. int i = 1;
  1263. bg->put("x", command.value(i++));
  1264. bg->put("y", command.value(i++));
  1265. bg->put("elevation", command.value(i++));
  1266. bg->put("item", command.value(i++));
  1267. bg->put("flag", command.value(i++));
  1268. bg->put("event_group_type", "bg_event_group");
  1269. bg->put("event_type", EventType::HiddenItem);
  1270. map->events["bg_event_group"].append(bg);
  1271. } else if (command.value(0) == "bg_secret_base_event") {
  1272. Event *bg = new Event;
  1273. bg->put("map_name", map->name);
  1274. int i = 1;
  1275. bg->put("x", command.value(i++));
  1276. bg->put("y", command.value(i++));
  1277. bg->put("elevation", command.value(i++));
  1278. bg->put("secret_base_map", command.value(i++));
  1279. bg->put("event_group_type", "bg_event_group");
  1280. bg->put("event_type", EventType::SecretBase);
  1281. map->events["bg_event_group"].append(bg);
  1282. }
  1283. }
  1284. }
  1285. void Project::setNewMapEvents(Map *map) {
  1286. map->events["object_event_group"].clear();
  1287. map->events["warp_event_group"].clear();
  1288. map->events["coord_event_group"].clear();
  1289. map->events["bg_event_group"].clear();
  1290. }
  1291. QStringList Project::readCArray(QString text, QString label) {
  1292. QStringList list;
  1293. if (label.isNull()) {
  1294. return list;
  1295. }
  1296. QRegExp *re = new QRegExp(QString("\\b%1\\b\\s*\\[?\\s*\\]?\\s*=\\s*\\{([^\\}]*)\\}").arg(label));
  1297. int pos = re->indexIn(text);
  1298. if (pos != -1) {
  1299. QString body = re->cap(1);
  1300. body = body.replace(QRegExp("\\s*"), "");
  1301. list = body.split(',');
  1302. /*
  1303. QRegExp *inner = new QRegExp("&?\\b([A-Za-z0-9_\\(\\)]*)\\b,");
  1304. int pos = 0;
  1305. while ((pos = inner->indexIn(body, pos)) != -1) {
  1306. list << inner->cap(1);
  1307. pos += inner->matchedLength();
  1308. }
  1309. */
  1310. }
  1311. return list;
  1312. }
  1313. QString Project::readCIncbin(QString text, QString label) {
  1314. QString path;
  1315. if (label.isNull()) {
  1316. return path;
  1317. }
  1318. QRegExp *re = new QRegExp(QString(
  1319. "\\b%1\\b"
  1320. "\\s*\\[?\\s*\\]?\\s*=\\s*"
  1321. "INCBIN_[US][0-9][0-9]?"
  1322. "\\(\"([^\"]*)\"\\)").arg(label));
  1323. int pos = re->indexIn(text);
  1324. if (pos != -1) {
  1325. path = re->cap(1);
  1326. }
  1327. return path;
  1328. }
  1329. QMap<QString, int> Project::readCDefines(QString text, QStringList prefixes) {
  1330. ParseUtil parser;
  1331. QMap<QString, int> allDefines;
  1332. QMap<QString, int> filteredDefines;
  1333. QRegularExpression re("#define\\s+(?<defineName>\\w+)[^\\S\\n]+(?<defineValue>.+)");
  1334. QRegularExpressionMatchIterator iter = re.globalMatch(text);
  1335. while (iter.hasNext()) {
  1336. QRegularExpressionMatch match = iter.next();
  1337. QString name = match.captured("defineName");
  1338. QString expression = match.captured("defineValue");
  1339. expression.replace(QRegularExpression("//.*"), "");
  1340. int value = parser.evaluateDefine(expression, &allDefines);
  1341. allDefines.insert(name, value);
  1342. for (QString prefix : prefixes) {
  1343. if (name.startsWith(prefix)) {
  1344. filteredDefines.insert(name, value);
  1345. }
  1346. }
  1347. }
  1348. return filteredDefines;
  1349. }