public void UpdateInfo(PlanetData planet) { activePlanet = planet; Header.text = planet.Name; UpgradeFactoryUpdate(); UpgradeHangarUpdate(); UpdateSendShipBtn(); }
// Returns the planet that belongs to the given planetData //public Planet getPlanet(PlanetData planetData) { // foreach (Planet p in planets) { // if(p.planetData == planetData) { // return p; // } // } // return null; //} public Planet getPlanet(PlanetData pData) { Planet p = null; planetDict.TryGetValue(pData, out p); Debug.Log("Searched and Found Planet: " + p.name); return p; //return null; }
private void CheckPlanetForSupplyDesignation(PlanetData pData) { if (pData.Rank == PlanetData.ePlanetRank.EstablishedColony || pData.Rank == PlanetData.ePlanetRank.NewColony) { if (!pData.IsSupplyPlanet && !pData.IsTradeHub) // only valid if not a trade hub and not a capital planet { List<PlanetData> supplyHubList = new List<PlanetData>(); // get list of supply hubs in province foreach (PlanetData planetData in pData.System.Province.PlanetList) { if (planetData.IsTradeHub) { supplyHubList.Add(planetData); } } UpdatePlanetTradeInfo(pData); // check for resources sent already // check each resource and if there is a shortfall and the planet has a surplus, chance that designation occurs foreach (PlanetData planetD in supplyHubList) { float supplyPlanetChance = 0; if (planetD.FoodDifference < 0 && pData.FoodExportAvailable > 0) { supplyPlanetChance += Mathf.Abs(planetD.FoodDifference) + pData.FoodExportAvailable; } if (planetD.EnergyDifference < 0 && pData.EnergyExportAvailable > 0) { supplyPlanetChance += Mathf.Abs(planetD.EnergyDifference) + pData.EnergyExportAvailable; } if (planetD.AlphaPreProductionDifference < 0 && pData.AlphaExportAvailable > 0) { supplyPlanetChance += Mathf.Abs(planetD.AlphaPreProductionDifference) + pData.AlphaExportAvailable; } if (planetD.RarePreProductionDifference < 0 && pData.RareExportAvailable > 0) { supplyPlanetChance += Mathf.Abs(planetD.RarePreProductionDifference) + pData.RareExportAvailable; } if (planetD.HeavyPreProductionDifference < 0 && pData.HeavyExportAvailable > 0) { supplyPlanetChance += Mathf.Abs(planetD.HeavyPreProductionDifference) + pData.HeavyExportAvailable; } if (supplyPlanetChance >= UnityEngine.Random.Range(0,200)) { pData.IsSupplyPlanet = true; pData.SupplyToPlanetID = planetD.ID; break; // exit, the supply planet is found } } if (pData.IsSupplyPlanet) { CreateSupplyTrade(pData); } } } }
public static SpaceData GenerateRandomMap(int planetCount) { SpaceData spaceData = new SpaceData(); //List<PlanetData> planets = new List<PlanetData>();//hold the list of planets to check if they are correctly disributed PlanetData planet; float minPlanetDistance = 70; float spacePerPlanet = 500; float spaceArea = planetCount * spacePerPlanet; Vector2 size = new Vector2(spaceArea /9, spaceArea / 16 ); Rect mapSize = new Rect(new Vector2(0, 0), size); Vector2 newPosition = new Vector2(); bool canPositionPlanet = true; for (int i = 0; i < planetCount; i++) { int timeout = 100; do { newPosition.x = Random.Range(mapSize.xMin, mapSize.xMax); newPosition.y = Random.Range(mapSize.yMin, mapSize.yMax); canPositionPlanet = true; foreach (PlanetData p in spaceData.planets) { if (Vector2.Distance(newPosition, p.Position) < minPlanetDistance) { canPositionPlanet = false; break; } } timeout--; } while (!canPositionPlanet && timeout > 0); int hangarSize = Random.Range(30, 500); int ships = (int)((float)hangarSize * Random.Range(0.05f, 0.4f)); int factorySpeed = System.Math.Min((int)((float)hangarSize * Random.Range(0.2f, 0.45f)), 100); planet = new PlanetData(new Vector2(newPosition.x, newPosition.y), Random.Range(15, 58f), ships, hangarSize, factorySpeed, true); spaceData.AddPlanet(planet); } Vector2 minMapSize = mapSize.size / 2; // M Vector2 upsizingFactor = new Vector2(spaceData.GetSize().x / minMapSize.x, spaceData.GetSize().y / minMapSize.y); if (upsizingFactor.x < 1) { upsizingFactor.x = 1; } if (upsizingFactor.y < 1) { upsizingFactor.y = 1; } foreach (PlanetData p in spaceData.planets) { p.Position = new Vector2(p.Position.x * upsizingFactor.x, p.Position.y * upsizingFactor.y); } spaceData.ForceBoundRecalculation(); return spaceData; }
public void Init(PlanetData start, PlanetData target, int shipCount, int currentDay) { StartPlanet = start; TargetPlanet = target; ShipCount = shipCount; if (start == null) { Owner = null; ArrivalTime = 0; } else { Owner = start.Owner; ArrivalTime = (int)System.Math.Round(currentDay + start.GetSurfaceDistance(target) / TravelSpeed); TravelTime = GetTravelTime(start, target); ArrivalTime = TravelTime + currentDay; } }
float getAttackPoints(PlanetData origin, PlanetData target, int distanceInDays) { // = ~ <difference of ships between planets Debug.Assert(origin.Owner != null); if(lastDayAtk.Contains(origin, target)) { return NO_POINTS; } int shipsOnPlanetAtArrivalday = getEstimatedShipsOnPlanet(target, distanceInDays); float certanyFactor = 0; if (distanceInDays >= 2) { certanyFactor = (distanceInDays * distanceInDays * 0.015f); // exp. curve certanyFactor = Math.Min(certanyFactor, 1); // [0..1] 1 day: 0.015, ... 5 days: 0.375, 6 days: 0.54; 7 days: 0.738; 8 days: 96; 9 days: 1 } float points = origin.Ships - shipsOnPlanetAtArrivalday; points -= certanyFactor * 200; return points; }
public void Init(PlanetData planet) { planetData = planet; this.name = "Planet '" + planet.Name + "'"; this.transform.position = planet.Position; // spriteRenderer = GetComponent<SpriteRenderer>(); //load planet sprite if (planet.TextureName == "") { int index = Random.Range(0, planetSprites.Length - 1); spriteRenderer.sprite = planetSprites[index]; planet.TextureName = spriteRenderer.sprite.name; } else { foreach (Sprite s in planetSprites) { if (s.name == planet.TextureName) { spriteRenderer.sprite = s; } } } if (planet.TextureFXName == "") { glow.sprite = planetFX[0]; planet.TextureFXName = planetFX[0].name; } else { foreach (Sprite s in planetFX) { if (s.name == planet.TextureFXName) { glow.sprite = s; } } } Vector2 spriteSize = spriteRenderer.sprite.rect.size; if (spriteSize.x != spriteSize.y) { Debug.LogWarning("The used planet sprite is not rectangular and therefore distorted"); } this.transform.localScale = new Vector3(planet.Diameter / spriteSize.x, planet.Diameter / spriteSize.y, 1); spriteCollider.radius = spriteSize.x; //Smaller planets need a larger outline (in comparison with the planet), to let it appear as thick as for big planets: glowUpscaling = (planetData.Diameter + 5) / planetData.Diameter; spriteSize = glow.sprite.rect.size; if (spriteSize.x != spriteSize.y) { Debug.LogWarning("The used planet sprite for glow is not rectangular and therefore distorted"); } sign.transform.position = new Vector3(sign.transform.position.x, transform.position.y + planetData.Diameter * 1.6f, transform.position.z); UpdateGraphicalRepresentation(); }
public void AddPlanet(PlanetData planet) { if(planet.Name == "") { planet.Name = GetUniqueRandomPlanetName(); } foreach (PlanetData otherPlanet in planets) { if (otherPlanet.Name.Equals(planet.Name)) { //ID's must be unique throw new UnityException("Unable to create planet. There is already a planet with the name " + planet.Name); } } Debug.Log("Adding planet \"" + planet.Name + "\""); planets.Add(planet); if(planet.IsStartPlanet) { ++MaxPlayerCount; } UpdateBoundsWithNewPlanet(planet, planets.Count == 1); }
public static void AddStockpilesToPlanet(PlanetData pData) { if (pData.FoodDifference > 0) { pData.FoodStored = UnityEngine.Random.Range(20, 100) * pData.FoodDifference; // number of months of storage based on food flow } else pData.FoodStored = UnityEngine.Random.Range(0, 5000); if (pData.AlphaPreProductionDifference > 0) { pData.AlphaStored = UnityEngine.Random.Range(20, 100) * pData.AlphaPreProductionDifference; // number of months of storage based on food flow } else pData.AlphaStored = UnityEngine.Random.Range(0, 3000); if (pData.HeavyPreProductionDifference > 0) { pData.HeavyStored = UnityEngine.Random.Range(20, 100) * pData.HeavyPreProductionDifference; // number of months of storage based on food flow } else pData.HeavyStored = UnityEngine.Random.Range(0, 500); if (pData.RarePreProductionDifference > 0) { pData.RareStored = UnityEngine.Random.Range(20, 100) * pData.RarePreProductionDifference; // number of months of storage based on food flow } else pData.RareStored = UnityEngine.Random.Range(0, 300); if (pData.EnergyDifference > 0) { pData.EnergyStored = UnityEngine.Random.Range(20, 100) * pData.EnergyDifference; // number of months of storage based on food flow } else pData.EnergyStored = UnityEngine.Random.Range(0, 5000); }
public static Int32 DefaultResolution = 256; //Разрешение текстур планет /// <summary> /// Создает новый экземпляр генератора с заданным разрешением (если оно удовлетворяет ограничениям) и зерном случайных /// чисел. /// </summary> /// <param name="ySize">Вертикальное разрешение</param> /// <param name="planetData">Ссылка на планету.</param> protected PlanetTextureGenerator(Int32 ySize, PlanetData planetData) { PlanetData = planetData; YSize = ySize; }
private static PlanetData GeneratePlanet(PlanetData.ePlanetType planetType, StarData curSys, int systemSpot) { PlanetData cPlan = new PlanetData(); PlanetAttributeTable pTable = new PlanetAttributeTable(); PlanetAttributeData pData = new PlanetAttributeData(); // assign the attribute table for the planet type try { pData = DataManager.planetAttributeDataList.Find(p => p.planetType == planetType); pTable = pData.planetTraitsTable; } catch (Exception ex) { Debug.LogError("Could not lookup " + planetType.ToString() + " table for planet type " + planetType.ToString() + "! Error:" + ex.ToString()); return null; // try again with the next planet } // Step 0: Log spot of planet in system cPlan.PlanetSpot = systemSpot; // Step 1: Determine type of planet cPlan.Type = (StellarObjects.PlanetData.ePlanetType)planetType; // assign the planet type // Step 2: Pick name for planet and assign ID(will change to generic star name) systemSpot = curSys.PlanetList.Count + 1; if (cPlan.Type == PlanetData.ePlanetType.AsteroidBelt) cPlan.Name = curSys.Name + " AB-" + HelperFunctions.StringConversions.ConvertToRomanNumeral(systemSpot); else if (cPlan.Type == PlanetData.ePlanetType.IceBelt) cPlan.Name = curSys.Name + " IB-" + HelperFunctions.StringConversions.ConvertToRomanNumeral(systemSpot); else if (cPlan.Type == PlanetData.ePlanetType.DustRing) cPlan.Name = curSys.Name + " DR-" + HelperFunctions.StringConversions.ConvertToRomanNumeral(systemSpot); else cPlan.Name = curSys.Name + " " + HelperFunctions.StringConversions.ConvertToRomanNumeral(systemSpot); // convert to planet and spot cPlan.ID = curSys.Name.Substring(0,2) + UnityEngine.Random.Range(0,9999); // set ID // Step 3: Determine size/axial tilt of planet try { int sizeVar = UnityEngine.Random.Range(0, pTable.sizeVar); int sizeResult = pTable.size + sizeVar; cPlan.Size = sizeResult; // sizeMod; } catch(Exception ex) { Debug.LogError("Could not calcuate. Error: " + ex.ToString()); } cPlan.AxialTilt = UnityEngine.Random.Range(0f, 70f); // tilt between 0-70 // Step 4: Determine habitibility of planet try { int habVar = UnityEngine.Random.Range(0, pTable.habVar); float habResult = pTable.habitability + habVar; float spotVar = 0f; switch (cPlan.PlanetSpot) { case 1: if ((int)curSys.SpectralClass < 5) { spotVar = .6f; break; } else { spotVar = .9f; break; } case 2: spotVar = .9f; break; case 3: spotVar = 1f; break; case 4: spotVar = 1f; break; case 5: spotVar = .9f; break; case 6: spotVar = .7f; break; default: spotVar = 1f; break; } cPlan.Bio = (int)(habResult * spotVar); } catch (Exception ex) { Debug.LogError("Could not calcuate. Error: " + ex.ToString()); } // Step 5: Determine industrial modifier of planet cPlan.IndustrialMultiplier = (pTable.indMult / 100); // Step 6: Determine if planet has any rings if (UnityEngine.Random.Range(0, 100) <= pTable.ringChance) cPlan.Rings = true; else cPlan.Rings = false; // Step 7: Determine how many moons the planet has if (UnityEngine.Random.Range(0, 100) <= pTable.moonChance) cPlan.Moons = UnityEngine.Random.Range(1,pTable.maxMoons); // change later to expand on moons // Step 7b: Adjust habitability based on moons if (cPlan.Moons > 0) if (((int)cPlan.Type == 7) || ((int)cPlan.Type == 8)) { cPlan.Bio += (cPlan.Moons * 2); } if (((int)cPlan.Type == 10) || ((int)cPlan.Type == 3) || ((int)cPlan.Type == 2) || ((int)cPlan.Type == 13)) { cPlan.Bio += (cPlan.Moons * 5); } // Step 8: Determine rating of alpha materials try { int alphaVar = UnityEngine.Random.Range(0, pTable.alpVar); cPlan.BasicMaterials = pTable.alpMaterial + alphaVar; } catch (Exception ex) { Debug.LogError("Could not calcuate. Error: " + ex.ToString()); } // Step 9: Determine rating of heavy materials try { int heavyVar = UnityEngine.Random.Range(0, pTable.heavVar); cPlan.HeavyMaterials = (int)(pTable.heavyMaterial * (1 + (curSys.pMaterial / 20))); cPlan.HeavyMaterials = cPlan.HeavyMaterials * (1 + ((5 - systemSpot) / 10)); cPlan.HeavyMaterials += heavyVar; } catch (Exception ex) { Debug.LogError("Could not calcuate. Error: " + ex.ToString()); } // Step 10: Determine rating of rare materials try { int rareMod = UnityEngine.Random.Range(0, pTable.rareVar); cPlan.RareMaterials = (int)(pTable.rareMaterial * (1 + (curSys.pMaterial / 12))); cPlan.RareMaterials = cPlan.RareMaterials * (1 + ((5 - systemSpot) / 8)); cPlan.RareMaterials += rareMod; } catch (Exception ex) { Debug.LogError("Could not calcuate. Error: " + ex.ToString()); } // Step 11: Determine energy rating try { cPlan.Energy = (int)(pTable.energy * (1 + (curSys.pMaterial / 12))); cPlan.Energy = cPlan.Energy * (1 + ((5 - systemSpot) / 10)); cPlan.Energy += UnityEngine.Random.Range(0, 30); } catch (Exception ex) { Debug.LogError("Could not calcuate. Error: " + ex.ToString()); } // Step 12: Generate sprite number (to show type of planet) if ((cPlan.Type != PlanetData.ePlanetType.DustRing) && (cPlan.Type != PlanetData.ePlanetType.IceBelt) && (cPlan.Type != PlanetData.ePlanetType.AsteroidBelt)) cPlan.PlanetSpriteNumber = UnityEngine.Random.Range(0, SpritesPerPlanetType - 1); else cPlan.PlanetSpriteNumber = UnityEngine.Random.Range(0, SpritesPerBeltType - 1); // Step 13: Generate ring sprite number if applicable cPlan.PlanetRingSpriteNumber = UnityEngine.Random.Range(0, SpritesPerRingType - 1); cPlan.PlanetRingTilt = UnityEngine.Random.Range(-10, 10); // Step 13: Determine planetary traits DeterminePlanetTraits(cPlan); // Step 14: Determine total and habitable tiles based on bio level cPlan.MaxTiles = (cPlan.Size / 3); for (int x = 0; x < cPlan.MaxTiles; x++) { if (UnityEngine.Random.Range(0, 100) < cPlan.AdjustedBio) { cPlan.MaxHabitableTiles += 1; } } // Step 15: Create and assign tiles to the planet GeneratePlanetRegions(cPlan); // Step 16: Send the planet data back! return cPlan; }
private void CreateSupplyTrade(PlanetData pData) { TradeAgreement newTrade = new TradeAgreement(); newTrade.ExportPlanetID = pData.ID; newTrade.Status = TradeAgreement.eAgreementStatus.Supply_Trade; newTrade.ImportPlanetID = pData.SupplyToPlanetID; if (pData.FoodExportAvailable > 0) { newTrade.FoodSent = pData.FoodExportAvailable / Constants.Constants.SupplyPlanetLow; } if (pData.EnergyExportAvailable > 0) { newTrade.EnergySent = pData.EnergyExportAvailable / Constants.Constants.SupplyPlanetLow; } if (pData.AlphaExportAvailable > 0) { newTrade.AlphaSent = pData.AlphaExportAvailable / Constants.Constants.SupplyPlanetLow; } if (pData.HeavyExportAvailable > 0) { newTrade.HeavySent = pData.HeavyExportAvailable / Constants.Constants.SupplyPlanetLow; } if (pData.RareExportAvailable > 0) { newTrade.RareSent = pData.RareExportAvailable / Constants.Constants.SupplyPlanetLow; } Debug.Log("Supply trade created from " + newTrade.ExportPlanet.Name + " to " + newTrade.ImportPlanet.Name + " for " + newTrade.TotalSent.ToString("N2") + " units, costing " + newTrade.Cost.ToString("N2") + "."); gDataRef.ActiveTradeAgreements.Add(newTrade); }
public static bool GetOrCreateFactory_Prefix(GameData __instance, PlanetFactory __result, PlanetData planet) { // We want the original method to run on the host client or in single player games if (!SimulatedWorld.Initialized || LocalPlayer.IsMasterClient) { return(true); } // Get the recieved bytes from the remote server that we will import byte[] factoryBytes; if (!LocalPlayer.PendingFactories.TryGetValue(planet.id, out factoryBytes)) { // We messed up, just defer to the default behaviour on the client (will cause desync but not outright crash) Log.Error($"PendingFactories did not have value we wanted, factory will not be synced!"); return(true); } // Take it off the list, as we will process it now LocalPlayer.PendingFactories.Remove(planet.id); using (BinaryUtils.Reader reader = new BinaryUtils.Reader(factoryBytes)) { int factoryIndex = GameMain.data.factoryCount++; // Import the factory from the given bytes, which will have been gotten or created on the host by the original function __instance.factories[factoryIndex] = new PlanetFactory(); if (planet.factory == null) { __instance.factories[factoryIndex].Import(factoryIndex, __instance, reader.BinaryReader); planet.factory = __instance.factories[factoryIndex]; planet.factoryIndex = factoryIndex; } else { __instance.factories[planet.factoryIndex].Import(planet.factoryIndex, __instance, reader.BinaryReader); planet.factory = __instance.factories[planet.factoryIndex]; } } // Assign the factory to the result __result = __instance.factories[planet.factoryIndex]; // Do not run the original method return(false); }
public void AddPlanetDataToList(PlanetData pData) { GalaxyPlanetDataList.Add(pData); }
private static void UpdateSettingsUI(StationUI packet) { UIStationWindow stationWindow = UIRoot.instance.uiGame.stationWindow; if (stationWindow != null) { int _stationId = (int)AccessTools.Field(typeof(UIStationWindow), "_stationId")?.GetValue(stationWindow); PlanetData pData = GameMain.galaxy.PlanetById(packet.planetId); if (pData?.factory == null || pData?.factory?.transport == null) { if (GameMain.data.galacticTransport.stationPool.Length > packet.stationGId && GameMain.data.galacticTransport.stationPool[packet.stationGId] != null) { // client never was on this planet before or has it unloaded, but has a fake structure created, so update it UpdateSettingsUIBackground(packet, pData, packet.stationGId); } return; } for (int i = 0; i < pData.factory.transport.stationPool.Length; i++) { if (pData.factory.transport.stationPool[i] != null && pData.factory.transport.stationPool[i].gid == packet.stationGId) { if (pData.factory.transport.stationPool[i].id != _stationId) { // receiving side has the UI closed or another stations UI opened. still update drones, ships, warpers and power consumption for clients and update all for host UpdateSettingsUIBackground(packet, pData, pData.factory.transport.stationPool[i].gid); return; } else { break; } } } LocalPlayer.PatchLocks["UIStationWindow"] = true; LocalPlayer.PatchLocks["UIStationStorage"] = true; if (packet.settingIndex == 0) { stationWindow.OnMaxChargePowerSliderValueChange(packet.settingValue); } if (packet.settingIndex == 1) { stationWindow.OnMaxTripDroneSliderValueChange(packet.settingValue); } if (packet.settingIndex == 2) { stationWindow.OnMaxTripVesselSliderValueChange(packet.settingValue); } if (packet.settingIndex == 3) { stationWindow.OnMinDeliverDroneValueChange(packet.settingValue); } if (packet.settingIndex == 4) { stationWindow.OnMinDeliverVesselValueChange(packet.settingValue); } if (packet.settingIndex == 5) { stationWindow.OnWarperDistanceValueChange(packet.settingValue); } if (packet.settingIndex == 6) { stationWindow.OnWarperNecessaryClick(0); } if (packet.settingIndex == 7) { Type[] args = new Type[1]; object[] values = new object[1]; args[0] = typeof(int); values[0] = 0; AccessTools.Method(typeof(UIStationWindow), "OnIncludeOrbitCollectorClick", args).Invoke(stationWindow, values); } if (packet.settingIndex >= 8 && packet.settingIndex <= 10) { StationComponent[] stationPool = pData.factory.transport.stationPool; if (packet.settingIndex == 8) { Type[] args = new Type[1]; object[] values = new object[1]; args[0] = typeof(int); values[0] = 0; if (UIRequestedShipDronWarpChange) { AccessTools.Method(typeof(UIStationWindow), "OnDroneIconClick", args).Invoke(stationWindow, values); UIRequestedShipDronWarpChange = false; } stationPool[_stationId].idleDroneCount = (int)packet.settingValue; } if (packet.settingIndex == 9) { Type[] args = new Type[1]; object[] values = new object[1]; args[0] = typeof(int); values[0] = 0; if (UIRequestedShipDronWarpChange) { AccessTools.Method(typeof(UIStationWindow), "OnShipIconClick", args).Invoke(stationWindow, values); UIRequestedShipDronWarpChange = false; } stationPool[_stationId].idleShipCount = (int)packet.settingValue; } if (packet.settingIndex == 10) { Type[] args = new Type[1]; object[] values = new object[1]; args[0] = typeof(int); values[0] = 0; if (UIRequestedShipDronWarpChange) { AccessTools.Method(typeof(UIStationWindow), "OnWarperIconClick", args).Invoke(stationWindow, values); UIRequestedShipDronWarpChange = false; } stationPool[_stationId].warperCount = (int)packet.settingValue; } } if (packet.settingIndex == 11) { StationComponent[] stationPool = pData.factory.transport.stationPool; if (stationPool[_stationId].storage != null) { if (packet.shouldMimick) { BaseEventData mouseEvent = lastMouseEvent; PointerEventData pointEvent = mouseEvent as PointerEventData; UIStationStorage[] storageUIs = (UIStationStorage[])AccessTools.Field(typeof(UIStationWindow), "storageUIs").GetValue(stationWindow); if (lastMouseEvent != null) { if (lastMouseEventWasDown) { storageUIs[packet.storageIdx].OnItemIconMouseDown(mouseEvent); StationUI packet2 = new StationUI(packet.stationGId, packet.planetId, packet.storageIdx, 12, packet.itemId, stationPool[_stationId].storage[packet.storageIdx].count); LocalPlayer.SendPacket(packet2); } else { storageUIs[packet.storageIdx].OnItemIconMouseUp(mouseEvent); StationUI packet2 = new StationUI(packet.stationGId, packet.planetId, packet.storageIdx, 12, packet.itemId, stationPool[_stationId].storage[packet.storageIdx].count); LocalPlayer.SendPacket(packet2); } lastMouseEvent = null; } } else { //stationPool[_stationId].storage[packet.storageIdx].count = (int)packet.settingValue; } } } if (packet.settingIndex == 12) { Debug.Log("should set it"); StationComponent[] stationPool = pData.factory.transport.stationPool; if (stationPool[_stationId].storage != null) { stationPool[_stationId].storage[packet.storageIdx].count = (int)packet.settingValue; } } LocalPlayer.PatchLocks["UIStationWindow"] = false; LocalPlayer.PatchLocks["UIStationStorage"] = false; } }
/* * When the host notifies the client that a ship started its travel client needs to check if he got both ILS in his gStationPool * if not we create a fake entry (which gets updated to the full one when client arrives that planet) and also request the stations dock position */ public static void IdleShipGetToWork(ILSShipData packet) { PlanetData planetA = GameMain.galaxy.PlanetById(packet.planetA); PlanetData planetB = GameMain.galaxy.PlanetById(packet.planetB); if (planetA != null && planetB != null) { if (GameMain.data.galacticTransport.stationCapacity <= packet.planetAStationGID) { CreateFakeStationComponent(packet.planetAStationGID, packet.planetA); } else if (GameMain.data.galacticTransport.stationPool[packet.planetAStationGID] == null) { CreateFakeStationComponent(packet.planetAStationGID, packet.planetA); } else if (GameMain.data.galacticTransport.stationPool[packet.planetAStationGID].shipDockPos == Vector3.zero) { RequestgStationDockPos(packet.planetAStationGID); } if (GameMain.data.galacticTransport.stationCapacity <= packet.planetBStationGID) { CreateFakeStationComponent(packet.planetBStationGID, packet.planetB); } else if (GameMain.data.galacticTransport.stationPool[packet.planetBStationGID] == null) { CreateFakeStationComponent(packet.planetBStationGID, packet.planetB); } else if (GameMain.data.galacticTransport.stationPool[packet.planetBStationGID].shipDockPos == Vector3.zero) { RequestgStationDockPos(packet.planetBStationGID); } StationComponent stationComponent = GameMain.data.galacticTransport.stationPool[packet.planetAStationGID]; stationComponent.workShipDatas[stationComponent.workShipCount].stage = -2; stationComponent.workShipDatas[stationComponent.workShipCount].planetA = packet.planetA; stationComponent.workShipDatas[stationComponent.workShipCount].planetB = packet.planetB; stationComponent.workShipDatas[stationComponent.workShipCount].otherGId = packet.planetBStationGID; stationComponent.workShipDatas[stationComponent.workShipCount].direction = 1; stationComponent.workShipDatas[stationComponent.workShipCount].t = 0f; stationComponent.workShipDatas[stationComponent.workShipCount].itemId = packet.itemId; stationComponent.workShipDatas[stationComponent.workShipCount].itemCount = packet.itemCount; stationComponent.workShipDatas[stationComponent.workShipCount].gene = 0; // WHAT IS THIS? stationComponent.workShipDatas[stationComponent.workShipCount].shipIndex = packet.origShipIndex; stationComponent.workShipDatas[stationComponent.workShipCount].warperCnt = packet.warperCnt; stationComponent.warperCount = packet.stationWarperCnt; stationComponent.workShipCount++; stationComponent.idleShipCount--; if (stationComponent.idleShipCount < 0) { stationComponent.idleShipCount = 0; } if (stationComponent.workShipCount > ILSMaxShipCount) { stationComponent.workShipCount = ILSMaxShipCount; } stationComponent.IdleShipGetToWork(packet.origShipIndex); StationComponent otherStationComponent = GameMain.data.galacticTransport.stationPool[packet.planetBStationGID]; if (otherStationComponent != null && otherStationComponent.storage != null) { for (int i = 0; i < otherStationComponent.storage.Length; i++) { if (otherStationComponent.storage[i].itemId == packet.itemId) { otherStationComponent.storage[i].remoteOrder += packet.itemCount; RefreshValuesUI(otherStationComponent, i); break; } } } } }
/// <summary> /// <c>rot_back</c> /// Adds reference orbit to chebyshew series (if SEI_FLG_ELLIPSE), /// rotates series to mean equinox of J2000 /// </summary> private int RotateBack(PlanetData pdp, JulianDayNumber segmentStart, double[] coefficients, Epsilon epsilon) { int nco = pdp.CoefficientsNumber; var t = segmentStart.Raw + pdp.SegmentSize / 2; // data align: chcfx double[nco] + chcfy double[nco] + chcfz double[nco] // allsize: nco * 3 var segp = coefficients; var chcfx = new Span <double>(segp, 0, nco); var chcfy = new Span <double>(segp, nco, nco); var chcfz = new Span <double>(segp, nco * 2, nco); var tdiff = (t - pdp.ElementsEpoch) / 365250.0; double qav, pav; if (pdp.InternalBodyNumber == (int)InternalPlanets.Moon) { var dn = pdp.Prot + tdiff * pdp.Dprot; var i = (int)(dn / Consts.TwoPi); dn -= i * Consts.TwoPi; qav = (pdp.Qrot + tdiff * pdp.Dqrot) * Math.Cos(dn); pav = (pdp.Qrot + tdiff * pdp.Dqrot) * Math.Sin(dn); } else { qav = pdp.Qrot + tdiff * pdp.Dqrot; pav = pdp.Prot + tdiff * pdp.Dprot; } // calculate cosine and sine of average perihelion longitude. var x = new double[nco, 3]; for (int i = 0; i < nco; i++) { x[i, 0] = chcfx[i]; x[i, 1] = chcfy[i]; x[i, 2] = chcfz[i]; } if (pdp.Flags.HasFlag(PlanetFlags.Ellipse)) { var refepx = new Span <double>(pdp.ReferenceEllipseCoefficients, 0, nco); var refepy = new Span <double>(pdp.ReferenceEllipseCoefficients, nco, nco); var omtild = pdp.Perigee + tdiff + pdp.DPerigee; int i = (int)(omtild / Consts.TwoPi); omtild -= i * Consts.TwoPi; var com = Math.Cos(omtild); var som = Math.Sin(omtild); // add reference orbit. for (i = 0; i < nco; i++) { x[i, 0] = chcfx[i] + com * refepx[i] - som * refepy[i]; x[i, 1] = chcfy[i] + com * refepy[i] + som * refepx[i]; } } /* construct right handed orthonormal system with first axis along * origin of longitudes and third axis along angular momentum * this uses the standard formulas for equinoctal variables * (see papers by broucke and by cefola). */ var cosih2 = 1.0 / (1.0 + qav * qav + pav * pav); // calculate orbit pole. Span <double> uiz = stackalloc double[3]; uiz[0] = 2.0 * pav * cosih2; uiz[1] = -2.0 * qav * cosih2; uiz[2] = (1.0 - qav * qav - pav * pav) * cosih2; // calculate origin of longitudes vector. Span <double> uix = stackalloc double[3]; uix[0] = (1.0 + qav * qav - pav * pav) * cosih2; uix[1] = 2.0 * qav * pav * cosih2; uix[2] = -2.0 * pav * cosih2; // calculate vector in orbital plane orthogonal to origin of longitudes. Span <double> uiy = stackalloc double[3]; uiy[0] = 2.0 * qav * pav * cosih2; uiy[1] = (1.0 - qav * qav + pav * pav) * cosih2; uiy[2] = 2.0 * qav * cosih2; int evaluateCoefficientsCount = 0; // rotate to actual orientation in space. for (var i = 0; i < nco; i++) { var xrot = x[i, 0] * uix[0] + x[i, 1] * uiy[0] + x[i, 2] * uiz[0]; var yrot = x[i, 0] * uix[1] + x[i, 1] * uiy[1] + x[i, 2] * uiz[1]; var zrot = x[i, 0] * uix[2] + x[i, 1] * uiy[2] + x[i, 2] * uiz[2]; if (Math.Abs(xrot) + Math.Abs(yrot) + Math.Abs(zrot) >= 1e-14) { evaluateCoefficientsCount = i; } x[i, 0] = xrot; x[i, 1] = yrot; x[i, 2] = zrot; if (pdp.InternalBodyNumber == (int)InternalPlanets.Moon) { /* rotate to j2000 equator */ x[i, 1] = epsilon.CosEps * yrot - epsilon.SinEps * zrot; x[i, 2] = epsilon.SinEps * yrot + epsilon.CosEps * zrot; } } for (var i = 0; i < nco; i++) { chcfx[i] = x[i, 0]; chcfy[i] = x[i, 1]; chcfz[i] = x[i, 2]; } return(evaluateCoefficientsCount); }
public static void CreatePrebuildsRequest(CreatePrebuildsRequest packet) { PlanetData planet = GameMain.galaxy.PlanetById(packet.PlanetId); if (planet.factory == null) { if (FactoryManager.EventFromServer) { // We only execute the code if the client has loaded the factory at least once. // Else it will get it once it goes to the planet for the first time. return; } Log.Warn($"planet.factory was null create new one"); planet.factory = GameMain.data.GetOrCreateFactory(planet); } PlayerAction_Build pab = GameMain.mainPlayer.controller != null ? GameMain.mainPlayer.controller.actionBuild : null; BuildTool[] buildTools = pab.tools; BuildTool buildTool = null; for (int i = 0; i < buildTools.Length; i++) { if (buildTools[i].GetType().ToString() == packet.BuildToolType) { buildTool = buildTools[i]; break; } } if (pab != null && buildTool != null) { FactoryManager.TargetPlanet = packet.PlanetId; FactoryManager.PacketAuthor = packet.AuthorId; PlanetFactory tmpFactory = null; NearColliderLogic tmpNearcdLogic = null; PlanetPhysics tmpPlanetPhysics = null; bool loadExternalPlanetData = GameMain.localPlanet != planet; if (loadExternalPlanetData) { //Make backup of values that are overwritten tmpFactory = buildTool.factory; tmpNearcdLogic = buildTool.actionBuild.nearcdLogic; tmpPlanetPhysics = buildTool.actionBuild.planetPhysics; } //Create Prebuilds from incoming packet and prepare new position List <BuildPreview> tmpList = new List <BuildPreview>(); tmpList.AddRange(buildTool.buildPreviews); buildTool.buildPreviews.Clear(); buildTool.buildPreviews.AddRange(packet.GetBuildPreviews()); FactoryManager.EventFactory = planet.factory; //Check if some mandatory variables are missing if (planet.physics == null || planet.physics.colChunks == null) { planet.physics = new PlanetPhysics(planet); planet.physics.Init(); } if (planet.aux == null) { planet.aux = new PlanetAuxData(planet); } //Set temporary Local Planet / Factory data that are needed for original methods CheckBuildConditions() and CreatePrebuilds() buildTool.factory = planet.factory; pab.factory = planet.factory; pab.noneTool.factory = planet.factory; if (FactoryManager.EventFromClient) { // Only the server needs to set these pab.planetPhysics = planet.physics; pab.nearcdLogic = planet.physics.nearColliderLogic; } //Check if prebuilds can be build (collision check, height check, etc) bool canBuild = false; if (FactoryManager.EventFromClient) { GameMain.mainPlayer.mecha.buildArea = float.MaxValue; canBuild = CheckBuildingConnections(buildTool.buildPreviews, planet.factory.entityPool, planet.factory.prebuildPool); } Debug.Log(buildTool.buildPreviews[0].condition); if (canBuild || FactoryManager.EventFromServer) { if (FactoryManager.EventFromClient) { CheckAndFixConnections(buildTool, planet); } if (packet.BuildToolType == typeof(BuildTool_Click).ToString()) { ((BuildTool_Click)buildTool).CreatePrebuilds(); } else if (packet.BuildToolType == typeof(BuildTool_Path).ToString()) { ((BuildTool_Path)buildTool).CreatePrebuilds(); } else if (packet.BuildToolType == typeof(BuildTool_Inserter).ToString()) { ((BuildTool_Inserter)buildTool).CreatePrebuilds(); } } //Revert changes back to the original planet if (loadExternalPlanetData) { buildTool.factory = tmpFactory; pab.factory = tmpFactory; pab.noneTool.factory = tmpFactory; if (FactoryManager.EventFromClient) { pab.planetPhysics = tmpPlanetPhysics; pab.nearcdLogic = tmpNearcdLogic; planet.physics.Free(); planet.physics = null; } } GameMain.mainPlayer.mecha.buildArea = Configs.freeMode.mechaBuildArea; FactoryManager.EventFactory = null; buildTool.buildPreviews.Clear(); buildTool.buildPreviews.AddRange(tmpList); FactoryManager.TargetPlanet = FactoryManager.PLANET_NONE; FactoryManager.PacketAuthor = -1; } }
/// <summary> /// Fetch chebyshew coefficients from sweph file /// </summary> /// <param name="pdp">Planet</param> /// <param name="jd">Time</param> /// <param name="epsilonJ2000">Epsilon for J2000</param> /// <see cref="get_new_segment"/> internal SEFileSegment ReadSegment(PlanetData pdp, JulianDayNumber jd, Epsilon epsilonJ2000) { int segmentNumber = (int)((jd - pdp.StartDate).Raw / pdp.SegmentSize); var segmentStart = pdp.StartDate + JulianDayNumber.FromRaw(pdp.SegmentSize * segmentNumber); var fpos = pdp.FileIndexStart + segmentNumber * 3; fpos = ReadInt32From3Bytes(fpos); _stream.Seek(fpos, SeekOrigin.Begin); var rmax = pdp.NormalizationFactor; double[] segp = new double[pdp.CoefficientsNumber * 3]; // read coefficients for 3 coordinates for (var icoord = 0; icoord < 3; icoord++) { var idbl = icoord * pdp.CoefficientsNumber; // first read header // first bit indicates number of sizes of packed coefficients int nco; int nsizes; int[] nsize = new int[6]; var c = ReadData(1, 2); if ((c[0] & 128) > 0) { var c2 = ReadData(1, 2); nsizes = 6; nsize[0] = c[1] / 16; nsize[1] = c[1] % 16; nsize[2] = c2[0] / 16; nsize[3] = c2[0] % 16; nsize[4] = c2[1] / 16; nsize[5] = c2[1] % 16; nco = nsize[0] + nsize[1] + nsize[2] + nsize[3] + nsize[4] + nsize[5]; } else { nsizes = 4; nsize[0] = c[0] / 16; nsize[1] = c[0] % 16; nsize[2] = c[1] / 16; nsize[3] = c[1] % 16; nco = nsize[0] + nsize[1] + nsize[2] + nsize[3]; } // there may not be more coefficients than interpolation order + 1 if (nco > pdp.CoefficientsNumber) { throw new FormatException($"Error in ephemeris file: {nco} coefficients instead of {pdp.CoefficientsNumber}"); } // now unpack for (var i = 0; i < nsizes; i++) { if (nsize[i] == 0) { continue; } if (i < 4) { int j = 4 - i; int k = nsize[i]; var longs = ReadUints(j, k); for (int m = 0; m < k; m++) { if ((longs[m] & 1) > 0) // will be negative { segp[idbl] = -(((longs[m] + 1) / 2) / 1e+9 * rmax / 2); } else { segp[idbl] = (longs[m] / 2) / 1e+9 * rmax / 2; } idbl++; } } else if (i == 4) // half byte packing { int k = (nsize[i] + 1) / 2; var longs = ReadUints(1, k); for (int m = 0, j = 0; m < k && j < nsize[i]; m++) { for (int n = 0, o = 16; n < 2 && j < nsize[i]; n++, j++, idbl++, longs[m] %= (uint)o, o /= 16) { if ((longs[m] & o) > 0) { segp[idbl] = -(((longs[m] + o) / o / 2) * rmax / 2 / 1e+9); } else { segp[idbl] = (longs[m] / o / 2) * rmax / 2 / 1e+9; } } } } else if (i == 5) // quarter byte packing { int k = (nsize[i] + 3) / 4; var longs = ReadUints(1, k); for (int m = 0, j = 0; m < k && j < nsize[i]; m++) { for (int n = 0, o = 64; n < 4 && j < nsize[i]; n++, j++, idbl++, longs[m] %= (uint)o, o /= 4) { if ((longs[m] & o) > 0) { segp[idbl] = -(((longs[m] + o) / o / 2) * rmax / 2 / 1e+9); } else { segp[idbl] = (longs[m] / o / 2) * rmax / 2 / 1e+9; } } } } } } int evaluateCoefficientsCount = pdp.Flags.HasFlag(PlanetFlags.Rotate) ? RotateBack(pdp, segmentStart, segp, epsilonJ2000) : pdp.CoefficientsNumber; var segment = new SEFileSegment(segmentStart, JulianDayNumber.FromRaw(pdp.SegmentSize), segp, evaluateCoefficientsCount); return(segment); }
public Gas(Int32 YSize, PlanetData planetData) : base(YSize, planetData) { }
public static Mesh CreateWaterMesh(PlanetData planet) { Stopwatch sw = new Stopwatch(); sw.Start(); int oceanIndex = -1; for (int i = 0; i < planet.biomes.Length; i++) { if (planet.biomes[i].isOceanBiome) { oceanIndex = i; break; } } if (oceanIndex < 0) { return(null); } int size = 0; for (int i = 0; i < planet.triangles.Length; i++) { int b1 = planet.points[planet.triangles[i].v1].biomeID; int b2 = planet.points[planet.triangles[i].v2].biomeID; int b3 = planet.points[planet.triangles[i].v3].biomeID; if (b1 == oceanIndex || b2 == oceanIndex || b3 == oceanIndex) { size++; } } int[] triangles = new int[size * 3]; Color32[] colors = new Color32[size * 3]; Vector3[] points = new Vector3[size * 3]; int index = 0; for (int i = 0; i < planet.triangles.Length; i++) { int b1 = planet.points[planet.triangles[i].v1].biomeID; int b2 = planet.points[planet.triangles[i].v2].biomeID; int b3 = planet.points[planet.triangles[i].v3].biomeID; if (b1 != oceanIndex && b2 != oceanIndex && b3 != oceanIndex) { continue; } points[3 * index] = planet.points[planet.triangles[i].v1].point * planet.scale; points[3 * index + 1] = planet.points[planet.triangles[i].v2].point * planet.scale; points[3 * index + 2] = planet.points[planet.triangles[i].v3].point * planet.scale; var biomeID = PlanetEx.biomeIndexOfTriangle(planet, i); Color biomeColor = planet.biomes[oceanIndex].color; colors[3 * index] = biomeColor; colors[3 * index + 1] = biomeColor; colors[3 * index + 2] = biomeColor; index++; } for (int i = 0; i < size * 3; i++) { triangles[i] = i; } Mesh m = new Mesh(); m.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32; m.vertices = points; m.colors32 = colors; m.triangles = triangles; m.RecalculateNormals(); m.RecalculateTangents(); m.RecalculateBounds(); sw.Stop(); UnityEngine.Debug.Log("Elapsed water renderer " + sw.Elapsed); return(m); }
public static void ClaimCivPlanet(PlanetData pData, Civilization newCiv) { // assign a name for the civ's planet if (DataManager.planetNameList.Count > 0) { var nameIndex = UnityEngine.Random.Range(0, DataManager.planetNameList.Count); pData.Name = DataManager.planetNameList[nameIndex]; DataManager.planetNameList.RemoveAt(nameIndex); DataManager.planetNameList.TrimExcess(); } else pData.Name = "GenericName"; pData.Rank = PlanetData.ePlanetRank.EstablishedColony; newCiv.PlanetIDList.Add(pData.ID); // add the planet }
public static bool GetClosestIndex(Ray ray, PlanetData localPlanet, out int closestVeinGroupIndex, out int closestVeinIndex, out float closestVeinDistance, out float closestVeinDistance2D) { float realRadius = localPlanet.realRadius; closestVeinGroupIndex = -1; closestVeinIndex = -1; closestVeinDistance = -1; closestVeinDistance2D = -1; float closestVeinGroupDistance = 100f; Vector3 vector = Vector3.zero; if (Phys.RayCastSphere(ray.origin, ray.direction, 600f, Vector3.zero, realRadius + 1f, out var rch)) { Dictionary <int, float> distMap = new Dictionary <int, float>(); // First pass check for vein Group. Uses veinGroups (cheaper) for (int i = 0; i < localPlanet.veinGroups.Length; i++) { PlanetData.VeinGroup veinGroup = localPlanet.veinGroups[i]; if (veinGroup.type == EVeinType.None) { continue; } float currentveinGroupDistance = Vector3.Distance(rch.point, veinGroup.pos * realRadius); //Debug.Log("Comp: veinGroup: " + veinGroup.ToString() + " index: " + i + " Pos: " + veinGroup.pos.ToString() + " dist: " + currentveinGroupDistance); distMap[i] = currentveinGroupDistance; if (currentveinGroupDistance < closestVeinGroupDistance) { closestVeinGroupDistance = currentveinGroupDistance; closestVeinGroupIndex = i; vector = veinGroup.pos * (realRadius + 2.5f); } } // Second Pass. Looks up distance to specific vein nodes. var limitedCandidates = distMap.OrderBy(key => key.Value).Take(Math.Min(distMap.Count(), 5)); //var veinCandidates = from vg in limitedCandidates select from vp in localPlanet.factory.veinPool where vp; closestVeinDistance = closestVeinGroupDistance; closestVeinDistance2D = closestVeinGroupDistance; foreach (var candkv in limitedCandidates) { //Debug.Log("Cand: VeinGroup Idx=" + candkv.Key + "\t Dist: " + candkv.Value); for (int i = 1; i < localPlanet.factory.veinCursor; i++) { var vein = localPlanet.factory.veinPool[i]; if (vein.id != i || vein.groupIndex != candkv.Key) { continue; } float veinDistance = Vector3.Distance(rch.point, vein.pos); if (veinDistance < closestVeinDistance) { closestVeinDistance = veinDistance; closestVeinGroupIndex = candkv.Key; closestVeinIndex = vein.id; } float veinDistance2D = Vector2.Distance(rch.point, vein.pos); if (veinDistance2D < closestVeinDistance2D) { closestVeinDistance2D = veinDistance2D; closestVeinGroupIndex = candkv.Key; closestVeinIndex = vein.id; } } } //Debug.Log("Closest: VgIdx=" + closestVeinGroupIndex + " Vein Idx=" + closestVeinIndex + "\t Dist: " + closestVeinDistance + ", Dist2D: " + closestVeinDistance2D); // Cheat for now //Assert.Equals(closestVeinGroupIndex, limitedCandidates.First().Key); //closestVeinGroupIndex = candidates.First().Key; } // Check if there are any vein colliders inside a radius 5f sphere. if (closestVeinGroupIndex >= 0) { /* * if (!Phys.RayCastSphere(ray.origin, ray.direction, 600f, vector, 5f, out rch)) * { * Debug.Log("Resetting to -1! "); * closestVeinGroupIndex = -1; * closestVeinIndex = -1; * return false; * } */ if (closestVeinDistance2D < 5) { return(true); } else { //Debug.Log("Resetting to -1! Distance is above: 5"); closestVeinGroupIndex = -1; closestVeinIndex = -1; closestVeinDistance2D = -1; return(false); } } return(false); }
public static StarData CreateSystemPlanets(StarData curSys) { PlanetGenerationData pgList = new PlanetGenerationData(); SpotPlanetGenerationTable pgTable = new SpotPlanetGenerationTable(); bool planetFound = false; try { pgList = planetGenerationDataList.Find(p => p.starType == curSys.SpectralClass); } catch (Exception ex) { Debug.LogError("Could not lookup " + curSys.SpectralClass.ToString() + " table for system " + curSys.Name + "! Error:" + ex.ToString()); return null; // try again with the next star } for (int x = 0; x < MaxPlanetsPerSystem; x++) // 6 spots to generate { pgTable = pgList.planetGenerationTable[x]; planetFound = false; // reset planet flag int generationChance = 0; int planetTypeChance = 0; // Step 1: check to see if there is a chance of a planet generationChance = UnityEngine.Random.Range(0, 100); if (generationChance <= pgTable.baseChance + (curSys.pMaterial * pgTable.materialMultiplier) - ((int)curSys.starMultipleType * pgTable.companionModifier)) // Step 2: look up the planet generation tables for this type of star and determine which planet type is generated { planetTypeChance = UnityEngine.Random.Range(0, 100); for (int y = 0; y < pgTable.chanceData.Count; y++) // look up planet data on each table { if (!planetFound) { int curChance = pgTable.chanceData[y]; if (planetTypeChance <= curChance) { PlanetData curPlanetData = new PlanetData(); curPlanetData = GeneratePlanet((PlanetData.ePlanetType)pgTable.typeData[y],curSys,x+1); curPlanetData.SystemID = curSys.ID; galaxyDataRef.AddPlanetDataToList(curPlanetData); //curSys.PlanetList.Add(curPlanetData); // a planet is born! Generate it now curSys.PlanetSpots[x] = curPlanetData; // stick it in the correct 'spot' (probably will rewrite) planetFound = true; } } } } } return curSys; }
/// <summary> /// unittest用 /// </summary> /// <param name="subIndex">targetNoList決定に使用</param> /// <returns></returns> public Dictionary <int, PlanetData> setHouse(Dictionary <int, PlanetData> pdata, double[] houses, SettingData setting, int subIndex) { PlanetData pAsc = new PlanetData() { absolute_position = houses[1], no = CommonData.ZODIAC_ASC, sensitive = true, speed = 1, aspects = new List <AspectInfo>(), secondAspects = new List <AspectInfo>(), thirdAspects = new List <AspectInfo>() }; if (subIndex >= 0) { if (setting.dispPlanet[subIndex][CommonData.ZODIAC_ASC]) { pAsc.isDisp = true; } else { pAsc.isDisp = false; } if (setting.dispAspectPlanet[subIndex][CommonData.ZODIAC_ASC]) { pAsc.isAspectDisp = true; } else { pAsc.isAspectDisp = false; } } pdata[CommonData.ZODIAC_ASC] = pAsc; PlanetData pMc = new PlanetData() { isAspectDisp = true, isDisp = true, absolute_position = houses[10], no = CommonData.ZODIAC_MC, sensitive = true, speed = 1, aspects = new List <AspectInfo>(), secondAspects = new List <AspectInfo>(), thirdAspects = new List <AspectInfo>() }; if (subIndex >= 0) { if (setting.dispPlanet[subIndex][CommonData.ZODIAC_MC]) { pMc.isDisp = true; } else { pMc.isDisp = false; } if (setting.dispAspectPlanet[subIndex][CommonData.ZODIAC_MC]) { pMc.isAspectDisp = true; } else { pMc.isAspectDisp = false; } } pdata[CommonData.ZODIAC_MC] = pMc; return(pdata); }
//Returns the distance between two planets (their surfaces, not their centers) public float GetSurfaceDistance(PlanetData other) { return GetDistance(other.Position) - (other.Diameter + Diameter) / 2; }
// 天体の位置を計算する public Dictionary <int, PlanetData> PositionCalc(DateTime d, double lat, double lng, int houseKind, int subIndex) { Dictionary <int, PlanetData> planetdata = new Dictionary <int, PlanetData>();; // absolute position double[] x = { 0, 0, 0, 0, 0, 0 }; string serr = ""; int utc_year = 0; int utc_month = 0; int utc_day = 0; int utc_hour = 0; int utc_minute = 0; double utc_second = 0; // [0]:Ephemeris Time [1]:Universal Time double[] dret = { 0.0, 0.0 }; int ii = 0; // utcに変換 // 本来ここにJSTの9.0を入れるのだが・・・ s.swe_utc_time_zone(d.Year, d.Month, d.Day, d.Hour, d.Minute, d.Second, 0.0, ref utc_year, ref utc_month, ref utc_day, ref utc_hour, ref utc_minute, ref utc_second); s.swe_utc_to_jd(utc_year, utc_month, utc_day, utc_hour, utc_minute, utc_second, 1, dret, ref serr); // 10天体ループ // 11(DH/TrueNode)、14(Earth)、15(Chiron)もついでに計算 Enumerable.Range(0, 16).ToList().ForEach(i => { int flag = SwissEph.SEFLG_SWIEPH | SwissEph.SEFLG_SPEED; if (config.centric == ECentric.HELIO_CENTRIC) { flag |= SwissEph.SEFLG_HELCTR; } if (config.sidereal == Esidereal.SIDEREAL) { flag |= SwissEph.SEFLG_SIDEREAL; s.swe_set_sid_mode(SwissEph.SE_SIDM_LAHIRI, 0, 0); // ayanamsa計算 double daya = 0.0; double ut = s.swe_get_ayanamsa_ex_ut(dret[1], SwissEph.SEFLG_SWIEPH, out daya, ref serr); // Ephemeris Timeで計算, 結果はxに入る s.swe_calc_ut(dret[1], i, flag, x, ref serr); } else { // Universal Timeで計算, 結果はxに入る s.swe_calc_ut(dret[1], i, flag, x, ref serr); } PlanetData p = new PlanetData() { no = i, absolute_position = x[0], speed = x[3], aspects = new List <AspectInfo>(), secondAspects = new List <AspectInfo>(), thirdAspects = new List <AspectInfo>(), sensitive = false }; if (i < 10 && subIndex >= 0) { if (main.currentSetting.dispPlanet[subIndex][main.dispListMap[i]]) { p.isDisp = true; } else { p.isDisp = false; } if (main.currentSetting.dispAspectPlanet[subIndex][main.dispListMap[i]]) { p.isAspectDisp = true; } else { p.isAspectDisp = false; } } if (config.centric == ECentric.HELIO_CENTRIC && i == 0) { // ヘリオセントリック太陽 p.isDisp = false; p.isAspectDisp = false; } if (i == 10) { // MEAN NODE p.isDisp = false; p.isAspectDisp = false; } if (i == 11 && subIndex >= 0 && config.centric == ECentric.GEO_CENTRIC) { // TRUE NODE ヘッド if (main.currentSetting.dispPlanet[subIndex][11]) { p.isDisp = true; } else { p.isDisp = false; } if (main.currentSetting.dispAspectPlanet[subIndex][11]) { p.isAspectDisp = true; } else { p.isAspectDisp = false; } } if (i == 12) { // mean apogee、どうでもいい p.isDisp = false; p.isAspectDisp = false; } if (i == 13 && subIndex >= 0) { // true apogee、要はリリス if (main.currentSetting.dispPlanet[subIndex][CommonData.ZODIAC_LILITH]) { p.isDisp = true; } else { p.isDisp = false; } if (main.currentSetting.dispAspectPlanet[subIndex][CommonData.ZODIAC_LILITH]) { p.isAspectDisp = true; } else { p.isAspectDisp = false; } } if (config.centric == ECentric.HELIO_CENTRIC && i == 14 && subIndex >= 0) { // ヘリオセントリック地球 if (main.currentSetting.dispPlanet[subIndex][main.dispListMap[i]]) { p.isDisp = true; } else { p.isDisp = false; } if (main.currentSetting.dispAspectPlanet[subIndex][main.dispListMap[i]]) { p.isAspectDisp = true; } else { p.isAspectDisp = false; } } if (i == 15 && subIndex >= 0) { if (main.currentSetting.dispPlanet[subIndex][CommonData.ZODIAC_CHIRON]) { p.isDisp = true; } else { p.isDisp = false; } if (main.currentSetting.dispAspectPlanet[subIndex][CommonData.ZODIAC_CHIRON]) { p.isAspectDisp = true; } else { p.isAspectDisp = false; } } ii = i; planetdata[i] = p; }); s.swe_close(); // ハウスを後ろにくっつける double[] houses = CuspCalc(d, lat, lng, houseKind); planetdata = setHouse(planetdata, houses, main.currentSetting, subIndex); return(planetdata); }
private void PlacePlanet(PlanetData data) { GameObject go = (GameObject) GameObject.Instantiate(_planetPrefab, data.Pos, Quaternion.identity); if (go == null) { Logger.Log("There is an error Instantiating Planet", 4); return; } go.name = data.Type.ToString(); go.transform.SetParent(Global.World.transform, false); // Attach Behavior PlanetBase planet = AttachPlanetBehavior(go, data.Type); if(planet== null) { Logger.Log("There is an error Instantiating Planet", 4); return; } planet.Initialize(data); data.Placed = true; _planets.Add(planet); }
// CPS // 月、水星、金星、太陽は一日一年法 // 火星以降および感受点は一度一年法 // 一年を365.24日で計算、当然ずれが生じる // 面倒なのでとりあえず放置 public Dictionary <int, PlanetData> CompositProgressionCalc(Dictionary <int, PlanetData> natallist, DateTime natalTime, DateTime transitTime) { Dictionary <int, PlanetData> progresslist = new Dictionary <int, PlanetData>(); TimeSpan ts = transitTime - natalTime; double years = ts.TotalDays / year_days; // 日付を秒数に変換する int seconds = (int)(years * 86400); TimeSpan add = TimeSpan.FromSeconds(seconds); DateTime newTime = natalTime + add; // absolute position double[] x = { 0, 0, 0, 0, 0, 0 }; string serr = ""; int utc_year = 0; int utc_month = 0; int utc_day = 0; int utc_hour = 0; int utc_minute = 0; double utc_second = 0; // [0]:Ephemeris Time [1]:Universal Time double[] dret = { 0.0, 0.0 }; // utcに変換 s.swe_utc_time_zone(newTime.Year, newTime.Month, newTime.Day, newTime.Hour, newTime.Minute, newTime.Second, 0.0, ref utc_year, ref utc_month, ref utc_day, ref utc_hour, ref utc_minute, ref utc_second); s.swe_utc_to_jd(utc_year, utc_month, utc_day, utc_hour, utc_minute, utc_second, 1, dret, ref serr); foreach (KeyValuePair <int, PlanetData> pair in natallist) { PlanetData progressdata; if (config.centric == ECentric.HELIO_CENTRIC && pair.Key == CommonData.ZODIAC_SUN) { // ヘリオセントリック太陽 continue; } if (pair.Key == 10) { // MEAN NODE continue; } if (pair.Key == 12) { // mean apogee、どうでもいい continue; } if (pair.Key == 13) { // true apogee、リリス continue; } if (config.centric == ECentric.GEO_CENTRIC && pair.Key == CommonData.ZODIAC_EARTH) { // ジオセントリック地球 continue; } if ((pair.Key != CommonData.ZODIAC_MOON) && (pair.Key != CommonData.ZODIAC_MERCURY) && (pair.Key != CommonData.ZODIAC_VENUS) && (pair.Key != CommonData.ZODIAC_SUN)) { progressdata = new PlanetData() { absolute_position = pair.Value.absolute_position, no = pair.Key, sensitive = pair.Value.sensitive, speed = pair.Value.speed, aspects = new List <AspectInfo>(), secondAspects = new List <AspectInfo>(), thirdAspects = new List <AspectInfo>(), fourthAspects = null, fifthAspects = null, sixthAspects = null, seventhAspects = null, isDisp = true, }; progressdata.absolute_position += years; progressdata.absolute_position %= 365; progresslist[pair.Key] = progressdata; continue; } int flag = SwissEph.SEFLG_SWIEPH | SwissEph.SEFLG_SPEED; if (config.centric == ECentric.HELIO_CENTRIC) { flag |= SwissEph.SEFLG_HELCTR; } if (config.sidereal == Esidereal.SIDEREAL) { flag |= SwissEph.SEFLG_SIDEREAL; s.swe_set_sid_mode(SwissEph.SE_SIDM_LAHIRI, 0, 0); // ayanamsa計算 double daya = 0.0; double ut = s.swe_get_ayanamsa_ex_ut(dret[1], SwissEph.SEFLG_SWIEPH, out daya, ref serr); // Ephemeris Timeで計算, 結果はxに入る s.swe_calc_ut(dret[1], pair.Key, flag, x, ref serr); // tropicalからayanamsaをマイナス x[0] = x[0] > daya ? x[0] - daya : x[0] - daya + 360; } else { // Universal Timeで計算, 結果はxに入る s.swe_calc_ut(dret[1], pair.Key, flag, x, ref serr); } progressdata = new PlanetData() { absolute_position = x[0], no = pair.Key, sensitive = pair.Value.sensitive, speed = pair.Value.speed, aspects = new List <AspectInfo>(), secondAspects = new List <AspectInfo>(), thirdAspects = new List <AspectInfo>(), fourthAspects = new List <AspectInfo>(), fifthAspects = new List <AspectInfo>(), isDisp = true, isAspectDisp = true }; progresslist[pair.Key] = progressdata; } return(progresslist); }
public static Mesh CreateRiversMesh(PlanetData planet) { Stopwatch sw = new Stopwatch(); sw.Start(); int biomeIndex = -1; for (int i = 0; i < planet.biomes.Length; i++) { if (planet.biomes[i].isRiverBiome) { biomeIndex = i; break; } } if (biomeIndex < 0) { return(null); } List <Vector3> points = new List <Vector3>(); List <int> triangles = new List <int>(); List <Color32> colors = new List <Color32>(); int index = 0; for (int i = 0; i < planet.points.Length; i++) { if (!planet.points[i].riverInfo.isRiver() || planet.points[i].riverInfo.nextIndex < 0) { continue; } int nextIndex = planet.points[i].riverInfo.nextIndex; Vector3 currentLeft, currentRight, nextLeft, nextRight; switch (planet.points[i].riverInfo.previousIndexs.Count) { case 0: { var h = Vector3.Cross(planet.points[nextIndex].point - planet.points[i].point, planet.points[i].point).normalized; currentLeft = planet.points[i].point + h * planet.points[i].riverInfo.width * planet.riverWidth; currentRight = planet.points[i].point - h * planet.points[i].riverInfo.width * planet.riverWidth; } break; case 1: { var h = Vector3.Cross(planet.points[nextIndex].point - planet.points[planet.points[i].riverInfo.previousIndexs[0]].point, planet.points[i].point).normalized; currentLeft = planet.points[i].point + h * planet.points[i].riverInfo.width * planet.riverWidth; currentRight = planet.points[i].point - h * planet.points[i].riverInfo.width * planet.riverWidth; } break; default: { List <Vector3> previous = new List <Vector3>(); foreach (var pt in planet.points[i].riverInfo.previousIndexs) { previous.Add(planet.points[pt].point); } var left = MathEx.getLeft(previous, planet.points[i].point, planet.points[nextIndex].point, planet.points[i].point.normalized); var right = MathEx.getRight(previous, planet.points[i].point, planet.points[nextIndex].point, planet.points[i].point.normalized); var hLeft = Vector3.Cross(planet.points[nextIndex].point - left, planet.points[i].point).normalized; var hRight = Vector3.Cross(planet.points[nextIndex].point - right, planet.points[i].point).normalized; currentLeft = planet.points[i].point + hLeft * planet.points[i].riverInfo.width * planet.riverWidth; currentRight = planet.points[i].point - hRight * planet.points[i].riverInfo.width * planet.riverWidth; } break; } List <Vector3> nextPoints = new List <Vector3>(); foreach (var pt in planet.points[nextIndex].riverInfo.previousIndexs) { if (pt == i) { continue; } nextPoints.Add(planet.points[pt].point); } if (planet.points[nextIndex].riverInfo.nextIndex >= 0) { nextPoints.Add(planet.points[planet.points[nextIndex].riverInfo.nextIndex].point); } switch (nextPoints.Count) { case 0: { var h = Vector3.Cross(planet.points[i].point - planet.points[nextIndex].point, planet.points[nextIndex].point).normalized; nextLeft = planet.points[nextIndex].point - h * planet.points[nextIndex].riverInfo.width * planet.riverWidth; nextRight = planet.points[nextIndex].point + h * planet.points[nextIndex].riverInfo.width * planet.riverWidth; } break; case 1: { var h = Vector3.Cross(nextPoints[0] - planet.points[i].point, planet.points[nextIndex].point).normalized; nextLeft = planet.points[nextIndex].point + h * planet.points[nextIndex].riverInfo.width * planet.riverWidth; nextRight = planet.points[nextIndex].point - h * planet.points[nextIndex].riverInfo.width * planet.riverWidth; } break; default: { var left = MathEx.getLeft(nextPoints, planet.points[nextIndex].point, planet.points[i].point, planet.points[nextIndex].point.normalized); var right = MathEx.getRight(nextPoints, planet.points[nextIndex].point, planet.points[i].point, planet.points[nextIndex].point.normalized); var hLeft = Vector3.Cross(planet.points[i].point - left, planet.points[nextIndex].point).normalized; var hRight = Vector3.Cross(planet.points[i].point - right, planet.points[nextIndex].point).normalized; nextLeft = planet.points[nextIndex].point - hLeft * planet.points[nextIndex].riverInfo.width * planet.riverWidth; nextRight = planet.points[nextIndex].point + hRight * planet.points[nextIndex].riverInfo.width * planet.riverWidth; } break; } var current = planet.points[i].point * (planet.points[i].height + 1 + planet.riverMoreHeight) * planet.scale; var next = planet.points[nextIndex].point * (planet.points[nextIndex].height + 1 + planet.riverMoreHeight) * planet.scale; currentLeft *= (planet.points[i].height + 1 + planet.riverMoreHeight) * planet.scale; currentRight *= (planet.points[i].height + 1 + planet.riverMoreHeight) * planet.scale; nextLeft *= (planet.points[nextIndex].height + 1 + planet.riverMoreHeight) * planet.scale; nextRight *= (planet.points[nextIndex].height + 1 + planet.riverMoreHeight) * planet.scale; points.Add(currentLeft); points.Add(nextLeft); points.Add(next); points.Add(current); points.Add(currentLeft); points.Add(next); points.Add(currentRight); points.Add(current); points.Add(next); points.Add(currentRight); points.Add(next); points.Add(nextRight); for (int j = index; j < index + 12; j++) { triangles.Add(j); colors.Add(planet.biomes[biomeIndex].color); } index += 12; } Mesh m = new Mesh(); m.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32; m.vertices = points.ToArray(); m.colors32 = colors.ToArray(); m.triangles = triangles.ToArray(); m.RecalculateNormals(); m.RecalculateTangents(); m.RecalculateBounds(); sw.Stop(); UnityEngine.Debug.Log("Elapsed rivers renderer " + sw.Elapsed); return(m); }
public void Init() { _transform = transform; data = new PlanetData(transform.localScale.x * transform.localScale.x, transform.localScale.x, _transform.position, _transform.forward * startSpeed); _transform.position = data.position; }
public void ProcessPacket(CreatePrebuildsRequest packet, NebulaConnection conn) { PlanetData planet = GameMain.galaxy.PlanetById(packet.PlanetId); if (planet.factory == null) { // We only execute the code if the client has loaded the factory at least once. // Else it will get it once it goes to the planet for the first time. return; } PlayerAction_Build pab = GameMain.mainPlayer.controller?.actionBuild; if (pab != null) { //Make backup of values that are overwritten List <BuildPreview> tmpList = pab.buildPreviews; bool tmpConfirm = pab.waitConfirm; UnityEngine.Vector3 tmpPos = pab.previewPose.position; UnityEngine.Quaternion tmpRot = pab.previewPose.rotation; PlanetFactory tmpFactory = (PlanetFactory)AccessTools.Field(typeof(PlayerAction_Build), "factory").GetValue(GameMain.mainPlayer.controller.actionBuild); PlanetPhysics tmpPlanetPhysics = (PlanetPhysics)AccessTools.Field(typeof(PlayerAction_Build), "planetPhysics").GetValue(pab); //Create Prebuilds from incomming packet pab.buildPreviews = packet.GetBuildPreviews(); pab.waitConfirm = true; using (FactoryManager.EventFromServer.On()) { FactoryManager.EventFactory = planet.factory; pab.previewPose.position = new UnityEngine.Vector3(packet.PosePosition.x, packet.PosePosition.y, packet.PosePosition.z); pab.previewPose.rotation = new UnityEngine.Quaternion(packet.PoseRotation.x, packet.PoseRotation.y, packet.PoseRotation.z, packet.PoseRotation.w); AccessTools.Field(typeof(PlayerAction_Build), "factory").SetValue(GameMain.mainPlayer.controller.actionBuild, planet.factory); //Create temporary physics for spawning building's colliders if (planet.physics == null || planet.physics.colChunks == null) { planet.physics = new PlanetPhysics(planet); planet.physics.Init(); } if (BeltManager.GetCargoTraffic(planet.factory.cargoTraffic) == null) { planet.factory.cargoTraffic.CreateRenderingBatches(); } //Take item from the inventory if player is author of the build if (packet.AuthorId == LocalPlayer.PlayerId) { foreach (BuildPreview buildPreview in pab.buildPreviews) { if (GameMain.mainPlayer.inhandItemId == buildPreview.item.ID && GameMain.mainPlayer.inhandItemCount > 0) { GameMain.mainPlayer.UseHandItems(1); } else { int num = 1; GameMain.mainPlayer.package.TakeTailItems(ref buildPreview.item.ID, ref num, false); } } } AccessTools.Field(typeof(PlayerAction_Build), "planetPhysics").SetValue(GameMain.mainPlayer.controller.actionBuild, planet.physics); pab.CreatePrebuilds(); FactoryManager.EventFactory = null; } //Author has to call this for the continuous belt building if (packet.AuthorId == LocalPlayer.PlayerId) { pab.AfterPrebuild(); } //Revert changes back AccessTools.Field(typeof(PlayerAction_Build), "planetPhysics").SetValue(GameMain.mainPlayer.controller.actionBuild, tmpPlanetPhysics); AccessTools.Field(typeof(PlayerAction_Build), "factory").SetValue(GameMain.mainPlayer.controller.actionBuild, tmpFactory); pab.buildPreviews = tmpList; pab.waitConfirm = tmpConfirm; pab.previewPose.position = tmpPos; pab.previewPose.rotation = tmpRot; } }
public static void IdleShipGetToWork(ILSShipData packet) { PlanetData planetA = GameMain.galaxy.PlanetById(packet.planetA); PlanetData planetB = GameMain.galaxy.PlanetById(packet.planetB); if (planetA != null && planetB != null) { if (GameMain.data.galacticTransport.stationCapacity <= packet.planetAStationGID) { CreateFakeStationComponent(packet.planetAStationGID, packet.planetA); } else if (GameMain.data.galacticTransport.stationPool[packet.planetAStationGID] == null) { CreateFakeStationComponent(packet.planetAStationGID, packet.planetA); } else if (GameMain.data.galacticTransport.stationPool[packet.planetAStationGID].shipDockPos == Vector3.zero) { RequestgStationDockPos(packet.planetAStationGID); } if (GameMain.data.galacticTransport.stationCapacity <= packet.planetBStationGID) { CreateFakeStationComponent(packet.planetBStationGID, packet.planetB); } else if (GameMain.data.galacticTransport.stationPool[packet.planetBStationGID] == null) { CreateFakeStationComponent(packet.planetBStationGID, packet.planetB); } else if (GameMain.data.galacticTransport.stationPool[packet.planetBStationGID].shipDockPos == Vector3.zero) { RequestgStationDockPos(packet.planetBStationGID); } StationComponent stationComponent = GameMain.data.galacticTransport.stationPool[packet.planetAStationGID]; stationComponent.workShipDatas[stationComponent.workShipCount].stage = -2; stationComponent.workShipDatas[stationComponent.workShipCount].planetA = packet.planetA; stationComponent.workShipDatas[stationComponent.workShipCount].planetB = packet.planetB; stationComponent.workShipDatas[stationComponent.workShipCount].otherGId = packet.planetBStationGID; stationComponent.workShipDatas[stationComponent.workShipCount].direction = 1; stationComponent.workShipDatas[stationComponent.workShipCount].t = 0f; stationComponent.workShipDatas[stationComponent.workShipCount].itemId = packet.itemId; stationComponent.workShipDatas[stationComponent.workShipCount].itemCount = packet.itemCount; stationComponent.workShipDatas[stationComponent.workShipCount].gene = 0; // WHAT IS THIS? stationComponent.workShipDatas[stationComponent.workShipCount].shipIndex = packet.origShipIndex; stationComponent.workShipDatas[stationComponent.workShipCount].warperCnt = packet.warperCnt; stationComponent.warperCount = packet.stationWarperCnt; stationComponent.workShipCount++; stationComponent.idleShipCount--; if (stationComponent.idleShipCount < 0) { stationComponent.idleShipCount = 0; } if (stationComponent.workShipCount > 10) { stationComponent.workShipCount = 10; } stationComponent.IdleShipGetToWork(packet.origShipIndex); Log.Info($"Received ship message (departing): {planetA.displayName} -> {planetB.displayName} transporting {packet.itemCount} of {packet.itemId} and index is {packet.origShipIndex}"); //Log.Info($"Array Length is: {GameMain.data.galacticTransport.stationPool.Length} and there is also: {GameMain.data.galacticTransport.stationCapacity}"); } else { Debug.Log(((planetA == null) ? "null" : "not null") + ((planetB == null) ? "null" : "not null") + packet.planetA + " " + packet.planetB); } }
private static void DeterminePlanetTraits(PlanetData cPlan) { int baseChance = 0; bool traitFound = false; bool checkValid = true; // was a trait found? If so, keep going int diceRoll = 0; while (checkValid) { // determine chance for a planet trait if (cPlan.PlanetTraits.Count == 0) baseChance = TraitChanceWith0Traits; if (cPlan.PlanetTraits.Count == 1) baseChance = TraitChanceWith1Traits; if (cPlan.PlanetTraits.Count == 2) baseChance = TraitChanceWith2Traits; if (cPlan.PlanetTraits.Count > 2) { Debug.Log("Exiting trait generation for planet " + cPlan.Name); break; } diceRoll = UnityEngine.Random.Range(0, 101); if (diceRoll < baseChance) { traitFound = true; } else { checkValid = false; Debug.Log("Exiting trait generation for planet " + cPlan.Name); break; } if (traitFound) { bool validTraitFound = false; bool validTypeFound = false; int tryCount = 0; // how many attempts have been made to find a trait while (!validTraitFound && tryCount < 5) { newTest: tryCount += 1; PlanetTraits testTrait = DataManager.planetTraitDataList[UnityEngine.Random.Range(0, DataManager.planetTraitDataList.Count)]; // grab a trait if (testTrait != null) { if (testTrait.PlanetType[0] != 0) // a zero in slot 1 means any type { for (int x = 0; x < 5; x++ ) { if (testTrait.PlanetType[x] == cPlan.Type) { validTypeFound = true; break; } else validTypeFound = false; } } else validTypeFound = true; if (validTypeFound) { if (testTrait.MoonsNecessary > cPlan.Moons) // check moon requirement goto newTest; if (cPlan.PlanetTraits.Count > 0) // only check if there is at least one trait, otherwise always valid { foreach (PlanetTraits trait in cPlan.PlanetTraits) { if (trait.Category == testTrait.Category) goto newTest; } } if (testTrait.BeltEligible == 0) // check for exclusion traits with belts { if (cPlan.Type == PlanetData.ePlanetType.AsteroidBelt || cPlan.Type == PlanetData.ePlanetType.DustRing || cPlan.Type == PlanetData.ePlanetType.IceBelt) goto newTest; } validTraitFound = true; } if (validTraitFound) { cPlan.PlanetTraits.Add(testTrait); break; } } else { Debug.Log("Error generating planet trait: Read trait was null."); break; //error } } } } }
public GeologicalRandomizer(CelestialBody body, PlanetData bodyData) { SetBody(body, bodyData); }
public static void AddPopsToPlanet(PlanetData pData, Civilization civ) { // add pops to each region on a planet foreach (Region rData in pData.RegionList) { for (int x = 0; x < rData.MaxSafePopulationLevel; x++ ) { float generationChance = 0; int generationTarget = 0; // determine base chance for pop generation generationChance = UnityEngine.Random.Range(0, 135); if (pData.Rank == PlanetData.ePlanetRank.EstablishedColony) generationTarget = ChanceForPopOnStandardColony; if (pData.Rank == PlanetData.ePlanetRank.SystemCapital) generationTarget = ChanceForPopOnSystemCapital; if (pData.Rank == PlanetData.ePlanetRank.ProvinceCapital) generationTarget = ChanceForPopOnProvinceCapital; if (pData.Rank == PlanetData.ePlanetRank.ImperialCapital) generationTarget = ChanceForPopOnCivCapital; generationChance -= (float)(rData.HabitatationInfrastructureLevel / 2f); // adjust for existing infrastructure generationChance += rData.MaxSafePopulationLevel - (rData.MaxSafePopulationLevel - rData.PopsInTile.Count); if (rData.PopsInTile.Count == 0 && rData.TotalDevelopmentLevel > 0) { generationChance = 0; // always add at least one pop! } if (rData.TotalDevelopmentLevel == 0) { break; } if (generationChance <= generationTarget) { GenerateNewPop(civ, rData, false); // add a new pop to the region } } } }
/// <summary> /// Orignal PlayerAction_Build::DetermineDestructPreviews /// </summary> public static void CreateEntityDestructPreview( PlayerAction_Build __instance, List <int> idList, List <EObjectType> typeList, DeterminePreviews.PreviewsFilter filter ) { if (!VFInput.onGUI) { UICursor.SetCursor(ECursor.Delete); } __instance.previewPose.position = Vector3.zero; __instance.previewPose.rotation = Quaternion.identity; __instance.ClearBuildPreviews(); foreach (int entityId in idList) { //int entityId = typeList[index] != EObjectType.Entity ? -entityIdList[index] : entityIdList[index]; ItemProto itemProto = (ItemProto)Traverse.Create(__instance).Method("GetItemProto", entityId).GetValue(); Pose objectPose = (Pose)Traverse.Create(__instance).Method("GetObjectPose", entityId).GetValue(); if (itemProto != null && filter(itemProto) == false) { //Add Build Preview __instance.AddBuildPreview(new BuildPreview()); BuildPreview buildPreview = __instance.buildPreviews[__instance.buildPreviews.Count - 1]; buildPreview.item = itemProto; buildPreview.desc = itemProto.prefabDesc; buildPreview.lpos = objectPose.position; buildPreview.lrot = objectPose.rotation; buildPreview.objId = entityId; int num = buildPreview.desc.lodCount <= 0 ? 0 : ((Object)buildPreview.desc.lodMeshes[0] != (Object)null ? 1 : 0); buildPreview.needModel = num != 0; buildPreview.isConnNode = true; if (buildPreview.desc.isInserter) { Pose objectPose2 = (Pose)Traverse.Create(__instance).Method("GetObjectPose2", buildPreview.objId).GetValue(); buildPreview.lpos2 = objectPose2.position; buildPreview.lrot2 = objectPose2.rotation; } PlanetData planetData = __instance.player.planetData; Vector3 vector3_1 = __instance.player.position; if (planetData.type == EPlanetType.Gas) { vector3_1 = vector3_1.normalized; Vector3 vector3_2 = vector3_1 * planetData.realRadius; } else { buildPreview.condition = EBuildCondition.Ok; __instance.cursorText = "拆除".Translate() + buildPreview.item.name + "\r\n" + "连锁拆除提示".Translate(); } if (buildPreview.desc.multiLevel) { int otherObjId; PlanetFactory factory = Traverse.Create((object)__instance).Field("factory").GetValue <PlanetFactory>(); factory.ReadObjectConn(buildPreview.objId, 15, out bool _, out otherObjId, out int _); if ((uint)otherObjId > 0U) { buildPreview.condition = EBuildCondition.Covered; __instance.cursorText = buildPreview.conditionText; } } } } }
public static void AddTradeInfrastructureToPlanet(PlanetData pData) { // determine starbase level if (pData.Rank == PlanetData.ePlanetRank.ImperialCapital) pData.StarbaseLevel = UnityEngine.Random.Range(3, 5); else if (pData.Rank == PlanetData.ePlanetRank.ProvinceCapital) pData.StarbaseLevel = UnityEngine.Random.Range(1, 4); else if (pData.Rank == PlanetData.ePlanetRank.SystemCapital) pData.StarbaseLevel = UnityEngine.Random.Range(0, 3); else if (pData.Rank == PlanetData.ePlanetRank.EstablishedColony) pData.StarbaseLevel = UnityEngine.Random.Range(0, 2); else pData.StarbaseLevel = 0; // determine whether a trade hub if (pData.StarbaseLevel > 0 && pData.Rank != PlanetData.ePlanetRank.EstablishedColony) { int baseChance = pData.StarbaseLevel * 20; if (UnityEngine.Random.Range(0, 100) >= baseChance) pData.IsTradeHub = true; } }
public static void MineVegetable(VegeMined packet) { if (!remotePlayersModels.TryGetValue((ushort)packet.PlayerId, out RemotePlayerModel pModel)) { Debug.Log("FAILED TO SYNC VEGE DATA"); } PlanetData planet = GameMain.galaxy?.PlanetById(pModel.Movement.localPlanetId); if (planet == null) { return; } if (packet.isVegetable) // Trees, rocks, leaves, etc { VegeData vData = (VegeData)planet.factory?.GetVegeData(packet.MiningID); VegeProto vProto = LDB.veges.Select((int)vData.protoId); if (vProto != null && planet.id == GameMain.localPlanet?.id) { VFEffectEmitter.Emit(vProto.MiningEffect, vData.pos, vData.rot); VFAudio.Create(vProto.MiningAudio, null, vData.pos, true); } planet.factory?.RemoveVegeWithComponents(vData.id); } else // veins { VeinData vData = (VeinData)planet.factory?.GetVeinData(packet.MiningID); VeinProto vProto = LDB.veins.Select((int)vData.type); if (vProto != null) { if (planet.factory?.veinPool[packet.MiningID].amount > 0) { VeinData[] vPool = planet.factory?.veinPool; PlanetData.VeinGroup[] vGroups = planet.factory?.planet.veinGroups; long[] vAmounts = planet.veinAmounts; vPool[packet.MiningID].amount -= 1; vGroups[(int)vData.groupIndex].amount -= 1; vAmounts[(int)vData.type] -= 1; if (planet.id == GameMain.localPlanet?.id) { VFEffectEmitter.Emit(vProto.MiningEffect, vData.pos, Maths.SphericalRotation(vData.pos, 0f)); VFAudio.Create(vProto.MiningAudio, null, vData.pos, true); } } else { PlanetData.VeinGroup[] vGroups = planet.factory?.planet.veinGroups; vGroups[vData.groupIndex].count -= 1; if (planet.id == GameMain.localPlanet?.id) { VFEffectEmitter.Emit(vProto.MiningEffect, vData.pos, Maths.SphericalRotation(vData.pos, 0f)); VFAudio.Create(vProto.MiningAudio, null, vData.pos, true); } planet.factory?.RemoveVeinWithComponents(vData.id); } } } }
public static Civilization CreateNewCivilization() { List<String> civNameList = DataManager.civNameList; // populate the color list if needed if (civColorList.Count == 0) PopulateCivColorList(); Civilization newCiv = new Civilization(); int dieRoll = 0; galaxyDataRef = GameObject.Find("GameManager").GetComponent<GalaxyData>(); // access galaxy data gameDataRef = GameObject.Find("GameManager").GetComponent<GlobalGameData>(); // access galaxy data // Step 1: Generate type of civ dieRoll = UnityEngine.Random.Range(1, 7); newCiv.Type = (Civilization.eCivType)dieRoll; // cast to enum // Step 2: Generate ID of civ newCiv.ID = "CIV" + gameDataRef.CivList.Count.ToString("N0"); // Step 2: Generate name of civ string primaryName = ""; string surName = ""; if (civNameList.Count > 0) { var nameIndex = UnityEngine.Random.Range(0, civNameList.Count); primaryName = civNameList[nameIndex]; civNameList.RemoveAt(nameIndex); civNameList.TrimExcess(); } else primaryName = "GenericName"; var surNameIndex = UnityEngine.Random.Range(0, DataManager.civSurNameList.Count); surName = DataManager.civSurNameList[surNameIndex]; newCiv.Name = primaryName + " " + surName; // Step 3: Generate other base stats (treasury, size, etc) // size/range newCiv.Range = 40; // to start with int size = UnityEngine.Random.Range(0, 100); // adjust size/other ratings for civ type switch(newCiv.Type) { case Civilization.eCivType.Confederation : { size += 55; break; } case Civilization.eCivType.MinorEmpire: { size += 40; break; } case Civilization.eCivType.Satrapy: { size += 20; break; } case Civilization.eCivType.BrokenCivilization: { size -= 30; break; } case Civilization.eCivType.Pirates: { size -= 15; break; } } // add a empire type mod here if (size < 40) newCiv.Size = Civilization.eCivSize.SinglePlanet; else if (size < 70) newCiv.Size = Civilization.eCivSize.Local; else if (size < 90) { newCiv.Size = Civilization.eCivSize.Minor; newCiv.Range = UnityEngine.Random.Range(MultiSystemEmpireRange - 200, MultiSystemEmpireRange + 200); } else { newCiv.Size = Civilization.eCivSize.Major; newCiv.Range = UnityEngine.Random.Range(MultiRegionEmpireRange - 400, MultiRegionEmpireRange + 400); } // skill ratings newCiv.FarmingBaseRating = UnityEngine.Random.Range(70, 100) - (int)newCiv.Type * 10; newCiv.MiningBaseRating = UnityEngine.Random.Range(50, 90) - (int)newCiv.Type * 10; newCiv.ScienceBaseRating = UnityEngine.Random.Range(0, 50) + (int)newCiv.Type * 10; newCiv.HighTechBaseRating = UnityEngine.Random.Range(0, 40) + (int)newCiv.Type * 10; newCiv.ManufacturingBaseRating = UnityEngine.Random.Range(5, 50) + (int)newCiv.Type * 10; // tolerance newCiv.PlanetMinTolerance = UnityEngine.Random.Range(40, 60); // sets the base minimum habitable world a civilization is willing to tolerate // province size if (newCiv.Size == Civilization.eCivSize.Major) { newCiv.CivMaxProvinceSize = UnityEngine.Random.Range(1, 6); // sets a province size between 1 and 5 systems newCiv.AdminRating = UnityEngine.Random.Range(5, 21); // generates the civ's base admin rating (how efficient they are in adminstering provinces } else { newCiv.CivMaxProvinceSize = 0; // no provinces can be created; the civ is essentially one province newCiv.AdminRating = 1; } // admin rating // Step 4: Determine planet of origin retryPlanet: // beginning of retry loop PlanetData civPlanet = new PlanetData(); dieRoll = UnityEngine.Random.Range(0, galaxyDataRef.GalaxyPlanetDataList.Count); // find the planets in the quadrant civPlanet = galaxyDataRef.GalaxyPlanetDataList[dieRoll]; if (galaxyDataRef.GalaxyPlanetDataList[dieRoll].AdjustedBio < newCiv.PlanetMinTolerance) // if the bio is too low, throw it out goto retryPlanet; if (gameDataRef.CivList.Count > 0) { foreach (Civilization civ in gameDataRef.CivList) { List<StarData> populatedHomeSystems = new List<StarData>(); populatedHomeSystems = HelperFunctions.DataRetrivalFunctions.GetCivSystemList(civ); if (civPlanet.ID == civ.CapitalPlanetID) // check for capital world goto retryPlanet; if (civ.PlanetIDList.Exists(p => p == civPlanet.ID)) // then all other worlds goto retryPlanet; if (newCiv.ID != civ.ID) if (populatedHomeSystems.Exists(p => p.ID == civPlanet.SystemID)) // check for systems that other civs have claimed goto retryPlanet; } // assign a name for the civ's planet if (DataManager.planetNameList.Count > 0) { var nameIndex = UnityEngine.Random.Range(0, DataManager.planetNameList.Count); civPlanet.Name = DataManager.planetNameList[nameIndex]; DataManager.planetNameList.RemoveAt(nameIndex); DataManager.planetNameList.TrimExcess(); } else civPlanet.Name = "GenericName"; // set as capital and send to assign pops, developments, etc. newCiv.CapitalPlanetID = civPlanet.ID; ClaimCivPlanet(civPlanet, newCiv); civPlanet.Rank = PlanetData.ePlanetRank.ImperialCapital; newCiv.PlanetIDList.Add(civPlanet.ID); // add the planet } // Step 5: Determine additional planets if (newCiv.Size != Civilization.eCivSize.SinglePlanet) ClaimPlanetsForCiv(newCiv); // Step 5: Generate color of civ retryColor: // beginning of retry loop Color civColor = new Color(); civColor = new Color(UnityEngine.Random.Range(.01f, .99f), UnityEngine.Random.Range(.01f, .99f), UnityEngine.Random.Range(.01f, .99f)); // select a random color if (gameDataRef.CivList.Count > 0) { foreach (Civilization civ in gameDataRef.CivList) { if (civColor == civ.Color) goto retryColor; } newCiv.Color = civColor; } return newCiv; }
private void HandleClick() { Vector3 worldPos; // RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTrans, Input.mousePosition, uicam, out var localPoint); Ray ray = GameCamera.main.ScreenPointToRay(Input.mousePosition); if (Input.GetMouseButtonDown(0)) { // Debug.Log("Clicking screen pos: " + Input.mousePosition.ToString() + " Ray: " + ray.ToString()); PlanetData localPlanet = GameMain.localPlanet; if (localPlanet == null) { return; } if (Physics.Raycast(ray, out var hitInfo, 1000f, 15873, QueryTriggerInteraction.Ignore)) { worldPos = hitInfo.point; // Debug.Log("Clicked on world pos: " + worldPos.ToString()); Gardener.VeinGroup.GetClosestIndex(ray, localPlanet, out int closestVeinGroupIndex, out int closestVeinIndex, out float closestVeinDistance, out float closestVeinDistance2D); switch (modMode) { case eVeinModificationMode.AddVein: if (closestVeinGroupIndex < 0) { var veinGroup = Gardener.VeinGroup.New(EVeinType.Iron, worldPos.normalized); closestVeinGroupIndex = localPlanet.AddVeinGroupData(veinGroup); Debug.Log("Adding new veinGroup: " + veinGroup.type.ToString() + " index: " + closestVeinGroupIndex + " Pos: " + veinGroup.pos * localPlanet.radius); } Gardener.Vein.Add(localPlanet, worldPos, closestVeinGroupIndex); break; case eVeinModificationMode.ModifyVeinGroup: if (closestVeinGroupIndex >= 0) { PlanetData.VeinGroup veinGroup = localPlanet.veinGroups[closestVeinGroupIndex]; Debug.Log("Clicked on veinGroup: " + veinGroup.ToString() + " index: " + closestVeinGroupIndex + " Type: " + veinGroup.type); Debug.Log("VeinGroup: " + veinGroup.pos.ToString() + " index: " + (veinGroup.pos * (localPlanet.realRadius + 2.5f))); dialog = new UIVeinGroupDialog() { localPlanet = localPlanet, veinGroupIndex = closestVeinGroupIndex, Show = true }; } else { dialog = null; } break; case eVeinModificationMode.RemoveVein: if (closestVeinGroupIndex >= 0 && closestVeinIndex >= 0 && closestVeinDistance2D < 1) { Debug.Log("Removing vein: " + closestVeinIndex + " in group: " + closestVeinGroupIndex); Gardener.Vein.Remove(localPlanet, closestVeinIndex, closestVeinGroupIndex); Gardener.VeinGroup.UpdatePosFromChildren(closestVeinGroupIndex); } break; case eVeinModificationMode.Deactivated: default: break; } } } }
public static void AddDevelopmentToPlanet(PlanetData pData) { // populate the planet by adding industry foreach (Region rData in pData.RegionList) { int farmChance = 0; int mineChance = 0; int adminChance = 0; int scienceChance = 0; int factoryChance = 0; int highTechChance = 0; int minDevelopmentLevel = rData.MaxDevelopmentLevel - 10; if (minDevelopmentLevel <= 0) { minDevelopmentLevel = 0; } int maxDevelopmentAmount = UnityEngine.Random.Range(minDevelopmentLevel, rData.MaxDevelopmentLevel); for (int x = 0; x < maxDevelopmentAmount; x++) { farmChance = 0; mineChance = 0; adminChance = 0; scienceChance = 0; factoryChance = 0; highTechChance = 0; int govAdjust = 20; // basic adjustment for capitals to have more government developments if (HelperFunctions.DataRetrivalFunctions.GetPlanet(rData.PlanetLocationID).Rank == PlanetData.ePlanetRank.SystemCapital) govAdjust = 30; if (HelperFunctions.DataRetrivalFunctions.GetPlanet(rData.PlanetLocationID).Rank == PlanetData.ePlanetRank.ProvinceCapital) govAdjust = 45; if (HelperFunctions.DataRetrivalFunctions.GetPlanet(rData.PlanetLocationID).Rank == PlanetData.ePlanetRank.ImperialCapital) govAdjust = 60; // adjust by region characteristics, as well as what is already there if (rData.FarmingLevel == 0) { farmChance += 40; // try to get at least one farm } if (rData.HighTechLevel == 0) { highTechChance += 30; // try to get at least one energy station } // normalize to have a roughly equal amount of mines and factories if (rData.MiningLevel < rData.ManufacturingLevel) { mineChance += 5 * (rData.ManufacturingLevel - rData.MiningLevel); } if (rData.MiningLevel > rData.ManufacturingLevel) { factoryChance += 5 * (rData.MiningLevel - rData.ManufacturingLevel); } farmChance += 23 + (rData.BioRating / 3) + UnityEngine.Random.Range(0, 10) + rData.MiningLevel + rData.ManufacturingLevel + rData.GovernmentLevel + rData.HighTechLevel - rData.FarmingLevel; mineChance += 15 + ((rData.AlphaRating + rData.HeavyRating) / 4) + (rData.RareRating / 4) + rData.FarmingLevel + rData.ManufacturingLevel - rData.MiningLevel + UnityEngine.Random.Range(0, 10); adminChance += govAdjust + UnityEngine.Random.Range(5, 30) + rData.FarmingLevel + rData.MiningLevel + rData.ManufacturingLevel + rData.HighTechLevel; scienceChance += 38 + rData.FarmingLevel + rData.MiningLevel + rData.ManufacturingLevel + UnityEngine.Random.Range(0, 10) + rData.FarmingLevel; factoryChance += 15 + ((rData.AlphaRating + rData.HeavyRating) / 4) + rData.MiningLevel + rData.FarmingLevel + UnityEngine.Random.Range(0, 20); highTechChance += 30 + (rData.EnergyRating / 3) + rData.FarmingLevel + rData.MiningLevel + rData.ManufacturingLevel + rData.GovernmentLevel + UnityEngine.Random.Range(5, 10); // generate a sorted list Dictionary<string,int> developmentDictionary = new Dictionary<string,int>(); developmentDictionary.Add("Farm",farmChance); developmentDictionary.Add("Mine",mineChance); developmentDictionary.Add("Admin",adminChance); developmentDictionary.Add("Science",scienceChance); developmentDictionary.Add("Factory",factoryChance); developmentDictionary.Add("HighTech",highTechChance); List<KeyValuePair<string, int>> SortedDevelopments = developmentDictionary.ToList(); SortedDevelopments.Sort((firstPair, nextPair) => { return firstPair.Value.CompareTo(nextPair.Value); } ); if (SortedDevelopments.Last().Key == "Farm") rData.FarmingLevel += 1; else if (SortedDevelopments.Last().Key == "Mine") rData.MiningLevel += 1; else if (SortedDevelopments.Last().Key == "Admin") rData.GovernmentLevel += 1; else if (SortedDevelopments.Last().Key == "Science") rData.ScienceLevel += 1; else if (SortedDevelopments.Last().Key == "Factory") rData.ManufacturingLevel += 1; else if (SortedDevelopments.Last().Key == "HighTech") rData.HighTechLevel += 1; } } }
private static void exportStar(PlanetData planet) { UnityEngine.Debug.Log("-- planet: " + planet.id); PlanetAlgorithm planetAlgorithm = PlanetModelingManager.Algorithm(planet); planet.data = new PlanetRawData(planet.precision); planet.modData = planet.data.InitModData(planet.modData); planet.data.CalcVerts(); planet.aux = new PlanetAuxData(planet); planetAlgorithm.GenerateTerrain(planet.mod_x, planet.mod_y); planetAlgorithm.CalcWaterPercent(); if (planet.type != EPlanetType.Gas) { planetAlgorithm.GenerateVegetables(); } if (planet.type != EPlanetType.Gas) { planetAlgorithm.GenerateVeins(false); } Monitor.Enter(streamWriter); try { if (!firstPlanet) { streamWriter.Write(","); } else { firstPlanet = false; } streamWriter.Write("\"" + planet.name + "\":{" + "\"seed\":" + planet.seed + ",\"index\":" + planet.index + ",\"id\":" + planet.id + ",\"orbitAround\":" + planet.orbitAround + ",\"number\":" + planet.number + ",\"orbitIndex\":" + planet.orbitIndex + ",\"name\":\"" + planet.name + "\"" + ",\"orbitRadius\":" + planet.orbitRadius + ",\"orbitInclination\":" + planet.orbitInclination + ",\"orbitLongitude\":" + planet.orbitLongitude + ",\"orbitalPeriod\":" + planet.orbitalPeriod + ",\"orbitPhase\":" + planet.orbitPhase + ",\"obliquity\":" + planet.obliquity + ",\"rotationPeriod\":" + planet.rotationPeriod + ",\"rotationPhase\":" + planet.rotationPhase + ",\"radius\":" + planet.radius + ",\"scale\":" + planet.scale + ",\"sunDistance\":" + planet.sunDistance + ",\"habitableBias\":" + planet.habitableBias + ",\"temperatureBias\":" + planet.temperatureBias + ",\"ionHeight\":" + planet.ionHeight + ",\"windStrength\":" + planet.windStrength + ",\"luminosity\":" + planet.luminosity + ",\"landPercent\":" + planet.landPercent + ",\"mod_x\":" + planet.mod_x + ",\"mod_y\":" + planet.mod_y + ",\"type\":" + (int)planet.type + ",\"singularity\":" + (int)planet.singularity + ",\"theme\":" + planet.theme + ",\"algoId\":" + planet.algoId + ",\"waterHeight\":" + planet.waterHeight); if (planet.waterItemId > 0) { ItemProto water = LDB.items.Select(planet.waterItemId); streamWriter.Write( ",\"waterItem\":\"" + water.name + "\"" ); } if (planet.type == EPlanetType.Gas) { streamWriter.Write(",\"gasTotalHeat\":" + planet.gasTotalHeat); streamWriter.Write(",\"gas\":{"); // open gas[] bool firstvein = true; for (int k = 0; k < planet.gasItems.Length; k++) { ItemProto gas = LDB.items.Select(planet.gasItems[k]); if (firstvein == false) { streamWriter.Write(","); } else { firstvein = false; } streamWriter.Write("\"" + gas.name + "\":{" + "\"gasName\":\"" + gas.name + "\"" + ",\"gasItem\":" + planet.gasItems[k] + ",\"gasSpeed\":\"" + planet.gasSpeeds[k] + "\"" + ",\"gasHeatValue\":\"" + planet.gasHeatValues[k] + "\"}"); } streamWriter.Write("}"); // close gas[] } else { streamWriter.Write(",\"vein\":{"); // open vein[] bool firstvein = true; for (int k = 0; k < planet.veinAmounts.Length; k++) { if (planet.veinAmounts[k] == 0) { continue; } if (firstvein == false) { streamWriter.Write(","); } else { firstvein = false; } streamWriter.Write("\"" + (EVeinType)k + "\":" + planet.veinAmounts[k]); } streamWriter.Write("}"); // close vein[] } streamWriter.Write(",\"uPosition\":{\"x\":" + planet.uPosition.x + ",\"y\":" + planet.uPosition.y + ",\"z\":" + planet.uPosition.z + "}}"); // close planet } finally { Monitor.Exit(streamWriter); } planet.Unload(); }
public virtual void Initialize(PlanetData data) { PlanetObject = gameObject.transform.GetChild(0).gameObject; GravityObject = gameObject.transform.GetChild(1).gameObject; if(PlanetObject == null || GravityObject == null) {Logger.Log("Error Initializing Planet " + data.Type, 4);return;} _data = data; _active = true; _orbitActive = false; Type = data.Type; BodyRadius = data.Body; GravityDepth = data.Gravity; }
private void UpdatePlanetTradeInfo(PlanetData pData) { // update trade stats List<TradeAgreement> expList = new List<TradeAgreement>(); List<TradeAgreement> impList = new List<TradeAgreement>(); float totalImports = 0f; float totalExports = 0f; if (gDataRef.ActiveTradeAgreements.Exists(p => p.ExportPlanetID == pData.ID)) { expList = gDataRef.ActiveTradeAgreements.FindAll(p => p.ExportPlanetID == pData.ID); } if (gDataRef.ActiveTradeAgreements.Exists(p => p.ImportPlanetID == pData.ID)) { impList = gDataRef.ActiveTradeAgreements.FindAll(p => p.ImportPlanetID == pData.ID); } foreach (TradeAgreement t in expList) { totalExports += t.Cost; } pData.ExportRevenue = totalExports; foreach (TradeAgreement t in impList) { totalImports += t.Cost; } pData.ImportCosts = totalImports; float totalFood = 0f; foreach (TradeAgreement t in impList) { if (t.FoodSent > 0) totalFood += t.FoodSent; } pData.FoodImported = totalFood; totalFood = 0f; foreach (TradeAgreement t in expList) { if (t.FoodSent > 0) totalFood += t.FoodSent; } pData.FoodExported = totalFood; float totalEnergy = 0f; foreach (TradeAgreement t in impList) { if (t.EnergySent > 0) totalEnergy += t.EnergySent; } pData.EnergyImported = totalEnergy; totalEnergy = 0f; foreach (TradeAgreement t in expList) { if (t.EnergySent > 0) totalEnergy += t.EnergySent; } pData.EnergyExported = totalEnergy; }
public void PopulateDataBox(string pID) { pData = HelperFunctions.DataRetrivalFunctions.GetPlanet(pID); // show viceroy image if eligible string cID = HelperFunctions.DataRetrivalFunctions.GetPlanetViceroyID(pData.ID); if (cID != "none") { Transform vPanel = transform.Find("Viceroy Image"); vPanel.gameObject.SetActive(true); string vID = HelperFunctions.DataRetrivalFunctions.GetCharacter(cID).PictureID; vPanel.GetComponent<Image>().sprite = graphicsDataRef.CharacterList.Find(p => p.name == vID); vPanel.GetComponent<CharacterTooltip>().InitializeTooltipData(HelperFunctions.DataRetrivalFunctions.GetCharacter(cID), -20f); vPanel.GetComponent<CharacterScreenActivation>().InitializeData(HelperFunctions.DataRetrivalFunctions.GetCharacter(cID)); } else { transform.Find("Viceroy Image").gameObject.SetActive(false); } // moons only show if there are any if (pData.Moons > 0) { Transform mPanel = transform.Find("Moon Panel"); mPanel.gameObject.SetActive(true); mPanel.transform.Find("Moon Count").GetComponent<Text>().text = pData.Moons.ToString("N0"); } else transform.Find("Moon Panel").gameObject.SetActive(false); string isExporting = ""; if (pData.TradeAmount != 0) { isExporting = "($" + pData.TradeAmount.ToString("N2") + ")"; } transform.Find("Planet Name").GetComponent<Text>().text = pData.Name.ToUpper() + " " + isExporting; // assign the name to the text object child transform.Find("Planet Name").GetComponent<Text>().color = HelperFunctions.DataRetrivalFunctions.FindPlanetOwnerColor(pData); transform.Find("Planet Type").GetComponent<Text>().text = "CLASS " + HelperFunctions.StringConversions.ConvertToRomanNumeral((int)(pData.Size / 10)) + " " + HelperFunctions.StringConversions.ConvertPlanetEnum(pData.Type).ToUpper(); // assign the name to the text object child transform.Find("Planet Type").GetComponent<Text>().color = Color.yellow; transform.Find("Planet Status").GetComponent<Text>().text = HelperFunctions.DataRetrivalFunctions.FindOwnerName(pData); transform.Find("Planet Status").GetComponent<Text>().color = Color.cyan; // assign each child text value and color if (!gameDataRef.DebugMode) // if not in debug mode, just show the text { if (pData.SurfaceScanLevel >= 1.0f) { transform.Find("Energy Level").GetComponent<Text>().text = HelperFunctions.StringConversions.ConvertValueToDescription(pData.Energy); // assign the name to the text object child transform.Find("Energy Level").GetComponent<Text>().color = HelperFunctions.StringConversions.GetTextValueColor(pData.Energy); } if (pData.AtmosphereScanLevel >= 1.0f) { transform.Find("Bio Level").GetComponent<Text>().text = HelperFunctions.StringConversions.ConvertValueToDescription(pData.AdjustedBio); // assign the name to the text object child //transform.Find("Planet Size").GetComponent<Text>().color = HelperFunctions.StringConversions.GetTextValueColor(pData.Size); transform.Find("Bio Level").GetComponent<Text>().color = HelperFunctions.StringConversions.GetTextValueColor(pData.Bio); } if (pData.InteriorScanLevel >= 1.0f) { transform.Find("Rare Materials Level").GetComponent<Text>().text = HelperFunctions.StringConversions.ConvertValueToDescription(pData.RareMaterials); // assign the name to the text object child transform.Find("Alpha Materials Level").GetComponent<Text>().text = HelperFunctions.StringConversions.ConvertValueToDescription(pData.BasicMaterials); // assign the name to the text object child transform.Find("Heavy Materials Level").GetComponent<Text>().text = HelperFunctions.StringConversions.ConvertValueToDescription(pData.HeavyMaterials); // assign the name to the text object child transform.Find("Rare Materials Level").GetComponent<Text>().color = HelperFunctions.StringConversions.GetTextValueColor(pData.RareMaterials); transform.Find("Alpha Materials Level").GetComponent<Text>().color = HelperFunctions.StringConversions.GetTextValueColor(pData.BasicMaterials); transform.Find("Heavy Materials Level").GetComponent<Text>().color = HelperFunctions.StringConversions.GetTextValueColor(pData.HeavyMaterials); } if (pData.IntelLevel == 10) { transform.Find("Planet Size").GetComponent<Text>().text = pData.AverageDevelopmentLevel.ToString("N1"); // assign the name to the text object child transform.Find("Treasury Level").GetComponent<Text>().text = HelperFunctions.StringConversions.ConvertFloatDollarToText(pData.GrossPlanetaryProduct); // assign the name to the text object child if (pData.GrossPlanetaryProduct < 0) { transform.Find("Treasury Level").GetComponent<Text>().color = Color.red; } else { transform.Find("Treasury Level").GetComponent<Text>().color = Color.green; } string pChangeSign = ""; if (pData.PopulationChangeLastTurn > 0) pChangeSign = "+"; transform.Find("Total Admin Level").GetComponent<Text>().text = pData.TotalAdmin.ToString("N0"); // assign the name to the text object child transform.Find("Manufacturing Level").GetComponent<Text>().text = pData.FactoriesStaffed.ToString("N1") + "/" + pData.ManufacturingLevel.ToString("N0"); // assign the name to the text object child transform.Find("Population Level").GetComponent<Text>().text = HelperFunctions.StringConversions.ConvertIntToText(pData.TotalPopulation) + "(" + pChangeSign + HelperFunctions.StringConversions.ConvertIntToText(pData.PopulationChangeLastTurn) + ")"; // assign the name to the text object child transform.Find("Farming Level").GetComponent<Text>().text = pData.FarmsStaffed.ToString("N1") + "/" + pData.FarmingLevel.ToString("N0"); // assign the name to the text object child transform.Find("High Tech Level").GetComponent<Text>().text = pData.HighTechFacilitiesStaffed.ToString("N0") + "/" + pData.HighTechLevel.ToString("N0"); // assign the name to the text object child transform.Find("Science Level").GetComponent<Text>().text = pData.LabsStaffed.ToString("N1") + "/" + pData.ScienceLevel.ToString("N0"); // assign the name to the text object child transform.Find("Mining Level").GetComponent<Text>().text = pData.MinesStaffed.ToString("N1") + "/" + pData.MiningLevel.ToString("N0"); // assign the name to the text object child transform.Find("Government Level").GetComponent<Text>().text = pData.GovernmentFacilitiesStaffed.ToString("N1") + "/" + pData.GovernmentLevel.ToString("N0"); // assign the name to the text object child transform.Find("Posup Level").GetComponent<Text>().text = pData.PopularSupportLevel.ToString("P1"); // assign the name to the text object child transform.Find("Unemployment Level").GetComponent<Text>().text = pData.UnemploymentLevel.ToString("P1"); // assign the name to the text object child } if (!pData.IsInhabited) { transform.Find("Treasury Level").GetComponent<Text>().text = "-"; // assign the name to the text object child transform.Find("Total Admin Level").GetComponent<Text>().text = "-"; // assign the name to the text object child transform.Find("Manufacturing Level").GetComponent<Text>().text = "-"; // assign the name to the text object child transform.Find("Population Level").GetComponent<Text>().text = "-"; // assign the name to the text object child transform.Find("Farming Level").GetComponent<Text>().text = "-"; // assign the name to the text object child transform.Find("High Tech Level").GetComponent<Text>().text = "-"; // assign the name to the text object child transform.Find("Science Level").GetComponent<Text>().text = "-"; // assign the name to the text object child transform.Find("Mining Level").GetComponent<Text>().text = "-"; transform.Find("Government Level").GetComponent<Text>().text = "-"; transform.Find("Posup Level").GetComponent<Text>().text = "-"; // assign the name to the text object child transform.Find("Unemployment Level").GetComponent<Text>().text = "-"; } } else // assign the actual value { transform.Find("Energy Level").GetComponent<Text>().text = pData.Energy.ToString("N0"); // assign the name to the text object child transform.Find("Energy Level").GetComponent<Text>().color = HelperFunctions.StringConversions.GetTextValueColor(pData.Energy); transform.Find("Bio Level").GetComponent<Text>().text = pData.AdjustedBio.ToString("N0") + "(" + pData.Bio.ToString("N0") + ")"; // assign the name to the text object child transform.Find("Planet Size").GetComponent<Text>().text = pData.AdjustedMaxHabitableTiles.ToString("N0") + "(" + pData.MaxHabitableTiles.ToString("N0") + ")"; // assign the name to the text object child transform.Find("Rare Materials Level").GetComponent<Text>().text = pData.RareMaterials.ToString("N0"); // assign the name to the text object child transform.Find("Alpha Materials Level").GetComponent<Text>().text = pData.BasicMaterials.ToString("N0"); // assign the name to the text object child transform.Find("Heavy Materials Level").GetComponent<Text>().text = pData.HeavyMaterials.ToString("N0"); // assign the name to the text object child transform.Find("Treasury Level").GetComponent<Text>().text = HelperFunctions.StringConversions.ConvertFloatDollarToText(pData.GrossPlanetaryProduct); // assign the name to the text object child if (pData.GrossPlanetaryProduct < 0) { transform.Find("Treasury Level").GetComponent<Text>().color = Color.red; } else { transform.Find("Treasury Level").GetComponent<Text>().color = Color.green; } transform.Find("Total Admin Level").GetComponent<Text>().text = pData.TotalAdmin.ToString("N0"); // assign the name to the text object child transform.Find("Manufacturing Level").GetComponent<Text>().text = pData.ManufacturingLevel.ToString("N0"); // assign the name to the text object child transform.Find("Population Level").GetComponent<Text>().text = HelperFunctions.StringConversions.ConvertIntToText(pData.TotalPopulation); // assign the name to the text object child } transform.Find("Scan Level").GetComponent<Text>().text = pData.ScanLevel.ToString("P0"); // assign the name to the text object child // draw traits if (pData.PlanetTraits.Count > 0) { transform.Find("Planet Trait 1").GetComponent<Text>().text = pData.PlanetTraits[0].Name.ToUpper(); transform.Find("Planet Trait 1").GetComponent<Text>().color = Color.white; } else transform.Find("Planet Trait 1").GetComponent<Text>().color = Color.grey; if (pData.PlanetTraits.Count > 1) transform.Find("Planet Trait 2").GetComponent<Text>().text = pData.PlanetTraits[1].Name.ToUpper(); else transform.Find("Planet Trait 2").GetComponent<Text>().text = ""; }
public static void PrintStat(PlanetData PD) //TODO: make for multi-threading, this method will be inherently safe (doesn't write, and only uses objects not being changed) { int layerCount = PD.LiveMap.Count; int stratoCount = PD.LiveStratoMap.Count; KWSCellMap <WeatherCell> cellMap = new KWSCellMap <WeatherCell>(PD.gridLevel); float avgValue = 0; float maxValue = 0; float minValue = 0; uint maxIndex = 0; uint minIndex = 0; // Cell thisCell = new Cell(); string[] values = { "temperature", "pressure", "relativeHumidity", "CCN", "cloud.dropletSize", "cloud.rainyDuration", "windvector.y" }; //the values we want to get from the cell // check if Stat folder exists, create it if (!Directory.Exists(KSPUtil.ApplicationRootPath + "/GameData/KerbalWeatherSystems/Stat")) { Directory.CreateDirectory(KSPUtil.ApplicationRootPath + "/GameData/KerbalWeatherSystems/Stat"); } //write to Statistics Log file Debug.Log("Writing Statistics file"); int num = Directory.GetFiles(KSPUtil.ApplicationRootPath + "/GameData/KerbalWeatherSystems/Stat/").Length; using (System.IO.StreamWriter file = new System.IO.StreamWriter(@KSPUtil.ApplicationRootPath + "/GameData/KerbalWeatherSystems/Stat/Stat" + num + "cy" + CellUpdater.run + ".txt")) { // int layer = 0; String STS = " | "; file.WriteLine("Body: " + PD.body.bodyName + STS + "Update Cycle: " + CellUpdater.run + STS + "AvgProcessTime (μs): " + WeatherSimulator.AvgCycleTime); file.WriteLine(); // print: Total cells, other general data about the collection file.WriteLine("Number of cells: " + Cell.CountAtLevel(PD.gridLevel)); file.WriteLine(); foreach (string s in values) // each valid s prints a section { file.WriteLine(s); file.WriteLine("layer" + STS + " average " + STS + " minimum " + " cell " + STS + " maximum " + " cell " + STS); for (int i = stratoCount - 1; i >= 0; i--) { cellMap = PD.LiveStratoMap[i]; if (cellMap[new Cell(0)].GetType().GetProperty(s) != null && cellMap[new Cell(0)].GetType().GetProperty(s).Name.Equals(s)) { avgValue = cellMap.Average(cell => (float)cell.Value.GetType().GetProperty(s).GetValue(cell.Value, null)); minValue = cellMap.Min(cell => (float)cell.Value.GetType().GetProperty(s).GetValue(cell.Value, null)); maxValue = cellMap.Max(cell => (float)cell.Value.GetType().GetProperty(s).GetValue(cell.Value, null)); foreach (Cell cell in Cell.AtLevel(PD.gridLevel)) { if ((float)cellMap[cell].GetType().GetProperty(s).GetValue(cellMap[cell], null) == minValue) { minIndex = cell.Index; } if ((float)cellMap[cell].GetType().GetProperty(s).GetValue(cellMap[cell], null) == maxValue) { maxIndex = cell.Index; } } } else { avgValue = 0; minValue = 0; maxValue = 0; minIndex = 0; maxIndex = 0; } file.WriteLine("{0,-4} {1,5} {2,12:N4} {3,5} {4,12:N4} {5,6} {6,5} {7,12:N4} {8,6} {9,5}", "St_" + i, STS, avgValue, STS, minValue, minIndex, STS, maxValue, maxIndex, STS); } for (int i = layerCount - 1; i >= 0; i--) { cellMap = PD.LiveMap[i]; if (cellMap[new Cell(0)].GetType().GetProperty(s) != null && cellMap[new Cell(0)].GetType().GetProperty(s).Name.Equals(s)) { avgValue = cellMap.Average(cell => cell.Value.GetType().GetProperty(s).Name.Equals(s) ? (float)cell.Value.GetType().GetProperty(s).GetValue(cell.Value, null) : 0f); minValue = cellMap.Min(cell => cell.Value.GetType().GetProperty(s).Name.Equals(s) ? (float)cell.Value.GetType().GetProperty(s).GetValue(cell.Value, null) : 0f); maxValue = cellMap.Max(cell => cell.Value.GetType().GetProperty(s).Name.Equals(s) ? (float)cell.Value.GetType().GetProperty(s).GetValue(cell.Value, null) : 0f); foreach (Cell cell in Cell.AtLevel(PD.gridLevel)) { if ((float)cellMap[cell].GetType().GetProperty(s).GetValue(cellMap[cell], null) == minValue) { minIndex = cell.Index; } if ((float)cellMap[cell].GetType().GetProperty(s).GetValue(cellMap[cell], null) == maxValue) { maxIndex = cell.Index; } } } else { avgValue = 0; minValue = 0; maxValue = 0; minIndex = 0; maxIndex = 0; } file.WriteLine("{0,-4} {1,5} {2,12:N4} {3,5} {4,12:N4} {5,6} {6,5} {7,12:N4} {8,6} {9,5}", "Tp_" + i, STS, avgValue, STS, minValue, minIndex, STS, maxValue, maxIndex, STS); } // Soil layer if (PD.LiveSoilMap[new Cell(0)].GetType().GetProperty(s) != null && cellMap[new Cell(0)].GetType().GetProperty(s).Name.Equals(s)) { avgValue = PD.LiveSoilMap.Average(cell => (float)cell.Value.GetType().GetProperty(s).GetValue(cell.Value, null)); minValue = PD.LiveSoilMap.Min(cell => (float)cell.Value.GetType().GetProperty(s).GetValue(cell.Value, null)); maxValue = PD.LiveSoilMap.Max(cell => (float)cell.Value.GetType().GetProperty(s).GetValue(cell.Value, null)); foreach (Cell cell in Cell.AtLevel(PD.gridLevel)) { if ((float)PD.LiveSoilMap[cell].GetType().GetProperty(s).GetValue(cellMap[cell], null) == minValue) { minIndex = cell.Index; } if ((float)PD.LiveSoilMap[cell].GetType().GetProperty(s).GetValue(cellMap[cell], null) == maxValue) { maxIndex = cell.Index; } } file.WriteLine("{0,-4} {1,5} {2,12:N4} {3,5} {4,12:N4} {5,6} {6,5} {7,12:N4} {8,6} {9,5}", "Soil", STS, avgValue, STS, minValue, minIndex, STS, maxValue, maxIndex, STS); } file.WriteLine(); // closing section // avgValue = cellMap.Average(cell => cell.Value.cloud.GetType().GetProperty(s).GetValue(cell.Value, null)); } } }
public void RegisterPlanet(PlanetEditor planet) { PlanetData pd = new PlanetData(planet.Type, planet.PlanetObject.transform.position, 0f, planet.GravityDepth, planet.PlanetRadius); _planetsData.Add(pd); planet.Terminate(); }
private static void UpdateSettingsUIBackground(StationUI packet, PlanetData pData, int stationGId) { StationComponent[] stationPool = GameMain.data.galacticTransport.stationPool; int stationId = stationGId; // if we have the planet factory loaded take the local transport array, if not take the global galactic array if (pData?.factory != null && pData?.factory?.transport != null) { stationPool = pData.factory.transport.stationPool; for (int i = 0; i < stationPool.Length; i++) { if (stationPool[i] != null && stationPool[i].gid == stationGId) { stationId = stationPool[i].id; break; } } } // update drones, ships and warpers for everyone if ((packet.settingIndex >= 8 && packet.settingIndex <= 10) || packet.settingIndex == 0) { if (stationPool.Length > stationId) { if (packet.settingIndex == 0 && pData.factory.powerSystem != null) { PowerConsumerComponent[] consumerPool = pData.factory.powerSystem.consumerPool; if (consumerPool.Length > stationPool[stationId].pcId) { consumerPool[stationPool[stationId].pcId].workEnergyPerTick = (long)(50000.0 * (double)packet.settingValue + 0.5); } } if (packet.settingIndex == 8) { stationPool[stationId].idleDroneCount = (int)packet.settingValue; } if (packet.settingIndex == 9) { stationPool[stationId].idleShipCount = (int)packet.settingValue; Debug.Log("ADDED SHIPS!!"); } if (packet.settingIndex == 10) { stationPool[stationId].warperCount = (int)packet.settingValue; Debug.Log("ADDED WARPER!!"); } } } // only host should update everything if (!LocalPlayer.IsMasterClient) { return; } if (packet.settingIndex == 0) { PowerConsumerComponent[] consumerPool = pData.factory.powerSystem.consumerPool; if (consumerPool.Length > stationPool[stationId].pcId) { consumerPool[stationPool[stationId].pcId].workEnergyPerTick = (long)(50000.0 * (double)packet.settingValue + 0.5); } } if (packet.settingIndex == 1) { if (stationPool.Length > stationId) { stationPool[stationId].tripRangeDrones = Math.Cos((double)packet.settingValue / 180.0 * 3.141592653589793); } } if (packet.settingIndex == 2) { if (stationPool.Length > stationId) { double value = packet.settingValue; if (value > 40.5) { value = 10000.0; } else if (value > 20.5) { value = value * 2f - 20f; } stationPool[stationId].tripRangeShips = 2400000.0 * value; } } if (packet.settingIndex == 3) { if (stationPool.Length > stationId) { int value = (int)(packet.settingValue * 10f + 0.5f); if (value < 1) { value = 1; } stationPool[stationId].deliveryDrones = value; } } if (packet.settingIndex == 4) { if (stationPool.Length > stationId) { int value = (int)(packet.settingValue * 10f + 0.5f); if (value < 1) { value = 1; } stationPool[stationId].deliveryShips = value; } } if (packet.settingIndex == 5) { if (stationPool.Length > stationId) { double value = packet.settingValue; if (value < 1.5) { value = 0.2; } else if (value < 7.5) { value = value * 0.5 - 0.5; } else if (value < 16.5) { value -= 4f; } else if (value < 20.5) { value = value * 2f - 20f; } else { value = 60; } stationPool[stationId].warpEnableDist = 40000.0 * value; } } if (packet.settingIndex == 6) { if (stationPool.Length > stationId) { stationPool[stationId].warperNecessary = !stationPool[stationId].warperNecessary; } } if (packet.settingIndex == 7) { if (stationPool.Length > stationId) { stationPool[stationId].includeOrbitCollector = !stationPool[stationId].includeOrbitCollector; } } if (packet.settingIndex == 11) { if (stationPool.Length > stationId && stationPool[stationId].storage != null) { for (int i = 0; i < stationPool[stationId].storage.Length; i++) { if (stationPool[stationId].storage[i].itemId == packet.itemId) { stationPool[stationId].storage[i].count = (int)packet.settingValue; break; } } } } }
private bool PlanetIsInRange(PlanetData data) { // TODO: Need to determine what constitutes a planet being in range. return true; }
private void SetHover(PlanetData planet) { hoveredPlanet = planet; hoveredStar = (StarData)null; }
private float MigrationValueOfPlanet(PlanetData pData, Pops pop) { float planetValue = 0f; float FarmerJobsOnPlanet = 0f; float MinerJobsOnPlanet = 0f; float EngineerJobsOnPlanet = 0f; float FluxmenJobsOnPlanet = 0f; float AdministratorJobsOnPlanet = 0f; float ScientistJobsOnPlanet = 0f; float releventJobsOnPlanet = 0f; foreach (Region rData in pData.RegionList) { FarmerJobsOnPlanet += rData.FarmingLevel - rData.FarmsStaffed; MinerJobsOnPlanet += rData.MiningLevel - rData.MinesStaffed; EngineerJobsOnPlanet += rData.ManufacturingLevel - rData.FactoriesStaffed; FluxmenJobsOnPlanet += rData.HighTechLevel - rData.HighTechFacilitiesStaffed; AdministratorJobsOnPlanet += rData.GovernmentLevel - rData.GovernmentFacilitiesStaffed; ScientistJobsOnPlanet += rData.ScienceLevel - rData.LabsStaffed; } switch (pop.PopClass) { case Pops.ePopClass.Scientist: releventJobsOnPlanet = ScientistJobsOnPlanet; break; case Pops.ePopClass.Farmer: releventJobsOnPlanet = FarmerJobsOnPlanet; break; case Pops.ePopClass.Miner: releventJobsOnPlanet = MinerJobsOnPlanet; break; case Pops.ePopClass.Engineer: releventJobsOnPlanet = EngineerJobsOnPlanet; break; case Pops.ePopClass.Fluxmen: releventJobsOnPlanet = FluxmenJobsOnPlanet; break; case Pops.ePopClass.Merchants: break; case Pops.ePopClass.Administrators: releventJobsOnPlanet = AdministratorJobsOnPlanet; break; case Pops.ePopClass.None: break; default: break; } planetValue += (2500 - HelperFunctions.Formulas.MeasureDistanceBetweenSystems(pData.System, pop.PlanetLocated.System)) + pData.AdjustedBio + pData.BasePlanetValue + (releventJobsOnPlanet * 50); return planetValue; }
public void ProcessPacket(CreatePrebuildsRequest packet, NebulaConnection conn) { PlanetData planet = GameMain.galaxy.PlanetById(packet.PlanetId); if (planet.factory == null) { Log.Warn($"planet.factory was null create new one"); planet.factory = GameMain.data.GetOrCreateFactory(planet); } PlayerAction_Build pab = GameMain.mainPlayer.controller?.actionBuild; if (pab != null) { //Make backup of values that are overwritten List <BuildPreview> tmpList = pab.buildPreviews; bool tmpConfirm = pab.waitConfirm; UnityEngine.Vector3 tmpPos = pab.previewPose.position; UnityEngine.Quaternion tmpRot = pab.previewPose.rotation; PlanetFactory tmpFactory = null; NearColliderLogic tmpNearcdLogic = null; PlanetPhysics tmpPlanetPhysics = null; float tmpBuildArea = GameMain.mainPlayer.mecha.buildArea; PlanetData tmpData = null; bool loadExternalPlanetData = GameMain.localPlanet != planet; //Load temporary planet data, since host is not there if (loadExternalPlanetData) { tmpFactory = (PlanetFactory)AccessTools.Field(typeof(PlayerAction_Build), "factory").GetValue(GameMain.mainPlayer.controller.actionBuild); tmpNearcdLogic = (NearColliderLogic)AccessTools.Field(typeof(PlayerAction_Build), "nearcdLogic").GetValue(GameMain.mainPlayer.controller.actionBuild); tmpPlanetPhysics = (PlanetPhysics)AccessTools.Field(typeof(PlayerAction_Build), "planetPhysics").GetValue(pab); tmpData = GameMain.mainPlayer.planetData; } //Create Prebuilds from incomming packet and prepare new position pab.buildPreviews = packet.GetBuildPreviews(); pab.waitConfirm = true; using (FactoryManager.EventFromServer.On()) { FactoryManager.EventFactory = planet.factory; pab.previewPose.position = new UnityEngine.Vector3(packet.PosePosition.x, packet.PosePosition.y, packet.PosePosition.z); pab.previewPose.rotation = new UnityEngine.Quaternion(packet.PoseRotation.x, packet.PoseRotation.y, packet.PoseRotation.z, packet.PoseRotation.w); //Check if some mandatory variables are missing if (planet.physics == null || planet.physics.colChunks == null) { planet.physics = new PlanetPhysics(planet); planet.physics.Init(); } planet.factory.cargoTraffic.GetOrCreateBeltRenderingBatches(); if (planet.aux == null) { planet.aux = new PlanetAuxData(planet); } //Set temporary Local Planet / Factory data that are needed for original methods CheckBuildConditions() and CreatePrebuilds() AccessTools.Field(typeof(PlayerAction_Build), "factory").SetValue(GameMain.mainPlayer.controller.actionBuild, planet.factory); AccessTools.Field(typeof(PlayerAction_Build), "planetPhysics").SetValue(GameMain.mainPlayer.controller.actionBuild, planet.physics); AccessTools.Field(typeof(PlayerAction_Build), "nearcdLogic").SetValue(GameMain.mainPlayer.controller.actionBuild, planet.physics.nearColliderLogic); AccessTools.Property(typeof(global::Player), "planetData").SetValue(GameMain.mainPlayer, planet, null); //Check if prebuilds can be build (collision check, height check, etc) GameMain.mainPlayer.mecha.buildArea = float.MaxValue; bool canBuild; using (FactoryManager.IgnoreBasicBuildConditionChecks.On()) { canBuild = pab.CheckBuildConditions(); canBuild &= CheckBuildingConnections(pab.buildPreviews, planet.factory.entityPool, planet.factory.prebuildPool); } if (canBuild) { FactoryManager.PacketAuthor = packet.AuthorId; pab.CreatePrebuilds(); FactoryManager.PacketAuthor = -1; } //Revert changes back to the original planet if (loadExternalPlanetData) { planet.physics.Free(); planet.physics = null; AccessTools.Property(typeof(global::Player), "planetData").SetValue(GameMain.mainPlayer, tmpData, null); AccessTools.Field(typeof(PlayerAction_Build), "planetPhysics").SetValue(GameMain.mainPlayer.controller.actionBuild, tmpPlanetPhysics); AccessTools.Field(typeof(PlayerAction_Build), "factory").SetValue(GameMain.mainPlayer.controller.actionBuild, tmpFactory); AccessTools.Field(typeof(PlayerAction_Build), "nearcdLogic").SetValue(GameMain.mainPlayer.controller.actionBuild, tmpNearcdLogic); } GameMain.mainPlayer.mecha.buildArea = tmpBuildArea; FactoryManager.EventFactory = null; } pab.buildPreviews = tmpList; pab.waitConfirm = tmpConfirm; pab.previewPose.position = tmpPos; pab.previewPose.rotation = tmpRot; } }
public static void AdjustViceroyBuildPlan(PlanetData pData, bool forceBuildPlanChance) { GlobalGameData gDataRef = GameObject.Find("GameManager").GetComponent<GlobalGameData>(); Character vic = pData.Viceroy; bool targetRegionSelected = false; if (vic != null) { // determine focus and if change needed bool changeFocus = DoesBuildFocusChange(pData, vic, gDataRef); if (changeFocus || forceBuildPlanChance) { float farmPriority = 1f; float highTechPriority = 1f; float minePriority = 1f; float infrastructurePriority = 1f; float labPriority = 1f; float adminPriority = 1f; float factoryPriority = 1f; float militaryGroundPriority = 0f; targetRegionSelected = false; float militarySpacePriority = 0f; // determine the current need for builds if (pData.FoodDifference < 0) { farmPriority += Mathf.Abs(pData.FoodDifference * 4); } if (pData.FoodDifference > pData.TotalFoodConsumed) { farmPriority -= pData.FoodDifference / pData.TotalFoodConsumed; } if (pData.EnergyDifference < 0) { highTechPriority += Mathf.Abs(pData.EnergyDifference * 2f); } if (pData.EnergyDifference > pData.TotalEnergyConsumed) { highTechPriority -= pData.EnergyDifference / pData.TotalEnergyConsumed; } // determine the amount of overcrowding in the planet regions float infraNeed = 0f; foreach (Region rData in pData.RegionList) { if (rData.PopsInTile.Count > rData.MaxSafePopulationLevel) { float crowding = (float)(rData.PopsInTile.Count / (float)rData.MaxSafePopulationLevel) - 1f; if (crowding < 0f) crowding = 0f; infraNeed += crowding; } } if (pData.ManufacturingLevel < 10) { factoryPriority += (10 - pData.ManufacturingLevel) / 2f; } if (pData.AlphaPreProductionDifference < 0) { minePriority += Mathf.Abs(pData.AlphaPreProductionDifference); } if (pData.HeavyPreProductionDifference < 0) { minePriority += Mathf.Abs(pData.HeavyPreProductionDifference / 2f); } if (pData.RarePreProductionDifference < 0) { minePriority += Mathf.Abs(pData.RarePreProductionDifference / 3f); } adminPriority += ((float)pData.Rank * 1.5f); farmPriority += vic.Empathy / 20f; // characters with high Empathy will focus on food and power highTechPriority += vic.Empathy / 20f; // now determine based on tendencies of viceroy farmPriority += (float)(vic.PopsTendency / 100f); highTechPriority += (float)(vic.PopsTendency / 100f); infrastructurePriority += (float)(vic.PopsTendency / 100f); adminPriority += (float)(vic.AdminTendency / 100f); minePriority += (float)(vic.WealthTendency / 100f); factoryPriority += (float)(((vic.WealthTendency + vic.PopsTendency) / 2f) / 100f); labPriority += (float)(vic.ScienceTendency / 100f); // use traits to also determine specific biases if (vic.Traits.Exists(p => p.Name.ToUpper() == "TECHNOPHILE")) { labPriority += UnityEngine.Random.Range(0, 2f); } if (vic.Traits.Exists(p => p.Name.ToUpper() == "INDUSTRIALIST")) { factoryPriority += UnityEngine.Random.Range(0, 2f); } if (vic.Traits.Exists(p => p.Name.ToUpper() == "TECHNOPHOBE")) { labPriority = 0; } if (vic.Traits.Exists(p => p.Name.ToUpper() == "BUREAUCRAT")) { adminPriority += UnityEngine.Random.Range(0, 2f); } // normalize results below 0 if (farmPriority < 0f) farmPriority = 0f; if (highTechPriority < 0f) highTechPriority = 0f; if (adminPriority < 0f) adminPriority = 0f; if (minePriority < 0f) minePriority = 0f; if (factoryPriority < 0f) factoryPriority = 0f; if (labPriority < 0f) labPriority = 0f; if (infrastructurePriority < 0f) infrastructurePriority = 0f; // now normalize the priorities to percentage of 100 float sumPriorities = farmPriority + highTechPriority + minePriority + infrastructurePriority + labPriority + adminPriority + factoryPriority + militaryGroundPriority + militarySpacePriority + pData.BuildPlan.TotalEdictAllocation; pData.BuildPlan.FarmsAllocation = farmPriority / sumPriorities; pData.BuildPlan.HighTechAllocation = highTechPriority / sumPriorities; pData.BuildPlan.MineAllocation = minePriority / sumPriorities; pData.BuildPlan.LabsAllocation = labPriority / sumPriorities; pData.BuildPlan.AdminAllocation = adminPriority / sumPriorities; pData.BuildPlan.InfraAllocation = infrastructurePriority / sumPriorities; pData.BuildPlan.FactoryAllocation = factoryPriority / sumPriorities; pData.BuildPlan.GroundMilitaryAllocation = militaryGroundPriority / sumPriorities; pData.BuildPlan.StarshipAllocation = militarySpacePriority / sumPriorities; pData.BuildPlan.Status = BuildPlan.eBuildPlanStatus.Pending; if (pData.BuildPlan.InfraAllocation > 0f && !targetRegionSelected) { Region mostOvercrowdedRegion = null; float highRegionCrowding = 0f; List<Region> regionsEligible = new List<Region>(); foreach (Region rData in pData.RegionList) { { if (rData.IsHabitable) regionsEligible.Add(rData); } } foreach (Region rID in regionsEligible) { Region testRegion = rID; float currentRegionCrowding = (float)testRegion.PopsInTile.Count / (float)testRegion.MaxSafePopulationLevel; if (currentRegionCrowding > highRegionCrowding) { highRegionCrowding = currentRegionCrowding; mostOvercrowdedRegion = testRegion; } } targetRegionSelected = true; pData.BuildPlan.TargetRegion = mostOvercrowdedRegion; } } pData.BuildPlan.OverdriveMultiplier = 1; // set overdrive at 1 until I write the AI for it } }
public ReadOnlyPlanetData(PlanetData planet, int position) { Position = position; _planet = planet ?? throw new ArgumentNullException(nameof(planet)); }
public override void Initialize(PlanetData data) { base.Initialize(data); }
private void Reset() { hoveredStar = (StarData)null; hoveredPlanet = (PlanetData)null; }
private static bool DoesBuildFocusChange(PlanetData pData, Character vic, GlobalGameData gDataRef) { float timeSinceChange = vic.TimeSinceBuildFocusChange; float changeChance = 0; if (vic.Traits.Exists(p => p.Name == "Erratic")) { changeChance += 20f; } changeChance -= (vic.GoalStabilityTendency / 10f); changeChance += timeSinceChange * 10f; // if there are critical shortfalls on planets, vics are much less likely to change their focus if (vic.BuildFocus == Character.eBuildFocus.Farms) { if (pData.FoodDifference > 0) { changeChance -= pData.FoodDifference; } } if (vic.BuildFocus == Character.eBuildFocus.Hightech) { if (pData.EnergyDifference > 0) { changeChance -= pData.EnergyDifference; } } if (changeChance > 80) { return true; // yes, the focus changes } return false; }
private void SetHover(StarData star) { hoveredStar = star; hoveredPlanet = (PlanetData)null; }