Sin descripción

project.cpp 56KB

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