Нет описания

project.cpp 55KB

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