Geen omschrijving

project.cpp 61KB

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