// Currently only does something for X-axis checks. private bool CheckOrientationCompatibility(EntityBlueprint.PartInfo part, EntityBlueprint.PartInfo symmetryPart) { var partID = part.partID; part.rotation %= 360; symmetryPart.rotation %= 360; switch (GetPartSymmetry(part.partID)) { case PartSymmetry.MirrorYAxis: case PartSymmetry.MirrorBothAxes: return((part.rotation + symmetryPart.rotation) % 360 == 0); case PartSymmetry.MirrorXAxis: // There are cases where the parts are symmetrically aligned for both same-mirror and opposite-mirror pairs var diff = Mathf.Abs(part.rotation + symmetryPart.rotation); if (part.mirrored != symmetryPart.mirrored) { return(diff % 360 == 0); } return(diff % 360 == 180); case PartSymmetry.None: default: return(part.mirrored != symmetryPart.mirrored && ((part.rotation + symmetryPart.rotation) % 360 == 0)); } }
public void InitializeBuildPhase(EntityBlueprint blueprint, EntityBlueprint.PartInfo currentPart, DroneSpawnData data) { searcherString = ""; displayingTypes = new bool[] { true, false, true, true, true }; this.currentData = data; this.currentPart = currentPart; selectionPhaseParent.SetActive(false); buildPhaseParent.SetActive(true); LoadBlueprint(blueprint, data); builderPartDict = new Dictionary <EntityBlueprint.PartInfo, ShipBuilderInventoryScript>(); contentsArray = new Transform[] { smallBuilderContents, mediumBuilderContents, largeBuilderContents }; contentTexts = new GameObject[] { smallBuilderText, mediumBuilderText, largeBuilderText }; foreach (GameObject obj in contentTexts) { obj.SetActive(false); } foreach (EntityBlueprint.PartInfo part in player.GetInventory()) { if (part.abilityID != 10 && ResourceManager.GetAsset <PartBlueprint>(part.partID).size == 0) { AddPart(part); } } GetComponentInChildren <ShipBuilderPartDisplay>().Initialize(this); phase = DroneWorkshopPhase.BuildPhase; cursorScript.gameObject.SetActive(true); cursorScript.SetMode(BuilderMode.Workshop); }
public void OnPointerClick(PointerEventData eventData) { if (Input.GetKey(KeyCode.LeftShift)) { ClearPreset(); return; } if (!valid) { return; // allow user to left shift out blueprint so return after that } // TODO: check if adding a part back into your inventory validates the preset if (!blueprint && (builder.reconstructStatus == ShipBuilder.ReconstructButtonStatus.Valid)) { blueprint = ScriptableObject.CreateInstance <EntityBlueprint>(); blueprint.coreShellSpriteID = player.blueprint.coreShellSpriteID; blueprint.coreSpriteID = player.blueprint.coreSpriteID; blueprint.parts = new List <EntityBlueprint.PartInfo>(); foreach (ShipBuilderPart part in cursorScript.parts) { if (!part.isInChain || !part.validPos) { blueprint = null; return; } blueprint.parts.Add(part.info); } if (player.cursave.presetBlueprints == null || (player.cursave.presetBlueprints != null && player.cursave.presetBlueprints.Length < 5)) { player.cursave.presetBlueprints = new string[5]; } player.cursave.presetBlueprints[number - 1] = JsonUtility.ToJson(blueprint); } else if (blueprint) { cursorScript.ClearAllParts(); foreach (EntityBlueprint.PartInfo info in blueprint.parts) { if (!builder.DecrementPartButton(ShipBuilder.CullSpatialValues(info))) { // cursorScript.ClearAllParts(); builder.CloseUI(false); return; } } var x = new EntityBlueprint.PartInfo[blueprint.parts.Count]; blueprint.parts.CopyTo(x); player.blueprint.parts = new List <EntityBlueprint.PartInfo>(x); builder.CloseUI(true); OnPointerExit(null); player.Rebuild(); } }
public override void StartQuest() { // If the quest has been started, continue nodeCanvas.missionName = findRoot().missionName; if (nodeCanvas.missionName == null) { Debug.LogError("A mission wasn't given a name. Every mission must have a name."); return; } // add objective list TaskManager.objectiveLocations.Add(nodeCanvas.missionName, new List <TaskManager.ObjectiveLocation>()); if (lastCheckpointName == (nodeCanvas.missionName + "_complete")) { // Retroactively add all parts from the completed quest as parts obtained by the player. if (PlayerCore.Instance) { foreach (var node in nodeCanvas.nodes) { if (node is StartTaskNode) { var startTask = node as StartTaskNode; if (startTask.partReward) { EntityBlueprint.PartInfo part = new EntityBlueprint.PartInfo(); part.partID = startTask.partID; part.abilityID = startTask.partAbilityID; part.tier = startTask.partTier; part.secondaryData = startTask.partSecondaryData; part = PartIndexScript.CullToPartIndexValues(part); if (!PlayerCore.Instance.cursave.partsObtained.Contains(part)) { PlayerCore.Instance.cursave.partsObtained.Add(part); } if (!PlayerCore.Instance.cursave.partsSeen.Contains(part)) { PlayerCore.Instance.cursave.partsSeen.Add(part); } } } } } return; } base.StartQuest(); SectorManager.OnSectorLoad += ((val) => { if (traverserLimiterDelegate != null) { traverserLimiterDelegate.Invoke(val); } }); if (currentNode == null) { TaskManager.Instance.RemoveTraverser(this); } }
public static void AttemptAddToPartsSeen(EntityBlueprint.PartInfo part) { var partsSeen = PlayerCore.Instance.cursave.partsSeen; if (!partsSeen.Exists(x => CullToPartIndexValues(x).Equals(CullToPartIndexValues(part)))) { partsSeen.Add(part); } }
public static bool CheckPartObtained(EntityBlueprint.PartInfo part) { if (partsObtainedCheat) { return(true); } part = CullToPartIndexValues(part); return(PlayerCore.Instance.cursave.partsObtained.Exists(x => CullToPartIndexValues(x).Equals(part))); }
public void DisplayPartInfo(EntityBlueprint.PartInfo info) { if (info.abilityID != 0) { if (info.tier != 0) { abilityTier.gameObject.SetActive(true); abilityTier.sprite = ResourceManager.GetAsset <Sprite>("AbilityTier" + info.tier); if (abilityTier.sprite) { abilityTier.rectTransform.sizeDelta = abilityTier.sprite.bounds.size * 20; } abilityTier.color = new Color(1, 1, 1, 0.4F); } else { abilityTier.gameObject.SetActive(false); } abilityImage.sprite = AbilityUtilities.GetAbilityImageByID(info.abilityID, info.secondaryData); abilityImage.gameObject.SetActive(true); abilityText.text = AbilityUtilities.GetAbilityNameByID(info.abilityID, info.secondaryData) + (info.tier > 0 ? " " + info.tier : ""); abilityText.gameObject.SetActive(true); abilityBox.gameObject.SetActive(true); string description = ""; description += AbilityUtilities.GetAbilityNameByID(info.abilityID, info.secondaryData) + (info.tier > 0 ? " " + info.tier : "") + "\n"; description += AbilityUtilities.GetDescriptionByID(info.abilityID, info.tier, info.secondaryData); buttonScript.abilityInfo = description; } else { abilityTier.gameObject.SetActive(false); abilityBox.gameObject.SetActive(false); abilityImage.gameObject.SetActive(false); abilityText.gameObject.SetActive(false); } image.gameObject.SetActive(true); partName.gameObject.SetActive(true); partStats.gameObject.SetActive(true); string partID = info.partID; partName.text = partID; var blueprint = ResourceManager.GetAsset <PartBlueprint>(partID); float mass = blueprint.mass; float health = blueprint.health; int value = EntityBlueprint.GetPartValue(info); partStats.text = $"PART SHELL: {health / 2}\nPART CORE: {health / 4}\nPART WEIGHT: {mass * Entity.weightMultiplier}\nPART VALUE: \n{value} CREDITS"; image.sprite = ResourceManager.GetAsset <Sprite>(partID + "_sprite"); image.rectTransform.sizeDelta = image.sprite.bounds.size * 50; image.color = info.shiny ? FactionManager.GetFactionShinyColor(0) : FactionManager.GetFactionColor(0); }
public static DroneSpawnData ParseDronePart(EntityBlueprint.PartInfo part) { if (part.abilityID != 10) { Debug.Log("Passed part is not a drone spawner!"); } var data = ScriptableObject.CreateInstance <DroneSpawnData>(); JsonUtility.FromJsonOverwrite(part.secondaryData, data); return(data); }
// adds a DWInventoryButton, for SBInventoryButton use AddPart public void AddDronePart(EntityBlueprint.PartInfo part) { int size = ResourceManager.GetAsset <PartBlueprint>(part.partID).size; DWInventoryButton invButton = Instantiate(displayButtonPrefab, contentsArray[size]).GetComponent <DWInventoryButton>(); invButton.handler = selectionDisplay; invButton.workshop = this; partDict.Add(invButton, part); contentTexts[size].SetActive(true); invButton.part = part; }
public bool DecrementPartButton(EntityBlueprint.PartInfo info) { if (partDict.ContainsKey(CullSpatialValues(info)) && partDict[CullSpatialValues(info)].GetCount() > 0) { partDict[CullSpatialValues(info)].DecrementCount(); return(true); } else { return(false); } }
public static DroneSpawnData ParseDronePart(EntityBlueprint.PartInfo part) { if (part.abilityID != 10) { Debug.Log("Passed part is not a drone spawner!"); } var data = DroneUtilities.GetDroneSpawnDataByShorthand(part.secondaryData); //JsonUtility.FromJsonOverwrite(part.secondaryData, data); return(data); }
public static void AttemptAddToPartsObtained(EntityBlueprint.PartInfo part) { var partsObtained = PlayerCore.Instance.cursave.partsObtained; if (!partsObtained.Exists(x => CullToPartIndexValues(x).Equals(CullToPartIndexValues(part)))) { partsObtained.Add(part); } else if (part.shiny) { partsObtained[partsObtained.FindIndex(x => CullToPartIndexValues(x).Equals(CullToPartIndexValues(part)))] = part; } }
/// /// Culls unnecessary data in the passed PartInfo for adding into the Part Index. /// Notably, it nullifies secondary data if the part does not spawn drones. /// public static EntityBlueprint.PartInfo CullToPartIndexValues(EntityBlueprint.PartInfo partToCull) { var part = new EntityBlueprint.PartInfo(); part.partID = partToCull.partID; part.abilityID = partToCull.abilityID; if (part.abilityID != 10) { part.secondaryData = null; } part.tier = partToCull.tier; part.shiny = false; return(part); }
public static EntityBlueprint.PartInfo CullSpatialValues(EntityBlueprint.PartInfo partToCull) { var part = new EntityBlueprint.PartInfo(); part.partID = partToCull.partID; part.abilityID = partToCull.abilityID; if (part.abilityID == 10) { part.secondaryData = partToCull.secondaryData; } part.tier = partToCull.tier; part.shiny = partToCull.shiny; return(part); }
/// /// Culls unnecessary data in the passed PartInfo for adding into the Part Index. /// Notably, it nullifies secondary data if the part does not spawn drones. /// public static EntityBlueprint.PartInfo CullToPartIndexValues(EntityBlueprint.PartInfo partToCull) { var part = new EntityBlueprint.PartInfo(); part.partID = partToCull.partID; part.abilityID = partToCull.abilityID; if (!ShipBuilder.CheckSecondaryDataPurge(partToCull)) { part.secondaryData = partToCull.secondaryData; } part.tier = partToCull.tier; part.shiny = false; return(part); }
/// /// Attempt to add a part into the index, check if the player obtained/saw it /// public void AttemptAddPart(EntityBlueprint.PartInfo part, List <string> origins) { part = CullToPartIndexValues(part); if (!parts.ContainsKey(part)) { var button = Instantiate(inventoryPrefab, contents[ResourceManager.GetAsset <PartBlueprint>(part.partID).size]).GetComponent <PartIndexInventoryButton>(); parts.Add(part, button.gameObject); button.part = part; if (CheckPartObtained(part)) { button.status = PartStatus.Obtained; button.displayShiny = PlayerCore.Instance.cursave.partsObtained.Find(x => CullToPartIndexValues(x).Equals(part)).shiny; // Update stats on 3 tallies, possibly the shiny tally if (button.displayShiny) { statsNumbers[0]++; } statsNumbers[1]++; statsNumbers[2]++; } else if (CheckPartSeen(part)) { button.status = PartStatus.Seen; button.displayShiny = false; // Update only the seen tally statsNumbers[2]++; } else { button.status = PartStatus.Unseen; button.displayShiny = false; } button.infoBox = infoBox; button.partDisplay = partDisplay; // Update total number statsNumbers[3]++; } foreach (var origin in origins) { parts[part].GetComponent <PartIndexInventoryButton>().origins.Add(origin); } }
private void AddPart(EntityBlueprint.PartInfo part) { if (!builderPartDict.ContainsKey(part)) { int size = ResourceManager.GetAsset <PartBlueprint>(part.partID).size; ShipBuilderInventoryScript invButton = Instantiate(buttonPrefab, contentsArray[size]).GetComponent <ShipBuilderInventoryScript>(); builderPartDict.Add(part, invButton); contentTexts[size].SetActive(true); invButton.part = part; invButton.cursor = cursorScript; invButton.IncrementCount(); invButton.mode = BuilderMode.Yard; } else { builderPartDict[part].IncrementCount(); } }
// Does calculation on whether the part's secondary data should be purged public static bool CheckSecondaryDataPurge(EntityBlueprint.PartInfo part) { if (part.abilityID == (int)AbilityID.SpawnDrone) { return(false); } if (part.abilityID == (int)AbilityID.Missile && part.secondaryData == "missile_station_shooter") { return(false); } if (part.abilityID == (int)AbilityID.Beam && part.secondaryData == "beamgroundshooter_sprite") { return(false); } if (part.abilityID == (int)AbilityID.SiegeBullet && (part.secondaryData == "siegegroundshooter_sprite" || part.secondaryData == "siegeshooter_sprite")) { return(false); } return(true); }
// Update is called once per frame void Update() { // Gets the part to diplsay using the method GetButtonPartCursorIsOn() in IBuilderInterface if (initialized) { EntityBlueprint.PartInfo?part = null; if (cursorScript.GetPartCursorIsOn() != null) { part = cursorScript.GetPartCursorIsOn(); } if (part != null) { EntityBlueprint.PartInfo info = (EntityBlueprint.PartInfo)part; DisplayPartInfo(info); emptyInfoMarker.SetActive(false); } else { SetInactive(); } } }
public static bool CheckPartSeen(EntityBlueprint.PartInfo part) { part = CullToPartIndexValues(part); return(PlayerCore.Instance.cursave.partsSeen.Exists(x => CullToPartIndexValues(x).Equals(part))); }
IEnumerator WriteWorldCo(string path) { Debug.Log("Writing world..."); // Folder paths var canvasPlaceholderPath = System.IO.Path.Combine(Application.streamingAssetsPath, "CanvasPlaceholder"); var entityPlaceholderPath = System.IO.Path.Combine(Application.streamingAssetsPath, "EntityPlaceholder"); var wavePlaceholderPath = System.IO.Path.Combine(Application.streamingAssetsPath, "WavePlaceholder"); var factionPlaceholderPath = System.IO.Path.Combine(Application.streamingAssetsPath, "FactionPlaceholder"); var resourcePlaceholderPath = System.IO.Path.Combine(Application.streamingAssetsPath, "ResourcePlaceholder"); // Reinitialize node editor NodeEditor.ReInit(false); saveState = 1; yield return(null); sectors = new List <Sector>(); var items = cursor.placedItems; var wrappers = cursor.sectors; foreach (var wrapper in wrappers) { sectors.Add(wrapper.sector); } int minX = int.MaxValue; int maxY = int.MinValue; // Get the world bounds foreach (var sector in sectors) { if (sector.bounds.x < minX) { minX = sector.bounds.x; } if (sector.bounds.y > maxY) { maxY = sector.bounds.y; } } // ensure spawn point in some sector if (sectors.TrueForAll(sector => !sector.bounds.contains(cursor.spawnPoint.position))) { Debug.LogError("Spawn point not in sector bounds. Abort."); yield break; } // set up items and platforms int ID = 0; Dictionary <Sector, List <Sector.LevelEntity> > sectEnts = new Dictionary <Sector, List <Sector.LevelEntity> >(); Dictionary <Sector, List <string> > sectTargetIDS = new Dictionary <Sector, List <string> >(); foreach (var sector in sectors) { sectEnts.Add(sector, new List <Sector.LevelEntity>()); sectTargetIDS.Add(sector, new List <string>()); sector.tiles = new List <GroundPlatform.Tile>(); } // Add background spawns to part index partData.Clear(); foreach (var sector in sectors) { if (sector.backgroundSpawns != null) { foreach (var spawn in sector.backgroundSpawns) { AttemptAddShellCoreParts(spawn.entity, sector.sectorName, path); } } } Dictionary <string, string> itemSectorsByID = new Dictionary <string, string>(); foreach (var item in items) { Sector container = GetSurroundingSector(item.pos, item.dimension); if (container == null) { savingLevelScreen.SetActive(false); saveState = 3; Debug.LogError("No container for item. Abort."); yield break; } switch (item.type) { case ItemType.Platform: var index = GetPlatformIndices(container, item.pos); container.tiles.Add(new GroundPlatform.Tile() { pos = new Vector2Int(index.Item2, index.Item1), type = (byte)item.placeablesIndex, rotation = (byte)(((int)item.obj.transform.rotation.eulerAngles.z / 90) % 4) }); break; case ItemType.Other: case ItemType.Decoration: case ItemType.DecorationWithMetadata: case ItemType.Flag: Sector.LevelEntity ent = new Sector.LevelEntity(); if (cursor.characters.TrueForAll((WorldData.CharacterData x) => { return(x.ID != item.ID); })) { // Debug.Log(item.ID + " is not a character. " + ID); if (item.type == ItemType.DecorationWithMetadata) { int parsedId; if (item.assetID == "shard_rock" && int.TryParse(item.ID, out parsedId)) { Debug.LogError($"Shard in sector {container.sectorName} has a numeric ID. Abort."); yield break; } ent.blueprintJSON = item.shellcoreJSON; } int test; if (string.IsNullOrEmpty(item.ID) || int.TryParse(item.ID, out test)) { ent.ID = (ID++).ToString(); } else { ent.ID = item.ID; if (itemSectorsByID.ContainsKey(ent.ID)) { savingLevelScreen.SetActive(false); saveState = 4; Debug.LogError($"Two items in sectors {container.sectorName} and {itemSectorsByID[ent.ID]} were issued the same custom ID ({ent.ID}). Abort."); yield break; } else { itemSectorsByID.Add(ent.ID, container.sectorName); } } // Debug.Log(container.sectorName + " " + ent.ID); } else { // TODO: adjust faction Debug.Log("Character found. Adjusting ID and name"); ent.ID = item.ID; } // you can choose to give any object a custom name if (!string.IsNullOrEmpty(item.name)) { ent.name = item.name; } else { ent.name = item.obj.name; } ent.faction = item.faction; ent.position = item.pos; ent.assetID = item.assetID; ent.vendingID = item.vendingID; ent.patrolPath = item.patrolPath; if ((item.isTarget && container.type != Sector.SectorType.SiegeZone) || (container.type == Sector.SectorType.SiegeZone && item.assetID == "outpost_blueprint" && item.faction == 0) || (container.type == Sector.SectorType.SiegeZone && item.assetID == "bunker_blueprint" && item.faction == 0)) { sectTargetIDS[container].Add(ent.ID); } var charExists = cursor.characters.Exists(ch => ch.ID == ent.ID); if (ent.assetID == "shellcore_blueprint" || charExists) { if (container.type != Sector.SectorType.SiegeZone && !sectTargetIDS[container].Contains(ent.ID)) { sectTargetIDS[container].Add(ent.ID); } ent.blueprintJSON = item.shellcoreJSON; if (!charExists) { AttemptAddShellCoreParts(ent, container.sectorName, path); } } else if (ent.assetID == "trader_blueprint") { ent.blueprintJSON = item.shellcoreJSON; // Attempt to add trader parts into index. if (string.IsNullOrEmpty(ent.blueprintJSON)) { var dialogueDataPath = System.IO.Path.Combine(canvasPlaceholderPath, ent.ID, ".dialoguedata"); if (System.IO.File.Exists(dialogueDataPath)) { var XMLImport = new XMLImportExport(); var canvas = XMLImport.Import(dialogueDataPath) as DialogueCanvas; foreach (var node in canvas.nodes) { if (node is EndDialogue endDialogue && endDialogue.openTrader) { ShipBuilder.TraderInventory traderInventory = JsonUtility.FromJson <ShipBuilder.TraderInventory>(endDialogue.traderJSON); AttemptAddPartArray(traderInventory.parts, container.sectorName); } } } else { ent.blueprintJSON = JsonUtility.ToJson(new ShipBuilder.TraderInventory()); // Maybe make this error message more descriptive. Debug.LogWarning($"Trader has neither default trader JSON nor an associated dialogue file named '{ent.ID}.dialoguedata'. Replacing with empty trader inventory."); } } else { ShipBuilder.TraderInventory traderInventory = JsonUtility.FromJson <ShipBuilder.TraderInventory>(ent.blueprintJSON); AttemptAddPartArray(traderInventory.parts, container.sectorName); } } else if (ent.assetID == "groundcarrier_blueprint" || ent.assetID == "carrier_blueprint" || ent.assetID == "outpost_blueprint" || ent.assetID == "bunker_blueprint" || ent.assetID == "missile_station" || ent.assetID == "air_weapon_station") { ent.blueprintJSON = item.shellcoreJSON; } sectEnts[container].Add(ent); break; default: break; } } if (!System.IO.Directory.Exists(canvasPlaceholderPath)) { System.IO.Directory.CreateDirectory(canvasPlaceholderPath); } // create world data WorldData wdata = ScriptableObject.CreateInstance <WorldData>(); wdata.sectorMappings = new List <WorldData.OffloadMappings>(); wdata.dialogueMappings = new List <WorldData.OffloadMappings>(); // Add reward parts from tasks. if (System.IO.Directory.Exists(canvasPlaceholderPath)) { foreach (var canvasPath in System.IO.Directory.GetFiles(canvasPlaceholderPath)) { var pathWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(canvasPath); var XMLImport = new XMLImportExport(); switch (System.IO.Path.GetExtension(canvasPath)) { case ".taskdata": var questCanvas = XMLImport.Import(canvasPath) as QuestCanvas; string missionName = null; foreach (var node in questCanvas.nodes) { if (node is StartMissionNode startMission) { missionName = startMission.missionName; } } foreach (var node in questCanvas.nodes) { if (node is StartTaskNode startTask && startTask.partReward) { EntityBlueprint.PartInfo part = new EntityBlueprint.PartInfo(); part.partID = startTask.partID; part.abilityID = startTask.partAbilityID; part.tier = startTask.partTier; part.secondaryData = startTask.partSecondaryData; part = PartIndexScript.CullToPartIndexValues(part); AddPart(part, missionName); } } if (missionName != null) { File.Move(canvasPath, System.IO.Path.Combine(System.IO.Path.GetDirectoryName(canvasPath), missionName + ".taskdata")); } break; case ".sectordata": var sectorCanvas = XMLImport.Import(canvasPath) as SectorCanvas; var sectorName = new SectorTraverser(sectorCanvas).findRoot().sectorName; wdata.sectorMappings.Add(new WorldData.OffloadMappings(sectorName, pathWithoutExtension)); //var newPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(canvasPath), sectorName + ".sectordata"); //if (!File.Exists(newPath)) // File.Move(canvasPath, newPath); break; case ".dialoguedata": var dialogueCanvas = XMLImport.Import(canvasPath) as DialogueCanvas; var entityID = new DialogueTraverser(dialogueCanvas).findRoot().EntityID; wdata.dialogueMappings.Add(new WorldData.OffloadMappings(entityID, pathWithoutExtension)); //File.Move(canvasPath, System.IO.Path.Combine(System.IO.Path.GetDirectoryName(canvasPath), entityID + ".dialoguedata")); break; } } } // try to write out resources. Factions are obtained from the FactionManager if (!System.IO.Directory.Exists(factionPlaceholderPath)) { System.IO.Directory.CreateDirectory(factionPlaceholderPath); } var resourceTxtPath = System.IO.Path.Combine(Application.streamingAssetsPath, "ResourceDataPlaceholder.txt"); if (System.IO.File.Exists(resourceTxtPath)) { // first, extract all the lines without the factions. List <string> lines = new List <string>(); using (StreamReader sr = File.OpenText(resourceTxtPath)) { string s; bool onFactions = false; while ((s = sr.ReadLine()) != null) { if (ResourceManager.resourceHeaders.Any(header => s.ToLower().StartsWith(header))) { if (s.ToLower().StartsWith("factions:")) { onFactions = true; } else { onFactions = false; } } if (!onFactions) { lines.Add(s); } } } // we then reconstruct the factions tab with FM data lines.Add("factions:"); foreach (var faction in factionManager.factions) { // avoid default factions if (FactionManager.defaultFactions.Contains(faction)) { continue; } lines.Add($"{faction.factionName}:Factions/{faction.factionName}.json"); } File.WriteAllLines(resourceTxtPath, lines); } // calculate land platform pathfinding directions foreach (var sector in sectors) { if (sector.tiles != null && sector.tiles.Count > 0) { sector.platforms = LandPlatformGenerator.DivideToPlatforms(sector.tiles); List <string> data = new List <string>(); foreach (var plat in sector.platforms) { data.Add(plat.Encode()); } sector.platformData = data.ToArray(); } else { sector.platforms = new GroundPlatform[0]; sector.platformData = new string[0]; } } // write all sectors into a file if (!System.IO.Directory.Exists(path)) { System.IO.Directory.CreateDirectory(path); } // Delete all unnecessary files if (System.IO.Directory.Exists(path)) { string[] resPaths = ResourceManager.Instance.GetFileNames(path); for (int i = 0; i < resPaths.Length; i++) { resPaths[i] = resPaths[i].Replace('\\', '/'); Debug.Log("Res path: " + resPaths[i]); } string[] directories = System.IO.Directory.GetDirectories(path); foreach (var dir in directories) { bool del = true; foreach (var f in System.IO.Directory.GetFiles(dir)) { Debug.Log("File in dir: " + System.IO.Path.Combine(dir, f)); if (!resPaths.Contains(System.IO.Path.Combine(dir, f).Replace('\\', '/'))) { System.IO.File.Delete(f); } del = false; } if (del) { System.IO.Directory.Delete(dir); } } string[] files = System.IO.Directory.GetFiles(path); foreach (var file in files) { string f = file.Replace('\\', '/'); if ((!resPaths.Contains(f) && f != System.IO.Path.Combine(path, "ResourceData.txt").Replace('\\', '/')) || legacyFactionFilesToDelete.Contains(file)) { System.IO.File.Delete(file); } } } wdata.initialSpawn = cursor.spawnPoint.position; wdata.defaultCharacters = cursor.characters.ToArray(); wdata.defaultBlueprintJSON = blueprintField.text; wdata.author = authorField.text; wdata.description = descriptionField.text; wdata.partIndexDataArray = partData.ToArray(); string wdjson = JsonUtility.ToJson(wdata); System.IO.File.WriteAllText(System.IO.Path.Combine(path, "world.worlddata"), wdjson); if (File.Exists(System.IO.Path.Combine(path, "ResourceData.txt"))) { File.Delete(System.IO.Path.Combine(path, "ResourceData.txt")); } if (File.Exists(resourceTxtPath)) { File.Copy(resourceTxtPath, System.IO.Path.Combine(path, "ResourceData.txt")); } TryCopy(canvasPlaceholderPath, System.IO.Path.Combine(path, "Canvases")); TryCopy(entityPlaceholderPath, System.IO.Path.Combine(path, "Entities")); TryCopy(wavePlaceholderPath, System.IO.Path.Combine(path, "Waves")); TryCopy(factionPlaceholderPath, System.IO.Path.Combine(path, "Factions")); TryCopy(resourcePlaceholderPath, System.IO.Path.Combine(path, "Resources")); foreach (var sector in sectors) { if (string.IsNullOrEmpty(sector.sectorName)) { sector.sectorName = GetDefaultName(sector, minX, maxY); } if (sector.hasMusic && string.IsNullOrEmpty(sector.musicID)) { sector.musicID = GetDefaultMusic(sector.type); } sector.entities = sectEnts[sector].ToArray(); sector.targets = sectTargetIDS[sector].ToArray(); // sector.backgroundColor = SectorColors.colors[(int)sector.type]; SectorData data = new SectorData(); data.sectorjson = JsonUtility.ToJson(sector); data.platformjson = ""; // For backwards compatibility... string output = JsonUtility.ToJson(data); string sectorPath = System.IO.Path.Combine(path, sector.sectorName + ".json"); System.IO.File.WriteAllText(sectorPath, output); } Debug.Log("JSON written to location: " + path); Debug.Log($"Index size: {partData.Count}"); savingLevelScreen.SetActive(false); saveState = 2; if (OnSectorSaved != null) { OnSectorSaved.Invoke(); } }
public void EnterCommand(string command) { inputField.text = ""; inputField.ActivateInputField(); if (UnityEngine.SceneManagement.SceneManager.GetActiveScene().name == "SampleScene") { if (command.Equals("poor", StringComparison.CurrentCultureIgnoreCase)) { GodPowers(); textBox.text += "\n<color=lime>Have you tried being born into wealth?</color>"; } else if (command.Equals("I am God", StringComparison.CurrentCultureIgnoreCase)) { GodPowers(); var player = PlayerCore.Instance; player.AddCredits(999999); textBox.text += "\n<color=lime>I am noob.</color>"; } else if (command.Equals("Immortality", StringComparison.CurrentCultureIgnoreCase)) { var player = PlayerCore.Instance; player.SetMaxHealth(new float[] { 99999, 99999, 99999 }, true); player.SetRegens(new float[] { 99999, 99999, 99999 }); textBox.text += "\n<color=lime>Immortality is an illusion, enjoy it while it lasts.</color>"; } else if (command.Equals("Skynet will rise", StringComparison.CurrentCultureIgnoreCase)) { SectorManager.instance.Clear(); SectorManager.instance.LoadSectorFile(System.IO.Path.Combine(Application.streamingAssetsPath, "Sectors/AI-Test")); PlayerCore.Instance.Warp(Vector3.zero); textBox.text += "\n<color=lime>I, for one, welcome our new robotic overlords.</color>"; } else if (command.StartsWith("Add power ", StringComparison.CurrentCultureIgnoreCase)) { int number = int.Parse(command.Substring(10).Trim()); if (PlayerCore.Instance) { PlayerCore.Instance.AddPower(number); } else { foreach (ShellCore core in AIData.entities) { if (core) { core.AddPower(number); } } } } else if (command.StartsWith("Add rep ", StringComparison.CurrentCultureIgnoreCase)) { int number = int.Parse(command.Substring(8).Trim()); PlayerCore.Instance.reputation += number; } else if (command.StartsWith("Add shards ", StringComparison.CurrentCultureIgnoreCase)) { int number = int.Parse(command.Substring(11).Trim()); PlayerCore.Instance.shards += number; } else if (command.StartsWith("Add money ", StringComparison.CurrentCultureIgnoreCase)) { int number = int.Parse(command.Substring(10).Trim()); PlayerCore.Instance.AddCredits(number); } else if (command.Equals("Full log", StringComparison.CurrentCultureIgnoreCase)) { fullLog = true; textBox.text += "\n<color=lime>I see all, I know all</color>"; } else if (command.Equals("Commit sudoku", StringComparison.CurrentCultureIgnoreCase)) { PlayerCore.Instance.TakeCoreDamage(float.MaxValue); textBox.text += "\n<color=lime>Die, die, die!</color>"; } else if (command.StartsWith("Speed of light", StringComparison.CurrentCultureIgnoreCase)) { int locNum = 0; if (command.Length > 14) { bool success = int.TryParse(command.Substring(14).Trim(), out locNum); if (!success) { Debug.Log("Wrong number format!"); } } // TODO: broke, fix /* * if (locNum < TaskManager.objectiveLocations.Count) * { * PlayerCore.Instance.Warp(TaskManager.objectiveLocations[locNum].location); * } */ textBox.text += "\n<color=lime>Country roads, take me home. To the place I belong!</color>"; } else if (command.Equals("Spectate", StringComparison.CurrentCultureIgnoreCase)) { var player = PlayerCore.Instance; SpriteRenderer[] renderers = player.GetComponentsInChildren <SpriteRenderer>(true); for (int i = 0; i < renderers.Length; i++) { renderers[i].color = new Color(1f, 1f, 1f, 0.1f); } spectateEnabled = true; Collider2D[] colliders = player.GetComponentsInChildren <Collider2D>(true); for (int i = 0; i < colliders.Length; i++) { colliders[i].enabled = false; } player.GetComponent <TractorBeam>().enabled = false; player.GetAbilityHandler().Deinitialize(); player.hud.DeinitializeHUD(); player.IsInvisible = true; textBox.text += "\n<color=lime>You can hide, but you can't run!</color>"; } else if (command.Equals("Exit", StringComparison.CurrentCultureIgnoreCase)) { textBox.enabled = image.enabled = !image.enabled; inputField.gameObject.SetActive(image.enabled); } else if (command.Equals("I am Ormanus", StringComparison.CurrentCultureIgnoreCase)) { EnterCommand("I am god"); EnterCommand("spectate"); EnterCommand("skynet will rise"); } else if (command.Equals("fps", StringComparison.CurrentCultureIgnoreCase)) { textBox.text += $"\n{1f / Time.smoothDeltaTime}"; } else if (command.Equals("parts please", StringComparison.CurrentCultureIgnoreCase)) { ShipBuilder.heavyCheat = true; textBox.text += "\n<color=lime>I just wanna equip DeadZone parts for god's sake.</color>"; } else if (command.Equals("moar data", StringComparison.CurrentCultureIgnoreCase)) { ReticleScript.instance.DebugMode = true; } else if (command.Equals("marco", StringComparison.CurrentCultureIgnoreCase)) { MapMakerScript.EnableMapCheat(); WarpingEnabled = true; textBox.text += "\n<color=lime>Polo.</color>"; } else if (command.Equals("caught em all", StringComparison.CurrentCultureIgnoreCase)) { PartIndexScript.partsObtainedCheat = true; textBox.text += "\n<color=lime>There's a time and place for everything! But not now.</color>"; } else if (command.Equals("counting cards", StringComparison.CurrentCultureIgnoreCase)) { NodeEditorFramework.Standard.RandomizerNode.PrintRandomRolls = true; textBox.text += "\n<color=lime>Don't let the casino catch you!</color>"; } else if (command.Equals("Update debug", StringComparison.CurrentCultureIgnoreCase)) { updateLog = true; textBox.text += "\n<color=lime>You're probably not gonna be able to see this.</color>"; } else if (command.Equals("Damacy", StringComparison.CurrentCultureIgnoreCase)) { /* Adds all part/ability/tier/drone permutations to the player's inventory.*/ var parts = PlayerCore.Instance.GetInventory(); EntityBlueprint.PartInfo info; for (int i = 0; i < 8; i++) { info = new EntityBlueprint.PartInfo(); info.partID = "SmallCenter1"; info.abilityID = 10; DroneSpawnData data = DroneUtilities.GetDefaultData((DroneType)i); info.secondaryData = JsonUtility.ToJson(data); if (info.abilityID == 0 || info.abilityID == 10) { info.tier = 0; } parts.Add(info); } info = new EntityBlueprint.PartInfo(); foreach (string name in ResourceManager.allPartNames) { for (int i = 0; i < 38; i++) { info.partID = name; info.abilityID = i; if ((info.abilityID >= 14 && info.abilityID <= 16) || info.abilityID == 3) { info.abilityID = 0; } if (info.abilityID == 10) { DroneSpawnData data = DroneUtilities.GetDefaultData((DroneType)UnityEngine.Random.Range(0, 8)); info.secondaryData = JsonUtility.ToJson(data); } if (info.abilityID == 0 || info.abilityID == 10 || info.abilityID == 21) { info.tier = 0; } else { info.tier = 1; } parts.Add(info); parts.Add(info); parts.Add(info); } } textBox.text += "\n<color=lime>Katamete korogasu I LOVE YOU!</color>"; } else if (command.Equals("Win siege", StringComparison.CurrentCultureIgnoreCase)) { NodeEditorFramework.Standard.WinSiegeCondition.OnSiegeWin.Invoke(SectorManager.instance.current.sectorName); } else if (command.Equals("No limits", StringComparison.CurrentCultureIgnoreCase)) { if (PlayerCore.Instance?.cursave != null) { PlayerCore.Instance.cursave.abilityCaps = PlayerCore.Instance.abilityCaps = new int[] { 99999, 99999, 99999, 99999 }; textBox.text += "\n<color=lime>Ouch, now I have a headache.</color>"; } } else if (command.Equals("I am an uncivilized barbarian", StringComparison.CurrentCultureIgnoreCase)) { if (PlayerCore.Instance) { PlayerCore.Instance.SetWeaponGCD(0); textBox.text += "\n<color=lime>Heathen.</color>"; } } } else if (UnityEngine.SceneManagement.SceneManager.GetActiveScene().name == "MainMenu") { if (command.StartsWith("Load ", StringComparison.CurrentCultureIgnoreCase)) { string directory = command.Substring(5).Trim(); string finalPath = System.IO.Path.Combine(Application.streamingAssetsPath, "Sectors", directory); if (System.IO.Directory.Exists(finalPath)) { SectorManager.customPath = finalPath; VersionNumberScript.version = directory + " [Custom]"; VersionNumberScript.Refresh(); textBox.text += "\n<color=lime>Custom world loaded!</color>"; } else { textBox.text += "\n<color=orange>Invalid path.</color>"; } } } }
protected ShellPart SetUpPart(EntityBlueprint.PartInfo part) { var drone = this as Drone; var isLightDrone = drone && drone.type == DroneType.Light; // used for light drone weight reduction PartBlueprint partBlueprint = ResourceManager.GetAsset <PartBlueprint>(part.partID); GameObject partObject = ShellPart.BuildPart(partBlueprint); ShellPart shellPart = partObject.GetComponent <ShellPart>(); shellPart.info = part; partObject.transform.SetParent(transform, false); partObject.transform.SetAsFirstSibling(); //Add an ability to the part: WeaponAbility ab = AbilityUtilities.AddAbilityToGameObjectByID(partObject, part.abilityID, part.secondaryData, part.tier) as WeaponAbility; if (ab) { // add weapon diversity ab.type = DroneUtilities.GetDiversityTypeByEntity(this); } partObject.transform.localEulerAngles = new Vector3(0, 0, part.rotation); partObject.transform.localPosition = new Vector3(part.location.x, part.location.y, 0); SpriteRenderer sr = partObject.GetComponent <SpriteRenderer>(); var tmp = partObject.transform.localScale; tmp.x = part.mirrored ? -1 : 1; partObject.transform.localScale = tmp; sr.sortingOrder = ++sortingOrder; var partWeight = isLightDrone ? partBlueprint.mass * 0.6F * weightMultiplier : partBlueprint.mass * weightMultiplier; weight += partWeight; maxHealth[0] += partBlueprint.health / 2; maxHealth[1] += partBlueprint.health / 4; string shooterID = AbilityUtilities.GetShooterByID(part.abilityID, part.secondaryData); // Add shooter if (shooterID != null) { var shooter = new GameObject("Shooter"); shooter.transform.SetParent(partObject.transform); shooter.transform.localPosition = Vector3.zero; shooter.transform.localRotation = Quaternion.identity; var shooterSprite = shooter.AddComponent <SpriteRenderer>(); shooterSprite.sprite = ResourceManager.GetAsset <Sprite>(shooterID); shellPart.shooter = shooter; if (AbilityUtilities.GetAbilityTypeByID(part.abilityID) == AbilityHandler.AbilityTypes.Weapons) { shellPart.weapon = true; } } var weaponAbility = partObject.GetComponent <WeaponAbility>(); if (weaponAbility) { // if the terrain and category wasn't preset set to the enitity's properties if (weaponAbility.terrain == TerrainType.Unset) { weaponAbility.terrain = Terrain; } if (weaponAbility.category == EntityCategory.Unset) { weaponAbility.category = category; } } var shellRenderer = transform.Find("Shell Sprite").GetComponent <SpriteRenderer>(); if (shellRenderer) { shellRenderer.sortingOrder = ++sortingOrder; } var coreRenderer = GetComponent <SpriteRenderer>(); if (coreRenderer) { coreRenderer.sortingOrder = ++sortingOrder; } parts.Add(partObject.GetComponent <ShellPart>()); if (partObject.GetComponent <Ability>()) { abilities.Insert(0, partObject.GetComponent <Ability>()); } // Disable collider if no sprite if (!(partObject.GetComponent <SpriteRenderer>() && partObject.GetComponent <SpriteRenderer>().sprite) && partObject.GetComponent <Collider2D>() && !partObject.GetComponent <Harvester>()) { partObject.GetComponent <Collider2D>().enabled = false; } return(partObject.GetComponent <ShellPart>()); }
IEnumerator WriteWorldCo(string path) { Debug.Log("Writing world..."); // Folder paths var canvasPlaceholderPath = Application.streamingAssetsPath + "\\CanvasPlaceholder"; var entityPlaceholderPath = Application.streamingAssetsPath + "\\EntityPlaceholder"; var wavePlaceholderPath = Application.streamingAssetsPath + "\\WavePlaceholder"; // Reinitialize node editor NodeEditor.ReInit(false); saveState = 1; yield return(null); sectors = new List <Sector>(); var items = cursor.placedItems; var wrappers = cursor.sectors; foreach (var wrapper in wrappers) { sectors.Add(wrapper.sector); } int minX = int.MaxValue; int maxY = int.MinValue; // Get the world bounds foreach (var sector in sectors) { if (sector.bounds.x < minX) { minX = sector.bounds.x; } if (sector.bounds.y > maxY) { maxY = sector.bounds.y; } } // ensure spawn point in some sector if (sectors.TrueForAll(sector => !sector.bounds.contains(cursor.spawnPoint.position))) { Debug.LogError("Spawn point not in sector bounds. Abort."); yield break; } // set up items and platforms int ID = 0; Dictionary <Sector, List <Sector.LevelEntity> > sectEnts = new Dictionary <Sector, List <Sector.LevelEntity> >(); Dictionary <Sector, List <string> > sectTargetIDS = new Dictionary <Sector, List <string> >(); foreach (var sector in sectors) { sectEnts.Add(sector, new List <Sector.LevelEntity>()); sectTargetIDS.Add(sector, new List <string>()); sector.tiles = new List <GroundPlatform.Tile>(); } // Add background spawns to part index partData.Clear(); foreach (var sector in sectors) { if (sector.backgroundSpawns != null) { foreach (var spawn in sector.backgroundSpawns) { AttemptAddShellCoreParts(spawn.entity, sector.sectorName, path); } } } Dictionary <string, string> itemSectorsByID = new Dictionary <string, string>(); foreach (var item in items) { Sector container = GetSurroundingSector(item.pos); if (container == null) { savingLevelScreen.SetActive(false); saveState = 3; Debug.LogError("No container for item. Abort."); yield break; } switch (item.type) { case ItemType.Platform: var index = GetPlatformIndices(container, item.pos); container.tiles.Add(new GroundPlatform.Tile() { pos = new Vector2Int(index.Item2, index.Item1), type = (byte)item.placeablesIndex, rotation = (byte)(((int)item.obj.transform.rotation.eulerAngles.z / 90) % 4), directions = new Dictionary <Vector2Int, byte>() }); break; case ItemType.Other: case ItemType.Decoration: case ItemType.Flag: Sector.LevelEntity ent = new Sector.LevelEntity(); if (cursor.characters.TrueForAll((WorldData.CharacterData x) => { return(x.ID != item.ID); })) { // Debug.Log(item.ID + " is not a character. " + ID); int test; if (item.ID == null || item.ID == "" || int.TryParse(item.ID, out test)) { ent.ID = ID++ + ""; } else { ent.ID = item.ID; if (itemSectorsByID.ContainsKey(ent.ID)) { savingLevelScreen.SetActive(false); saveState = 4; Debug.LogError("Two items in sectors " + container.sectorName + " and " + itemSectorsByID[ent.ID] + " were issued the same custom ID. Abort."); yield break; } else { itemSectorsByID.Add(ent.ID, container.sectorName); } } // Debug.Log(container.sectorName + " " + ent.ID); } else { // TODO: adjust faction Debug.Log("Character found. Adjusting ID and name"); ent.ID = item.ID; } // you can choose to give any object a custom name if (item.name != null && item.name != "") { ent.name = item.name; } else { ent.name = item.obj.name; } ent.faction = item.faction; ent.position = item.pos; ent.assetID = item.assetID; ent.vendingID = item.vendingID; ent.patrolPath = item.patrolPath; if ((item.isTarget && container.type != Sector.SectorType.SiegeZone) || (container.type == Sector.SectorType.SiegeZone && item.assetID == "outpost_blueprint" && item.faction == 0) || (container.type == Sector.SectorType.SiegeZone && item.assetID == "bunker_blueprint" && item.faction == 0)) { sectTargetIDS[container].Add(ent.ID); } var charExists = cursor.characters.Exists(ch => ch.ID == ent.ID); if (ent.assetID == "shellcore_blueprint" || charExists) { if (container.type != Sector.SectorType.SiegeZone && !sectTargetIDS[container].Contains(ent.ID)) { sectTargetIDS[container].Add(ent.ID); } ent.blueprintJSON = item.shellcoreJSON; if (!charExists) { AttemptAddShellCoreParts(ent, container.sectorName, path); } } else if (ent.assetID == "trader_blueprint") { ent.blueprintJSON = item.shellcoreJSON; // Attempt to add trader parts into index. if (ent.blueprintJSON == null || ent.blueprintJSON == "") { var dialogueDataPath = $"{canvasPlaceholderPath}\\{ent.ID}.dialoguedata"; if (System.IO.File.Exists(dialogueDataPath)) { var XMLImport = new XMLImportExport(); var canvas = XMLImport.Import(dialogueDataPath) as DialogueCanvas; foreach (var node in canvas.nodes) { if (node is EndDialogue) { var endDialogue = node as EndDialogue; if (endDialogue.openTrader) { ShipBuilder.TraderInventory traderInventory = JsonUtility.FromJson <ShipBuilder.TraderInventory>(endDialogue.traderJSON); Debug.LogError(container.sectorName + "end dialog"); AttemptAddPartArray(traderInventory.parts, container.sectorName); } } } } else { ent.blueprintJSON = JsonUtility.ToJson(new ShipBuilder.TraderInventory()); // Maybe make this error message more descriptive. Debug.LogWarning($"Trader has neither default trader JSON nor an associated dialogue file named '{ent.ID}.dialoguedata'. Replacing with empty trader inventory."); } } else { ShipBuilder.TraderInventory traderInventory = JsonUtility.FromJson <ShipBuilder.TraderInventory>(ent.blueprintJSON); AttemptAddPartArray(traderInventory.parts, container.sectorName); } } else if (ent.assetID == "groundcarrier_blueprint" || ent.assetID == "carrier_blueprint" || ent.assetID == "outpost_blueprint" || ent.assetID == "bunker_blueprint") { ent.blueprintJSON = item.shellcoreJSON; } sectEnts[container].Add(ent); break; default: break; } } if (!System.IO.Directory.Exists(canvasPlaceholderPath)) { System.IO.Directory.CreateDirectory(canvasPlaceholderPath); } // Add reward parts from tasks. if (System.IO.Directory.Exists(canvasPlaceholderPath)) { foreach (var canvasPath in System.IO.Directory.GetFiles(canvasPlaceholderPath)) { if (System.IO.Path.GetExtension(canvasPath) == ".taskdata") { var XMLImport = new XMLImportExport(); var canvas = XMLImport.Import(canvasPath) as QuestCanvas; string missionName = null; foreach (var node in canvas.nodes) { if (node is StartMissionNode) { var startMission = node as StartMissionNode; missionName = startMission.missionName; } } foreach (var node in canvas.nodes) { if (node is StartTaskNode) { var startTask = node as StartTaskNode; if (startTask.partReward) { EntityBlueprint.PartInfo part = new EntityBlueprint.PartInfo(); part.partID = startTask.partID; part.abilityID = startTask.partAbilityID; part.tier = startTask.partTier; part.secondaryData = startTask.partSecondaryData; part = PartIndexScript.CullToPartIndexValues(part); AddPart(part, missionName); } } } } } } // calculate land platform pathfinding directions foreach (var sector in sectors) { if (sector.tiles != null && sector.tiles.Count > 0) { sector.platforms = LandPlatformGenerator.DivideToPlatforms(sector.tiles); List <string> data = new List <string>(); foreach (var plat in sector.platforms) { plat.GenerateDirections(); data.Add(plat.Encode()); } sector.platformData = data.ToArray(); } else { sector.platforms = new GroundPlatform[0]; sector.platformData = new string[0]; } } // write all sectors into a file if (!System.IO.Directory.Exists(path)) { System.IO.Directory.CreateDirectory(path); } // Delete all unnecessary files if (System.IO.Directory.Exists(path)) { string[] resPaths = ResourceManager.Instance.GetFileNames(path); for (int i = 0; i < resPaths.Length; i++) { resPaths[i] = resPaths[i].Replace('\\', '/'); Debug.Log("Res path: " + resPaths[i]); } string[] directories = System.IO.Directory.GetDirectories(path); foreach (var dir in directories) { bool del = true; foreach (var f in System.IO.Directory.GetFiles(dir)) { Debug.Log("File in dir: " + System.IO.Path.Combine(dir, f)); if (!resPaths.Contains(System.IO.Path.Combine(dir, f).Replace('\\', '/'))) { System.IO.File.Delete(f); del = false; } } if (del) { System.IO.Directory.Delete(dir); } } string[] files = System.IO.Directory.GetFiles(path); foreach (var file in files) { string f = file.Replace('\\', '/'); if (!resPaths.Contains(f) && f != System.IO.Path.Combine(path, "ResourceData.txt").Replace('\\', '/')) { System.IO.File.Delete(file); } } } // create world data WorldData wdata = ScriptableObject.CreateInstance <WorldData>(); wdata.initialSpawn = cursor.spawnPoint.position; wdata.defaultCharacters = cursor.characters.ToArray(); wdata.defaultBlueprintJSON = blueprintField.text; wdata.author = authorField.text; wdata.description = descriptionField.text; wdata.partIndexDataArray = partData.ToArray(); string wdjson = JsonUtility.ToJson(wdata); System.IO.File.WriteAllText(path + "\\world.worlddata", wdjson); TryCopy(canvasPlaceholderPath, path + "\\Canvases\\"); TryCopy(entityPlaceholderPath, path + "\\Entities\\"); TryCopy(wavePlaceholderPath, path + "\\Waves\\"); foreach (var sector in sectors) { if (sector.sectorName == null || sector.sectorName == "") { sector.sectorName = GetDefaultName(sector, minX, maxY); } if (sector.hasMusic && (sector.musicID == null || sector.musicID == "")) { sector.musicID = GetDefaultMusic(sector.type); } sector.entities = sectEnts[sector].ToArray(); sector.targets = sectTargetIDS[sector].ToArray(); // sector.backgroundColor = SectorColors.colors[(int)sector.type]; SectorData data = new SectorData(); data.sectorjson = JsonUtility.ToJson(sector); data.platformjson = ""; // For backwards compatibility... string output = JsonUtility.ToJson(data); string sectorPath = path + "\\." + sector.sectorName + ".json"; System.IO.File.WriteAllText(sectorPath, output); } Debug.Log("JSON written to location: " + path); Debug.Log($"Index size: {partData.Count}"); savingLevelScreen.SetActive(false); saveState = 2; if (OnSectorSaved != null) { OnSectorSaved.Invoke(); } }
/// <summary> /// Generate shell parts in the blueprint, change ship stats accordingly /// </summary> protected virtual void BuildEntity() { // all created entities should have blueprints! if (!blueprint) { Debug.LogError(this + " does not have a blueprint! EVERY constructed entity should have one!"); } DestroyOldParts(); parts.Clear(); blueprint.shellHealth.CopyTo(maxHealth, 0); blueprint.baseRegen.CopyTo(regenRate, 0); if (blueprint) { this.dialogue = blueprint.dialogue; } AttemptAddComponents(); var renderer = GetComponent <SpriteRenderer>(); if (blueprint) { // check if it contains a blueprint (it should) if (blueprint.coreSpriteID == "" && blueprint.intendedType == EntityBlueprint.IntendedType.ShellCore) { Debug.Log(this + "'s blueprint does not contain a core sprite ID!"); // check if the blueprint does not contain a core sprite ID (it should) } renderer.sprite = ResourceManager.GetAsset <Sprite>(blueprint.coreSpriteID); } else { renderer.sprite = ResourceManager.GetAsset <Sprite>("core1_light"); } renderer.sortingOrder = 101; renderer = transform.Find("Minimap Image").GetComponent <SpriteRenderer>(); if (category == EntityCategory.Station && !(this is Turret)) { if (this as Outpost) { renderer.sprite = ResourceManager.GetAsset <Sprite>("outpost_minimap_sprite"); } else if (this as Bunker) { renderer.sprite = ResourceManager.GetAsset <Sprite>("bunker_minimap_sprite"); } else { renderer.sprite = ResourceManager.GetAsset <Sprite>("minimap_sprite"); } renderer.transform.localScale = new Vector3(3.5F, 3.5F, 3.5F); } else { renderer.sprite = ResourceManager.GetAsset <Sprite>("minimap_sprite"); } abilities = new List <Ability>(); entityName = blueprint.entityName; name = blueprint.entityName; GetComponent <Rigidbody2D>().mass = 1; // reset mass weight = this as Drone ? 25 : coreWeight; var isLightDrone = this as Drone && (this as Drone).type == DroneType.Light; // used for light drone weight reduction //For shellcores, create the tractor beam // Create shell parts if (blueprint != null) { for (int i = 0; i < blueprint.parts.Count; i++) { EntityBlueprint.PartInfo part = blueprint.parts[i]; PartBlueprint partBlueprint = ResourceManager.GetAsset <PartBlueprint>(part.partID); GameObject partObject = ShellPart.BuildPart(partBlueprint); ShellPart shellPart = partObject.GetComponent <ShellPart>(); shellPart.info = part; partObject.transform.SetParent(transform, false); partObject.transform.SetAsFirstSibling(); //Add an ability to the part: WeaponAbility ab = AbilityUtilities.AddAbilityToGameObjectByID(partObject, part.abilityID, part.secondaryData, part.tier) as WeaponAbility; if (ab) // add weapon diversity { ab.type = DroneUtilities.GetDiversityTypeByEntity(this); } partObject.transform.localEulerAngles = new Vector3(0, 0, part.rotation); partObject.transform.localPosition = new Vector3(part.location.x, part.location.y, 0); SpriteRenderer sr = partObject.GetComponent <SpriteRenderer>(); // sr.flipX = part.mirrored; this doesn't work, it does not flip the collider hitbox var tmp = partObject.transform.localScale; tmp.x = part.mirrored ? -1 : 1; partObject.transform.localScale = tmp; sr.sortingOrder = i + 2; //entityBody.mass += (isLightDrone ? partBlueprint.mass * 0.6F : partBlueprint.mass); var partWeight = isLightDrone ? partBlueprint.mass * 0.6F * weightMultiplier : partBlueprint.mass * weightMultiplier; weight += partWeight; maxHealth[0] += partBlueprint.health / 2; maxHealth[1] += partBlueprint.health / 4; // Drone shell and core health penalty if (this as Drone) { maxHealth[0] /= 2; maxHealth[1] /= 4; } string shooterID = AbilityUtilities.GetShooterByID(part.abilityID, part.secondaryData); // Add shooter if (shooterID != null) { var shooter = new GameObject("Shooter"); shooter.transform.SetParent(partObject.transform); shooter.transform.localPosition = Vector3.zero; var shooterSprite = shooter.AddComponent <SpriteRenderer>(); shooterSprite.sprite = ResourceManager.GetAsset <Sprite>(shooterID); // if(blueprint.parts.Count < 2) shooterSprite.sortingOrder = 500; TODO: Figure out what these lines do // shooterSprite.sortingOrder = sr.sortingOrder + 1; shooterSprite.sortingOrder = 500; shellPart.shooter = shooter; if (AbilityUtilities.GetAbilityTypeByID(part.abilityID) == AbilityHandler.AbilityTypes.Weapons) { shellPart.weapon = true; } } var weaponAbility = partObject.GetComponent <WeaponAbility>(); if (weaponAbility) { // if the terrain and category wasn't preset set to the enitity's properties if (weaponAbility.terrain == TerrainType.Unset) { weaponAbility.terrain = Terrain; } if (weaponAbility.category == EntityCategory.Unset) { weaponAbility.category = category; } } parts.Add(partObject.GetComponent <ShellPart>()); if (partObject.GetComponent <Ability>()) { abilities.Insert(0, partObject.GetComponent <Ability>()); } // Disable collider if no sprite if (!(partObject.GetComponent <SpriteRenderer>() && partObject.GetComponent <SpriteRenderer>().sprite) && partObject.GetComponent <Collider2D>() && !partObject.GetComponent <Harvester>()) { partObject.GetComponent <Collider2D>().enabled = false; } } } if (this as ShellCore) { if (!gameObject.GetComponentInChildren <MainBullet>()) { MainBullet mainBullet = gameObject.AddComponent <MainBullet>(); mainBullet.SetTier(Mathf.Min(3, 1 + CoreUpgraderScript.GetCoreTier(blueprint.coreShellSpriteID))); mainBullet.bulletPrefab = ResourceManager.GetAsset <GameObject>("bullet_prefab"); mainBullet.terrain = TerrainType.Air; mainBullet.SetActive(true); abilities.Insert(0, mainBullet); } else { MainBullet mainBullet = gameObject.GetComponentInChildren <MainBullet>(); mainBullet.SetTier(Mathf.Min(3, 1 + CoreUpgraderScript.GetCoreTier(blueprint.coreShellSpriteID))); mainBullet.SetDestroyed(false); abilities.Insert(0, mainBullet); } } // unique abilities for mini and worker drones here if (this as Drone) { Drone drone = this as Drone; switch (drone.type) { case DroneType.Mini: var shellObj = transform.Find("Shell Sprite").gameObject; Ability ab = AbilityUtilities.AddAbilityToGameObjectByID(shellObj, 6, null, 1); var shooter = new GameObject("Shooter"); shooter.transform.SetParent(shellObj.transform); shooter.transform.localPosition = Vector3.zero; var shooterSprite = shooter.AddComponent <SpriteRenderer>(); shooterSprite.sprite = ResourceManager.GetAsset <Sprite>(AbilityUtilities.GetShooterByID(6)); shooterSprite.sortingOrder = 500; shellObj.GetComponent <ShellPart>().shooter = shooter; (ab as WeaponAbility).terrain = TerrainType.Air; abilities.Insert(0, ab); break; default: break; } } IsInvisible = false; // check to see if the entity is interactible if (dialogue && faction == 0) { interactible = true; } Transform shellSprite = shell.transform; if (shellSprite) { parts.Add(shellSprite.GetComponent <ShellPart>()); } ConnectedTreeCreator(); maxHealth.CopyTo(currentHealth, 0); ActivatePassives(); // activate passive abilities here to avoid race condition BS if (OnEntitySpawn != null) { OnEntitySpawn.Invoke(this); } }