diff --git a/BulldozeIcon.cs b/BulldozeIcon.cs index 83964c3..9c40d4a 100644 --- a/BulldozeIcon.cs +++ b/BulldozeIcon.cs @@ -5,7 +5,7 @@ namespace Bulldozer public class BulldozeIcon { // var fileBytes = File.ReadAllBytes("C:\\Users\\matts\\src\\dsp-factory-map\\Bulldozer\\Bulldozer\\bulldozer_gs.png"); - private static byte[] pngBytes = + private static readonly byte[] pngBytes = { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x08, 0x06, 0x00, 0x00, 0x00, 0xF4, 0x78, 0xD4, 0xFA, 0x00, 0x00, 0x00, 0x04, 0x73, 0x42, 0x49, 0x54, 0x08, 0x08, 0x08, 0x08, 0x7C, 0x08, 0x64, 0x88, 0x00, 0x00, 0x00, 0x09, 0x70, @@ -729,8 +729,10 @@ public class BulldozeIcon public static Texture2D GetIconTexture(string spriteName) { - var readTex = new Texture2D(48, 48); - readTex.name = spriteName; + var readTex = new Texture2D(48, 48) + { + name = spriteName + }; var result = readTex.LoadImage(pngBytes, false); if (result) { @@ -758,7 +760,6 @@ public static Texture2D GetIconTexture(string spriteName) tex.Apply(true); return tex; } - return null; } } diff --git a/BulldozerPlugin.cs b/BulldozerPlugin.cs index 29d5e10..39e91b4 100644 --- a/BulldozerPlugin.cs +++ b/BulldozerPlugin.cs @@ -55,10 +55,7 @@ private void Update() } var platformSystem = GameMain.localPlanet.factory.platformSystem; - if (_reformIndexInfoProvider == null) - { - _reformIndexInfoProvider = new ReformIndexInfoProvider(platformSystem); - } + _reformIndexInfoProvider ??= new ReformIndexInfoProvider(platformSystem); _reformIndexInfoProvider.DoInitWork(GameMain.localPlanet); @@ -157,7 +154,7 @@ private void Decorate() if (_reformIndexInfoProvider.platformSystem != GameMain.localPlanet?.factory?.platformSystem) { _reformIndexInfoProvider.PlanetChanged(GameMain.localPlanet); - } + } LogAndPopupMessage("not initted"); return; } @@ -272,7 +269,7 @@ private void InvokePavePlanetNoBury() GameMain.localPlanet.factory.RenderLocalPlanetHeightmap(); } - factory.planet.landPercentDirty = true; + factory.planet.landPercentDirtyFlag = true; if (!outOfSoilPile || PluginConfig.soilPileConsumption.Value != OperationMode.Honest) { @@ -331,10 +328,7 @@ public static void UIBuildMenu_OnCategoryButtonClick_Postfix(UIBuildMenu __insta if (uiBuildMenu.currentCategory != 9) { - if (instance._ui != null) - { - instance._ui.Hide(); - } + instance._ui?.Hide(); return; } @@ -342,7 +336,7 @@ public static void UIBuildMenu_OnCategoryButtonClick_Postfix(UIBuildMenu __insta var inittedThisTime = false; if (instance._ui == null) { - instance.InitUi(uiBuildMenu); + instance.InitUi(); inittedThisTime = true; } else @@ -365,13 +359,13 @@ public static void UIBuildMenu_OnCategoryButtonClick_Postfix(UIBuildMenu __insta instance._ui.Show(inittedThisTime); } - private void InitUi(UIBuildMenu uiBuildMenu) + private void InitUi() { GameObject environmentModificationContainer = GameObject.Find("UI Root/Overlay Canvas/In Game/Function Panel/Build Menu/child-group"); var containerRect = environmentModificationContainer.GetComponent(); var foundationButton = GameObject.Find("UI Root/Overlay Canvas/In Game/Function Panel/Build Menu/child-group/button-1"); var reformAllButton = GameObject.Find("UI Root/Overlay Canvas/In Game/Function Panel/Build Menu/reform-group/button-reform-all"); - + _ui = containerRect.gameObject.AddComponent(); UIElements.logger = logger; if (containerRect == null || foundationButton == null) @@ -379,7 +373,7 @@ private void InitUi(UIBuildMenu uiBuildMenu) return; } - _ui.AddBulldozeComponents(containerRect, uiBuildMenu, foundationButton, reformAllButton, bt => + _ui.AddBulldozeComponents(containerRect, foundationButton, bt => { StartCoroutine(InvokeAction(1, () => { @@ -473,7 +467,7 @@ private string ConstructPopupMessage(PlanetData localPlanet) if (PluginConfig.IsLatConstrained()) { popupMessage += "\nAdd foundation to locations in Selected Latitudes"; - } + } else if (PluginConfig.guideLinesOnly.Value) { popupMessage += "\nAdd foundation needed to paint guidelines"; @@ -613,7 +607,9 @@ static void EnterGame() [HarmonyPostfix] [HarmonyPatch(typeof(GameSave), "LoadCurrentGame")] +#pragma warning disable IDE0060 // Remove unused parameter static void LoadCurrentGame(bool __result, string saveName) +#pragma warning restore IDE0060 // Remove unused parameter { if (instance != null && instance._reformIndexInfoProvider != null) instance._reformIndexInfoProvider.PlanetChanged(null); diff --git a/CheckboxControl.cs b/CheckboxControl.cs index 60a37c5..76a5633 100644 --- a/CheckboxControl.cs +++ b/CheckboxControl.cs @@ -9,7 +9,7 @@ public class CheckboxControl : MonoBehaviour, IPointerEnterHandler, IPointerExit { private GameObject _hoverText; public string HoverText = ""; - public event Action onClick; + public event Action OnClick; public Text textObject; public void Start() @@ -50,7 +50,7 @@ public void OnPointerExit(PointerEventData eventData) public void OnPointerClick(PointerEventData eventData) { - onClick?.Invoke(eventData); + OnClick?.Invoke(eventData); } } } \ No newline at end of file diff --git a/GridExplorer.cs b/GridExplorer.cs index a6fdd35..fb2a37e 100644 --- a/GridExplorer.cs +++ b/GridExplorer.cs @@ -18,8 +18,7 @@ public delegate void PostComputeReformAction(SnapArgs snapArgs, Vector3 center, float lastLat = 0, float lastLon = 0); - public static void IterateReform(BuildTool_Reform reformTool, PostComputeReformAction postComputeFn, int maxExecutionMs, float startLat = -89.9f, - float startLon = -179.9f) + public static void IterateReform(BuildTool_Reform reformTool, PostComputeReformAction postComputeFn, int maxExecutionMs, float startLat = -89.9f) { var checkedReformIndices = new HashSet(); var checkedDataPos = new HashSet(); @@ -69,17 +68,17 @@ public static void IterateReform(BuildTool_Reform reformTool, PostComputeReformA { checkedDataPos.Add(reformTool.planet.data.QueryIndex(cursorPoint)); } - - var flattenTerrainReform = reformTool.factory.ComputeFlattenTerrainReform(snapArgs.points, center, radius, cursorPointCount); - postComputeFn?.Invoke(snapArgs, center, radius, 10, flattenTerrainReform); + int costSandCount = 0; + int getSandcount = 0; + reformTool.factory.ComputeFlattenTerrainReform(snapArgs.points, center, radius, cursorPointCount, ref costSandCount, ref getSandcount); + postComputeFn?.Invoke(snapArgs, center, radius, 10, costSandCount); if (stopwatch.ElapsedMilliseconds > maxExecutionMs) { LogAndPopupMessage($"cancel after running ${stopwatch.ElapsedMilliseconds} lat={lat} / lon={lon}"); stopwatch.Stop(); // signal that we did not finish this task - if (postComputeFn != null) - postComputeFn(snapArgs, center, radius, 10, 0, true, lat, lon); + postComputeFn?.Invoke(snapArgs, center, radius, 10, 0, true, lat, lon); break; } } diff --git a/GuideMarker.cs b/GuideMarker.cs index d66be51..2cc4509 100644 --- a/GuideMarker.cs +++ b/GuideMarker.cs @@ -80,7 +80,7 @@ private static void PaintEquator(PlatformSystem platformSystem) { // equator stripe var coordLineOffset = GetCoordLineOffset(platformSystem.planet); - List indexes = new List(); + List indexes = new(); for (var lon = -179.9f; lon < 180; lon += 0.25f) { for (var latOffset = -1; latOffset < 1; latOffset++) @@ -159,7 +159,7 @@ private static void PaintMeridians(PlatformSystem platformSystem) var lonOffsetMax = 2; - HashSet actualIndexes = new HashSet(); + HashSet actualIndexes = new(); for (var lonOffset = lonOffsetMin; lonOffset < lonOffsetMax; lonOffset++) { var lon = coordLineOffset * lonOffset + meridianOffset * 90f; @@ -208,13 +208,13 @@ private static void PaintMinorMeridians(PlatformSystem platformSystem) if (PluginConfig.LatitudeOutOfBounds(lat)) continue; - for (var meridianOffset = -180; meridianOffset < 180; meridianOffset += interval) + for (var meridianOffset = -180; meridianOffset < 180; meridianOffset += Mathf.RoundToInt(interval)) { var lonOffsetMin = -1; var lonOffsetMax = 2; - HashSet actualIndexes = new HashSet(); + HashSet actualIndexes = new(); for (var lonOffset = lonOffsetMin; lonOffset < lonOffsetMax; lonOffset++) { var lon = coordLineOffset * lonOffset + meridianOffset; diff --git a/LatLon.cs b/LatLon.cs index 1446fed..7b1c8c8 100644 --- a/LatLon.cs +++ b/LatLon.cs @@ -13,7 +13,7 @@ namespace Bulldozer public float Lat => Precision == 1 ? _lat : _lat / (float) Precision; public float Long => Precision == 1 ? _lng : _lng / (float) Precision; - public static LatLon Empty => new (-1000, -1000, 1); + public static LatLon Empty => new (-0, 0, 0); private static readonly Dictionary> PoolLatToLonToInstance = new(); public readonly int Precision; @@ -44,8 +44,8 @@ public static LatLon FromCoords(double lat, double lon, int precisionMultiple = throw new InvalidDataException("Invalid precision multiple " + precisionMultiple); } - int newLat = lat < 0 ? Mathf.CeilToInt((float)lat * precisionMultiple) : Mathf.FloorToInt((float)lat * precisionMultiple); - int newLon = lon < 0 ? Mathf.CeilToInt((float)lon * precisionMultiple) : Mathf.FloorToInt((float)lon * precisionMultiple); + int newLat = Mathf.RoundToInt((float)lat * precisionMultiple); + int newLon = Mathf.RoundToInt((float)lon * precisionMultiple); if (!PoolLatToLonToInstance.TryGetValue(newLat, out var lonLookup)) { lonLookup = new Dictionary(); @@ -62,12 +62,12 @@ public static LatLon FromCoords(double lat, double lon, int precisionMultiple = public bool Equals(LatLon other) { - return _lat == other._lat && _lng == other._lng; + return _lat == other._lat && _lng == other._lng && Precision == other.Precision; } public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) + if (obj is null) { return false; } @@ -90,7 +90,7 @@ public override int GetHashCode() public bool IsEmpty() { - return Precision == 0 || _lat == Empty._lat && _lng == Empty._lng; + return Precision == 0; } public override string ToString() @@ -98,7 +98,7 @@ public override string ToString() return $"{Lat},{Long}"; } - public LatLon Offset(int latOffset, int lonOffset) + public LatLon Offset(float latOffset, float lonOffset) { return FromCoords(Lat + latOffset, Long + lonOffset, Precision); } diff --git a/Log.cs b/Log.cs index bcd2204..3525b90 100644 --- a/Log.cs +++ b/Log.cs @@ -24,7 +24,7 @@ public static void Warn(string message) logger.LogWarning($"[{DateTime.Now:HH:mm:ss.fff}] {message}"); } - private static Dictionary _logCount = new (); + private static readonly Dictionary _logCount = new(); public static void LogNTimes(string msg, int maxTimes, params object[] args) { if (!_logCount.ContainsKey(msg) || maxTimes < 0) diff --git a/PluginConfig.cs b/PluginConfig.cs index 6302676..4a6d50f 100644 --- a/PluginConfig.cs +++ b/PluginConfig.cs @@ -1,7 +1,8 @@ -using System; +using BepInEx.Configuration; +using System; using System.Collections; using System.ComponentModel; -using BepInEx.Configuration; +using System.Globalization; namespace Bulldozer { @@ -52,8 +53,8 @@ public static class PluginConfig public static ConfigEntry factoryTeardownRunTimePerFrame; public static ConfigEntry soilPileConsumption; public static ConfigEntry foundationConsumption; - public static ConfigEntry maxLatitude; - public static ConfigEntry minLatitude; + public static ConfigEntry maxLatitude; + public static ConfigEntry minLatitude; // used to make UI checkbox values persistent public static ConfigEntry addGuideLines; @@ -64,7 +65,7 @@ public static class PluginConfig public static ConfigEntry addGuideLinesMeridian; public static ConfigEntry addGuideLinesTropic; public static ConfigEntry addGuideLinesPoles; - public static ConfigEntry minorMeridianInterval; + public static ConfigEntry minorMeridianInterval; public static ConfigEntry guideLinesEquatorColor; public static ConfigEntry guideLinesTropicColor; @@ -94,13 +95,13 @@ public static void InitConfig(ConfigFile configFile) { PluginConfigFile = configFile; - minLatitude = configFile.Bind("Control", "Min Latitude", -90, + minLatitude = configFile.Bind("Control", "Min Latitude", -90f, new ConfigDescription("Minimum latitude to work on. Set equal to Max Latitude to apply to entire planet", - new AcceptableValueRange(-90, 90))); + new AcceptableValueRange(-90f, 90f))); - maxLatitude = configFile.Bind("Control", "Max Latitude", 90, + maxLatitude = configFile.Bind("Control", "Max Latitude", 90f, new ConfigDescription("Max latitude to work on, set min and max to the same value to apply to entire planet", - new AcceptableValueRange(-90, 90))); + new AcceptableValueRange(-90f, 90f))); minLatitude.SettingChanged += OnMinLatitudeChange; maxLatitude.SettingChanged += OnMaxLatitudeChange; @@ -141,10 +142,10 @@ public static void InitConfig(ConfigFile configFile) "Enable/disable of the tropic guidelines individually. No effect if AddGuideLines is disabled"); addGuideLinesPoles = configFile.Bind("Decoration", "AddGuideLinesPoles", false, "Enable/disable painting polar areas. No effect if AddGuideLines is disabled. Poles are considered first 2 tropics"); - minorMeridianInterval = configFile.Bind("Decoration", "MinorMeridianInterval", 0, + minorMeridianInterval = configFile.Bind("Decoration", "MinorMeridianInterval", 0f, new ConfigDescription( "Paint meridians starting at 0 and incrementing by this value. E.g., a value of 10 would add a meridian line every 10 degrees 18, 36 total. 0 to disable", - new AcceptableValueRange(0, 89), "meridians")); + new AcceptableValueRange(0f, 120f), "meridians")); guideLinesEquatorColor = configFile.Bind("CustomColors", "Equator Color", 7, new ConfigDescription("Index of color in palette to paint equator. Default is green", new AcceptableValueRange(0, 31), "color")); @@ -196,7 +197,7 @@ public static void InitConfig(ConfigFile configFile) private static void OnMaxLatitudeChange(object sender, EventArgs e) { - if (sender is ConfigEntry entry && minLatitude.Value > entry.Value) + if (sender is ConfigEntry entry && minLatitude.Value > entry.Value) { minLatitude.Value = maxLatitude.Value; } @@ -204,9 +205,9 @@ private static void OnMaxLatitudeChange(object sender, EventArgs e) private static void OnMinLatitudeChange(object sender, EventArgs e) { - if (sender is ConfigEntry entry && maxLatitude.Value < entry.Value) + if (sender is ConfigEntry entry && maxLatitude.Value < entry.Value) { - maxLatitude.Value = entry.Value; + maxLatitude.Value = minLatitude.Value; } } @@ -300,7 +301,7 @@ public static string GetLatRangeString() maxLatDir = "° "; } - return $"{minlat}{latDir} - {maxlat}{maxLatDir}"; + return $"{minlat.ToString("F2", CultureInfo.CurrentCulture)}{latDir} - {maxlat.ToString("F2", CultureInfo.CurrentCulture)}{maxLatDir}"; } } } \ No newline at end of file diff --git a/PluginConfigWindow.cs b/PluginConfigWindow.cs index e50bdb4..75266bc 100644 --- a/PluginConfigWindow.cs +++ b/PluginConfigWindow.cs @@ -18,7 +18,7 @@ public class PluginConfigWindow public static bool NeedReinit; private static Texture2D _tooltipBg; - private static Dictionary _customColorTextures = new(); + private static readonly Dictionary _customColorTextures = new(); private static readonly Dictionary previousSelections = new(); private static string _savedGUISkin; @@ -226,6 +226,11 @@ private static void DrawSetting(ConfigEntryBase configEntry) descriptionAdded = DrawRangeField(configEntry); } + if (!descriptionAdded && configEntry.SettingType == typeof(float)) + { + descriptionAdded = DrawFloatRangeField(configEntry); + } + if (!descriptionAdded) { //something went wrong, default to text field @@ -283,6 +288,47 @@ private static bool DrawRangeField(ConfigEntryBase configEntry) return true; } + private static bool DrawFloatRangeField(ConfigEntryBase configEntry) + { + if (configEntry.Description.AcceptableValues is not AcceptableValueRange acceptableValueRange) + { + return false; + } + + GUILayout.BeginHorizontal(); + AcceptableValueRange acceptableValues = acceptableValueRange; + var converted = (float)configEntry.BoxedValue; + var leftValue = acceptableValues.MinValue; + var rightValue = acceptableValues.MaxValue; + + var result = GUILayout.HorizontalSlider(converted, leftValue, rightValue, GUILayout.MinWidth(200)); + if (Math.Abs(result - converted) > Mathf.Abs(rightValue - leftValue) / 1000) + { + var newValue = Convert.ChangeType(Mathf.Round(result / 0.36f) * 0.36f, configEntry.SettingType, CultureInfo.InvariantCulture); + configEntry.BoxedValue = newValue; + } + + var strVal = ((float)configEntry.BoxedValue).ToString("F2", CultureInfo.CurrentCulture); + var strResult = GUILayout.TextField(strVal, GUILayout.Width(50)); + + GUILayout.EndHorizontal(); + if (strResult != strVal) + { + try + { + var resultVal = float.Parse(strResult, NumberStyles.Any, CultureInfo.CurrentCulture); + var clampedResultVal = Mathf.Clamp(resultVal, leftValue, rightValue); + configEntry.BoxedValue = clampedResultVal; + } + catch (FormatException) + { + // Ignore user typing in bad data + } + } + + return true; + } + public static Color GetColorByIndex(int index) { if (index < 0 || index > 31) diff --git a/PluginUI.cs b/PluginUI.cs index e88369b..0ff6eb1 100644 --- a/PluginUI.cs +++ b/PluginUI.cs @@ -24,7 +24,7 @@ public class UIElements : MonoBehaviour "Destroy all factory machines in selected latitude range"; public static ManualLogSource logger; - private static List gameObjectsToDestroy = new(); + private static readonly List gameObjectsToDestroy = new(); public GameObject DrawEquatorCheck; public Sprite spriteChecked; @@ -174,7 +174,7 @@ private static void ResetButtonPos(RectTransform rectTransform) } else if (posStr != PluginConfig.originalReformButtonPosition.Value) { - var parts = PluginConfig.originalReformButtonPosition.Value.Split(','); + var parts = PluginConfig.originalReformButtonPosition.Value.Split(new char[] { ',' }); try { if (float.TryParse(parts[0].Trim(), out var resultx)) @@ -194,20 +194,20 @@ private static void ResetButtonPos(RectTransform rectTransform) Log.Debug($"Failed to parse xvalue {parts[0]}"); } } - catch (Exception e) + catch (Exception ex) { + Log.Warn($"Failed to parse original button position {ex.Message}"); // ignored } } } - public void AddBulldozeComponents(RectTransform environmentModificationContainer, UIBuildMenu uiBuildMenu, GameObject foundationButton, - GameObject reformAllButton, Action action) + public void AddBulldozeComponents(RectTransform environmentModificationContainer, GameObject foundationButton, Action action) { InitOnOffSprites(); InitActionButton(foundationButton, action); - InitDrawEquatorCheckbox(environmentModificationContainer, foundationButton); + InitDrawEquatorCheckbox(environmentModificationContainer); InitAlterVeinsCheckbox(environmentModificationContainer); InitDestroyMachinesCheckbox(environmentModificationContainer); InitConfigButton(environmentModificationContainer); @@ -218,7 +218,7 @@ private void InitActionButton(GameObject buttonToCopy, Action action) buttonOneRectTransform = buttonToCopy.gameObject.GetComponent(); countText = null; ResetButtonPos(buttonOneRectTransform); - + if (GameMain.sandboxToolsEnabled) buttonOneRectTransform.anchoredPosition = new Vector2((float)(buttonOneRectTransform.anchoredPosition.x - buttonOneRectTransform.sizeDelta.x / 1.5), buttonOneRectTransform.anchoredPosition.y); BulldozeButton = CopyButton(buttonOneRectTransform, Vector2.right * (buttonOneRectTransform.sizeDelta.x), out countText, @@ -236,7 +236,7 @@ private void InitOnOffSprites() spriteUnChecked = Sprite.Create(texOff, new Rect(0, 0, texOff.width, texOff.height), new Vector2(0.5f, 0.5f)); } - private void InitDrawEquatorCheckbox(RectTransform environmentModificationContainer, GameObject button1) + private void InitDrawEquatorCheckbox(RectTransform environmentModificationContainer) { DrawEquatorCheck = new GameObject("Draw equator line"); gameObjectsToDestroy.Add(DrawEquatorCheck); @@ -250,7 +250,7 @@ private void InitDrawEquatorCheckbox(RectTransform environmentModificationContai rect.anchoredPosition = new Vector2(GetCheckBoxXValue(), -90); drawEquatorCheckboxButton = rect.gameObject.AddComponent(); drawEquatorCheckboxButton.HoverText = "Add painted guidelines at various locations (equator, tropics, meridians configurable)"; - drawEquatorCheckboxButton.onClick += OnDrawEquatorCheckClick; + drawEquatorCheckboxButton.OnClick += OnDrawEquatorCheckClick; gameObjectsToDestroy.Add(drawEquatorCheckboxButton.gameObject); if (countText != null) @@ -310,7 +310,7 @@ private void InitAlterVeinsCheckbox(RectTransform environmentModificationContain gameObjectsToDestroy.Add(AlterVeinsCheckBoxImage.gameObject); AlterVeinsCheckBoxImage.sprite = PluginConfig.alterVeinState.Value ? spriteChecked : spriteUnChecked; - repaveCheckboxButton.onClick += OnAlterVeinCheckClick; + repaveCheckboxButton.OnClick += OnAlterVeinCheckClick; } private void InitDestroyMachinesCheckbox(RectTransform environmentModificationContainer) @@ -348,7 +348,7 @@ private void InitDestroyMachinesCheckbox(RectTransform environmentModificationCo gameObjectsToDestroy.Add(DestroyMachinesCheckBoxImage.gameObject); DestroyMachinesCheckBoxImage.sprite = PluginConfig.destroyFactoryAssemblers.Value ? spriteChecked : spriteUnChecked; - destroyMachinesButton.onClick += OnDestroyMachinesCheckClick; + destroyMachinesButton.OnClick += OnDestroyMachinesCheckClick; } private float GetCheckBoxXValue() @@ -397,7 +397,7 @@ private void InitConfigButton(RectTransform environmentModificationContainer) var configImgGameObject = GameObject.Find("UI Root/Overlay Canvas/In Game/Game Menu/button-3-bg/button-3/icon"); ConfigIconImage.sprite = configImgGameObject.GetComponent().sprite; - invokeConfig.onClick += data => { PluginConfigWindow.visible = !PluginConfigWindow.visible; }; + invokeConfig.OnClick += data => { PluginConfigWindow.visible = !PluginConfigWindow.visible; }; } @@ -497,13 +497,9 @@ public void Show(bool inittedThisTime = false) BulldozeButton.gameObject.SetActive(true); PaveActionButton.gameObject.SetActive(true); CheckBoxImage.gameObject.SetActive(true); - if (AlterVeinsCheckBoxImage.gameObject != null) - { - AlterVeinsCheckBoxImage.gameObject.SetActive(true); - } + AlterVeinsCheckBoxImage.gameObject?.SetActive(true); - if (DestroyMachinesCheckBoxImage.gameObject != null) - DestroyMachinesCheckBoxImage.gameObject.SetActive(true); + DestroyMachinesCheckBoxImage.gameObject?.SetActive(true); ConfigIconImage.gameObject.SetActive(true); } diff --git a/RaptorFastDelete.cs b/RaptorFastDelete.cs index 668f251..18860f2 100644 --- a/RaptorFastDelete.cs +++ b/RaptorFastDelete.cs @@ -98,7 +98,7 @@ void RemoveConsumerComponent(int id) RemoveConsumerComponent(entityPool[entityId].powerConId); // Help remove the power consumers before removing the entity - factory.RemoveEntityWithComponents(entityId); + factory.RemoveEntityWithComponents(entityId, true); } for (int i = 0; i < powerSystem.netCursor; i++) @@ -113,8 +113,7 @@ void RemoveConsumerComponent(int id) } } - if (factory.planet.factoryModel != null) - factory.planet.factoryModel.RefreshPowerConsumers(); + factory.planet.factoryModel?.RefreshPowerConsumers(); } void DeleteBelts() @@ -172,7 +171,7 @@ void TakeBackItemsOptimized() cargoTraffic.beltRecycleCursor++; } - factory.RemoveEntityWithComponents(entityId); + factory.RemoveEntityWithComponents(entityId, true); } } diff --git a/ReformIndexInfoProvider.cs b/ReformIndexInfoProvider.cs index 1817933..1efc104 100644 --- a/ReformIndexInfoProvider.cs +++ b/ReformIndexInfoProvider.cs @@ -11,6 +11,7 @@ namespace Bulldozer public class ReformIndexInfoProvider { private const int LatitudesPerPass = 10; + internal const int latLonPrecision = 1000; private readonly Dictionary _llLookup = new(); private readonly LatLon[] _llModLookup = new LatLon[GameMain.localPlanet.data.modData.Length * 2]; private readonly HashSet _tropicsLatitudes = new(); @@ -27,6 +28,7 @@ public ReformIndexInfoProvider(PlatformSystem platformSystem) { this.platformSystem = platformSystem; _planetId = platformSystem.planet.id; + _latLookupWorkItemIndex = -90f + 90f / platformSystem?.latitudeCount ?? 500f; } public int PlanetId => _planetId; @@ -43,7 +45,7 @@ private void SetInitValues(PlatformSystem newPlatformSystem, int planetId) _lookupsCreated = false; _planetId = planetId; platformSystem = newPlatformSystem; - _latLookupWorkItemIndex = -89.9f; + _latLookupWorkItemIndex = -90f + 90f / platformSystem?.latitudeCount ?? 500f; _initUpdateCounter = 0; } @@ -124,7 +126,6 @@ public void DoInitWork(PlanetData planetData) var planetRawData = platformSystem.planet.data; var start = DateTime.Now; var maxRuntimeMS = GetMaxRuntimeMS(); - var latLonPrecision = planetData.realRadius < 250f ? 10 : 10; var latitudeCount = platformSystem.latitudeCount; var latDegIncrement = (90 * 2.0f) / latitudeCount; @@ -137,10 +138,16 @@ public void DoInitWork(PlanetData planetData) continue; prevStart = startNdx; var longitudeCounts = endNdxExclusive - startNdx; - if (longitudeCounts != prevLength) + if (longitudeCounts != prevLength && prevLength >= 0) { // got ourselves a new tropic here - _tropicsLatitudes.Add(LatLon.FromCoords(_latLookupWorkItemIndex, 0, latLonPrecision)); + // mark the north side of the tropic in the southern hemisphere and the south side in the northern hemisphere + // it might be better to switch these or add a setting to choose + if (_latLookupWorkItemIndex < 0) + _tropicsLatitudes.Add(LatLon.FromCoords(_latLookupWorkItemIndex, 0, latLonPrecision)); + else + _tropicsLatitudes.Add(LatLon.FromCoords(_latLookupWorkItemIndex - latDegIncrement, 0, latLonPrecision)); + } var latCoord = LatLon.FromCoords(_latLookupWorkItemIndex, 0, latLonPrecision); @@ -173,7 +180,7 @@ public void DoInitWork(PlanetData planetData) { var numLongitudes = (endNdxExclusive - startNdx); // longitudes above this index are in going west from 0 - var maxPositiveLongitudeIndex = (endNdxExclusive + startNdx) / 2; + var maxPositiveLongitudeIndex = (endNdxExclusive + startNdx) / 2 - 1; var negCounts = numLongitudes / 2; var degPerIndex = 180f / negCounts; var longMod = numLongitudes / 4; @@ -181,7 +188,7 @@ public void DoInitWork(PlanetData planetData) { if (desired > maxPositiveLongitudeIndex) { - var longDegrees = degPerIndex * (desired - maxPositiveLongitudeIndex); + var longDegrees = degPerIndex * (desired - maxPositiveLongitudeIndex - 0.5f); _llLookup[desired] = LatLon.FromCoords(_latLookupWorkItemIndex, -longDegrees, latLonPrecision); var pos = GeoUtil.LatLonToPosition(_latLookupWorkItemIndex, -longDegrees, platformSystem.planet.realRadius); @@ -190,7 +197,7 @@ public void DoInitWork(PlanetData planetData) } else { - var longDegrees = degPerIndex * (desired - startNdx); + var longDegrees = degPerIndex * (desired - startNdx + 0.5f); _llLookup[desired] = LatLon.FromCoords(_latLookupWorkItemIndex, longDegrees, latLonPrecision); var pos = GeoUtil.LatLonToPosition(_latLookupWorkItemIndex, longDegrees, platformSystem.planet.realRadius); var currentDataIndex = planetRawData.QueryIndex(pos); @@ -216,7 +223,7 @@ public void DoInitWork(PlanetData planetData) } } - if (_latLookupWorkItemIndex > 89) + if (_latLookupWorkItemIndex > 90) { _lookupsCreated = true; } @@ -249,18 +256,11 @@ public int InitPercentComplete() public (int offsetStartIndex, int offsetEndIndex) GetReformIndexesForLatitude(float latDegrees) { - double latInRads = Mathf.Deg2Rad * latDegrees; - var latIndex = (float)(latInRads / (Mathf.PI * 2)) * platformSystem.segment; - var scaledLat = Mathf.Round(latIndex * 10f); - var absScaledLat = Mathf.Abs(scaledLat); - var scaledLatFloat = scaledLat >= 0.0 ? absScaledLat : -absScaledLat; - var latitudeSeg = scaledLatFloat / 10f; - - var scaledLatSeg = latitudeSeg > 0.0 ? Mathf.CeilToInt(latitudeSeg * 5f) : Mathf.FloorToInt(latitudeSeg * 5f); var latCountsHalf = platformSystem.latitudeCount / 2; - var y = scaledLatSeg > 0 ? scaledLatSeg - 1 : latCountsHalf - scaledLatSeg - 1; - var startIndex = platformSystem.reformOffsets[y]; - var unscaledCount = PlatformSystem.DetermineLongitudeSegmentCount(Mathf.FloorToInt(Mathf.Abs(latitudeSeg)), platformSystem.segment); + var scaledLat = Mathf.FloorToInt(Mathf.Abs(latDegrees) * platformSystem.latitudeCount / 180f); + var latIndex = latDegrees >= 0 ? scaledLat : scaledLat + latCountsHalf; + var startIndex = platformSystem.reformOffsets[latIndex]; + var unscaledCount = PlatformSystem.DetermineLongitudeSegmentCount(scaledLat / 5, platformSystem.segment); var endIndex = startIndex + unscaledCount * 5; return (startIndex, endIndex); diff --git a/RegionColorConfig.cs b/RegionColorConfig.cs index f7fb194..a9d6535 100644 --- a/RegionColorConfig.cs +++ b/RegionColorConfig.cs @@ -7,10 +7,10 @@ namespace Bulldozer { public class RegionColorConfig { - public int minLatitude; - public int maxLatitude; - public int minLongitude; - public int maxLongitude; + public float minLatitude; + public float maxLatitude; + public float minLongitude; + public float maxLongitude; public bool mirror; public int colorIndex; @@ -18,43 +18,60 @@ public bool ContainsPosition(float lat, float lng) { bool allLatitudes = minLatitude == maxLatitude; bool allLongs = minLongitude == maxLongitude; - if (allLatitudes && allLongs) + if (!(allLatitudes || (minLatitude <= lat && maxLatitude >= lat) || mirror && (-minLatitude >= lat && -maxLatitude <= lat))) + return false; + if (minLongitude <= maxLongitude) + return allLongs || minLongitude <= lng && maxLongitude >= lng; + else + return !(maxLongitude < lng && minLongitude > lng); + } + + public List GetRects() + { + var result = new List(); + + var minLat = minLatitude; + var maxLat = maxLatitude; + var minLng = minLongitude; + var maxLng = maxLongitude; + + if (minLatitude == maxLatitude) + { + minLat = -90; + maxLat = 90; + } + if (minLongitude == maxLongitude) { - return true; + minLng = -180; + maxLng = 180; } - if (!allLatitudes && allLongs) + var height = maxLat - minLat; + if (minLongitude > maxLongitude) { - - bool defaultLatsMatch = (minLatitude <= lat && maxLatitude >= lat); - if (defaultLatsMatch) - return true; + result.Add(new Rect(minLng, minLat, 180 - minLng, height)); + result.Add(new Rect(-180, minLat, maxLng + 180, height)); if (mirror) - return (-minLatitude >= lat && -maxLatitude <= lat); - return false; + { + result.Add(new Rect(minLng, -maxLat, 180 - minLng, height)); + result.Add(new Rect(-180, -maxLat, maxLng + 180, height)); + } } - if (allLatitudes && !allLongs) + else { - - bool defaultLonsMatch = (minLongitude <= lng && maxLongitude >= lng); - if (defaultLonsMatch) - return true; - return false; + result.Add(new Rect(minLng, minLat, maxLng - minLng, height)); + if (mirror) + result.Add(new Rect(minLng, -maxLat, maxLng - minLng, height)); } - - if ((minLatitude <= lat && maxLatitude >= lat) && (minLongitude <= lng && maxLongitude >= lng)) - return true; - if (!mirror) - return false; - return (-minLatitude >= lat && -maxLatitude <= lat) - && minLongitude <= lng && maxLongitude >= lng; + + return result; } } public class RegionalColors { private static RegionalColors _instance; - private List _regionColorConfigs; + private readonly List _regionColorConfigs; public RegionalColors() { @@ -66,10 +83,7 @@ public static RegionalColors Instance { get { - if (_instance == null) - { - _instance = DeserializeFromConfigProperty(); - } + _instance ??= DeserializeFromConfigProperty(); return _instance; } @@ -106,12 +120,14 @@ private static RegionalColors DeserializeFromConfigProperty() var strVal = PluginConfig.regionColors.Value; if (strVal.Trim().Length == 0) { - var regionColorConfig = new RegionColorConfig(); - regionColorConfig.colorIndex = 2; - regionColorConfig.minLatitude = -89; - regionColorConfig.maxLatitude = -70; - regionColorConfig.minLongitude = 0; - regionColorConfig.maxLongitude = 0; + var regionColorConfig = new RegionColorConfig + { + colorIndex = 2, + minLatitude = -89, + maxLatitude = -70, + minLongitude = 0, + maxLongitude = 0 + }; var tmpResult = new RegionalColors(); tmpResult._regionColorConfigs.Add(regionColorConfig); return tmpResult; @@ -120,7 +136,7 @@ private static RegionalColors DeserializeFromConfigProperty() var result = new RegionalColors(); // format is "JSONREP$JSONREP" - var parts = strVal.Split('$'); + var parts = strVal.Split(new char[] { '$' }); Log.Debug($"Loading region color config from json {parts.Length} {strVal}"); foreach (var savedValue in parts) { diff --git a/RegionColorWindow.cs b/RegionColorWindow.cs index ccef115..1f86c94 100644 --- a/RegionColorWindow.cs +++ b/RegionColorWindow.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Globalization; using UnityEngine; @@ -15,8 +14,7 @@ public class RegionColorWindow private static Texture2D _tooltipBg; - private static int _loggedMessageCount = 0; - private static RegionalColors _regionalColors = RegionalColors.Instance; + private static readonly RegionalColors _regionalColors = RegionalColors.Instance; private static Pager _pager; private static bool lastOverLapCheckFailed; private static bool _overlapCheckDirty; @@ -171,34 +169,27 @@ private static void CheckOverlap() { _overlapCheckDirty = false; lastOverLapCheckFailed = false; - for (int i = -90; i < 90; i++) + var regions = _regionalColors.GetRegions(); + for (int i = 0; i < regions.Count - 1; i++) { - for (int j = -180; j < 180; j++) + var aRects = regions[i].GetRects(); + for (int j = i + 1; j < regions.Count; j++) { - int matchCount = 0; - List regionMatchingIndex = new List(); - - var regions = _regionalColors.GetRegions(); - for (int ndx = 0; ndx < regions.Count; ndx++) + var bRects = regions[j].GetRects(); + foreach (var a in aRects) { - var region = regions[ndx]; - if (region.ContainsPosition(i, j)) + foreach (var b in bRects) { - matchCount++; - regionMatchingIndex.Add(ndx); + if (a.Overlaps(b)) + { + lastOverLapCheckFailed = true; + _lastOverlapCheck = DateTime.Now; + return; + } } } - - if (matchCount > 1) - { - lastOverLapCheckFailed = true; - // var matchingIndexes = string.Join(",", regionMatchingIndex); - // Log.Debug($"overlap on points {i}, {j}, {matchingIndexes}"); - } } } - - _lastOverlapCheck = DateTime.Now; } } @@ -229,7 +220,7 @@ private static void DrawColorConfig(RegionColorConfig regionalColor) GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); - DrawSetting("Max Longitude", -180, 180, ref regionalColor.maxLongitude, regionalColor.minLongitude); + DrawSetting("Max Longitude", -180, 180, ref regionalColor.maxLongitude); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); @@ -324,25 +315,21 @@ private static void DrawCustomColor(int regionalColorColorIndex, ref int current } } - private static void DrawSetting(string title, int minVal, int maxVal, ref int current, int actualMin = -1) + private static void DrawSetting(string title, float minVal, float maxVal, ref float current, float actualMin = -1) { GUILayout.Label(title); - var converted = (float)Convert.ToDouble(current, CultureInfo.InvariantCulture); - var leftValue = (float)Convert.ToDouble(minVal, CultureInfo.InvariantCulture); - var rightValue = (float)Convert.ToDouble(maxVal, CultureInfo.InvariantCulture); - - var result = GUILayout.HorizontalSlider(converted, leftValue, rightValue, GUILayout.MinWidth(200)); - int newVal = current; - if (Math.Abs(result - converted) > Mathf.Abs(rightValue - leftValue) / 1000) + var result = GUILayout.HorizontalSlider(current, minVal, maxVal, GUILayout.MinWidth(200)); + float newVal = current; + if (Math.Abs(result - current) > Mathf.Abs(maxVal - minVal) / 1000) { - newVal = (int)result; + newVal = Mathf.Round(result / 0.36f) * 0.36f; } - var strResult = GUILayout.TextField(newVal.ToString(CultureInfo.CurrentCulture), GUILayout.Width(50)); + var strResult = GUILayout.TextField(newVal.ToString("F2", CultureInfo.CurrentCulture), GUILayout.Width(50)); try { - var updatedFromTextBox = int.Parse(strResult, NumberStyles.Any); + var updatedFromTextBox = float.Parse(strResult, NumberStyles.Any, CultureInfo.CurrentCulture); if (updatedFromTextBox >= minVal && updatedFromTextBox <= maxVal) { newVal = updatedFromTextBox; diff --git a/SelectiveDecoration/MinorMeridianPainter.cs b/SelectiveDecoration/MinorMeridianPainter.cs index 5340578..a532236 100644 --- a/SelectiveDecoration/MinorMeridianPainter.cs +++ b/SelectiveDecoration/MinorMeridianPainter.cs @@ -1,98 +1,64 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using UnityEngine; namespace Bulldozer.SelectiveDecoration { public class MinorMeridianPainter : ISelectivePlanetDecorator { - private readonly HashSet _minorMeridianLongitudes = new(); + private readonly HashSet _minorMeridianPoints = new(); private static DecorationConfig _minorMeridianConfig; + private readonly ReformIndexInfoProvider infoProvider; - - public MinorMeridianPainter() + public MinorMeridianPainter(ReformIndexInfoProvider reformIndexInfoProvider) { + infoProvider = reformIndexInfoProvider; _minorMeridianConfig = new DecorationConfig(PluginConfig.guideLinesMinorMeridianColor.Value); InitMeridianLongitudes(); } - private LatLon _lastRequest = LatLon.Empty; - private bool _lastResult; - public DecorationConfig GetDecorationForLocation(LatLon location) { - if (Math.Abs(location.Lat) > SelectiveDecorationBuilder.POLE_LATITUDE_START) - return DecorationConfig.None; - if (DistanceFromMajorMeridian(location.Long) < 5) - return DecorationConfig.None; - if (location.Long < 0) - { - if (_minorMeridianLongitudes.Contains(Mathf.CeilToInt(location.Long))) - { - _lastRequest = location; - _lastResult = true; - return _minorMeridianConfig; - } - } - else if (_minorMeridianLongitudes.Contains(Mathf.FloorToInt(location.Long))) - { - _lastRequest = location; - _lastResult = true; + // This check probably isn't needed now that the lines aren't thick and misaligned, but I left the logic intact just in case. + //if (DistanceFromMajorMeridian(location.Long) < 5) + // return DecorationConfig.None; + if (_minorMeridianPoints.Contains(location)) return _minorMeridianConfig; - } - - // before returning false see if there's a point in between the last request and this one that would work - if (_lastRequest.RawLat() == location.RawLat() && !_lastResult) - { - var delta = Mathf.Abs(_lastRequest.Long - location.Long) / 3.0f; - for (int j = 1; j <= 3; j++) - { - var inBetween = Mathf.MoveTowards(_lastRequest.Long, location.Long, delta * j); - - if (_minorMeridianLongitudes.Contains((int)inBetween)) - { - _lastRequest = location; - _lastResult = true; - return _minorMeridianConfig; - } - } - } - - _lastRequest = location; - _lastResult = false; - return DecorationConfig.None; } - private int DistanceFromMajorMeridian(float lon) - { - return lon switch - { - >= -5 and <= 5 => (int)Mathf.Abs(lon), - >= 85 and <= 95 => (int)Mathf.Abs(90 - lon), - >= 175 => (int)Mathf.Abs(180 - lon), - <= -85 and >= -95 => (int)Mathf.Abs(-90 - lon), - _ => (int)Mathf.Abs(-180 - lon) - }; - } - private void InitMeridianLongitudes() { var interval = PluginConfig.minorMeridianInterval.Value; - for (int i = 0; i < 180; i += interval) + var segment = infoProvider.platformSystem.segment; + var precision = ReformIndexInfoProvider.latLonPrecision; + var latitudeCount = infoProvider.platformSystem.latitudeCount; + var latDegIncrement = (90 * 2.0f) / latitudeCount; + + for (float lat = latDegIncrement / 2; lat <= SelectiveDecorationBuilder.POLE_LATITUDE_START; lat += latDegIncrement) { - _minorMeridianLongitudes.Add(i); - } + var latSegment = Mathf.FloorToInt(lat * latitudeCount / 180f) / 5; + var lonDivisions = PlatformSystem.DetermineLongitudeSegmentCount(latSegment, segment) * 5; + var lonStep = 360f / lonDivisions; + // arbitrary value of just over half a tile so that if the meridian is right between two tiles it gets both + // this could be used to adjust thickness of the line and might be better as a config option in the future + var proximityThreshold = lonStep * 0.501f; - for (int i = 0 - interval; i > -180; i -= interval) - { - _minorMeridianLongitudes.Add(i); - } + for (float meridianLon = 0f; meridianLon <= 180f; meridianLon += interval) + { + var minLon = (Mathf.Round((meridianLon - proximityThreshold) / lonStep) + 0.5) * lonStep; + var maxLon = (Mathf.Round((meridianLon + proximityThreshold) / lonStep) - 0.5) * lonStep; - var meridianVals = string.Join(",", _minorMeridianLongitudes); - Log.Debug($"minor meridians for {interval} are {meridianVals}"); + for (var tileLon = minLon; tileLon <= maxLon; tileLon += lonStep) + { + _minorMeridianPoints.Add(LatLon.FromCoords(lat, tileLon, precision)); + _minorMeridianPoints.Add(LatLon.FromCoords(-lat, tileLon, precision)); + _minorMeridianPoints.Add(LatLon.FromCoords(lat, -tileLon, precision)); + _minorMeridianPoints.Add(LatLon.FromCoords(-lat, -tileLon, precision)); + } + } + } } public string ActionSummary() diff --git a/SelectiveDecoration/SelectiveDecorationBuilder.cs b/SelectiveDecoration/SelectiveDecorationBuilder.cs index bfbb290..b2589ad 100644 --- a/SelectiveDecoration/SelectiveDecorationBuilder.cs +++ b/SelectiveDecoration/SelectiveDecorationBuilder.cs @@ -2,7 +2,7 @@ { public static class SelectiveDecorationBuilder { - public static readonly int POLE_LATITUDE_START = 85; + public static readonly float POLE_LATITUDE_START = 84.6f; public static SelectivePlanetPainter Build(ReformIndexInfoProvider reformIndexInfoProvider) { var result = new SelectivePlanetPainter(reformIndexInfoProvider); @@ -24,7 +24,7 @@ public static SelectivePlanetPainter Build(ReformIndexInfoProvider reformIndexIn if (PluginConfig.minorMeridianInterval.Value > 0) { - result.Register(new MinorMeridianPainter()); + result.Register(new MinorMeridianPainter(reformIndexInfoProvider)); } if (PluginConfig.addGuideLinesTropic.Value) diff --git a/SelectiveDecoration/SelectivePlanetPainter.cs b/SelectiveDecoration/SelectivePlanetPainter.cs index bcb3723..c75bb85 100644 --- a/SelectiveDecoration/SelectivePlanetPainter.cs +++ b/SelectiveDecoration/SelectivePlanetPainter.cs @@ -35,7 +35,6 @@ public void Decorate() var reformCount = platformSystem.maxReformCount; var setModIndexes = new HashSet(); var consumedFoundation = 0; - var foundationUsedUp = false; for (var index = 0; index < reformCount; ++index) { var latLon = _reformIndexInfoProvider.GetForIndex(index); @@ -52,7 +51,7 @@ public void Decorate() var decoration = DecoratorForLocation(latLon); if (decoration.IsNone()) continue; - + if (PluginConfig.guideLinesOnly.Value) { // probably need some flattening action @@ -90,7 +89,7 @@ public void Decorate() } for (int index = 0; index < platformSystem.planet.dirtyFlags.Length; ++index) platformSystem.planet.dirtyFlags[index] = true; - platformSystem.planet.landPercentDirty =true; + platformSystem.planet.landPercentDirtyFlag = true; if (platformSystem.planet.UpdateDirtyMeshes()) platformSystem.planet.factory.RenderLocalPlanetHeightmap(); } @@ -158,24 +157,24 @@ public SelectivePlanetPainter Flatten() GameMain.localPlanet.AddHeightMapModLevel(index, 3); continue; } - + if (PluginConfig.LatitudeOutOfBounds(latLonForModIndex.Lat)) { continue; } - + if (!ShouldPave(latLonForModIndex)) { continue; } - + GameMain.localPlanet.AddHeightMapModLevel(index, 3); } bool[] dirtyFlags = GameMain.localPlanet.dirtyFlags; int length2 = dirtyFlags.Length; for (int index = 0; index < length2; ++index) dirtyFlags[index] = true; - GameMain.localPlanet.landPercentDirty = true; + GameMain.localPlanet.landPercentDirtyFlag = true; if (GameMain.localPlanet.UpdateDirtyMeshes()) GameMain.localPlanet.factory.RenderLocalPlanetHeightmap(); @@ -190,42 +189,42 @@ private bool ShouldPave(LatLon latLon) { return true; } - + if (!DecoratorForLocation(latLon.Offset(-1, -1)).IsNone()) { return true; } - + if (!DecoratorForLocation(latLon.Offset(-1, 0)).IsNone()) { return true; } - + if (!DecoratorForLocation(latLon.Offset(-1, 1)).IsNone()) { return true; } - + if (!DecoratorForLocation(latLon.Offset(0, -1)).IsNone()) { return true; } - + if (!DecoratorForLocation(latLon.Offset(0, 1)).IsNone()) { return true; } - + if (!DecoratorForLocation(latLon.Offset(1, -1)).IsNone()) { return true; } - + if (!DecoratorForLocation(latLon.Offset(1, 0)).IsNone()) { return true; } - + if (!DecoratorForLocation(latLon.Offset(1, 1)).IsNone()) { return true; diff --git a/StorageSystemManager.cs b/StorageSystemManager.cs index 4d0a79a..bd39fb9 100644 --- a/StorageSystemManager.cs +++ b/StorageSystemManager.cs @@ -5,7 +5,6 @@ namespace Bulldozer /// Helps finding items on local planet from player, storage boxes and logistics stations public class StorageSystemManager { - private static StorageSystemManager _instance; private readonly PlanetFactory _factory; private readonly Player _player; @@ -88,7 +87,9 @@ private int DoRemove(int itemId, int count) return count; removed += removedFromLocation; (removedFromLocation, successful) = RemoveFromStations(itemId, count - removed); - return removed + removedFromLocation; + if (successful) + return removed + removedFromLocation; + return 0; } private (int, bool successful) RemoveFromStorage(int itemId, int count) diff --git a/WreckingBall.cs b/WreckingBall.cs index 9d77e9a..c5b218a 100644 --- a/WreckingBall.cs +++ b/WreckingBall.cs @@ -162,7 +162,7 @@ private void RemoveBuild(int objId) if (objId > 0) { - _player.factory.RemoveEntityWithComponents(objId); + _player.factory.RemoveEntityWithComponents(objId, true); } else if (objId < 0) {