diff --git a/include/ui/prefab.h b/include/ui/prefab.h index 83656e08..b3087a8a 100644 --- a/include/ui/prefab.h +++ b/include/ui/prefab.h @@ -30,6 +30,7 @@ private: QLabel *emptyPrefabLabel; QList items; void loadPrefabs(); + void savePrefabs(); QList getPrefabsForTilesets(QString primaryTileset, QString secondaryTileset); }; diff --git a/src/ui/prefab.cpp b/src/ui/prefab.cpp index 42979c7d..3a48cb01 100644 --- a/src/ui/prefab.cpp +++ b/src/ui/prefab.cpp @@ -15,6 +15,9 @@ #include #include +using OrderedJson = poryjson::Json; +using OrderedJsonDoc = poryjson::JsonDoc; + void Prefab::loadPrefabs() { this->items.clear(); @@ -77,6 +80,50 @@ void Prefab::loadPrefabs() { } } +void Prefab::savePrefabs() { + QString filepath = projectConfig.getPrefabFilepath(); + if (filepath.isEmpty()) return; + QFile prefabsFile(filepath); + if (!prefabsFile.open(QIODevice::WriteOnly)) { + logError(QString("Error: Could not open %1 for writing").arg(filepath)); + return; + } + + OrderedJson::array prefabsArr; + for (auto item : this->items) { + OrderedJson::object prefabObj; + prefabObj["name"] = item.name; + prefabObj["width"] = item.selection.dimensions.x(); + prefabObj["height"] = item.selection.dimensions.y(); + prefabObj["primary_tileset"] = item.primaryTileset; + prefabObj["secondary_tileset"] = item.secondaryTileset; + OrderedJson::array metatiles; + for (int y = 0; y < item.selection.dimensions.y(); y++) { + for (int x = 0; x < item.selection.dimensions.x(); x++) { + int index = y * item.selection.dimensions.x() + x; + auto metatileItem = item.selection.metatileItems.at(index); + if (metatileItem.enabled) { + auto collisionItem = item.selection.collisionItems.at(index); + OrderedJson::object metatileObj; + metatileObj["x"] = x; + metatileObj["y"] = y; + metatileObj["metatile_id"] = metatileItem.metatileId; + metatileObj["collision"] = collisionItem.collision; + metatileObj["elevation"] = collisionItem.elevation; + metatiles.push_back(metatileObj); + } + } + } + prefabObj["metatiles"] = metatiles; + prefabsArr.push_back(prefabObj); + } + + OrderedJson prefabJson(prefabsArr); + OrderedJsonDoc jsonDoc(&prefabJson); + jsonDoc.dump(&prefabsFile); + prefabsFile.close(); +} + QList Prefab::getPrefabsForTilesets(QString primaryTileset, QString secondaryTileset) { QList filteredPrefabs; for (auto item : this->items) { @@ -138,6 +185,7 @@ void Prefab::updatePrefabUi(Map *map) { for (int i = 0; i < this->items.size(); i++) { if (this->items[i].id == item.id) { this->items.removeAt(i); + this->savePrefabs(); this->updatePrefabUi(map); break; } @@ -168,6 +216,7 @@ void Prefab::addPrefab(MetatileSelection selection, Map *map, QString name) { usesSecondaryTileset ? map->layout->tileset_secondary_label: "", selection }); + this->savePrefabs(); this->updatePrefabUi(map); }