diff --git a/About/About.xml b/About/About.xml index 71a418a..1911fd5 100644 --- a/About/About.xml +++ b/About/About.xml @@ -1,40 +1,32 @@ - Backup Power - Fluffy - -
  • 1.2
  • -
    - add control units to generators to automatically switch them on and off when needed - -<size=24>Features</size> -Adds generator control boxes, which will automatically turn the generators they are attached to on and off depending on current power levels. - -Control boxes can be built after researching <i>Backup Power</i>, a follow-up to <i>Microelectronics</i>. Once researched, build a power control box on top of any generator to have it automatically toggled on/off depending on the electrical grid’s supply and demand. + Backup Power + Fluffy + Fluffy.BackupPower + add control units to generators to automatically switch them on and off when needed -Should work on any power generator that has the ‘flickable’ tag, so any vanilla or modded power producer that can be toggled on and off. - -Control boxes have an indicator light that can take three colours: +<size=28>Features</size> +Adds generator control boxes, which will automatically turn the generators they are attached to on and off depending on current power levels. -blue: control box is in standby, the generator is not currently needed. -green: control box is active, the generator is running. -red: control box error, the generator can not run. +Control boxes can be built after researching <i>Backup Power</i>, a follow-up to <i>Microelectronics</i>. Once researched, build a power control box on top of any generator to have it automatically toggled on/off depending on the electrical grid's supply and demand. -<size=24>Known Issues</size> -None (yet). +Should work on any power generator that has the 'flickable' tag, so any vanilla or modded power producer that can be toggled on and off. -<size=24>Contributors</size> +Control boxes have an indicator light that can take three colours: -Cenbes: Control box texture +- blue: control box is in standby, the generator is not currently needed. +- green: control box is active, the generator is running. +- red: control box error, the generator can not run. -<size=24>Version</size> -This is version 1.10.180, for RimWorld 1.2.2753. +<size=28>Known Issues</size> - - https://ludeon.com/forums/index.php?topic=16120 - fluffy.backuppower - -
  • Ludeon.RimWorld
  • -
    +None (yet).
    + https://github.com/fluffy-mods/BackupPower + +
  • 1.3
  • +
    + +
  • Ludeon.RimWorld
  • +
    \ No newline at end of file diff --git a/About/Preview.png b/About/Preview.png index 965e204..6f7cb6a 100644 Binary files a/About/Preview.png and b/About/Preview.png differ diff --git a/About/dependencies.json b/About/dependencies.json deleted file mode 100644 index 3cdba8e..0000000 --- a/About/dependencies.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "after": [ - "Ludeon.RimWorld" - ] -} \ No newline at end of file diff --git a/Assemblies/BackupPower.dll b/Assemblies/BackupPower.dll index cc7e717..a8d630c 100644 Binary files a/Assemblies/BackupPower.dll and b/Assemblies/BackupPower.dll differ diff --git a/Readme.md b/Readme.md index 8c2162c..6efbe4d 100644 --- a/Readme.md +++ b/Readme.md @@ -1,10 +1,9 @@ -[![RimWorld 1.2](https://img.shields.io/badge/RimWorld-1.2-brightgreen.svg)](http://rimworldgame.com/) - add control units to generators to automatically switch them on and off when needed ![Features](https://banners.karel-kroeze.nl/title/Features.png) Adds generator control boxes, which will automatically turn the generators they are attached to on and off depending on current power levels. -![Power Control Box](https://i.imgur.com/kQtPswV.gif) +![Power Control Box](https://i.imgur.com/kQtPswV.gif) + Control boxes can be built after researching _Backup Power_, a follow-up to _Microelectronics_. Once researched, build a power control box on top of any generator to have it automatically toggled on/off depending on the electrical grid's supply and demand. Should work on any power generator that has the 'flickable' tag, so any vanilla or modded power producer that can be toggled on and off. @@ -17,32 +16,37 @@ Control boxes have an indicator light that can take three colours: ![Known Issues](https://banners.karel-kroeze.nl/title/Known%20Issues.png) None (yet). +![Contributors](https://banners.karel-kroeze.nl/title/Contributors.png) +Juijote: [Simplified Chinese translation](https://github.com/fluffy-mods/BackupPower/commit/15d661c) -![Contributors](https://banners.karel-kroeze.nl/title/Contributors.png) - - Cenbes: Control box texture ![Think you found a bug?](https://banners.karel-kroeze.nl/title/Think%20you%20found%20a%20bug%3F.png) + Please read [this guide](http://steamcommunity.com/sharedfiles/filedetails/?id=725234314) before creating a bug report, and then create a bug report [here](https://github.com/fluffy-mods/BackupPower/issues) ![Older versions](https://banners.karel-kroeze.nl/title/Older%20versions.png) + All current and past versions of this mod can be downloaded from [GitHub](https://github.com/fluffy-mods/BackupPower/releases). ![License](https://banners.karel-kroeze.nl/title/License.png) + All original code in this mod is licensed under the [MIT license](https://opensource.org/licenses/MIT). Do what you want, but give me credit. All original content (e.g. text, imagery, sounds) in this mod is licensed under the [CC-BY-SA 4.0 license](http://creativecommons.org/licenses/by-sa/4.0/). -Parts of the code in this mod, and some content may be licensed by their original authors. If this is the case, the original author & license will either be given in the source code, or be in a LICENSE file next to the content. Please do not decompile my mods, but use the original source code available on [GitHub](https://github.com/fluffy-mods/BackupPower/), so license information in the source code is preserved. +Parts of the code in this mod, and some of the content may be licensed by their original authors. If this is the case, the original author & license will either be given in the source code, or be in a LICENSE file next to the content. Please do not decompile my mods, but use the original source code available on [GitHub](https://github.com/fluffy-mods/BackupPower/), so license information in the source code is preserved. + +Parts of this mod were created by, or derived from works created by; +- Freepik: power button preview icon ([BY-NC](https://www.freepik.com/)) +- Pixel Perfect: thunder preview icon ([BY-NC](https://icon54.com/)) -[![Supporters](https://banners.karel-kroeze.nl/donations.png)](https://ko-fi.com/fluffymods) ![Are you enjoying my mods?](https://banners.karel-kroeze.nl/title/Are%20you%20enjoying%20my%20mods%3F.png) -Become a supporter and show your appreciation by buying me a coffee (or contribute towards a nice single malt). -[![Buy Me a Coffee](http://i.imgur.com/EjWiUwx.gif)](https://ko-fi.com/fluffymods) +Become a supporter and show your appreciation by buying me a coffee (or contribute towards a nice single malt). -[![I Have a Black Dog](https://i.ibb.co/ss59Rwy/New-Project-2.png)](https://www.youtube.com/watch?v=XiCrniLQGYc) +[![Supporters](https://banners.karel-kroeze.nl/donations.png)](https://ko-fi.com/fluffymods) +[![Buy Me a Coffee](https://i.imgur.com/6P7Ap79.gif)](https://ko-fi.com/fluffymods) -![Version](https://banners.karel-kroeze.nl/title/Version.png) -This is version 1.10.180, for RimWorld 1.2.2753. \ No newline at end of file +[![I Have a Black Dog](https://i.ibb.co/ss59Rwy/New-Project-2.png)](https://www.youtube.com/watch?v=XiCrniLQGYc) diff --git a/Source/BackupPower.cs b/Source/BackupPower.cs index 56837a7..732144d 100644 --- a/Source/BackupPower.cs +++ b/Source/BackupPower.cs @@ -1,30 +1,25 @@ -// BackupPower.cs +// BackupPower.cs // Copyright Karel Kroeze, 2020-2020 using UnityEngine; using Verse; -namespace BackupPower -{ - public class BackupPower : Mod - { - public BackupPower( ModContentPack content ) : base( content ) - { +namespace BackupPower { + public class BackupPower: Mod { + public BackupPower(ModContentPack content) : base(content) { // initialize settings Settings = GetSettings(); } public static Settings Settings { get; private set; } - public override void DoSettingsWindowContents( Rect inRect ) - { - base.DoSettingsWindowContents( inRect ); - GetSettings().DoWindowContents( inRect ); + public override void DoSettingsWindowContents(Rect inRect) { + base.DoSettingsWindowContents(inRect); + GetSettings().DoWindowContents(inRect); } - public override string SettingsCategory() - { + public override string SettingsCategory() { return I18n.BackupPower; } } -} \ No newline at end of file +} diff --git a/Source/BackupPower.csproj b/Source/BackupPower.csproj index 2eb66c8..eafd73f 100644 --- a/Source/BackupPower.csproj +++ b/Source/BackupPower.csproj @@ -1,87 +1,16 @@ - - - - - Debug - AnyCPU - {D7D21B4A-1DA7-41D8-B202-C58CA8FA62AA} - Library - Properties - BackupPower - BackupPower - v4.7.2 - 512 - true - None - - - true - full - true - ..\Assemblies\ - DEBUG - prompt - 4 - true - false - 8 - - - pdbonly - true - ..\Assemblies\ - - - prompt - 4 - true - false - 8 - - - - C:\Program Files (x86)\Steam\steamapps\common\RimWorld\RimWorldWin64_Data\Managed\Assembly-CSharp.dll - False - - - - C:\Program Files (x86)\Steam\steamapps\common\RimWorld\RimWorldWin64_Data\Managed\UnityEngine.CoreModule.dll - False - - - C:\Program Files (x86)\Steam\steamapps\common\RimWorld\RimWorldWin64_Data\Managed\UnityEngine.IMGUIModule.dll - False - - - C:\Program Files (x86)\Steam\steamapps\common\RimWorld\RimWorldWin64_Data\Managed\UnityEngine.InputLegacyModule.dll - False - - - C:\Program Files (x86)\Steam\steamapps\common\RimWorld\RimWorldWin64_Data\Managed\UnityEngine.TextRenderingModule.dll - False - - - - - - - - - - - - - - - - - - - - - - - - mod update -x - - \ No newline at end of file + + + net472 + BackupPower + BackupPower + Copyright © 2020-2021 + true + ..\Assemblies\ + 8 + mod update + false + + + + + diff --git a/Source/Building_BackupPowerAttachment.cs b/Source/Building_BackupPowerAttachment.cs index 683033c..31a1b6f 100644 --- a/Source/Building_BackupPowerAttachment.cs +++ b/Source/Building_BackupPowerAttachment.cs @@ -1,4 +1,4 @@ -// Building_BackupPowerAttachment.cs +// Building_BackupPowerAttachment.cs // Copyright Karel Kroeze, 2020-2020 using System; @@ -7,17 +7,14 @@ using UnityEngine; using Verse; -namespace BackupPower -{ - public enum BackupPowerStatus - { +namespace BackupPower { + public enum BackupPowerStatus { Standby, Running, Error } - public class Building_BackupPowerAttachment : Building - { + public class Building_BackupPowerAttachment: Building { public FloatRange batteryRange = FloatRange.One; public bool runOnBatteriesOnly = true; private Command_BatteryRange _command_BatteryRange; @@ -26,134 +23,125 @@ public class Building_BackupPowerAttachment : Building private int _lastOnTick; private Color _prevColor; - public override Color DrawColor => Resources.StatusColor( Status ); - public CompFlickable Flickable => Parent?.FlickableComp(); + public override Color DrawColor => Resources.StatusColor(Status); + public CompFlickable Flickable => Parent?.FlickableComp(); public Building Parent { get; private set; } - public PowerNet PowerNet => Parent?.PowerComp?.PowerNet; + public PowerNet PowerNet => Parent?.PowerComp?.PowerNet; public CompPowerPlant PowerPlant => Parent?.PowerPlantComp(); - public BackupPowerStatus Status - { - get - { - if ( ( Parent?.BreakdownableComp()?.BrokenDown ?? false ) || - ( !Parent?.RefuelableComp()?.HasFuel ?? false ) ) + public BackupPowerStatus Status { + get { + if ((Parent?.BreakdownableComp()?.BrokenDown ?? false) || + (!Parent?.RefuelableComp()?.HasFuel ?? false)) { return BackupPowerStatus.Error; - if ( PowerPlant?.PowerOn ?? false ) + } + + if (PowerPlant?.PowerOn ?? false) { return BackupPowerStatus.Running; + } + return BackupPowerStatus.Standby; } } - public bool CanTurnOff() - { + public bool CanTurnOff() { return _lastOnTick + BackupPower.Settings.MinimumOnTime < Find.TickManager.TicksGame; } - public void CopySettingsTo( Building_BackupPowerAttachment other ) - { + public void CopySettingsTo(Building_BackupPowerAttachment other) { other.batteryRange = batteryRange; } - public override void Destroy( DestroyMode mode = DestroyMode.Vanish ) - { - try - { - MapComponent_PowerBroker.DeregisterBroker( this ); - } - catch ( Exception err ) - { - Verse.Log.Error( $"Error deregistering broker: {err}" ); + public override void Destroy(DestroyMode mode = DestroyMode.Vanish) { + try { + MapComponent_PowerBroker.DeregisterBroker(this); + } catch (Exception err) { + Verse.Log.Error($"Error deregistering broker: {err}"); } - base.Destroy( mode ); + base.Destroy(mode); } - public override void ExposeData() - { + public override void ExposeData() { base.ExposeData(); - Scribe_Values.Look( ref batteryRange, "batteryRange", FloatRange.One ); + Scribe_Values.Look(ref batteryRange, "batteryRange", FloatRange.One); Scribe_Values.Look(ref runOnBatteriesOnly, "runOnBatteriesOnly", true); } - public override IEnumerable GetGizmos() - { + public override IEnumerable GetGizmos() { yield return _command_BatteryRange; yield return _command_RunOnBatteriesOnly; - foreach ( var _gizmo in base.GetGizmos() ) + foreach (Gizmo _gizmo in base.GetGizmos()) { yield return _gizmo; + } } - public override string GetInspectString() - { - var desc = base.GetInspectString(); - return I18n.StatusString( Status, batteryRange.min, batteryRange.max, PowerNet.StorageLevel() ) + - ( desc.NullOrEmpty() ? "" : $"\n{desc}" ); + public override string GetInspectString() { + string desc = base.GetInspectString(); + return I18n.StatusString(Status, batteryRange.min, batteryRange.max, PowerNet.StorageLevel()) + + (desc.NullOrEmpty() ? "" : $"\n{desc}"); } - public override void Notify_ColorChanged() - { + public override void Notify_ColorChanged() { base.Notify_ColorChanged(); // again, for good measure. - Map.mapDrawer.MapMeshDirty( Position, MapMeshFlag.Things ); + Map.mapDrawer.MapMeshDirty(Position, MapMeshFlag.Things); _prevColor = DrawColor; } - public override void SpawnSetup( Map map, bool respawningAfterLoad ) - { - base.SpawnSetup( map, respawningAfterLoad ); - _command_BatteryRange = new Command_BatteryRange( this ); - _command_RunOnBatteriesOnly = new Command_Toggle() - { + public override void SpawnSetup(Map map, bool respawningAfterLoad) { + base.SpawnSetup(map, respawningAfterLoad); + _command_BatteryRange = new Command_BatteryRange(this); + _command_RunOnBatteriesOnly = new Command_Toggle() { icon = DefDatabase.GetNamed("Battery").uiIcon, - iconProportions = new Vector2( 2, 3 ), + iconProportions = new Vector2(2, 3), defaultLabel = I18n.RunOnBatteriesOnly_Label, defaultDesc = I18n.RunOnBatteriesOnly_Desc, isActive = () => runOnBatteriesOnly, toggleAction = () => runOnBatteriesOnly = !runOnBatteriesOnly }; - if ( !respawningAfterLoad ) - TryAttach( Map ); + if (!respawningAfterLoad) { + _ = TryAttach(Map); + } } - public override void Tick() - { - if ( this.IsHashIntervalTick( 60 ) && _prevColor != DrawColor ) + public override void Tick() { + if (this.IsHashIntervalTick(60) && _prevColor != DrawColor) { Notify_ColorChanged(); + } // TODO: think about refactoring this and hooking onto parents' Destroy() instead. base.Tick(); - if ( Parent.DestroyedOrNull() && !TryAttach( Map, true ) ) - { - Messages.Message( I18n.AttachmentDestroyedBecauseParentGone( Parent?.Label ?? I18n.Generator ), + if (Parent.DestroyedOrNull() && !TryAttach(Map, true)) { + Messages.Message(I18n.AttachmentDestroyedBecauseParentGone(Parent?.Label ?? I18n.Generator), MessageTypeDefOf.NegativeEvent, - false ); - Destroy( DestroyMode.Refund ); + false); + Destroy(DestroyMode.Refund); } } - public void TurnOff() - { - Flickable.Force( false ); + public void TurnOff() { + Flickable.Force(false); } - public void TurnOn() - { + public void TurnOn() { _lastOnTick = Find.TickManager.TicksGame; - Flickable.Force( true ); + Flickable.Force(true); } - private bool TryAttach( Map map, bool reAttach = false ) - { - Parent = Position.GetEdifice( map ); - var success = PowerPlant != null && Flickable != null; - if ( success ) MapComponent_PowerBroker.RegisterBroker( this, reAttach ); + private bool TryAttach(Map map, bool reAttach = false) { + Parent = Position.GetEdifice(map); + bool success = PowerPlant != null && Flickable != null; + if (success) { + MapComponent_PowerBroker.RegisterBroker(this, reAttach); + } + return success; } } -} \ No newline at end of file +} diff --git a/Source/Command_BatteryRange.cs b/Source/Command_BatteryRange.cs index d547f51..c7dd147 100644 --- a/Source/Command_BatteryRange.cs +++ b/Source/Command_BatteryRange.cs @@ -1,4 +1,4 @@ -// Command_BatteryRange.cs +// Command_BatteryRange.cs // Copyright Karel Kroeze, 2020-2020 using System.Collections.Generic; @@ -7,148 +7,135 @@ using UnityEngine; using Verse; -namespace BackupPower -{ - public class Command_BatteryRange : Command - { +namespace BackupPower { + public class Command_BatteryRange: Command { private readonly Building_BackupPowerAttachment parent; - public Command_BatteryRange( Building_BackupPowerAttachment parent ) - { + public Command_BatteryRange(Building_BackupPowerAttachment parent) { this.parent = parent; } public override string Desc => - I18n.StatusString( parent.Status, parent.batteryRange.min, - parent.batteryRange.max, parent.PowerNet.StorageLevel() ); + I18n.StatusString(parent.Status, parent.batteryRange.min, + parent.batteryRange.max, parent.PowerNet.StorageLevel()); public override string Label => I18n.CommandLabel; - public override GizmoResult GizmoOnGUI( Vector2 topLeft, float maxWidth ) - { + public override GizmoResult GizmoOnGUI(Vector2 topLeft, float maxWidth, GizmoRenderParms parms) { // setup - var width = GetWidth( maxWidth ); - var canvas = new Rect( topLeft, new Vector2( width, Height + 10 ) ); - var mouseOver = Mouse.IsOver( canvas ); + float width = GetWidth( maxWidth ); + Rect canvas = new Rect( topLeft, new Vector2( width, Height + 10 ) ); + bool mouseOver = Mouse.IsOver( canvas ); - Find.WindowStack.ImmediateWindow( 246685, canvas, WindowLayer.GameUI, () => - { + Find.WindowStack.ImmediateWindow(246685, canvas, WindowLayer.GameUI, () => { canvas = canvas.AtZero(); - var buttonRect = canvas.AtZero().TopPartPixels( Height ); + Rect buttonRect = canvas.AtZero().TopPartPixels( Height ); GUI.color = mouseOver ? Resources.blueish : Color.white; - Widgets.DrawAtlas( buttonRect, BGTexture ); + Widgets.DrawAtlas(buttonRect, BGTexture); GUI.color = Color.white; - TooltipHandler.TipRegion( buttonRect, () => Desc, 2338712 ); - if ( Mouse.IsOver( buttonRect ) && Input.GetMouseButtonDown( 1 ) ) - { - var options = new List + TooltipHandler.TipRegion(buttonRect, () => Desc, 2338712); + if (Mouse.IsOver(buttonRect) && Input.GetMouseButtonDown(1)) { + List options = new List { new FloatMenuOption( I18n.CopyTo_Room, CopyToRoom ), new FloatMenuOption( I18n.CopyTo_Connected, CopyToConnected ), new FloatMenuOption( I18n.CopyTo_All, CopyToAll ) }; - Find.WindowStack.Add( new FloatMenu( options, I18n.CopyTo ) ); + Find.WindowStack.Add(new FloatMenu(options, I18n.CopyTo)); } - var innerButtonRect = buttonRect.ContractedBy( 6 ); + Rect innerButtonRect = buttonRect.ContractedBy( 6 ); // sliders - var minSliderRect = innerButtonRect.LeftPart( .2f ); - var maxSliderRect = innerButtonRect.RightPart( .2f ); - var newMin = GUI.VerticalSlider( minSliderRect, parent.batteryRange.min, 1, 0 ); - var newMax = GUI.VerticalSlider( maxSliderRect, parent.batteryRange.max, 1, 0 ); + Rect minSliderRect = innerButtonRect.LeftPart( .2f ); + Rect maxSliderRect = innerButtonRect.RightPart( .2f ); + float newMin = GUI.VerticalSlider( minSliderRect, parent.batteryRange.min, 1, 0 ); + float newMax = GUI.VerticalSlider( maxSliderRect, parent.batteryRange.max, 1, 0 ); // enforce min < max to avoid flicker - if ( Mathf.Abs( newMin - parent.batteryRange.min ) > Mathf.Epsilon ) - { + if (Mathf.Abs(newMin - parent.batteryRange.min) > Mathf.Epsilon) { parent.batteryRange.min = newMin; - parent.batteryRange.max = Mathf.Max( parent.batteryRange.min, parent.batteryRange.max ); - } - else if ( Mathf.Abs( newMax - parent.batteryRange.max ) > Mathf.Epsilon ) - { + parent.batteryRange.max = Mathf.Max(parent.batteryRange.min, parent.batteryRange.max); + } else if (Mathf.Abs(newMax - parent.batteryRange.max) > Mathf.Epsilon) { parent.batteryRange.max = newMax; - parent.batteryRange.min = Mathf.Min( parent.batteryRange.min, parent.batteryRange.max ); + parent.batteryRange.min = Mathf.Min(parent.batteryRange.min, parent.batteryRange.max); } // battery GUI.color = Resources.whiteish; - var batteryRect = innerButtonRect.MiddlePart( .2f, .2f ).ContractedBy( 6f ); - GUI.DrawTexture( batteryRect, Resources.Battery ); + Rect batteryRect = innerButtonRect.MiddlePart( .2f, .2f ).ContractedBy( 6f ); + GUI.DrawTexture(batteryRect, Resources.Battery); - if ( parent.PowerNet?.batteryComps.Any() ?? false ) - { - var pct = parent.PowerNet.StorageLevel(); + if (parent.PowerNet?.batteryComps.Any() ?? false) { + float pct = parent.PowerNet.StorageLevel(); GUI.color = Resources.blueish; - GUI.DrawTextureWithTexCoords( batteryRect.BottomPart( pct ), Resources.Battery, - new Rect( 0, 0, 1, pct ) ); + GUI.DrawTextureWithTexCoords(batteryRect.BottomPart(pct), Resources.Battery, + new Rect(0, 0, 1, pct)); } // draw target lines - var minY = batteryRect.yMin + batteryRect.height * ( 1 - parent.batteryRange.min ); - var maxY = batteryRect.yMin + batteryRect.height * ( 1 - parent.batteryRange.max ); - Utilities.DrawLineDashed( new Vector2( batteryRect.xMin - 5, minY ), - new Vector2( batteryRect.xMin + batteryRect.width * 2 / 3f, minY ), - Resources.greenish, 2 ); - Utilities.DrawLineDashed( new Vector2( batteryRect.xMax + 5, maxY ), - new Vector2( batteryRect.xMin + batteryRect.width * 1 / 3f, maxY ), - Resources.reddish, 2 ); + float minY = batteryRect.yMin + (batteryRect.height * ( 1 - parent.batteryRange.min )); + float maxY = batteryRect.yMin + (batteryRect.height * ( 1 - parent.batteryRange.max )); + Utilities.DrawLineDashed(new Vector2(batteryRect.xMin - 5, minY), + new Vector2(batteryRect.xMin + (batteryRect.width * 2 / 3f), minY), + Resources.greenish, 2); + Utilities.DrawLineDashed(new Vector2(batteryRect.xMax + 5, maxY), + new Vector2(batteryRect.xMin + (batteryRect.width * 1 / 3f), maxY), + Resources.reddish, 2); GUI.color = Color.white; - var label = LabelCap; - if ( !label.NullOrEmpty() ) - { + string label = LabelCap; + if (!label.NullOrEmpty()) { Text.Font = GameFont.Tiny; - var height = Text.CalcHeight( label, canvas.width ); - var labelRect = new Rect( canvas.x, buttonRect.yMax - height + 12f, canvas.width, height ); - GUI.DrawTexture( labelRect, TexUI.GrayTextBG ); + float height = Text.CalcHeight( label, canvas.width ); + Rect labelRect = new Rect( canvas.x, buttonRect.yMax - height + 12f, canvas.width, height ); + GUI.DrawTexture(labelRect, TexUI.GrayTextBG); Text.Anchor = TextAnchor.UpperCenter; - Widgets.Label( labelRect, label ); - Text.Font = GameFont.Small; + Widgets.Label(labelRect, label); + Text.Font = GameFont.Small; Text.Anchor = TextAnchor.UpperLeft; } - }, false ); + }, false); return mouseOver - ? new GizmoResult( GizmoState.Mouseover ) - : new GizmoResult( GizmoState.Clear ); + ? new GizmoResult(GizmoState.Mouseover) + : new GizmoResult(GizmoState.Clear); } - private void CopyTo( IEnumerable brokers ) - { - if ( !brokers.EnumerableNullOrEmpty() ) - foreach ( var broker in brokers ) - parent.CopySettingsTo( broker ); + private void CopyTo(IEnumerable brokers) { + if (!brokers.EnumerableNullOrEmpty()) { + foreach (Building_BackupPowerAttachment broker in brokers) { + parent.CopySettingsTo(broker); + } + } } - private void CopyToAll() - { - var brokers = parent.Map.listerThings.ThingsOfDef( DefOf.BackupPower_Attachment ) + private void CopyToAll() { + IEnumerable brokers = parent.Map.listerThings.ThingsOfDef( DefOf.BackupPower_Attachment ) .Where( b => b.Faction == Faction.OfPlayer ) .OfType(); - CopyTo( brokers ); + CopyTo(brokers); } - private void CopyToConnected() - { - var brokers = parent.PowerNet.powerComps + private void CopyToConnected() { + IEnumerable brokers = parent.PowerNet.powerComps .SelectMany( cp => cp.parent.OccupiedRect() ) .SelectMany( c => c.GetThingList( parent.Map ) ) .Where( b => b.Faction == Faction.OfPlayer ) .OfType() .Distinct(); - CopyTo( brokers ); + CopyTo(brokers); } - private void CopyToRoom() - { - var brokers = parent.GetRoom()? + private void CopyToRoom() { + IEnumerable brokers = parent.GetRoom()? .ContainedThings( DefOf.BackupPower_Attachment ) .OfType() .Where( b => b.Faction == Faction.OfPlayer ); - CopyTo( brokers ); + CopyTo(brokers); } } -} \ No newline at end of file +} diff --git a/Source/DebugLog.cs b/Source/DebugLog.cs index 9218868..33129b6 100644 --- a/Source/DebugLog.cs +++ b/Source/DebugLog.cs @@ -1,21 +1,17 @@ -// DebugLog.cs +// DebugLog.cs // Copyright Karel Kroeze, 2020-2020 using System.Diagnostics; -namespace BackupPower -{ - internal static class Log - { - [Conditional( "DEBUG" )] - public static void Debug( string msg ) - { - Message( msg ); +namespace BackupPower { + internal static class Log { + [Conditional("DEBUG")] + public static void Debug(string msg) { + Message(msg); } - public static void Message( string msg ) - { - Verse.Log.Message( $"BackupPower :: {msg}" ); + public static void Message(string msg) { + Verse.Log.Message($"BackupPower :: {msg}"); } } -} \ No newline at end of file +} diff --git a/Source/I18n.cs b/Source/I18n.cs index be1023a..682d524 100644 --- a/Source/I18n.cs +++ b/Source/I18n.cs @@ -4,10 +4,8 @@ using UnityEngine; using Verse; -namespace BackupPower -{ - public static class I18n - { +namespace BackupPower { + public static class I18n { public static string BackupPower = "Fluffy.BackupPower".Translate(); public static string PlaceWorker_PlaceOnPowerPlant = Translate( "PlaceWorker.PlaceOnPowerPlant" ); public static string PlaceWorker_PlaceOnFlickable = Translate( "PlaceWorker.PlaceOnFlickable" ); @@ -23,70 +21,58 @@ public static class I18n public static string CopyTo_All = Translate( "CopyTo.All" ); - public static string AttachmentDestroyedBecauseParentGone( string label ) - { - return Translate( "AttachmentDestroyedBecauseParentGone", label ); + public static string AttachmentDestroyedBecauseParentGone(string label) { + return Translate("AttachmentDestroyedBecauseParentGone", label); } - public static string CurrentStatus( BackupPowerStatus status ) - { - return Translate( "CurrentStatus", StatusLabel( status ).Colorize( Resources.StatusColor( status ) ) ); + public static string CurrentStatus(BackupPowerStatus status) { + return Translate("CurrentStatus", StatusLabel(status).Colorize(Resources.StatusColor(status))); } - public static string CurrentStorage( float cur ) - { - return Translate( "CurrentStorage", cur.ToStringPercent().Colorize( Color.white ) ); + public static string CurrentStorage(float cur) { + return Translate("CurrentStorage", cur.ToStringPercent().Colorize(Color.white)); } - public static string FormatSeconds( this float seconds ) - { - return seconds.ToString( "##.#'s'" ); + public static string FormatSeconds(this float seconds) { + return seconds.ToString("##.#'s'"); } - public static string Settings_MinimumOnTime( float value, float @default ) - { - return Translate( "Settings.MinimumOnTime", value.FormatSeconds(), @default.FormatSeconds() ); + public static string Settings_MinimumOnTime(float value, float @default) { + return Translate("Settings.MinimumOnTime", value.FormatSeconds(), @default.FormatSeconds()); } - public static string Settings_UpdateInterval( float value, float @default ) - { - return Translate( "Settings.UpdateInterval", value.FormatSeconds(), @default.FormatSeconds() ); + public static string Settings_UpdateInterval(float value, float @default) { + return Translate("Settings.UpdateInterval", value.FormatSeconds(), @default.FormatSeconds()); } - public static string StatusLabel( BackupPowerStatus status ) - { - return Translate( $"Status.{status}" ); + public static string StatusLabel(BackupPowerStatus status) { + return Translate($"Status.{status}"); } - public static string StatusString( BackupPowerStatus status, float min, float max, float cur ) - { - return CurrentStatus( status ) + "\n" + - CurrentStorage( cur ).Colorize( Color.grey ) + "\n" + - TurnsOnAt( min ).Colorize( Color.grey ) + "\n" + - TurnsOffAt( max ).Colorize( Color.grey ); + public static string StatusString(BackupPowerStatus status, float min, float max, float cur) { + return CurrentStatus(status) + "\n" + + CurrentStorage(cur).Colorize(Color.grey) + "\n" + + TurnsOnAt(min).Colorize(Color.grey) + "\n" + + TurnsOffAt(max).Colorize(Color.grey); } - public static string TurnsOffAt( float value ) - { - return Translate( "TurnsOffAbove", value.ToStringPercent().Colorize( Resources.reddish ) ); + public static string TurnsOffAt(float value) { + return Translate("TurnsOffAbove", value.ToStringPercent().Colorize(Resources.reddish)); } - public static string TurnsOnAt( float value ) - { - return Translate( "TurnsOnBelow", value.ToStringPercent().Colorize( Resources.greenish ) ); + public static string TurnsOnAt(float value) { + return Translate("TurnsOnBelow", value.ToStringPercent().Colorize(Resources.greenish)); } public static string RunOnBatteriesOnly_Label = Translate("RunOnBatteriesOnly.Label"); public static string RunOnBatteriesOnly_Desc = Translate("RunOnBatteriesOnly.Desc"); - private static string Key( string key ) - { + private static string Key(string key) { return $"Fluffy.BackupPower.{key}"; } - private static string Translate( string key, params NamedArgument[] args ) - { - return Key( key ).Translate( args ).Resolve(); + private static string Translate(string key, params NamedArgument[] args) { + return Key(key).Translate(args).Resolve(); } } -} \ No newline at end of file +} diff --git a/Source/MapComponent_PowerBroker.cs b/Source/MapComponent_PowerBroker.cs index 6e5f2f8..cd5607d 100644 --- a/Source/MapComponent_PowerBroker.cs +++ b/Source/MapComponent_PowerBroker.cs @@ -1,83 +1,79 @@ -// MapComponent_PowerBroker.cs +// MapComponent_PowerBroker.cs // Copyright Karel Kroeze, 2020-2020 using System; using System.Collections.Generic; using System.Linq; -using System.Text; using JetBrains.Annotations; using RimWorld; using UnityEngine; using Verse; -namespace BackupPower -{ - public class MapComponent_PowerBroker : MapComponent - { +namespace BackupPower { + public class MapComponent_PowerBroker: MapComponent { public HashSet brokers = new HashSet(); - public MapComponent_PowerBroker( Map map ) : base( map ) - { + public MapComponent_PowerBroker(Map map) : base(map) { } - public static void DeregisterBroker( [NotNull] Building_BackupPowerAttachment broker ) - { - For( broker.Map ).brokers.RemoveSafe( broker ); + public static void DeregisterBroker([NotNull] Building_BackupPowerAttachment broker) { + For(broker.Map).brokers.RemoveSafe(broker); } - public static MapComponent_PowerBroker For( [NotNull] Map map ) - { + public static MapComponent_PowerBroker For([NotNull] Map map) { return map?.GetComponent(); } - public static void RegisterBroker( [NotNull] Building_BackupPowerAttachment broker, bool update = false ) - { - var comp = For( broker.Map ); - if ( update ) comp.brokers.Remove( broker ); - comp.brokers.AddSafe( broker ); + public static void RegisterBroker([NotNull] Building_BackupPowerAttachment broker, bool update = false) { + MapComponent_PowerBroker comp = For( broker.Map ); + if (update) { + _ = comp.brokers.Remove(broker); + } + + comp.brokers.AddSafe(broker); } - public float Consumption( CompPowerTrader comp ) - { - if ( !comp.PowerOn && !FlickUtility.WantsToBeOn( comp.parent ) ) + public float Consumption(CompPowerTrader comp) { + if (!comp.PowerOn && !FlickUtility.WantsToBeOn(comp.parent)) { return 0; + } - return Mathf.Max( -comp.PowerOutput, 0f ); + return Mathf.Max(-comp.PowerOutput, 0f); } - public float CurrentProduction( CompPowerTrader comp ) - { - if ( !( comp is CompPowerPlant plant ) ) + public float CurrentProduction(CompPowerTrader comp) { + if (!(comp is CompPowerPlant plant)) { return 0; + } - if ( !plant.PowerOn ) + if (!plant.PowerOn) { return 0; + } - return Mathf.Max( plant.PowerOutput, 0 ); + return Mathf.Max(plant.PowerOutput, 0); } - public override void MapComponentTick() - { + public override void MapComponentTick() { base.MapComponentTick(); - if ( Find.TickManager.TicksGame % BackupPower.Settings.UpdateInterval != 0 ) + if (Find.TickManager.TicksGame % BackupPower.Settings.UpdateInterval != 0) { return; + } - foreach ( var group in brokers.Where( b => b.PowerNet != null ) - .GroupBy( b => b.PowerNet ) ) - PowerNetUpdate( group.Key, new HashSet( group ) ); + foreach (IGrouping group in brokers.Where(b => b.PowerNet != null) + .GroupBy(b => b.PowerNet)) { + PowerNetUpdate(group.Key, new HashSet(group)); + } } - public float PotentialProduction( CompPowerTrader comp ) - { + public float PotentialProduction(CompPowerTrader comp) { #if DEBUG - var _plant = comp as CompPowerPlant; - var _refuelable = _plant?.parent.RefuelableComp(); - var _breakdownable = _plant?.parent.BreakdownableComp(); + CompPowerPlant _plant = comp as CompPowerPlant; + CompRefuelable _refuelable = _plant?.parent.RefuelableComp(); + CompBreakdownable _breakdownable = _plant?.parent.BreakdownableComp(); - var msg = comp.parent.def.defName; + string msg = comp.parent.def.defName; msg += $"\n\tpowerplant: {_plant != null}"; - if ( _plant != null ) - { + if (_plant != null) { msg += $"\n\trefuelable: {_refuelable != null}"; msg += $"\n\tfueled: {_refuelable?.HasFuel}"; msg += $"\n\tbreakdownable: {_breakdownable != null}"; @@ -86,28 +82,30 @@ public float PotentialProduction( CompPowerTrader comp ) msg += $"\n\tcurrent: {_plant.PowerOutput}"; } - Log.Message( msg ); + Log.Message(msg); #endif - if ( !( comp is CompPowerPlant plant ) ) + if (!(comp is CompPowerPlant plant)) { return 0; + } - var refuelable = plant.parent.RefuelableComp(); - if ( refuelable != null && !refuelable.HasFuel ) + CompRefuelable refuelable = plant.parent.RefuelableComp(); + if (refuelable != null && !refuelable.HasFuel) { return 0; + } - var breakdownable = plant.parent.BreakdownableComp(); - if ( breakdownable != null && breakdownable.BrokenDown ) + CompBreakdownable breakdownable = plant.parent.BreakdownableComp(); + if (breakdownable != null && breakdownable.BrokenDown) { return 0; + } // TODO: check how this interacts with variable power output buildings, e.g. solar, wind. - return Mathf.Max( plant.DesiredOutput(), plant.PowerOutput, 0 ); + return Mathf.Max(plant.DesiredOutput(), plant.PowerOutput, 0); } - public void PowerNetUpdate( PowerNet net, HashSet brokers ) - { + public void PowerNetUpdate(PowerNet net, HashSet brokers) { // get desired power - var users = net.powerComps + IEnumerable<(CompPowerTrader comp, Building_BackupPowerAttachment broker, float consumption, float currentProduction, float potentialProduction)> users = net.powerComps .Select( p => ( comp: p, broker: p.parent is Building building ? brokers.FirstOrDefault( b => b.Parent == building ) @@ -116,39 +114,39 @@ public void PowerNetUpdate( PowerNet net, HashSet u.consumption ); - var production = users.Sum( u => u.currentProduction ); - var hasStorage = net.HasStorage(); - var storageLevel = net.StorageLevel(); + float need = users.Sum( u => u.consumption ); + float production = users.Sum( u => u.currentProduction ); + bool hasStorage = net.HasStorage(); + float storageLevel = net.StorageLevel(); // Log.Debug( $"need: {need}, production: {production}, static: {staticProduction}" ); - if ( production > need || hasStorage && storageLevel > 0 ) - { + if (production > need || hasStorage && storageLevel > 0) { // try to shut backups off - var backups = users.Where( u => u.broker != null + List<(CompPowerTrader comp, Building_BackupPowerAttachment broker, float consumption, float currentProduction, float potentialProduction)> backups = users.Where( u => u.broker != null && u.currentProduction > 0 && ( u.currentProduction <= ( production - need ) || u.broker.runOnBatteriesOnly ) && ( ( !hasStorage && !u.broker.runOnBatteriesOnly ) || storageLevel >= u.broker.batteryRange.max ) && u.broker.CanTurnOff() ) .ToList(); - if ( backups.TryRandomElementByWeight( c => 1 / c.currentProduction, out var backup ) ) + if (backups.TryRandomElementByWeight(c => 1 / c.currentProduction, out (CompPowerTrader comp, Building_BackupPowerAttachment broker, float consumption, float currentProduction, float potentialProduction) backup)) { backup.broker.TurnOff(); + } } - if ( production < need || hasStorage && storageLevel < 1 ) - { + if (production < need || hasStorage && storageLevel < 1) { // try to turn backups on - var backups = users.Where( u => u.broker != null + List<(CompPowerTrader comp, Building_BackupPowerAttachment broker, float consumption, float currentProduction, float potentialProduction)> backups = users.Where( u => u.broker != null && Math.Abs( u.currentProduction ) < Mathf.Epsilon && u.potentialProduction > 0 && ( !hasStorage || storageLevel <= u.broker.batteryRange.min ) ) .ToList(); - if ( backups.TryRandomElementByWeight( c => c.potentialProduction, out var backup ) ) + if (backups.TryRandomElementByWeight(c => c.potentialProduction, out (CompPowerTrader comp, Building_BackupPowerAttachment broker, float consumption, float currentProduction, float potentialProduction) backup)) { backup.broker.TurnOn(); + } } } } -} \ No newline at end of file +} diff --git a/Source/ModConfig.json b/Source/ModConfig.json deleted file mode 100644 index 3a1255e..0000000 --- a/Source/ModConfig.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "Backup Power", - "version": { - "major": 1, - "minor": 10, - "build": 180 - }, - "git_user": "fluffy-mods", - "git_repo": "BackupPower", - "visibility": 0, - "packageId": "fluffy.backuppower", - "changenote": "", - "changenotes": [ - { - "repo": "BackupPower", - "hash": "6598d015574b2eba15b3a4f7b1598c1fede12a63", - "date": "2020-12-08 19:12", - "author": "Fluffy", - "message": "Release 1.10.179 [nolog]" - } - ], - "contributors": { - "Cenbes": "Control box texture" - }, - "tags": [ - "1.1", - "1.2" - ], - "publishedfileid": "2084493662" -} \ No newline at end of file diff --git a/Source/PlaceWorker_OnFlickablePowerPlant.cs b/Source/PlaceWorker_OnFlickablePowerPlant.cs index 415b4be..95cbb08 100644 --- a/Source/PlaceWorker_OnFlickablePowerPlant.cs +++ b/Source/PlaceWorker_OnFlickablePowerPlant.cs @@ -1,25 +1,28 @@ -// PlaceWorker_OnFlickablePowerPlant.cs +// PlaceWorker_OnFlickablePowerPlant.cs // Copyright Karel Kroeze, 2020-2020 using System.Linq; using Verse; -namespace BackupPower -{ - public class PlaceWorker_OnFlickablePowerPlant : PlaceWorker - { - public override AcceptanceReport AllowsPlacing( BuildableDef checkingDef, IntVec3 loc, Rot4 rot, Map map, - Thing thingToIgnore = null, Thing thing = null ) - { +namespace BackupPower { + public class PlaceWorker_OnFlickablePowerPlant: PlaceWorker { + public override AcceptanceReport AllowsPlacing(BuildableDef checkingDef, IntVec3 loc, Rot4 rot, Map map, + Thing thingToIgnore = null, Thing thing = null) { // there's a power plant or battery here. - var edifice = loc.GetEdifice( map ); - if ( edifice?.PowerPlantComp() == null ) + Building edifice = loc.GetEdifice( map ); + if (edifice?.PowerPlantComp() == null) { return I18n.PlaceWorker_PlaceOnPowerPlant; - if ( edifice.FlickableComp() == null ) + } + + if (edifice.FlickableComp() == null) { return I18n.PlaceWorker_PlaceOnFlickable; - if ( edifice.OccupiedRect().Any( c => c.GetFirstThing( map ) != null ) ) + } + + if (edifice.OccupiedRect().Any(c => c.GetFirstThing(map) != null)) { return I18n.PlaceWorker_OnlyOneAttachmentAllowed; + } + return true; } } -} \ No newline at end of file +} diff --git a/Source/Properties/AssemblyInfo.cs b/Source/Properties/AssemblyInfo.cs deleted file mode 100644 index dcde9df..0000000 --- a/Source/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,38 +0,0 @@ -// AssemblyInfo.cs -// Copyright Karel Kroeze, 2020-2020 - -using System.Reflection; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle( "BackupPower" )] -[assembly: AssemblyDescription( "" )] -[assembly: AssemblyConfiguration( "" )] -[assembly: AssemblyCompany( "" )] -[assembly: AssemblyProduct( "BackupPower" )] -[assembly: AssemblyCopyright( "Copyright © 2020" )] -[assembly: AssemblyTrademark( "Fluffy" )] -[assembly: AssemblyCulture( "" )] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible( false )] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid( "d7d21b4a-1da7-41d8-b202-c58ca8fa62aa" )] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0")] -[assembly: AssemblyFileVersion("1.10.180")] diff --git a/Source/Resources.cs b/Source/Resources.cs index 634ef1e..4bf9fcd 100644 --- a/Source/Resources.cs +++ b/Source/Resources.cs @@ -1,15 +1,13 @@ -// Resources.cs +// Resources.cs // Copyright Karel Kroeze, 2020-2020 using System; using UnityEngine; using Verse; -namespace BackupPower -{ +namespace BackupPower { [StaticConstructorOnStartup] - public static class Resources - { + public static class Resources { public static Texture2D BackupPowerAttachment; public static Texture2D Battery; @@ -18,25 +16,18 @@ public static class Resources public static Color reddish = new Color( .6667f, .2157f, .2275f ); public static Color whiteish = new Color( 1f, 1f, 1f, .3f ); - static Resources() - { - Battery = ContentFinder.Get( "UI/Battery" ); - BackupPowerAttachment = ContentFinder.Get( "BackupPowerAttachment" ); + static Resources() { + Battery = ContentFinder.Get("UI/Battery"); + BackupPowerAttachment = ContentFinder.Get("BackupPowerAttachment"); } - public static Color StatusColor( BackupPowerStatus status ) - { - switch ( status ) - { - case BackupPowerStatus.Standby: - return blueish; - case BackupPowerStatus.Running: - return greenish; - case BackupPowerStatus.Error: - return reddish; - default: - throw new ArgumentOutOfRangeException(); - } + public static Color StatusColor(BackupPowerStatus status) { + return status switch { + BackupPowerStatus.Standby => blueish, + BackupPowerStatus.Running => greenish, + BackupPowerStatus.Error => reddish, + _ => throw new ArgumentOutOfRangeException(), + }; } } -} \ No newline at end of file +} diff --git a/Source/Settings.cs b/Source/Settings.cs index 987b4f5..6aa28cf 100644 --- a/Source/Settings.cs +++ b/Source/Settings.cs @@ -1,36 +1,32 @@ -// Settings.cs +// Settings.cs // Copyright Karel Kroeze, 2020-2020 using UnityEngine; using Verse; -namespace BackupPower -{ - public class Settings : ModSettings - { +namespace BackupPower { + public class Settings: ModSettings { public int MinimumOnTime = GenTicks.TicksPerRealSecond * 10; public int UpdateInterval = GenTicks.TicksPerRealSecond; - public void DoWindowContents( Rect canvas ) - { - var options = new Listing_Standard(); - options.Begin( canvas ); - options.Label( I18n.Settings_UpdateInterval( (float) UpdateInterval / GenTicks.TicksPerRealSecond, 1f ), - tooltip: I18n.Settings_UpdateInterval_Tooltip ); - UpdateInterval = (int) options.Slider( (float) UpdateInterval / GenTicks.TicksPerRealSecond, 1, 60 ) * + public void DoWindowContents(Rect canvas) { + Listing_Standard options = new Listing_Standard(); + options.Begin(canvas); + _ = options.Label(I18n.Settings_UpdateInterval((float) UpdateInterval / GenTicks.TicksPerRealSecond, 1f), + tooltip: I18n.Settings_UpdateInterval_Tooltip); + UpdateInterval = (int) options.Slider((float) UpdateInterval / GenTicks.TicksPerRealSecond, 1, 60) * GenTicks.TicksPerRealSecond; - options.Label( I18n.Settings_MinimumOnTime( (float) MinimumOnTime / GenTicks.TicksPerRealSecond, 10 ), - tooltip: I18n.Settings_MinimumOnTime_Tooltip ); - MinimumOnTime = (int) options.Slider( (float) MinimumOnTime / GenTicks.TicksPerRealSecond, 0, 60 ) * + _ = options.Label(I18n.Settings_MinimumOnTime((float) MinimumOnTime / GenTicks.TicksPerRealSecond, 10), + tooltip: I18n.Settings_MinimumOnTime_Tooltip); + MinimumOnTime = (int) options.Slider((float) MinimumOnTime / GenTicks.TicksPerRealSecond, 0, 60) * GenTicks.TicksPerRealSecond; options.End(); } - public override void ExposeData() - { - Scribe_Values.Look( ref UpdateInterval, "updateInterval", GenTicks.TicksPerRealSecond ); - Scribe_Values.Look( ref MinimumOnTime, "minimumOnTime", GenTicks.TicksPerRealSecond * 10 ); + public override void ExposeData() { + Scribe_Values.Look(ref UpdateInterval, "updateInterval", GenTicks.TicksPerRealSecond); + Scribe_Values.Look(ref MinimumOnTime, "minimumOnTime", GenTicks.TicksPerRealSecond * 10); } } -} \ No newline at end of file +} diff --git a/Source/Utilities.cs b/Source/Utilities.cs index 18d6aa2..2a93dd9 100644 --- a/Source/Utilities.cs +++ b/Source/Utilities.cs @@ -1,4 +1,4 @@ -// Utilities.cs +// Utilities.cs // Copyright Karel Kroeze, 2020-2020 using System.Collections.Generic; @@ -9,10 +9,8 @@ using UnityEngine; using Verse; -namespace BackupPower -{ - public static class Utilities - { +namespace BackupPower { + public static class Utilities { private static readonly ConditionalWeakTable _breakdownables = new ConditionalWeakTable(); @@ -35,130 +33,135 @@ public static class Utilities private static readonly ConditionalWeakTable _refuelables = new ConditionalWeakTable(); - public static void AddSafe( this HashSet set, T item ) - { - if ( item == null ) - Verse.Log.ErrorOnce( "tried adding null element to hashset", 123411 ); - if ( set.Contains( item ) ) - Verse.Log.ErrorOnce( "tried adding duplicate item to hashset", 123412 ); - set.Add( item ); + public static void AddSafe(this HashSet set, T item) { + if (item == null) { + Verse.Log.ErrorOnce("tried adding null element to hashset", 123411); + } + + if (set.Contains(item)) { + Verse.Log.ErrorOnce("tried adding duplicate item to hashset", 123412); + } + + _ = set.Add(item); } - public static string Bold( this string msg ) - { + public static string Bold(this string msg) { return $"{msg}"; } - public static Vector2 BottomLeft( this Rect rect ) - { - return new Vector2( rect.xMin, rect.yMax ); + public static Vector2 BottomLeft(this Rect rect) { + return new Vector2(rect.xMin, rect.yMax); } - public static CompBreakdownable BreakdownableComp( this ThingWithComps parent ) - { - if ( _breakdownables.TryGetValue( parent, out var breakdownable ) ) + public static CompBreakdownable BreakdownableComp(this ThingWithComps parent) { + if (_breakdownables.TryGetValue(parent, out CompBreakdownable breakdownable)) { return breakdownable; + } + breakdownable = parent.GetComp(); - _breakdownables.Add( parent, breakdownable ); + _breakdownables.Add(parent, breakdownable); return breakdownable; } - public static float DesiredOutput( this CompPowerPlant plant ) - { - return (float) _desiredOutputGetter_MI.Invoke( plant, null ); + public static float DesiredOutput(this CompPowerPlant plant) { + return (float) _desiredOutputGetter_MI.Invoke(plant, null); } - public static void DrawLineDashed( Vector2 start, Vector2 end, Color? color = null, float size = 1, + public static void DrawLineDashed(Vector2 start, Vector2 end, Color? color = null, float size = 1, float stroke = 5, - float dash = 3 ) - { - var partLength = dash + stroke; - var totalLength = ( end - start ).magnitude; - var direction = ( end - start ).normalized; - var done = 0f; - while ( done < totalLength ) - { - var _start = start + done * direction; - var _end = start + Mathf.Min( done + stroke, totalLength ) * direction; - Widgets.DrawLine( _start, _end, color.GetValueOrDefault( Color.white ), size ); + float dash = 3) { + float partLength = dash + stroke; + float totalLength = ( end - start ).magnitude; + Vector2 direction = ( end - start ).normalized; + float done = 0f; + while (done < totalLength) { + Vector2 _start = start + (done * direction); + Vector2 _end = start + (Mathf.Min( done + stroke, totalLength ) * direction); + Widgets.DrawLine(_start, _end, color.GetValueOrDefault(Color.white), size); done += partLength; } } - public static CompFlickable FlickableComp( this ThingWithComps parent ) - { - if ( _flickables.TryGetValue( parent, out var flickable ) ) + public static CompFlickable FlickableComp(this ThingWithComps parent) { + if (_flickables.TryGetValue(parent, out CompFlickable flickable)) { return flickable; + } + flickable = parent.GetComp(); - _flickables.Add( parent, flickable ); + _flickables.Add(parent, flickable); return flickable; } - public static void Force( this CompFlickable flickable, bool mode ) - { - if ( mode != flickable.SwitchIsOn ) + public static void Force(this CompFlickable flickable, bool mode) { + if (mode != flickable.SwitchIsOn) { flickable.SwitchIsOn = mode; - if ( flickable.WantsFlick() ) - _flickable_wantSwitchOn_FI.SetValue( flickable, mode ); + } + + if (flickable.WantsFlick()) { + _flickable_wantSwitchOn_FI.SetValue(flickable, mode); + } } - public static bool HasStorage( this PowerNet net ) - { + public static bool HasStorage(this PowerNet net) { return !net.batteryComps.NullOrEmpty(); } - public static Rect MiddlePart( this Rect rect, float left = 0f, float right = 0f, float top = 0f, - float bottom = 0f ) - { - return new Rect( rect.xMin + rect.width * left, - rect.yMin + rect.height * top, - rect.width * ( 1 - left - right ), - rect.height * ( 1 - top - bottom ) ); + public static Rect MiddlePart(this Rect rect, float left = 0f, float right = 0f, float top = 0f, + float bottom = 0f) { + return new Rect(rect.xMin + (rect.width * left), + rect.yMin + (rect.height * top), + rect.width * (1 - left - right), + rect.height * (1 - top - bottom)); } - public static CompPowerPlant PowerPlantComp( this ThingWithComps parent ) - { - if ( _powerplants.TryGetValue( parent, out var powerplant ) ) + public static CompPowerPlant PowerPlantComp(this ThingWithComps parent) { + if (_powerplants.TryGetValue(parent, out CompPowerPlant powerplant)) { return powerplant; + } + powerplant = parent.GetComp(); - _powerplants.Add( parent, powerplant ); + _powerplants.Add(parent, powerplant); return powerplant; } - public static CompRefuelable RefuelableComp( this ThingWithComps parent ) - { - if ( _refuelables.TryGetValue( parent, out var refuelable ) ) + public static CompRefuelable RefuelableComp(this ThingWithComps parent) { + if (_refuelables.TryGetValue(parent, out CompRefuelable refuelable)) { return refuelable; + } + refuelable = parent.GetComp(); - _refuelables.Add( parent, refuelable ); + _refuelables.Add(parent, refuelable); return refuelable; } - public static void RemoveSafe( this HashSet set, T item ) - { - if ( item == null ) - Verse.Log.ErrorOnce( "tried removing null element from hashset", 123413 ); - if ( !set.Contains( item ) ) - Verse.Log.ErrorOnce( "tried removing item from hashset that it does not have", 123414 ); - set.Remove( item ); + public static void RemoveSafe(this HashSet set, T item) { + if (item == null) { + Verse.Log.ErrorOnce("tried removing null element from hashset", 123413); + } + + if (!set.Contains(item)) { + Verse.Log.ErrorOnce("tried removing item from hashset that it does not have", 123414); + } + + _ = set.Remove(item); } - public static float StorageLevel( this PowerNet net ) - { - if ( net == null || net.batteryComps.NullOrEmpty() ) return 0; - - var (current, max) = net.batteryComps - .Select( b => ( b.StoredEnergy, b.Props.storedEnergyMax ) ) - .Aggregate( ( a, b ) => ( - a.StoredEnergy + b.StoredEnergy, - a.storedEnergyMax + b.storedEnergyMax ) ); + public static float StorageLevel(this PowerNet net) { + if (net == null || net.batteryComps.NullOrEmpty()) { + return 0; + } + + (float current, float max) = net.batteryComps + .Select(b => (b.StoredEnergy, b.Props.storedEnergyMax)) + .Aggregate((a, b) => ( + a.StoredEnergy + b.StoredEnergy, + a.storedEnergyMax + b.storedEnergyMax)); return current / max; } } [RimWorld.DefOf] - public static class DefOf - { + public static class DefOf { public static ThingDef BackupPower_Attachment; } -} \ No newline at end of file +} diff --git a/modinfo.json b/modinfo.json new file mode 100644 index 0000000..e37cba1 --- /dev/null +++ b/modinfo.json @@ -0,0 +1,68 @@ +{ + "name": "Backup Power", + "sourceDir": ".", + "targetDir": "BackupPower", + "url": "https://github.com/fluffy-mods/BackupPower", + "version": { + "major": 2, + "minor": 0, + "build": 6 + }, + "author": { + "name": "Fluffy", + "url": "https://github.com/fluffy-mods/", + "email": "fluffy.l2032@gmail.com" + }, + "git": { + "owner": "fluffy-mods", + "repo": "BackupPower", + "url": "https://github.com/fluffy-mods/BackupPower" + }, + "changelog": [ + { + "date": "2021-06-03T06:12:08.000Z", + "message": "Create BackupPower.xml", + "author": { + "name": "Juijote", + "email": "22154581+Juijote@users.noreply.github.com" + }, + "hash": "15d661cc0de073db960d3a4fc49823b341307f03" + } + ], + "contributions": [ + { + "hash": "15d661cc0de073db960d3a4fc49823b341307f03", + "author": "Juijote", + "description": "Simplified Chinese translation" + } + ], + "contributors": { + "Juijote": [ + { + "hash": "15d661c", + "author": "Juijote", + "description": "Simplified Chinese translation" + } + ] + }, + "dependencies": [ + { + "type": "loadAfter", + "id": "Ludeon.RimWorld" + } + ], + "attributions": [ + { + "description": "power button preview icon", + "author": "Freepik", + "license": "BY-NC", + "url": "https://www.freepik.com/" + }, + { + "description": "thunder preview icon", + "author": "Pixel Perfect", + "license": "BY-NC", + "url": "https://icon54.com/" + } + ] +} \ No newline at end of file