Без опису

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