public static bool GetPadAt(Vector3Int pos, out RoamingJobState state) { try { if (pos != null) { lock (RoamingJobManager.Objectives) { foreach (var kvp in RoamingJobManager.Objectives) { foreach (var p in kvp.Value) { if (p.Value.TryGetValue(pos, out var roamingJobState)) { if (roamingJobState.RoamObjective == SettlersBuiltIn.ItemTypes.TELEPORTPAD) { state = p.Value[pos]; return(true); } } } } } } } catch (Exception ex) { SettlersLogger.LogError(ex); } state = null; return(false); }
private static void UpdateMagicItemms(ColonyState state) { try { if (state.HealingUpdateTime < Time.SecondsSinceStartDouble) { var colony = state.ColonyRef; foreach (var follower in colony.Followers) { var inv = ColonistInventory.Get(follower); if (inv.HealingItemUpdateTime < Time.SecondsSinceStartDouble) { var hasBandages = colony.Stockpile.Contains(TreatedBandage.Item.ItemIndex) || colony.Stockpile.Contains(Bandage.Item.ItemIndex); if (hasBandages && follower.health < follower.Colony.NPCHealthMax && !HealingOverTimeNPC.NPCIsBeingHealed(follower)) { var healing = false; if (follower.Colony.NPCHealthMax - follower.health > TreatedBandage.INITIALHEAL) { colony.Stockpile.TryRemove(TreatedBandage.Item.ItemIndex); healing = true; AudioManager.SendAudio(follower.Position.Vector, GameLoader.NAMESPACE + ".Bandage"); var heal = new HealingOverTimeNPC(follower, TreatedBandage.INITIALHEAL, TreatedBandage.TOTALHOT, 5, TreatedBandage.Item.ItemIndex); } if (!healing) { colony.Stockpile.TryRemove(Bandage.Item.ItemIndex); healing = true; AudioManager.SendAudio(follower.Position.Vector, GameLoader.NAMESPACE + ".Bandage"); var heal = new HealingOverTimeNPC(follower, Bandage.INITIALHEAL, Bandage.TOTALHOT, 5, Bandage.Item.ItemIndex); } } inv.HealingItemUpdateTime = Time.SecondsSinceStartDouble + Random.Next(3, 5); } } state.HealingUpdateTime = Time.SecondsSinceStartDouble + 5; } } catch (Exception ex) { SettlersLogger.LogError(ex); } }
public static void OnNPCRecruited(NPCBase npc) { try { var npcInv = ColonistInventory.Get(npc); if (npc.CustomData == null) { npc.CustomData = new JSONNode(); } if (npc.NPCType.IsLaborer) { npcInv.UnemployedLeaveTime = TimeCycle.TotalHours + 48; } if (npc.CustomData.TryGetAs(ISSETTLER, out bool settler) && settler) { return; } var ps = ColonyState.GetColonyState(npc.Colony); npc.FoodHoursCarried = ServerManager.ServerSettings.NPCs.InitialFoodCarriedHours; if (ps.SettlersEnabled != API.Models.SettlersState.Disabled) { if (SettlersConfiguration.GetorDefault("ColonistsRecruitment", true)) { if (npc.Colony.FollowerCount > MAX_BUYABLE) { if (!ColonistsBought.BoughtCount.ContainsKey(npc.Colony)) { ColonistsBought.BoughtCount.Add(npc.Colony, new List <double>()); } ColonistsBought.BoughtCount[npc.Colony].Add(TimeCycle.TotalHours + 24); } ColonistInventory.Get(npc); UpdateFoodUse(ps); } else { PandaChat.Send(npc.Colony, _localizationHelper, "AdminDisabled", ChatColor.red); npc.health = 0; npc.Update(); } } } catch (Exception ex) { SettlersLogger.LogError(ex); } }
public static ItemId Repair(Colony colony, RoamingJobState machineState) { var retval = ItemId.GetItemId(GameLoader.NAMESPACE + ".Repairing"); try { if (machineState.GetActionEnergy(MachineConstants.REPAIR) < .75f && TurretSettings.ContainsKey(machineState.RoamObjective)) { var repaired = false; var requiredForFix = new List <InventoryItem>(); var stockpile = colony.Stockpile; foreach (var durability in TurretSettings[machineState.RoamObjective] .RequiredForFix.OrderByDescending(s => s.Key)) { if (machineState.GetActionEnergy(MachineConstants.REPAIR) < durability.Key) { requiredForFix = durability.Value; break; } } if (stockpile.Contains(requiredForFix)) { stockpile.TryRemove(requiredForFix); repaired = true; } else { foreach (var item in requiredForFix) { if (!stockpile.Contains(item) && item.Type != 0) { retval = ItemId.GetItemId(item.Type); break; } } } if (repaired) { machineState.ResetActionToMaxLoad(MachineConstants.REPAIR); } } } catch (Exception ex) { SettlersLogger.LogError(ex); } return(retval); }
public static void GenerateRecipes() { List <string> recipesAdded = new List <string>(); foreach (var item in _loadedItems) { var baseType = item.Key; var typeName = GameLoader.TYPEPREFIX + baseType + ".Blocks"; var typeNameRecipe = typeName + ".Recipe"; if (!recipesAdded.Contains(typeNameRecipe)) { var recipe = new TypeRecipeBase(); recipe.name = typeNameRecipe; recipe.requires.Add(new RecipeItem(baseType, 5)); recipe.Job = Jobs.DecorBuilderRegister.JOB_NAME; foreach (var i in item.Value) { recipe.results.Add(new RecipeResult(i.Item1)); } var requirements = new List <InventoryItem>(); var results = new List <RecipeResult>(); recipe.JsonSerialize(); foreach (var ri in recipe.requires) { if (ItemTypes.IndexLookup.TryGetIndex(ri.type, out var itemIndex)) { requirements.Add(new InventoryItem(itemIndex, ri.amount)); } else { SettlersLogger.LogToFile("\"" + typeNameRecipe + "\" bad requirement \"" + ri.type + "\""); } } foreach (var ri in recipe.results) { results.Add(ri); } var newRecipe = new Recipe(recipe.name, requirements, results, 0, 0, (int)recipe.defaultPriority); ServerManager.RecipeStorage.AddLimitTypeRecipe(recipe.Job, newRecipe); } } }
public static void CalculateBeds(Colony colony) { var cs = ColonyState.GetColonyState(colony); if (cs.Difficulty.Name != GameDifficulty.Normal.Name) { BedStateObject bso = new BedStateObject(); bso.Colony = colony; colony.BedTracker.ForeachBedInstance(ForEachAction, ref bso); int happiness = 0; foreach (var bed in bso.Beds) { try { var bedEnd = bed.Value.Position.Add(-1, 0, 0); if (bed.Key.BedType == ColonyBuiltIn.ItemTypes.BEDXP) { bedEnd = bed.Value.Position.Add(1, 0, 0); } else if (bed.Key.BedType == ColonyBuiltIn.ItemTypes.BEDZN) { bedEnd = bed.Value.Position.Add(0, 0, -1); } else if (bed.Key.BedType == ColonyBuiltIn.ItemTypes.BEDZP) { bedEnd = bed.Value.Position.Add(0, 0, 1); } if (!IsHappy(bed.Value.Position, bedEnd)) { happiness -= 1; bed.Value.IsHappy = false; } } catch (Exception ex) { SettlersLogger.LogError(ex); } } CachedHappiness[colony] = happiness; BedCache[colony] = bso; } }
public static void OnPlayerMoved(Players.Player p, UnityEngine.Vector3 oldPosition) { try { var posBelow = new Vector3Int(p.Position); if (GetPadAt(posBelow, out var machineState) && _paired.ContainsKey(machineState.Position) && GetPadAt(_paired[machineState.Position], out var paired)) { var startInt = Time.SecondsSinceStartInt; if (!_cooldown.ContainsKey(p)) { _cooldown.Add(p, 0); } if (_cooldown[p] <= startInt) { if (machineState.GetActionEnergy(MachineConstants.REPAIR) <= 0) { PandaChat.Send(p, _localizationHelper, "NeedsRepair", ChatColor.red); return; } if (machineState.GetActionEnergy(MachineConstants.REFUEL) <= 0) { PandaChat.Send(p, _localizationHelper, "", ChatColor.red); return; } Teleport.TeleportTo(p, paired.Position.Vector); AudioManager.SendAudio(machineState.Position.Vector, GameLoader.NAMESPACE + ".TeleportPadMachineAudio"); AudioManager.SendAudio(paired.Position.Vector, GameLoader.NAMESPACE + ".TeleportPadMachineAudio"); _cooldown[p] = SettlersConfiguration.GetorDefault("TeleportPadCooldown", 15) + startInt; } } } catch (Exception ex) { SettlersLogger.LogError(ex); } }
public static bool TryGetSchematicMetadata(string name, int colonyId, out SchematicMetadata metadata) { try { if (TryGetScematicMetadataFilePath(name + METADATA_FILEEXT, out string savePath)) { var json = JSON.Deserialize(savePath); metadata = JsonConvert.DeserializeObject <SchematicMetadata>(json.ToString()); } else { metadata = GenerateMetaData(name, colonyId); } } catch (Exception ex) { metadata = null; SettlersLogger.LogError(ex, "error getting metadata for schematic {0}", name); } return(metadata != null); }
public static ItemId Reload(Colony colony, RoamingJobState machineState) { var retval = ItemId.GetItemId(GameLoader.NAMESPACE + ".Reload"); try { if (TurretSettings.ContainsKey(machineState.RoamObjective) && machineState.GetActionEnergy(MachineConstants.RELOAD) < .75f) { var stockpile = colony.Stockpile; while (stockpile.Contains(TurretSettings[machineState.RoamObjective].Ammo) && machineState.GetActionEnergy(MachineConstants.RELOAD) <= RoamingJobState.GetActionsMaxEnergy(MachineConstants.RELOAD, colony, MachineConstants.MECHANICAL)) { if (stockpile.TryRemove(TurretSettings[machineState.RoamObjective].Ammo)) { machineState.AddToActionEmergy(MachineConstants.RELOAD, TurretSettings[machineState.RoamObjective].AmmoReloadValue); if (TurretSettings[machineState.RoamObjective].Ammo.Any(itm => itm.Type == ColonyBuiltIn.ItemTypes.GUNPOWDERPOUCH)) { stockpile.Add(ColonyBuiltIn.ItemTypes.LINENPOUCH); } } } if (machineState.GetActionEnergy(MachineConstants.RELOAD) < RoamingJobState.GetActionsMaxEnergy(MachineConstants.RELOAD, colony, MachineConstants.MECHANICAL)) { retval = ItemId.GetItemId(TurretSettings[machineState.RoamObjective].Ammo.FirstOrDefault(ammo => !stockpile.Contains(ammo)).Type); } } } catch (Exception ex) { SettlersLogger.LogError(ex); } return(retval); }
public static void OnSavingColony(Colony c, JSONNode n) { try { if (Knight.Knights.ContainsKey(c)) { if (n.HasChild(GameLoader.NAMESPACE + ".Knights")) { n.RemoveChild(GameLoader.NAMESPACE + ".Knights"); } var knightsNode = new JSONNode(NodeType.Array); foreach (var knight in Knight.Knights[c]) { var knightNode = new JSONNode().SetAs(nameof(knight.PatrolType), knight.PatrolType); var patrolPoints = new JSONNode(NodeType.Array); foreach (var point in knight.PatrolPoints) { patrolPoints.AddToArray((JSONNode)point); } knightNode.SetAs(nameof(knight.PatrolPoints), patrolPoints); knightsNode.AddToArray(knightNode); } n[GameLoader.NAMESPACE + ".Knights"] = knightsNode; } } catch (Exception ex) { SettlersLogger.LogError(ex); } }
public static void OnPlayerPushedNetworkUIButton(ButtonPressCallbackData data) { if (data.ButtonIdentifier == GameLoader.NAMESPACE + ".ChatHistory") { SettlersLogger.Log(data.ButtonIdentifier); NetworkMenu menu = new NetworkMenu(); var file = Path.Combine(GameLoader.SAVE_LOC, "ChatLog.log"); menu.ForceClosePopups = true; menu.Width = 1000; menu.Height = 700; menu.LocalStorage.SetAs("header", _localizationHelper.LocalizeOrDefault("ChatHistory", data.Player)); if (File.Exists(file)) { foreach (var item in File.ReadAllLines(file)) { menu.Items.Add(new Label(new LabelData(item, UnityEngine.Color.black, UnityEngine.TextAnchor.MiddleLeft, 18, LabelData.ELocalizationType.None))); } } NetworkMenuManager.SendServerPopup(data.Player, menu); } }
public static NetworkMenu ToolbarMenu(ButtonPressCallbackData data, bool error = false, bool?selectAll = null) { NetworkMenu menu = new NetworkMenu(); menu.LocalStorage.SetAs("header", _localizationHelper.LocalizeOrDefault("MoveItemsToBackpack", data.Player)); menu.Width = 1000; menu.Height = 600; try { if (error) { menu.Items.Add(new Label(new LabelData(_localizationHelper.GetLocalizationKey("invalidNumber"), UnityEngine.Color.red))); } List <ValueTuple <IItem, int> > headerItems = new List <ValueTuple <IItem, int> >(); headerItems.Add(ValueTuple.Create <IItem, int>(new Label(new LabelData(_localizationHelper.GetLocalizationKey("Numberofitems"), UnityEngine.Color.black)), 333)); headerItems.Add(ValueTuple.Create <IItem, int>(new InputField("Backpack.NumberOfItems"), 333)); headerItems.Add(ValueTuple.Create <IItem, int>(new ButtonCallback("Backpack.MoveItemsToBackpackFromToolbar", new LabelData(_localizationHelper.GetLocalizationKey("MoveItemsToBackpack"), UnityEngine.Color.black)), 333)); menu.Items.Add(new HorizontalRow(headerItems)); menu.Items.Add(new Line(UnityEngine.Color.black)); List <ValueTuple <IItem, int> > items = new List <ValueTuple <IItem, int> >(); items.Add(ValueTuple.Create <IItem, int>(new ButtonCallback("Backpack.MainMenu", new LabelData(_localizationHelper.GetLocalizationKey("Back"), UnityEngine.Color.black)), 250)); items.Add(ValueTuple.Create <IItem, int>(new EmptySpace(), 250)); items.Add(ValueTuple.Create <IItem, int>(new EmptySpace(), 250)); bool selected = false; if (selectAll == true) { selected = true; } else if (selectAll == false) { selected = false; } if (selected) { items.Add(ValueTuple.Create <IItem, int>(new ButtonCallback("Backpack.SelectNoneInBackpackToolbar", new LabelData(_localizationHelper.GetLocalizationKey("SelectNone"), UnityEngine.Color.black)), 250)); } else { items.Add(ValueTuple.Create <IItem, int>(new ButtonCallback("Backpack.SelectAllInBackpackToolbar", new LabelData(_localizationHelper.GetLocalizationKey("SelectAll"), UnityEngine.Color.black)), 250)); } menu.Items.Add(new HorizontalRow(items)); menu.Items.Add(new Line(UnityEngine.Color.black)); var invRef = data.Player.Inventory; var backpackID = ItemId.GetItemId(Backpack.NAME); foreach (var itemKvp in invRef.Items) { if (itemKvp.Type != ColonyBuiltIn.ItemTypes.AIR.Id && itemKvp.Type != backpackID) { items = new List <ValueTuple <IItem, int> >(); items.Add(ValueTuple.Create <IItem, int>(new ItemIcon(itemKvp.Type), 250)); items.Add(ValueTuple.Create <IItem, int>(new Label(new LabelData(ItemId.GetItemId(itemKvp.Type), UnityEngine.Color.black, UnityEngine.TextAnchor.MiddleLeft, 18, LabelData.ELocalizationType.Type)), 250)); items.Add(ValueTuple.Create <IItem, int>(new Label(new LabelData(_localizationHelper.LocalizeOrDefault("Toolbar", data.Player) + ": " + itemKvp.Amount.ToString(), UnityEngine.Color.black)), 250)); items.Add(ValueTuple.Create <IItem, int>(new Toggle(new LabelData(_localizationHelper.LocalizeOrDefault("Select", data.Player), UnityEngine.Color.black), "Backpack." + itemKvp.Type + ".ItemSelected"), 250)); if (selectAll == null) { menu.LocalStorage.TryGetAs("Backpack." + itemKvp.Type + ".ItemSelected", out selected); } menu.LocalStorage.SetAs("Backpack." + itemKvp.Type + ".ItemSelected", selected); menu.Items.Add(new HorizontalRow(items)); } } } catch (Exception ex) { SettlersLogger.LogError(ex); } return(menu); }
public void DoJob(IIterationType iterationType, IAreaJob areaJob, ConstructionJobInstance job, ref NPCBase.NPCState state) { int i = 0; var bpi = iterationType as SchematicIterator; if (bpi == null) { SettlersLogger.Log(ChatColor.yellow, "iterationType must be of type SchematicIterator for the SchematicBuilder."); state.SetIndicator(new Shared.IndicatorState(5f, ColonyBuiltIn.ItemTypes.ERRORIDLE.Name)); AreaJobTracker.RemoveJob(areaJob); return; } while (true) // This is to move past air. { if (i > 4000) { break; } var adjX = iterationType.CurrentPosition.x - bpi.BuilderSchematic.StartPos.x; var adjY = iterationType.CurrentPosition.y - bpi.BuilderSchematic.StartPos.y; var adjZ = iterationType.CurrentPosition.z - bpi.BuilderSchematic.StartPos.z; var block = bpi.BuilderSchematic.GetBlock(adjX, adjY, adjZ); var mapped = block.MappedBlock; var buildType = ItemTypes.GetType(mapped.CSIndex); if (buildType == null) { state.SetIndicator(new Shared.IndicatorState(5f, ColonyBuiltIn.ItemTypes.ERRORIDLE.Name)); AreaJobTracker.RemoveJob(areaJob); return; } if (World.TryGetTypeAt(iterationType.CurrentPosition, out ushort foundTypeIndex)) { i++; var founditemId = ItemId.GetItemId(foundTypeIndex); if (foundTypeIndex == buildType.ItemIndex || buildType.Name.Contains("bedend") || (founditemId.Name.Contains("bedend") && buildType.ItemIndex == ColonyBuiltIn.ItemTypes.AIR)) // check if the blocks are the same, if they are, move past. Most of the time this will be air. { if (iterationType.MoveNext()) { continue; } else { if (_needsChunkLoaded.Contains(bpi)) { _needsChunkLoaded.Remove(bpi); } state.SetIndicator(new Shared.IndicatorState(5f, ColonyBuiltIn.ItemTypes.ERRORIDLE.Name)); AreaJobTracker.RemoveJob(areaJob); return; } } Stockpile ownerStockPile = areaJob.Owner.Stockpile; bool stockpileContainsBuildItem = buildType.ItemIndex == ColonyBuiltIn.ItemTypes.AIR.Id; if (!stockpileContainsBuildItem && ownerStockPile.Contains(buildType.ItemIndex)) { stockpileContainsBuildItem = true; } if (!stockpileContainsBuildItem && buildType.Name.Contains("bed") && ownerStockPile.Contains(ItemId.GetItemId("bed"))) { stockpileContainsBuildItem = true; } if (!stockpileContainsBuildItem && !string.IsNullOrWhiteSpace(buildType.ParentType) && ownerStockPile.Contains(buildType.ParentItemType.ItemIndex)) { stockpileContainsBuildItem = true; } if (stockpileContainsBuildItem) { if (foundTypeIndex != ColonyBuiltIn.ItemTypes.AIR.Id && foundTypeIndex != ColonyBuiltIn.ItemTypes.WATER.Id) { var foundItem = ItemTypes.GetType(foundTypeIndex); if (foundItem != null && foundItem.ItemIndex != ColonyBuiltIn.ItemTypes.AIR.Id && foundItem.OnRemoveItems != null && foundItem.OnRemoveItems.Count > 0) { ownerStockPile.Add(foundItem.OnRemoveItems.Select(itm => itm.item).ToList()); } } var changeResult = ServerManager.TryChangeBlock(iterationType.CurrentPosition, buildType.ItemIndex, new BlockChangeRequestOrigin(job.Owner), ESetBlockFlags.DefaultAudio); if (changeResult == EServerChangeBlockResult.Success) { if (buildType.ItemIndex != ColonyBuiltIn.ItemTypes.AIR.Id) { if (--job.StoredItemCount <= 0) { job.ShouldTakeItems = true; state.JobIsDone = true; } ownerStockPile.TryRemove(buildType.ItemIndex); if (buildType.Name.Contains("bed")) { ownerStockPile.TryRemove(ItemId.GetItemId("bed")); } } } else if (changeResult != EServerChangeBlockResult.CancelledByCallback) { if (!_needsChunkLoaded.Contains(bpi)) { _needsChunkLoaded.Add(bpi); } state.SetIndicator(new Shared.IndicatorState(5f, buildType.Name)); ChunkQueue.QueuePlayerSurrounding(iterationType.CurrentPosition.ToChunk()); return; } } else { state.SetIndicator(new Shared.IndicatorState(5f, buildType.Name, true, false)); return; } } else { if (!_needsChunkLoaded.Contains(bpi)) { _needsChunkLoaded.Add(bpi); } ChunkQueue.QueuePlayerSurrounding(iterationType.CurrentPosition.ToChunk()); state.SetIndicator(new Shared.IndicatorState(5f, ColonyBuiltIn.ItemTypes.ERRORIDLE.Name)); return; } if (iterationType.MoveNext()) { if (buildType.ItemIndex != ColonyBuiltIn.ItemTypes.AIR.Id) { state.SetIndicator(new Shared.IndicatorState(GetCooldown(), buildType.ItemIndex)); } else { state.SetIndicator(new Shared.IndicatorState(GetCooldown(), foundTypeIndex)); } return; } else { if (_needsChunkLoaded.Contains(bpi)) { _needsChunkLoaded.Remove(bpi); } // failed to find next position to do job at, self-destruct state.SetIndicator(new Shared.IndicatorState(5f, ColonyBuiltIn.ItemTypes.ERRORIDLE.Name)); AreaJobTracker.RemoveJob(areaJob); return; } } if (iterationType.MoveNext()) { state.SetIndicator(new Shared.IndicatorState(5f, ColonyBuiltIn.ItemTypes.ERRORIDLE.Name)); return; } else { if (_needsChunkLoaded.Contains(bpi)) { _needsChunkLoaded.Remove(bpi); } // failed to find next position to do job at, self-destruct state.SetIndicator(new Shared.IndicatorState(5f, ColonyBuiltIn.ItemTypes.ERRORIDLE.Name)); AreaJobTracker.RemoveJob(areaJob); SettlersLogger.Log(ChatColor.yellow, "Failed to MoveNext after while. Iterator position: {0}.", iterationType.CurrentPosition); return; } }
public static void DoWork(Colony colony, RoamingJobState machineState) { try { if (TurretSettings.ContainsKey(machineState.RoamObjective) && machineState.GetActionEnergy(MachineConstants.REPAIR) > 0 && machineState.GetActionEnergy(MachineConstants.REFUEL) > 0 && machineState.NextTimeForWork < Time.SecondsSinceStartDouble) { var stockpile = colony.Stockpile; machineState.SubtractFromActionEnergy(MachineConstants.REPAIR, TurretSettings[machineState.RoamObjective].DurabilityPerDoWork); machineState.SubtractFromActionEnergy(MachineConstants.REFUEL, TurretSettings[machineState.RoamObjective].FuelPerDoWork); if (machineState.GetActionEnergy(MachineConstants.RELOAD) > 0) { var totalDamage = TurretSettings[machineState.RoamObjective].TotalDamage; var monster = MonsterTracker.Find(machineState.Position.Add(0, 1, 0), TurretSettings[machineState.RoamObjective].Range, totalDamage); if (monster == null) { monster = MonsterTracker.Find(machineState.Position.Add(1, 0, 0), TurretSettings[machineState.RoamObjective].Range, totalDamage); } if (monster == null) { monster = MonsterTracker.Find(machineState.Position.Add(-1, 0, 0), TurretSettings[machineState.RoamObjective].Range, totalDamage); } if (monster == null) { monster = MonsterTracker.Find(machineState.Position.Add(0, -1, 0), TurretSettings[machineState.RoamObjective].Range, totalDamage); } if (monster == null) { monster = MonsterTracker.Find(machineState.Position.Add(0, 0, 1), TurretSettings[machineState.RoamObjective].Range, totalDamage); } if (monster == null) { monster = MonsterTracker.Find(machineState.Position.Add(0, 0, -1), TurretSettings[machineState.RoamObjective].Range, totalDamage); } if (monster != null) { machineState.SubtractFromActionEnergy(MachineConstants.RELOAD, TurretSettings[machineState.RoamObjective].AmmoValue); if (World.TryGetTypeAt(machineState.Position.Add(0, 1, 0), out ushort above) && above == ColonyBuiltIn.ItemTypes.AIR.Id) { Indicator.SendIconIndicatorNear(machineState.Position.Add(0, 1, 0).Vector, new IndicatorState(TurretSettings[machineState.RoamObjective].WorkTime, TurretSettings[machineState.RoamObjective].Ammo.FirstOrDefault().Type)); } if (TurretSettings[machineState.RoamObjective].OnShootAudio != null) { AudioManager.SendAudio(machineState.Position.Vector, TurretSettings[machineState.RoamObjective].OnShootAudio); } if (TurretSettings[machineState.RoamObjective].OnHitAudio != null) { AudioManager.SendAudio(monster.PositionToAimFor, TurretSettings[machineState.RoamObjective].OnHitAudio); } TurretSettings[machineState.RoamObjective] .ProjectileAnimation .SendMoveToInterpolated(machineState.Position.Vector, monster.PositionToAimFor); ServerManager.SendParticleTrail(machineState.Position.Vector, monster.PositionToAimFor, 2); monster.OnHit(totalDamage, machineState, ModLoader.OnHitData.EHitSourceType.Misc); } } machineState.NextTimeForWork = machineState.RoamingJobSettings.WorkTime + Time.SecondsSinceStartDouble; } } catch (Exception ex) { SettlersLogger.LogError(ex, $"Turret shoot for {machineState.RoamObjective}"); } }
public void DoJob(IIterationType iterationType, IAreaJob areaJob, ConstructionJobInstance job, ref NPCBase.NPCState state) { int i = 0; var bpi = iterationType as ArchitectIterator; if (bpi == null) { SettlersLogger.Log(ChatColor.yellow, "iterationType must be of type ArchitectIterator for the ArchitectBuilder."); state.SetIndicator(new Shared.IndicatorState(5f, ColonyBuiltIn.ItemTypes.ERRORIDLE.Name)); AreaJobTracker.RemoveJob(areaJob); return; } while (true) // move past air { if (i > 4000) { break; } i++; var adjX = iterationType.CurrentPosition.x - bpi.BuilderSchematic.StartPos.x; var adjY = iterationType.CurrentPosition.y - bpi.BuilderSchematic.StartPos.y; var adjZ = iterationType.CurrentPosition.z - bpi.BuilderSchematic.StartPos.z; var prvX = bpi.PreviousPosition.x - bpi.BuilderSchematic.StartPos.x; var prvY = bpi.PreviousPosition.y - bpi.BuilderSchematic.StartPos.y; var prvZ = bpi.PreviousPosition.z - bpi.BuilderSchematic.StartPos.z; if (World.TryGetTypeAt(iterationType.CurrentPosition, out ItemTypes.ItemType foundType)) { state.SetCooldown(2); state.SetIndicator(new Shared.IndicatorState(2, foundType.Name)); if (foundType.ItemIndex == ColonyBuiltIn.ItemTypes.AIR || foundType.Name == ColonyBuiltIn.ItemTypes.BANNER) { if (!MoveNext(iterationType, areaJob, job, bpi, prvX, prvY, prvZ)) { return; } continue; } try { bpi.BuilderSchematic.Blocks[adjX, adjY, adjZ].BlockID = foundType.Name; } catch (IndexOutOfRangeException) { SettlersLogger.Log(ChatColor.red, $"Index out of range on ArchitectBuilder {adjX}, {adjY}, {adjZ} to a max of {bpi.BuilderSchematic.Blocks.GetLength(0)}, {bpi.BuilderSchematic.Blocks.GetLength(1)}, {bpi.BuilderSchematic.Blocks.GetLength(2)}."); CleanupJob(iterationType, areaJob, job, bpi, prvX, prvY, prvZ); break; } if (!foundType.Name.Contains("bedend")) { ServerManager.TryChangeBlock(iterationType.CurrentPosition, SettlersBuiltIn.ItemTypes.SELECTOR.Id, new BlockChangeRequestOrigin(job.Owner), ESetBlockFlags.DefaultAudio); } MoveNext(iterationType, areaJob, job, bpi, prvX, prvY, prvZ); } else { if (!_needsChunkLoaded.Contains(bpi)) { _needsChunkLoaded.Add(bpi); } ChunkQueue.QueuePlayerSurrounding(iterationType.CurrentPosition.ToChunk()); state.SetIndicator(new Shared.IndicatorState(5f, ColonyBuiltIn.ItemTypes.ERRORIDLE.Name)); } break; } }
public static void OnTryChangeBlockUser(ModLoader.OnTryChangeBlockData d) { try { if (d.CallbackState == ModLoader.OnTryChangeBlockData.ECallbackState.Cancelled || d.RequestOrigin.AsPlayer == null || d.RequestOrigin.AsPlayer.ActiveColony == null || d.TypeOld == null) { return; } if (d.TypeOld.ItemIndex == PatrolFlag.ItemIndex) { var toRemove = default(Knight); if (!Knight.Knights.ContainsKey(d.RequestOrigin.AsPlayer.ActiveColony)) { Knight.Knights.Add(d.RequestOrigin.AsPlayer.ActiveColony, new List <Knight>()); } foreach (var knight in Knight.Knights[d.RequestOrigin.AsPlayer.ActiveColony]) { try { if (knight.PatrolPoints.Contains(d.Position)) { toRemove = knight; knight.OnRemove(); foreach (var flagPoint in knight.PatrolPoints) { if (flagPoint != d.Position) { if (World.TryGetTypeAt(flagPoint, out ushort objType) && objType == PatrolFlag.ItemIndex) { ServerManager.TryChangeBlock(flagPoint, ColonyBuiltIn.ItemTypes.AIR.Id); d.RequestOrigin.AsPlayer.ActiveColony.Stockpile.Add(PatrolFlag.ItemIndex); } } } break; } } catch (Exception ex) { SettlersLogger.LogError(ex); } } if (toRemove != default(Knight)) { PandaChat.Send(d.RequestOrigin.AsPlayer, _localizationHelper, "PatrolsNotActive", ChatColor.orange, toRemove.PatrolPoints.Count.ToString()); Knight.Knights[d.RequestOrigin.AsPlayer.ActiveColony].Remove(toRemove); d.RequestOrigin.AsPlayer.ActiveColony.JobFinder.UnregisterJob(toRemove); d.RequestOrigin.AsPlayer.ActiveColony.JobFinder.Update(); } var state = PlayerState.GetPlayerState(d.RequestOrigin.AsPlayer); if (state.FlagsPlaced.Contains(d.Position)) { state.FlagsPlaced.Remove(d.Position); ServerManager.TryChangeBlock(d.Position, ColonyBuiltIn.ItemTypes.AIR.Id); } d.RequestOrigin.AsPlayer.ActiveColony.Stockpile.Add(PatrolFlag.ItemIndex); } } catch (Exception ex) { SettlersLogger.LogError(ex); } }
private static bool EvaluateBeds(ColonyState state) { var update = false; try { if (!TimeCycle.IsDay && TimeCycle.TotalHours > state.NextBedTime) { var remainingBeds = state.ColonyRef.BedTracker.CalculateTotalBedCount() - state.ColonyRef.FollowerCount; var left = 0; if (remainingBeds >= 0) { state.NeedsABed = 0; } else { if (state.NeedsABed == 0) { state.NeedsABed = TimeCycle.TotalHours + 24; PandaChat.Send(state.ColonyRef, _localizationHelper, SettlerReasoning.GetNeedBed(), ChatColor.grey); } else if (state.NeedsABed <= TimeCycle.TotalHours) { List <NPCBase> leaving = new List <NPCBase>(); foreach (var follower in state.ColonyRef.Followers) { if (follower.UsedBed == null) { left++; leaving.Add(follower); } } state.NeedsABed = 0; foreach (var npc in leaving) { NPCLeaving(npc); } } if (left > 0) { PandaChat.Send(state.ColonyRef, _localizationHelper, string.Concat(SettlerReasoning.GetNoBed(), string.Format(" {0} colonists have left your colony.", left)), ChatColor.red); update = true; } state.ColonyRef.SendCommonData(); } state.NextBedTime = TimeCycle.TotalHours + Random.Next(5, 8); } } catch (Exception ex) { SettlersLogger.LogError(ex, "EvaluateBeds"); } return(update); }
public static bool EvaluateSettlers(ColonyState state) { var update = false; if (state.SettlersEnabled != SettlersState.Disabled && state.ColonyRef.OwnerIsOnline()) { if (state.NextGenTime == 0) { state.NextGenTime = TimeCycle.TotalHours + Random.Next(8, 16); } if (TimeCycle.TotalHours > state.NextGenTime && state.ColonyRef.FollowerCount >= MAX_BUYABLE) { var chance = state.ColonyRef.TemporaryData.GetAsOrDefault(GameLoader.NAMESPACE + ".SettlerChance", 0f) + state.Difficulty.GetorDefault("AdditionalChance", 0); chance += SettlerEvaluation.SpawnChance(state); var rand = Random.NextFloat(); if (chance > rand) { var addCount = Math.Floor(SettlerManager.MaxPerSpawn(state.ColonyRef) * chance); // if we lost alot of colonists add extra to help build back up. if (state.ColonyRef.FollowerCount < state.HighestColonistCount) { var diff = state.HighestColonistCount - state.ColonyRef.FollowerCount; addCount += Math.Floor(diff * .25); } try { var skillChance = state.ColonyRef.TemporaryData.GetAsOrDefault(GameLoader.NAMESPACE + ".SkilledLaborer", 0f) + SkilledSettlerChance.GetSkilledSettlerChance(state.ColonyRef); var numbSkilled = 0; rand = Random.NextFloat(); try { if (skillChance > rand) { numbSkilled = Pipliz.Random.Next(1, 2 + Pipliz.Math.RoundToInt(state.ColonyRef.TemporaryData.GetAsOrDefault(GameLoader.NAMESPACE + ".NumberSkilledLaborer", 0f))); } } catch (Exception ex) { SettlersLogger.Log("NumberSkilledLaborer"); SettlersLogger.LogError(ex); } if (addCount > 0) { if (addCount > 30) { addCount = 30; } if (state.SettlersEnabled == SettlersState.AlwaysAccept) { AddNewSettlers(addCount, numbSkilled, state); } else { foreach (var p in state.ColonyRef.Owners) { if (p.IsConnected()) { NetworkMenu menu = new NetworkMenu(); menu.LocalStorage.SetAs("header", state.ColonyRef.Name + ": " + addCount + _localizationHelper.LocalizeOrDefault("NewSettlers", p)); menu.Width = 600; menu.Height = 300; menu.Items.Add(new ButtonCallback(GameLoader.NAMESPACE + ".NewSettlers." + state.ColonyRef.ColonyID + ".Accept." + addCount + "." + numbSkilled, new LabelData(_localizationHelper.GetLocalizationKey("Accept"), UnityEngine.Color.black, UnityEngine.TextAnchor.MiddleCenter))); menu.Items.Add(new ButtonCallback(GameLoader.NAMESPACE + ".NewSettlers." + state.ColonyRef.ColonyID + ".Decline", new LabelData(_localizationHelper.GetLocalizationKey("Decline"), UnityEngine.Color.black, UnityEngine.TextAnchor.MiddleCenter))); NetworkMenuManager.SendServerPopup(p, menu); } } } } } catch (Exception ex) { SettlersLogger.Log("SkilledLaborer"); SettlersLogger.LogError(ex); } if (state.ColonyRef.FollowerCount > state.HighestColonistCount) { state.HighestColonistCount = state.ColonyRef.FollowerCount; } } state.NextGenTime = TimeCycle.TotalHours + Random.Next(8, 16); state.ColonyRef.SendCommonData(); } } return(update); }
public static void LoadMappingFile(string file) { if (File.Exists(file)) { try { if (JSON.Deserialize(file, out var json)) { foreach (var node in json.LoopArray()) { MappingBlock newBlock = new MappingBlock(); if (node.TryGetAs("type", out int type)) { newBlock.Type = type; } if (node.TryGetAs("meta", out int meta)) { newBlock.Meta = meta; } if (node.TryGetAs("name", out string name)) { newBlock.Name = name; } if (node.TryGetAs("text_type", out string textType)) { newBlock.TextType = textType; } if (node.TryGetAs("cs_type", out string csType)) { newBlock.CSType = csType; if (!CStoMCMappings.ContainsKey(csType)) { CStoMCMappings.Add(csType, new List <MappingBlock>()); } CStoMCMappings[csType].Add(newBlock); } else { SettlersLogger.Log(ChatColor.yellow, "Unable to load item {0} from mapping file. This item will be mapped to air.", name); } if (newBlock.Meta > 0) { MCtoCSMappings[string.Format("{0}:{1}", newBlock.Type, newBlock.Meta)] = newBlock; } else { MCtoCSMappings[newBlock.Type.ToString()] = newBlock; } } } else { SettlersLogger.Log(ChatColor.red, ERROR_MESSAGE, file); } } catch (Exception ex) { SettlersLogger.Log(ChatColor.red, ERROR_MESSAGE, file); SettlersLogger.LogError(ex); } } }
public static void PressButton(ButtonPressCallbackData data) { switch (data.ButtonIdentifier) { case GameLoader.NAMESPACE + ".SetScemanticName": NetworkMenu saveMenu = new NetworkMenu(); saveMenu.LocalStorage.SetAs("header", _localizationHelper.LocalizeOrDefault("SaveSchematic", data.Player)); saveMenu.Width = 600; saveMenu.Height = 300; saveMenu.ForceClosePopups = true; saveMenu.Items.Add(new Label(new LabelData(_localizationHelper.GetLocalizationKey("SaveInstructions"), UnityEngine.Color.black))); saveMenu.Items.Add(new InputField("Construction.SetArchitectArea")); saveMenu.Items.Add(new ButtonCallback(GameLoader.NAMESPACE + ".SetArchitectArea", new LabelData(_localizationHelper.GetLocalizationKey("Start"), UnityEngine.Color.black))); NetworkMenuManager.SendServerPopup(data.Player, saveMenu); break; case GameLoader.NAMESPACE + ".SetArchitectArea": NetworkMenuManager.CloseServerPopup(data.Player); if (data.Storage.TryGetAs("Construction.SetArchitectArea", out string schematicName)) { var colonySaves = GameLoader.Schematic_SAVE_LOC + $"\\{data.Player.ActiveColony.ColonyID}\\"; if (!Directory.Exists(colonySaves)) { Directory.CreateDirectory(colonySaves); } var schematicFile = Path.Combine(colonySaves, schematicName + ".schematic"); if (File.Exists(schematicFile)) { File.Delete(schematicFile); } var metaDataSave = Path.Combine(GameLoader.Schematic_SAVE_LOC, schematicName + ".schematic.metadata.json"); if (File.Exists(metaDataSave)) { File.Delete(metaDataSave); } AreaJobTracker.StartCommandToolSelection(data.Player, new GenericCommandToolSettings() { Key = "pipliz.constructionarea", TranslationKey = _localizationHelper.LocalizeOrDefault("Architect", data.Player), JSONData = new JSONNode().SetAs(ArchitectLoader.NAME + ".ArchitectSchematicName", schematicName).SetAs("constructionType", GameLoader.NAMESPACE + ".Architect"), OneAreaOnly = true, Maximum3DBlockCount = int.MaxValue, Maximum2DBlockCount = int.MaxValue, MaximumHeight = int.MaxValue, MinimumHeight = 1, Minimum2DBlockCount = 1, Minimum3DBlockCount = 1 }); } break; case GameLoader.NAMESPACE + ".ShowMainMenu": SendMainMenu(data.Player); break; case GameLoader.NAMESPACE + ".ShowBuildDetails": List <FileInfo> options = SchematicReader.GetSchematics(data.Player); var index = data.Storage.GetAs <int>(Selected_Schematic); if (options.Count > index) { var selectedSchematic = options[index]; if (SchematicReader.TryGetSchematicMetadata(selectedSchematic.Name, data.Player.ActiveColony.ColonyID, out SchematicMetadata schematicMetadata)) { if (schematicMetadata.Blocks.Count == 1 && schematicMetadata.Blocks.ContainsKey(ColonyBuiltIn.ItemTypes.AIR.Id)) { PandaChat.Send(data.Player, _localizationHelper, "invlaidSchematic", ChatColor.red); } { NetworkMenu menu = new NetworkMenu(); menu.Width = 800; menu.Height = 600; menu.LocalStorage.SetAs("header", selectedSchematic.Name.Replace(".schematic", "") + " " + _localizationHelper.LocalizeOrDefault("Details", data.Player)); menu.Items.Add(new Label(new LabelData(_localizationHelper.LocalizeOrDefault("Height", data.Player) + ": " + schematicMetadata.MaxY, UnityEngine.Color.black))); menu.Items.Add(new Label(new LabelData(_localizationHelper.LocalizeOrDefault("Width", data.Player) + ": " + schematicMetadata.MaxZ, UnityEngine.Color.black))); menu.Items.Add(new Label(new LabelData(_localizationHelper.LocalizeOrDefault("Length", data.Player) + ": " + schematicMetadata.MaxX, UnityEngine.Color.black))); menu.LocalStorage.SetAs(Selected_Schematic, selectedSchematic.Name); List <ValueTuple <IItem, int> > headerItems = new List <ValueTuple <IItem, int> >(); headerItems.Add(ValueTuple.Create <IItem, int>(new Label(new LabelData(" ", UnityEngine.Color.black)), 200)); headerItems.Add(ValueTuple.Create <IItem, int>(new Label(new LabelData(_localizationHelper.LocalizeOrDefault("Item", data.Player), UnityEngine.Color.black)), 200)); headerItems.Add(ValueTuple.Create <IItem, int>(new Label(new LabelData(_localizationHelper.LocalizeOrDefault("Required", data.Player), UnityEngine.Color.black)), 200)); headerItems.Add(ValueTuple.Create <IItem, int>(new Label(new LabelData(_localizationHelper.LocalizeOrDefault("InStockpile", data.Player), UnityEngine.Color.black)), 200)); menu.Items.Add(new HorizontalRow(headerItems)); foreach (var kvp in schematicMetadata.Blocks) { try { if (ItemTypes.TryGetType(kvp.Key, out ItemTypes.ItemType item)) { var stockpileCount = 0; data.Player.ActiveColony.Stockpile.Items.TryGetValue(item.ItemIndex, out stockpileCount); List <ValueTuple <IItem, int> > items = new List <ValueTuple <IItem, int> >(); items.Add(ValueTuple.Create <IItem, int>(new ItemIcon(kvp.Key), 200)); items.Add(ValueTuple.Create <IItem, int>(new Label(new LabelData(item.Name, UnityEngine.Color.black, UnityEngine.TextAnchor.MiddleLeft, 18, LabelData.ELocalizationType.Type)), 200)); items.Add(ValueTuple.Create <IItem, int>(new Label(new LabelData(" x " + kvp.Value.Count, UnityEngine.Color.black)), 200)); items.Add(ValueTuple.Create <IItem, int>(new Label(new LabelData(" x " + stockpileCount, UnityEngine.Color.black)), 200)); menu.Items.Add(new HorizontalRow(items)); } else { SettlersLogger.Log(ChatColor.orange, "Unknown item for schematic: {0}", kvp.Key); } } catch (Exception ex) { SettlersLogger.LogError(ex); } } menu.Items.Add(new DropDown(new LabelData(_localizationHelper.GetLocalizationKey("Rotation"), UnityEngine.Color.black), Selected_Schematic + ".Rotation", _rotation.Select(r => r.ToString()).ToList())); menu.Items.Add(new HorizontalSplit(new ButtonCallback(GameLoader.NAMESPACE + ".ShowMainMenu", new LabelData("Back", UnityEngine.Color.black, UnityEngine.TextAnchor.MiddleCenter)), new ButtonCallback(GameLoader.NAMESPACE + ".SetBuildArea", new LabelData("Build", UnityEngine.Color.black, UnityEngine.TextAnchor.MiddleCenter)))); menu.LocalStorage.SetAs(Selected_Schematic + ".Rotation", 0); NetworkMenuManager.SendServerPopup(data.Player, menu); } } } break; case GameLoader.NAMESPACE + ".SetBuildArea": var scem = data.Storage.GetAs <string>(Selected_Schematic); var rotation = data.Storage.GetAs <int>(Selected_Schematic + ".Rotation"); SettlersLogger.Log("Schematic: {0}", scem); if (SchematicReader.TryGetSchematicMetadata(scem, data.Player.ActiveColony.ColonyID, out SchematicMetadata metadata)) { if (metadata.Blocks.Count == 1 && metadata.Blocks.ContainsKey(ColonyBuiltIn.ItemTypes.AIR.Id)) { PandaChat.Send(data.Player, _localizationHelper, "invlaidSchematic", ChatColor.red); } { _awaitingClick[data.Player] = Tuple.Create(SchematicClickType.Build, scem, _rotation[rotation]); PandaChat.Send(data.Player, _localizationHelper, "instructions"); NetworkMenuManager.CloseServerPopup(data.Player); } } break; } }
public static void AddArmor(Dictionary <string, ItemTypesServer.ItemTypeRaw> items) { try { // ---------------------------------------- // Copper // ---------------------------------------- // Helm var copperHelmName = GameLoader.NAMESPACE + ".CopperHelm"; var copperHelmNode = new JSONNode(); copperHelmNode["icon"] = new JSONNode(GameLoader.ICON_PATH + "CopperHelm.png"); copperHelmNode["isPlaceable"] = new JSONNode(false); var categories = new JSONNode(NodeType.Array); categories.AddToArray(new JSONNode("armor")); copperHelmNode.SetAs("categories", categories); var copperHelm = new ItemTypesServer.ItemTypeRaw(copperHelmName, copperHelmNode); items.Add(copperHelmName, copperHelm); ArmorFactory.ArmorLookup.Add(copperHelm.ItemIndex, new ArmorMetadata(0.05f, 15, copperHelmName, copperHelm, ArmorFactory.ArmorSlot.Helm)); // Chest var copperChestName = GameLoader.NAMESPACE + ".CopperChest"; var copperChestNode = new JSONNode(); copperChestNode["icon"] = new JSONNode(GameLoader.ICON_PATH + "CopperChest.png"); copperChestNode["isPlaceable"] = new JSONNode(false); copperChestNode.SetAs("categories", categories); var copperChest = new ItemTypesServer.ItemTypeRaw(copperChestName, copperChestNode); items.Add(copperChestName, copperChest); ArmorFactory.ArmorLookup.Add(copperChest.ItemIndex, new ArmorMetadata(.1f, 25, copperChestName, copperChest, ArmorFactory.ArmorSlot.Chest)); // Gloves var copperGlovesName = GameLoader.NAMESPACE + ".CopperGloves"; var copperGlovesNode = new JSONNode(); copperGlovesNode["icon"] = new JSONNode(GameLoader.ICON_PATH + "CopperGloves.png"); copperGlovesNode["isPlaceable"] = new JSONNode(false); copperGlovesNode.SetAs("categories", categories); var copperGloves = new ItemTypesServer.ItemTypeRaw(copperGlovesName, copperGlovesNode); items.Add(copperGlovesName, copperGloves); ArmorFactory.ArmorLookup.Add(copperGloves.ItemIndex, new ArmorMetadata(0.025f, 10, copperGlovesName, copperGloves, ArmorFactory.ArmorSlot.Gloves)); // Legs var copperLegsName = GameLoader.NAMESPACE + ".CopperLegs"; var copperLegsNode = new JSONNode(); copperLegsNode["icon"] = new JSONNode(GameLoader.ICON_PATH + "CopperLegs.png"); copperLegsNode["isPlaceable"] = new JSONNode(false); copperLegsNode.SetAs("categories", categories); var copperLegs = new ItemTypesServer.ItemTypeRaw(copperLegsName, copperLegsNode); items.Add(copperLegsName, copperLegs); ArmorFactory.ArmorLookup.Add(copperLegs.ItemIndex, new ArmorMetadata(0.07f, 20, copperLegsName, copperLegs, ArmorFactory.ArmorSlot.Legs)); // Boots var copperBootsName = GameLoader.NAMESPACE + ".CopperBoots"; var copperBootsNode = new JSONNode(); copperBootsNode["icon"] = new JSONNode(GameLoader.ICON_PATH + "CopperBoots.png"); copperBootsNode["isPlaceable"] = new JSONNode(false); copperBootsNode.SetAs("categories", categories); var copperBoots = new ItemTypesServer.ItemTypeRaw(copperBootsName, copperBootsNode); items.Add(copperBootsName, copperBoots); ArmorFactory.ArmorLookup.Add(copperBoots.ItemIndex, new ArmorMetadata(0.025f, 10, copperBootsName, copperBoots, ArmorFactory.ArmorSlot.Boots)); // Shield var copperShieldName = GameLoader.NAMESPACE + ".CopperShield"; var copperShieldNode = new JSONNode(); copperShieldNode["icon"] = new JSONNode(GameLoader.ICON_PATH + "CopperShield.png"); copperShieldNode["isPlaceable"] = new JSONNode(false); copperShieldNode.SetAs("categories", categories); var copperShield = new ItemTypesServer.ItemTypeRaw(copperShieldName, copperShieldNode); items.Add(copperShieldName, copperShield); ArmorFactory.ArmorLookup.Add(copperShield.ItemIndex, new ArmorMetadata(0.05f, 30, copperShieldName, copperShield, ArmorFactory.ArmorSlot.Shield)); // ---------------------------------------- // Bronze // ---------------------------------------- // Helm var bronzeHelmName = GameLoader.NAMESPACE + ".BronzeHelm"; var bronzeHelmNode = new JSONNode(); bronzeHelmNode["icon"] = new JSONNode(GameLoader.ICON_PATH + "BronzeHelm.png"); bronzeHelmNode["isPlaceable"] = new JSONNode(false); bronzeHelmNode.SetAs("categories", categories); var bronzeHelm = new ItemTypesServer.ItemTypeRaw(bronzeHelmName, bronzeHelmNode); items.Add(bronzeHelmName, bronzeHelm); ArmorFactory.ArmorLookup.Add(bronzeHelm.ItemIndex, new ArmorMetadata(0.07f, 20, bronzeHelmName, bronzeHelm, ArmorFactory.ArmorSlot.Helm)); // Chest var bronzeChestName = GameLoader.NAMESPACE + ".BronzeChest"; var bronzeChestNode = new JSONNode(); bronzeChestNode["icon"] = new JSONNode(GameLoader.ICON_PATH + "BronzeChest.png"); bronzeChestNode["isPlaceable"] = new JSONNode(false); bronzeChestNode.SetAs("categories", categories); var bronzeChest = new ItemTypesServer.ItemTypeRaw(bronzeChestName, bronzeChestNode); items.Add(bronzeChestName, bronzeChest); ArmorFactory.ArmorLookup.Add(bronzeChest.ItemIndex, new ArmorMetadata(.15f, 30, bronzeChestName, bronzeChest, ArmorFactory.ArmorSlot.Chest)); // Gloves var bronzeGlovesName = GameLoader.NAMESPACE + ".BronzeGloves"; var bronzeGlovesNode = new JSONNode(); bronzeGlovesNode["icon"] = new JSONNode(GameLoader.ICON_PATH + "BronzeGloves.png"); bronzeGlovesNode["isPlaceable"] = new JSONNode(false); bronzeGlovesNode.SetAs("categories", categories); var bronzeGloves = new ItemTypesServer.ItemTypeRaw(bronzeGlovesName, bronzeGlovesNode); items.Add(bronzeGlovesName, bronzeGloves); ArmorFactory.ArmorLookup.Add(bronzeGloves.ItemIndex, new ArmorMetadata(0.04f, 15, bronzeGlovesName, bronzeGloves, ArmorFactory.ArmorSlot.Gloves)); // Legs var bronzeLegsName = GameLoader.NAMESPACE + ".BronzeLegs"; var bronzeLegsNode = new JSONNode(); bronzeLegsNode["icon"] = new JSONNode(GameLoader.ICON_PATH + "BronzeLegs.png"); bronzeLegsNode["isPlaceable"] = new JSONNode(false); bronzeLegsNode.SetAs("categories", categories); var bronzeLegs = new ItemTypesServer.ItemTypeRaw(bronzeLegsName, bronzeLegsNode); items.Add(bronzeLegsName, bronzeLegs); ArmorFactory.ArmorLookup.Add(bronzeLegs.ItemIndex, new ArmorMetadata(0.09f, 25, bronzeLegsName, bronzeLegs, ArmorFactory.ArmorSlot.Legs)); // Boots var bronzeBootsName = GameLoader.NAMESPACE + ".BronzeBoots"; var bronzeBootsNode = new JSONNode(); bronzeBootsNode["icon"] = new JSONNode(GameLoader.ICON_PATH + "BronzeBoots.png"); bronzeBootsNode["isPlaceable"] = new JSONNode(false); bronzeBootsNode.SetAs("categories", categories); var bronzeBoots = new ItemTypesServer.ItemTypeRaw(bronzeBootsName, bronzeBootsNode); items.Add(bronzeBootsName, bronzeBoots); ArmorFactory.ArmorLookup.Add(bronzeBoots.ItemIndex, new ArmorMetadata(0.04f, 15, bronzeBootsName, bronzeBoots, ArmorFactory.ArmorSlot.Boots)); // Shield var bronzeShieldName = GameLoader.NAMESPACE + ".BronzeShield"; var bronzeShieldNode = new JSONNode(); bronzeShieldNode["icon"] = new JSONNode(GameLoader.ICON_PATH + "BronzeShield.png"); bronzeShieldNode["isPlaceable"] = new JSONNode(false); bronzeShieldNode.SetAs("categories", categories); var bronzeShield = new ItemTypesServer.ItemTypeRaw(bronzeShieldName, bronzeShieldNode); items.Add(bronzeShieldName, bronzeShield); ArmorFactory.ArmorLookup.Add(bronzeShield.ItemIndex, new ArmorMetadata(0.07f, 40, bronzeShieldName, bronzeShield, ArmorFactory.ArmorSlot.Shield)); // ---------------------------------------- // Iron // ---------------------------------------- // Helm var ironHelmName = GameLoader.NAMESPACE + ".IronHelm"; var ironHelmNode = new JSONNode(); ironHelmNode["icon"] = new JSONNode(GameLoader.ICON_PATH + "IronHelm.png"); ironHelmNode["isPlaceable"] = new JSONNode(false); ironHelmNode.SetAs("categories", categories); var ironHelm = new ItemTypesServer.ItemTypeRaw(ironHelmName, ironHelmNode); items.Add(ironHelmName, ironHelm); ArmorFactory.ArmorLookup.Add(ironHelm.ItemIndex, new ArmorMetadata(0.09f, 30, ironHelmName, ironHelm, ArmorFactory.ArmorSlot.Helm)); // Chest var ironChestName = GameLoader.NAMESPACE + ".IronChest"; var ironChestNode = new JSONNode(); ironChestNode["icon"] = new JSONNode(GameLoader.ICON_PATH + "IronChest.png"); ironChestNode["isPlaceable"] = new JSONNode(false); ironChestNode.SetAs("categories", categories); var ironChest = new ItemTypesServer.ItemTypeRaw(ironChestName, ironChestNode); items.Add(ironChestName, ironChest); ArmorFactory.ArmorLookup.Add(ironChest.ItemIndex, new ArmorMetadata(.2f, 40, ironChestName, ironChest, ArmorFactory.ArmorSlot.Chest)); // Gloves var ironGlovesName = GameLoader.NAMESPACE + ".IronGloves"; var ironGlovesNode = new JSONNode(); ironGlovesNode["icon"] = new JSONNode(GameLoader.ICON_PATH + "IronGloves.png"); ironGlovesNode["isPlaceable"] = new JSONNode(false); ironGlovesNode.SetAs("categories", categories); var ironGloves = new ItemTypesServer.ItemTypeRaw(ironGlovesName, ironGlovesNode); items.Add(ironGlovesName, ironGloves); ArmorFactory.ArmorLookup.Add(ironGloves.ItemIndex, new ArmorMetadata(0.055f, 25, ironGlovesName, ironGloves, ArmorFactory.ArmorSlot.Gloves)); // Legs var ironLegsName = GameLoader.NAMESPACE + ".IronLegs"; var ironLegsNode = new JSONNode(); ironLegsNode["icon"] = new JSONNode(GameLoader.ICON_PATH + "IronLegs.png"); ironLegsNode["isPlaceable"] = new JSONNode(false); ironLegsNode.SetAs("categories", categories); var ironLegs = new ItemTypesServer.ItemTypeRaw(ironLegsName, ironLegsNode); items.Add(ironLegsName, ironLegs); ArmorFactory.ArmorLookup.Add(ironLegs.ItemIndex, new ArmorMetadata(0.11f, 35, ironLegsName, ironLegs, ArmorFactory.ArmorSlot.Legs)); // Boots var ironBootsName = GameLoader.NAMESPACE + ".IronBoots"; var ironBootsNode = new JSONNode(); ironBootsNode["icon"] = new JSONNode(GameLoader.ICON_PATH + "IronBoots.png"); ironBootsNode["isPlaceable"] = new JSONNode(false); ironBootsNode.SetAs("categories", categories); var ironBoots = new ItemTypesServer.ItemTypeRaw(ironBootsName, ironBootsNode); items.Add(ironBootsName, ironBoots); ArmorFactory.ArmorLookup.Add(ironBoots.ItemIndex, new ArmorMetadata(0.055f, 25, ironBootsName, ironBoots, ArmorFactory.ArmorSlot.Boots)); // Shield var ironShieldName = GameLoader.NAMESPACE + ".IronShield"; var ironShieldNode = new JSONNode(); ironShieldNode["icon"] = new JSONNode(GameLoader.ICON_PATH + "IronShield.png"); ironShieldNode["isPlaceable"] = new JSONNode(false); ironShieldNode.SetAs("categories", categories); var ironShield = new ItemTypesServer.ItemTypeRaw(ironShieldName, ironShieldNode); items.Add(ironShieldName, ironShield); ArmorFactory.ArmorLookup.Add(ironShield.ItemIndex, new ArmorMetadata(0.1f, 50, ironShieldName, ironShield, ArmorFactory.ArmorSlot.Shield)); // ---------------------------------------- // Steel // ---------------------------------------- // Helm var steelHelmName = GameLoader.NAMESPACE + ".SteelHelm"; var steelHelmNode = new JSONNode(); steelHelmNode["icon"] = new JSONNode(GameLoader.ICON_PATH + "SteelHelm.png"); steelHelmNode["isPlaceable"] = new JSONNode(false); steelHelmNode.SetAs("categories", categories); var steelHelm = new ItemTypesServer.ItemTypeRaw(steelHelmName, steelHelmNode); items.Add(steelHelmName, steelHelm); ArmorFactory.ArmorLookup.Add(steelHelm.ItemIndex, new ArmorMetadata(0.11f, 40, steelHelmName, steelHelm, ArmorFactory.ArmorSlot.Helm)); // Chest var steelChestName = GameLoader.NAMESPACE + ".SteelChest"; var steelChestNode = new JSONNode(); steelChestNode["icon"] = new JSONNode(GameLoader.ICON_PATH + "SteelChest.png"); steelChestNode["isPlaceable"] = new JSONNode(false); steelChestNode.SetAs("categories", categories); var steelChest = new ItemTypesServer.ItemTypeRaw(steelChestName, steelChestNode); items.Add(steelChestName, steelChest); ArmorFactory.ArmorLookup.Add(steelChest.ItemIndex, new ArmorMetadata(.3f, 50, steelChestName, steelChest, ArmorFactory.ArmorSlot.Chest)); // Gloves var steelGlovesName = GameLoader.NAMESPACE + ".SteelGloves"; var steelGlovesNode = new JSONNode(); steelGlovesNode["icon"] = new JSONNode(GameLoader.ICON_PATH + "SteelGloves.png"); steelGlovesNode["isPlaceable"] = new JSONNode(false); steelGlovesNode.SetAs("categories", categories); var steelGloves = new ItemTypesServer.ItemTypeRaw(steelGlovesName, steelGlovesNode); items.Add(steelGlovesName, steelGloves); ArmorFactory.ArmorLookup.Add(steelGloves.ItemIndex, new ArmorMetadata(0.07f, 35, steelGlovesName, steelGloves, ArmorFactory.ArmorSlot.Gloves)); // Legs var steelLegsName = GameLoader.NAMESPACE + ".SteelLegs"; var steelLegsNode = new JSONNode(); steelLegsNode["icon"] = new JSONNode(GameLoader.ICON_PATH + "SteelLegs.png"); steelLegsNode["isPlaceable"] = new JSONNode(false); steelLegsNode.SetAs("categories", categories); var steelLegs = new ItemTypesServer.ItemTypeRaw(steelLegsName, steelLegsNode); items.Add(steelLegsName, steelLegs); ArmorFactory.ArmorLookup.Add(steelLegs.ItemIndex, new ArmorMetadata(0.13f, 40, steelLegsName, steelLegs, ArmorFactory.ArmorSlot.Legs)); // Boots var steelBootsName = GameLoader.NAMESPACE + ".SteelBoots"; var steelBootsNode = new JSONNode(); steelBootsNode["icon"] = new JSONNode(GameLoader.ICON_PATH + "SteelBoots.png"); steelBootsNode["isPlaceable"] = new JSONNode(false); steelBootsNode.SetAs("categories", categories); var steelBoots = new ItemTypesServer.ItemTypeRaw(steelBootsName, steelBootsNode); items.Add(steelBootsName, steelBoots); ArmorFactory.ArmorLookup.Add(steelBoots.ItemIndex, new ArmorMetadata(0.07f, 35, steelBootsName, steelBoots, ArmorFactory.ArmorSlot.Boots)); // Shield var steelShieldName = GameLoader.NAMESPACE + ".SteelShield"; var steelShieldNode = new JSONNode(); steelShieldNode["icon"] = new JSONNode(GameLoader.ICON_PATH + "SteelShield.png"); steelShieldNode["isPlaceable"] = new JSONNode(false); steelShieldNode.SetAs("categories", categories); var steelShield = new ItemTypesServer.ItemTypeRaw(steelShieldName, steelShieldNode); items.Add(steelShieldName, steelShield); ArmorFactory.ArmorLookup.Add(steelShield.ItemIndex, new ArmorMetadata(0.12f, 60, steelShieldName, steelShield, ArmorFactory.ArmorSlot.Shield)); ArmorFactory.ArmorLookup = ArmorFactory.ArmorLookup.OrderBy(kvp => kvp.Value.name).ThenBy(kvp => kvp.Value.ArmorRating) .ToDictionary(k => k.Key, v => v.Value); } catch (Exception ex) { SettlersLogger.LogError(ex); } }
public static void generateTypes(Dictionary <string, ItemTypeRaw> types) { Dictionary <string, ItemTypeRaw> newItemsDic = new Dictionary <string, ItemTypeRaw>(); var mi = typeof(ItemTypesServer.BlockRotator).GetMethod("CreateAndRegisterRotatedBlocks", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); var generatedIconDir = GameLoader.ICON_PATH + "gen/"; if (!Directory.Exists(generatedIconDir)) { Directory.CreateDirectory(generatedIconDir); } if (mi != null) { foreach (var itemType in types.Values) { if (itemType.Categories == null) { continue; } if (!itemType.Categories.Contains("decorative")) { continue; } if (itemType.Mesh != null) { continue; } if (itemType.Mesh != null && !string.IsNullOrEmpty(itemType.Mesh.MeshPath)) { continue; } if (!string.IsNullOrEmpty(itemType.RotatedXMinus) || !string.IsNullOrEmpty(itemType.RotatedXPlus) || !string.IsNullOrEmpty(itemType.RotatedZMinus) || !string.IsNullOrEmpty(itemType.RotatedZPlus)) { continue; } if (!itemType.IsPlaceable) { continue; } if (string.IsNullOrEmpty(itemType.SideAll)) { continue; } try { List <Tuple <string, string, string> > blockTypes = new List <Tuple <string, string, string> >(); foreach (var blockType in CollederStorage.Colliders_Dict) { var overlayIcon = GameLoader.ICON_PATH + blockType.Key + GameLoader.ICONTYPE; var newIcon = generatedIconDir + itemType.name + "." + blockType.Key + GameLoader.ICONTYPE; var newType = new DecorTypeBase(); var typeName = itemType.name + " " + blockType.Key; blockTypes.Add(Tuple.Create(typeName, itemType.name, blockType.Key)); if (!File.Exists(newIcon)) { var back = new Texture2D(64, 64); if (File.Exists(itemType.Icon)) { back.LoadImage(File.ReadAllBytes(itemType.Icon)); } else { SettlersLogger.Log(ChatColor.red, "Icon not found:" + itemType.Icon); } var overlay = new Texture2D(64, 64); if (File.Exists(overlayIcon)) { overlay.LoadImage(File.ReadAllBytes(overlayIcon)); } else { SettlersLogger.Log(ChatColor.red, "Icon not found:" + overlayIcon); } var tex = AddWatermark(back, overlay); SaveTextureAsPNG(tex, newIcon); } newType.icon = newIcon; newType.name = typeName; newType.categories.Add(itemType.name); newType.categories.Add(blockType.Key); newType.categories.Add("decorative"); newType.categories.Add(GameLoader.NAMESPACE); newType.sideall = itemType.SideAll; newType.mesh = GameLoader.MESH_PATH + blockType.Key + GameLoader.MESHTYPE; if (File.Exists(GameLoader.MESH_PATH + blockType.Key + ".ply")) { newType.mesh = newType.mesh = GameLoader.MESH_PATH + blockType.Key + ".ply"; } newType.colliders.boxes = blockType.Value; if (itemType.CustomDataNode != null) { newType.customData = JObject.Parse(itemType.CustomDataNode.ToString()); } else { newType.customData = new JObject(); } var color = "#" + ColorUtility.ToHtmlStringRGB(((UnityEngine.Color)itemType.Color).gamma); newType.customData["useNormalMap"] = true; newType.customData["useHeightMap"] = true; newType.customData["colors"] = new JArray(new string[] { "#ffffff->" + color }); var itemJson = JsonConvert.SerializeObject(newType, Formatting.None, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }); var rawItem = new ItemTypeRaw(typeName, JSON.DeserializeString(itemJson)); mi.Invoke(null, new object[] { newItemsDic, new BlockRotator.RotatorSettings(rawItem, null, null, null, null), null }); } _loadedItems.Add(itemType.name, blockTypes); } catch (Exception ex) { SettlersLogger.LogError(ex); } } } foreach (var newItem in newItemsDic) { types[newItem.Key] = newItem.Value; } SettlersLogger.Log(newItemsDic.Count + " new items added."); }