SHARE
TWEET

Mining script improved by Terpla. Version TPMiningScript-201

a guest Aug 2nd, 2018 698 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Mining script improved by Terpla. Version TPMiningScript-2018-08-02v3
  2. Features:
  3.     - warp to bookmarks
  4.     - home stantion as bookmark
  5.     - launch drones in asteroid belt and scope them before warp
  6.     - activate shield booster if shield < 90%
  7.     new:
  8.     - now we can config our modules for better work ModuleMeasureAllTooltip
  9. */
  10.  
  11. /*
  12. This bot mines ore from asteroids and offloads the ore in a station.
  13.  
  14. Before running this bot, prepare the EVE online client as follows:
  15.  
  16. + Set the UI language to english.
  17. + Move your mining ship to a solar system which has asteroid belts and at least one station in which you can dock.
  18. + In the Overview, create a preset which includes asteroids and rats and enter the name of that preset in the configuration section below at 'OverviewPreset'. The bot will make sure this preset is loaded when it needs to use the overview.
  19. + Set Overview to sort by distance with the nearest entry at the top.
  20. + In the Inventory, select the 'List' view.
  21. + Enable the info panel 'System info'. The bot needs this to find asteroid belts and stations.
  22. + Arrange windows to not occlude ship modules or info panels.
  23. + In the ship UI, disable "Display Passive Modules" and disable "Display Empty Slots" and enable "Display Module Tooltips". The bot uses the module tooltips to automatically identify the properties of the modules.
  24.  
  25. This bot tracks the total mined amount of ore by watching inventory volume while mining modules are active.
  26. */
  27.  
  28. using BotSharp.ToScript.Extension;
  29. using MemoryStruct = Sanderling.Interface.MemoryStruct;
  30. using Parse = Sanderling.Parse;
  31.  
  32. //  Begin of configuration section ->
  33.  
  34. //  The bot loads this preset to the active tab in the Overview window.
  35. string OverviewPreset = null;
  36.  
  37. //  Activate shield hardener.
  38. var ActivateHardener = true;
  39.  
  40. //  Bot will switch mining site when rats are visible and shield hitpoints are lower than this value.
  41. var SwitchMiningSiteHitpointThresholdPercent = 35;
  42.  
  43. var EmergencyWarpOutHitpointPercent = 15;
  44.  
  45. //  Percentage of fill level at which to enter the offload process.
  46. var EnterOffloadOreContainerFillPercent = 96;
  47.  
  48. //  Warp to station when a neutral or hostile is visible in local.
  49. var RetreatOnNeutralOrHostileInLocal = false;
  50.  
  51. //  Name of the container to unload to as shown in inventory.
  52. string UnloadDestContainerName = "Item Hangar";
  53.  
  54. //  When this is set to true, the bot will try to unload when undocked.
  55. bool UnloadInSpace = false;
  56.  
  57. //  ----
  58. //  Should the bot use bookmarks for mining site?
  59. bool ShouldUseMiningBookmarks = true;
  60.  
  61. //  The bot uses the bookmarks from the menu which is opened from the button in the 'System info' panel.
  62. //  Bookmarks of places to mine. Add additional bookmarks separated by comma.
  63. string[] SetMiningSiteBookmark = new[] {
  64.     "mine1",
  65.     "mine2",
  66.     "mine3",
  67.     "mine4",
  68.     "mine5",
  69.     "mine6",
  70.     "mine7",
  71.     "mine8",
  72.     "mine9",
  73.     "mine10",
  74.     "mine11",
  75.     "mine12",
  76.     };
  77.  
  78. //  Bookmark of location where ore should be unloaded.
  79. string UnloadBookmark = "HOME";
  80.  
  81. //  Numbers of miner laser
  82. const int MinerLasersCount = 2;
  83. //  Numbers of ShieldBoosters
  84. const int ShieldBoostersCount = 1;
  85. //  Number of ArmorRepeirs
  86. const int ArmorRepairsCount = 0;
  87.  
  88. //  <- End of configuration section
  89.  
  90.  
  91. Func<object> BotStopActivity = () => null;
  92.  
  93. Func<object> NextActivity = MainStep;
  94.  
  95. Queue<string> visitedLocations = new Queue<string>();
  96.  
  97. // State used to track total mined ore. -->
  98. struct StatisticsMeasurementSnapshot
  99. {
  100.     public Int64 timeMilli;
  101.     public Int64 volumeMilli;
  102. }
  103. readonly Queue<StatisticsMeasurementSnapshot> efficiencyRawMeasurements = new Queue<StatisticsMeasurementSnapshot>();
  104. readonly Queue<StatisticsMeasurementSnapshot> efficiencyDebouncedMeasurements = new Queue<StatisticsMeasurementSnapshot>();
  105. Int64 miningModuleLastActiveTime = 0;
  106. Int64 totalMinedOreVolumeMilli = 0;
  107. // <-- State used to track total mined ore.
  108.  
  109. for(;;)
  110. {
  111.     var stepBeginTimeMilli = Host.GetTimeContinuousMilli();
  112.  
  113.     MemoryUpdate();
  114.  
  115.     Host.Log(
  116.         "ore container fill: " + OreContainerFillPercent + "%" +
  117.         ", mining range: " + MiningRange +
  118.         ", mining modules (inactive): " + SetModuleMiner?.Length + "(" + SetModuleMinerInactive?.Length + ")" +
  119.         ", shield.hp: " + ShieldHpPercent + "%" +
  120.         ", retreat: " + RetreatReason +
  121.         ", JLA: " + JammedLastAge +
  122.         ", overview.rats: " + ListRatOverviewEntry?.Length +
  123.         ", overview.roids: " + ListAsteroidOverviewEntry?.Length +
  124.         ", offload count: " + OffloadCount +
  125.         ", nextAct: " + NextActivity?.Method?.Name);
  126.  
  127.     CloseModalUIElement();
  128.  
  129.     if(0 < RetreatReason?.Length && !(Measurement?.IsDocked ?? false))
  130.     {
  131.         InitiateWarpToRetreat();
  132.         continue;
  133.     }
  134.  
  135.     NextActivity = NextActivity?.Invoke() as Func<object>;
  136.  
  137.     if(BotStopActivity == NextActivity)
  138.         break;
  139.  
  140.     if(null == NextActivity)
  141.         NextActivity = MainStep;
  142.  
  143.     Host.Delay((int)Math.Max(0, 1000 - (Host.GetTimeContinuousMilli() - stepBeginTimeMilli)));
  144. }
  145.  
  146. bool? ShipHasOreHold
  147. {
  148.     get
  149.     {
  150.         var inventoryActiveShipEntry = WindowInventory?.ActiveShipEntry;
  151.  
  152.         //  If the tree entry for the ship is not expanded....
  153.         if(!(IsExpanded(inventoryActiveShipEntry) ?? false))
  154.             return null;    // Then I do not know if there is an ore hold.
  155.  
  156.         return inventoryActiveShipEntry?.TreeEntryFromCargoSpaceType(ShipCargoSpaceTypeEnum.OreHold) != null;
  157.     }
  158. }
  159.    
  160.  
  161. //  seconds since ship was jammed.
  162. long? JammedLastAge => Jammed ? 0 : (Host.GetTimeContinuousMilli() - JammedLastTime) / 1000;
  163.  
  164. int?    ShieldHpPercent => ShipUi?.HitpointsAndEnergy?.Shield / 10;
  165.  
  166. bool    ShouldSwitchMiningSite =>
  167.     !(Measurement?.IsDocked ?? false) &&
  168.     0 < ListRatOverviewEntry?.Length &&
  169.     !(SwitchMiningSiteHitpointThresholdPercent < ShieldHpPercent) || JammedLastAge < 10;
  170.  
  171. bool    OreContainerFilledForOffload => Math.Max(0, Math.Min(100, EnterOffloadOreContainerFillPercent)) <= OreContainerFillPercent;
  172.  
  173. Int64?  JammedLastTime = null;
  174. string RetreatReasonTemporary = null;
  175. string RetreatReasonPermanent = null;
  176. string RetreatReason => RetreatReasonPermanent ?? RetreatReasonTemporary;
  177. int? LastCheckOreContainerFillPercent = null;
  178.  
  179. int OffloadCount = 0;
  180.  
  181. Func<object>    MainStep()
  182. {
  183.     if(Measurement?.IsDocked ?? false)
  184.     {
  185.         InInventoryUnloadItems();
  186.  
  187.         if (0 < RetreatReasonPermanent?.Length)
  188.             return BotStopActivity;
  189.  
  190.         if (0 < RetreatReason?.Length)
  191.             return MainStep;
  192.  
  193.         Undock();
  194.     }
  195.  
  196.     EnsureOverviewTypeSelectionLoaded();
  197.  
  198.     EnsureWindowInventoryOreContainerIsOpen();
  199.  
  200.     if(ReadyForManeuver)
  201.     {  
  202.         DroneEnsureInBay();
  203.        
  204.         if(OreContainerFilledForOffload)
  205.         {
  206.             if(ReadyForManeuver)
  207.                 InitiateDockToOffload();
  208.  
  209.             if (UnloadInSpace)
  210.             {
  211.                 Host.Delay(4444);
  212.                 InInventoryUnloadItems();
  213.             }
  214.  
  215.             return MainStep;
  216.         }
  217.  
  218.         if(!(ListAsteroidOverviewEntry?.Length > 0) || ShouldSwitchMiningSite)
  219.         {
  220.             if(ShouldUseMiningBookmarks)
  221.                 InitiateWarpToRandomMiningBookmark();
  222.             else
  223.                 InitiateWarpToMiningSite();
  224.         }
  225.     }
  226.  
  227.     ModuleMeasureAllTooltip();
  228.  
  229.     if(ActivateHardener)
  230.         ActivateHardenerExecute();
  231.  
  232.     return InBeltMineStep;
  233. }
  234.  
  235. int RandomInt() => new Random((int)Host.GetTimeContinuousMilli()).Next();
  236.  
  237. T RandomElement<T>(IEnumerable<T> sequence)
  238. {
  239.     var array = (sequence as T[]) ?? sequence?.ToArray();
  240.  
  241.     if (!(0 < array?.Length))
  242.         return default(T);
  243.  
  244.     return array[RandomInt() % array.Length];
  245. }
  246.  
  247. void CloseModalUIElement()
  248. {
  249.     var ButtonClose =
  250.         ModalUIElement?.ButtonText?.FirstOrDefault(button => (button?.Text).RegexMatchSuccessIgnoreCase("close|no|ok"));
  251.  
  252.     Sanderling.MouseClickLeft(ButtonClose);
  253. }
  254.  
  255. Func<object> InBeltMineStep()
  256. {
  257.     if(ShouldSwitchMiningSite)
  258.         return MainStep;
  259.  
  260.     EnsureWindowInventoryOreContainerIsOpen();
  261.  
  262.     EnsureOverviewTypeSelectionLoaded();
  263.  
  264.     if(OreContainerFilledForOffload)
  265.         return null;
  266.    
  267.     if (!(ReadyForManeuver))
  268.     {
  269.         DelayWhileUpdatingMemory(6000);
  270.         return InBeltMineStep;
  271.     }
  272.        
  273.     if (!(DronesInSpaceCount > 0) && (DronesInBayListEntryCount > 0))
  274.         DroneLaunch();
  275.  
  276.     bool ShouldTurnOnShieldBooster = ShieldHpPercent <90;
  277.     ToggleShieldBooster(ShouldTurnOnShieldBooster);
  278.    
  279.     var moduleMinerInactive = SetModuleMinerInactive?.FirstOrDefault();
  280.  
  281.     if (null == moduleMinerInactive)
  282.     {
  283.         DelayWhileUpdatingMemory(6000);
  284.         return InBeltMineStep;
  285.     }
  286.    
  287.     var setTargetAsteroidInRange    =
  288.         SetTargetAsteroid?.Where(target => target?.DistanceMax <= MiningRange)?.ToArray();
  289.  
  290.     var setTargetAsteroidInRangeNotAssigned =
  291.         setTargetAsteroidInRange?.Where(target => !(0 < target?.Assigned?.Length))?.ToArray();
  292.  
  293.     Host.Log("targeted asteroids in range (without assignment): " + setTargetAsteroidInRange?.Length + " (" + setTargetAsteroidInRangeNotAssigned?.Length + ")");
  294.  
  295.     if(0 < setTargetAsteroidInRangeNotAssigned?.Length)
  296.     {
  297.         var targetAsteroidInputFocus    =
  298.             setTargetAsteroidInRangeNotAssigned?.FirstOrDefault(target => target?.IsSelected ?? false);
  299.  
  300.         if(null == targetAsteroidInputFocus)
  301.             Sanderling.MouseClickLeft(setTargetAsteroidInRangeNotAssigned?.FirstOrDefault());
  302.  
  303.         ModuleToggle(moduleMinerInactive);
  304.  
  305.         return InBeltMineStep;
  306.     }  
  307.  
  308.     var asteroidOverviewEntryNext = ListAsteroidOverviewEntry?.FirstOrDefault();
  309.     var asteroidOverviewEntryNextNotTargeted = ListAsteroidOverviewEntry?.FirstOrDefault(entry => !((entry?.MeTargeted ?? false) || (entry?.MeTargeting ?? false)));
  310.  
  311.     Host.Log("next asteroid: (" + asteroidOverviewEntryNext?.Name + " , distance: " + asteroidOverviewEntryNext?.DistanceMax + ")" +
  312.         ", next asteroid not targeted: (" + asteroidOverviewEntryNext?.Name + " , distance: " + asteroidOverviewEntryNext?.DistanceMax + ")");
  313.  
  314.     if(null == asteroidOverviewEntryNext)
  315.     {
  316.         Host.Log("no asteroid available");
  317.         return null;
  318.     }
  319.  
  320.     if(null == asteroidOverviewEntryNextNotTargeted)
  321.     {
  322.         Host.Log("all asteroids targeted");
  323.         return null;
  324.     }
  325.  
  326.     if (!(asteroidOverviewEntryNextNotTargeted.DistanceMax < MiningRange))
  327.     {
  328.         if(!(1111 < asteroidOverviewEntryNext?.DistanceMin))
  329.         {
  330.             Host.Log("distance between asteroids too large");
  331.             return null;
  332.         }
  333.  
  334.         Host.Log("out of range, approaching");
  335.         ClickMenuEntryOnMenuRoot(asteroidOverviewEntryNext, "approach");
  336.     }
  337.     else
  338.     {
  339.         Host.Log("initiate lock asteroid");
  340.         ClickMenuEntryOnMenuRoot(asteroidOverviewEntryNextNotTargeted, "^lock");
  341.     }
  342.    
  343.     return InBeltMineStep;
  344. }
  345.  
  346. Sanderling.Accumulation.IShipUiModule[] SetModuleShieldBoosters =>
  347.     Sanderling.MemoryMeasurementAccu?.Value?.ShipUiModule?.Where(module => module?.TooltipLast?.Value?.IsShieldBooster ?? false)?.ToArray();
  348.  
  349. void ToggleShieldBooster(bool turnOn = true)
  350. {
  351.     var shieldBooster = SetModuleShieldBoosters?.FirstOrDefault();
  352.     if((shieldBooster?.RampActive ?? false) !=turnOn)
  353.     {      
  354.         Host.Log("toggle Shield Booster.");
  355.         ModuleToggle(shieldBooster);
  356.     }
  357. }
  358.  
  359. Sanderling.Parse.IMemoryMeasurement Measurement =>
  360.     Sanderling?.MemoryMeasurementParsed?.Value;
  361.  
  362. IWindow ModalUIElement =>
  363.     Measurement?.EnumerateReferencedUIElementTransitive()?.OfType<IWindow>()?.Where(window => window?.isModal ?? false)
  364.     ?.OrderByDescending(window => window?.InTreeIndex ?? int.MinValue)
  365.     ?.FirstOrDefault();
  366.  
  367. IEnumerable<Parse.IMenu> Menu => Measurement?.Menu;
  368.  
  369. Parse.IShipUi ShipUi => Measurement?.ShipUi;
  370.  
  371. bool Jammed => ShipUi?.EWarElement?.Any(EwarElement => (EwarElement?.EWarType).RegexMatchSuccess("electronic")) ?? false;
  372.  
  373. Sanderling.Interface.MemoryStruct.IMenuEntry MenuEntryLockTarget =>
  374.     Menu?.FirstOrDefault()?.Entry?.FirstOrDefault(entry => entry.Text.RegexMatchSuccessIgnoreCase("^lock"));
  375.  
  376. Sanderling.Parse.IWindowOverview    WindowOverview  =>
  377.     Measurement?.WindowOverview?.FirstOrDefault();
  378.  
  379. Sanderling.Parse.IWindowInventory   WindowInventory =>
  380.     Measurement?.WindowInventory?.FirstOrDefault();
  381.  
  382. ITreeViewEntry InventoryActiveShipOreContainer
  383. {
  384.     get
  385.     {
  386.         var hasOreHold = ShipHasOreHold;
  387.  
  388.         if(hasOreHold == null)
  389.             return null;
  390.  
  391.         return
  392.             WindowInventory?.ActiveShipEntry?.TreeEntryFromCargoSpaceType(
  393.                 hasOreHold.Value ? ShipCargoSpaceTypeEnum.OreHold : ShipCargoSpaceTypeEnum.General);
  394.     }
  395. }
  396.  
  397. IInventoryCapacityGauge OreContainerCapacityMilli =>
  398.     (InventoryActiveShipOreContainer?.IsSelected ?? false) ? WindowInventory?.SelectedRightInventoryCapacityMilli : null;
  399.  
  400. int? OreContainerFillPercent => (int?)((OreContainerCapacityMilli?.Used * 100) / OreContainerCapacityMilli?.Max);
  401.  
  402. Tab OverviewPresetTabActive =>
  403.     WindowOverview?.PresetTab
  404.     ?.OrderByDescending(tab => tab?.LabelColorOpacityMilli ?? 0)
  405.     ?.FirstOrDefault();
  406.  
  407. string OverviewTypeSelectionName =>
  408.     WindowOverview?.Caption?.RegexMatchIfSuccess(@"\(([^\)]*)\)")?.Groups?[1]?.Value;
  409.  
  410. Parse.IOverviewEntry[] ListRatOverviewEntry => WindowOverview?.ListView?.Entry?.Where(entry =>
  411.         (entry?.MainIconIsRed ?? false) && (entry?.IsAttackingMe ?? false))
  412.         ?.OrderBy(entry => entry?.DistanceMax ?? int.MaxValue)
  413.         ?.ToArray();
  414.  
  415. Parse.IOverviewEntry[] ListAsteroidOverviewEntry =>
  416.     WindowOverview?.ListView?.Entry
  417.     ?.Where(entry => null != OreTypeFromAsteroidName(entry?.Name))
  418.     ?.OrderBy(entry => entry.DistanceMax ?? int.MaxValue)
  419.     ?.ToArray();
  420.    
  421.  
  422. bool ReadyForManeuverNot =>
  423.     Measurement?.ShipUi?.Indication?.LabelText?.Any(indicationLabel =>
  424.         (indicationLabel?.Text).RegexMatchSuccessIgnoreCase("warp|docking")) ?? false;
  425.  
  426. bool ReadyForManeuver => !ReadyForManeuverNot && !(Measurement?.IsDocked ?? true);
  427.  
  428. Sanderling.Parse.IShipUiTarget[] SetTargetAsteroid =>
  429.     Measurement?.Target?.Where(target =>
  430.         target?.TextRow?.Any(textRow => textRow.RegexMatchSuccessIgnoreCase("asteroid")) ?? false)?.ToArray();
  431.  
  432. Sanderling.Interface.MemoryStruct.IListEntry    WindowInventoryItem =>
  433.     WindowInventory?.SelectedRightInventory?.ListView?.Entry?.FirstOrDefault();
  434.  
  435. Sanderling.Accumulation.IShipUiModule[] SetModuleMiner =>
  436.     Sanderling.MemoryMeasurementAccu?.Value?.ShipUiModule?.Where(module => module?.TooltipLast?.Value?.IsMiner ?? false)?.ToArray();
  437.  
  438. Sanderling.Accumulation.IShipUiModule[] SetModuleMinerInactive   =>
  439.     SetModuleMiner?.Where(module => !(module?.RampActive ?? false))?.ToArray();
  440.  
  441. int?    MiningRange => SetModuleMiner?.Select(module =>
  442.     module?.TooltipLast?.Value?.RangeOptimal ?? module?.TooltipLast?.Value?.RangeMax ?? module?.TooltipLast?.Value?.RangeWithin ?? 0)?.DefaultIfEmpty(0)?.Min();;
  443.  
  444. WindowChatChannel chatLocal =>
  445.      Sanderling.MemoryMeasurementParsed?.Value?.WindowChatChannel
  446.      ?.FirstOrDefault(windowChat => windowChat?.Caption?.RegexMatchSuccessIgnoreCase("local") ?? false);
  447.  
  448. //    assuming that own character is always visible in local
  449. bool hostileOrNeutralsInLocal => 1 != chatLocal?.ParticipantView?.Entry?.Count(IsNeutralOrEnemy);
  450.  
  451. //  extract the ore type from the name as seen in overview. "Asteroid (Plagioclase)"
  452. string OreTypeFromAsteroidName(string AsteroidName) =>
  453.     AsteroidName.ValueFromRegexMatchGroupAtIndex(@"Asteroid \(([^\)]+)", 0);
  454.  
  455. void ClickMenuEntryOnMenuRoot(IUIElement MenuRoot, string MenuEntryRegexPattern)
  456. {
  457.     Sanderling.MouseClickRight(MenuRoot);
  458.    
  459.     var Menu = Measurement?.Menu?.FirstOrDefault();
  460.    
  461.     var MenuEntry = Menu?.EntryFirstMatchingRegexPattern(MenuEntryRegexPattern, RegexOptions.IgnoreCase);
  462.    
  463.     Sanderling.MouseClickLeft(MenuEntry);
  464. }
  465.  
  466. void EnsureWindowInventoryOpen()
  467. {
  468.     if (null != WindowInventory)
  469.         return;
  470.  
  471.     Host.Log("open Inventory.");
  472.     Sanderling.MouseClickLeft(Measurement?.Neocom?.InventoryButton);
  473. }
  474.  
  475. void EnsureWindowInventoryOreContainerIsOpen()
  476. {
  477.     EnsureWindowInventoryOpen();
  478.  
  479.     var inventoryActiveShip = WindowInventory?.ActiveShipEntry;
  480.  
  481.     if(InventoryActiveShipOreContainer == null && !(IsExpanded(inventoryActiveShip) ?? false))
  482.     {
  483.         Host.Log("It looks like the active ships entry in the inventory is not expanded. I try to expand it to see if the ship has an ore hold.");
  484.         Sanderling.MouseClickLeft(inventoryActiveShip?.ExpandToggleButton);
  485.     }
  486.  
  487.     if(!(InventoryActiveShipOreContainer?.IsSelected ?? false))
  488.         Sanderling.MouseClickLeft(InventoryActiveShipOreContainer);
  489. }
  490.  
  491. //  sample label text: Intensive Reprocessing Array <color=#66FFFFFF>1,123 m</color>
  492. string InventoryContainerLabelRegexPatternFromContainerName(string containerName) =>
  493.     @"^\s*" + Regex.Escape(containerName) + @"\s*($|\<)";
  494.  
  495. void InInventoryUnloadItems() => InInventoryUnloadItemsTo(UnloadDestContainerName);
  496.  
  497. void InInventoryUnloadItemsTo(string DestinationContainerName)
  498. {
  499.     Host.Log("unload items to '" + DestinationContainerName + "'.");
  500.  
  501.     EnsureWindowInventoryOreContainerIsOpen();
  502.  
  503.     for (;;)
  504.     {
  505.         var oreContainerListItem = WindowInventory?.SelectedRightInventory?.ListView?.Entry?.ToArray();
  506.  
  507.         var oreContainerItem = oreContainerListItem?.FirstOrDefault();
  508.  
  509.         if(null == oreContainerItem)
  510.             break;    //    0 items in the container which holds the ore.
  511.  
  512.         if(2 < oreContainerListItem?.Length)
  513.             ClickMenuEntryOnMenuRoot(oreContainerItem, @"select\s*all");
  514.  
  515.         var DestinationContainerLabelRegexPattern =
  516.             InventoryContainerLabelRegexPatternFromContainerName(DestinationContainerName);
  517.  
  518.         var DestinationContainer =
  519.             WindowInventory?.LeftTreeListEntry?.SelectMany(entry => new[] { entry }.Concat(entry.EnumerateChildNodeTransitive()))
  520.             ?.FirstOrDefault(entry => entry?.Text?.RegexMatchSuccessIgnoreCase(DestinationContainerLabelRegexPattern) ?? false);
  521.  
  522.         if (null == DestinationContainer)
  523.             Host.Log("error: Inventory entry labeled '" + DestinationContainerName + "' not found");
  524.  
  525.         Sanderling.MouseDragAndDrop(oreContainerItem, DestinationContainer);
  526.     }
  527. }
  528. bool InitiateWarpToRandomMiningBookmark() =>
  529.     InitiateDockToOrWarpToLocationInSolarSystemMenu(RandomElement(SetMiningSiteBookmark));
  530.  
  531. bool InitiateWarpToMiningSite() =>
  532.     InitiateDockToOrWarpToLocationInSolarSystemMenu("asteroid belts", PickNextMiningSiteFromSystemMenu);
  533.  
  534. bool InitiateDockToOffload()    =>
  535.     InitiateDockToOrWarpToLocationInSolarSystemMenu(UnloadBookmark, PickPlaceToOffloadfFromSystemMenu);
  536.  
  537. bool InitiateWarpToRetreat()    =>
  538.     InitiateDockToOrWarpToLocationInSolarSystemMenu("stations");
  539.  
  540. MemoryStruct.IMenuEntry PickNextMiningSiteFromSystemMenu(IReadOnlyList<MemoryStruct.IMenuEntry> availableMenuEntries)
  541. {
  542.     Host.Log("I am seeing " + availableMenuEntries?.Count.ToString() + " mining sites to choose from.");
  543.  
  544.     var nextSite =
  545.         availableMenuEntries
  546.         ?.OrderBy(menuEntry => visitedLocations.ToList().IndexOf(menuEntry?.Text))
  547.         ?.FirstOrDefault();
  548.  
  549.     Host.Log("I pick '" + nextSite?.Text + "' as next mining site, based on the intent to rotate through the mining sites and recorded previous locations.");
  550.     return nextSite;
  551. }
  552.  
  553. MemoryStruct.IMenuEntry PickPlaceToOffloadfFromSystemMenu(IReadOnlyList<MemoryStruct.IMenuEntry> availableMenuEntries)
  554. {
  555.     Host.Log("I am seeing " + availableMenuEntries?.Count.ToString() + " stations to choose from for offloading ore.");
  556.  
  557.     var availableMenuEntriesTexts =
  558.         availableMenuEntries
  559.         ?.Select(menuEntry => menuEntry.Text)
  560.         ?.ToList();
  561.  
  562.     foreach(var visitedLocation in visitedLocations.Reverse())
  563.     {
  564.         var visitedLocationMenuEntry =
  565.             availableMenuEntries?.FirstOrDefault(menuEntry =>
  566.                 StationFromSystemInfoPanelEqualsStationFromSystemMenu(visitedLocation, menuEntry?.Text));
  567.  
  568.         if(visitedLocationMenuEntry == null)
  569.             continue;
  570.  
  571.         Host.Log("I pick '" + visitedLocationMenuEntry?.Text + "' as destination, because this is the last one visited.");
  572.         return visitedLocationMenuEntry;
  573.     }
  574.  
  575.     var dockMenuEntry = availableMenuEntries?.Where(x => x?.Text?.Contains("Dock") ?? false)?.FirstOrDefault();
  576.     var destination = dockMenuEntry ?? availableMenuEntries?.FirstOrDefault();
  577.  
  578.     Host.Log("I pick '" + destination?.Text + "' as destination, because I do not remember having visited any of the available stations.");
  579.     return destination;
  580. }
  581.  
  582. bool InitiateDockToOrWarpToLocationInSolarSystemMenu(
  583.     string submenuLabel,
  584.     Func<IReadOnlyList<MemoryStruct.IMenuEntry>, MemoryStruct.IMenuEntry> pickPreferredDestination = null)
  585. {  
  586.     Host.Log("Attempt to initiate dock to or warp to menu entry in submenu '" + submenuLabel + "'");
  587.    
  588.     var listSurroundingsButton = Measurement?.InfoPanelCurrentSystem?.ListSurroundingsButton;
  589.    
  590.     Sanderling.MouseClickRight(listSurroundingsButton);
  591.  
  592.     var submenuEntry = Measurement?.Menu?.FirstOrDefault()?.EntryFirstMatchingRegexPattern("^" + submenuLabel + "$", RegexOptions.IgnoreCase);
  593.  
  594.     if(null == submenuEntry)
  595.     {
  596.         Host.Log("Submenu '" + submenuLabel + "' not found in the solar system menu.");
  597.         return true;
  598.     }
  599.  
  600.     Sanderling.MouseClickLeft(submenuEntry);
  601.  
  602.     var submenu = Measurement?.Menu?.ElementAtOrDefault(1);
  603.  
  604.     var destinationMenuEntry = pickPreferredDestination?.Invoke(submenu?.Entry?.ToList()) ?? submenu?.Entry?.FirstOrDefault();
  605.  
  606.     if(destinationMenuEntry == null)
  607.     {
  608.         Host.Log("Failed to open submenu '" + submenuLabel + "' in the solar system menu.");
  609.         return true;
  610.     }
  611.  
  612.     Sanderling.MouseClickLeft(destinationMenuEntry);
  613.  
  614.     var actionsMenu = Measurement?.Menu?.ElementAtOrDefault(2);
  615.  
  616.     if(destinationMenuEntry == null)
  617.     {
  618.         Host.Log("Failed to open actions menu for '" + destinationMenuEntry.Text + "' in the solar system menu.");
  619.         return true;
  620.     }
  621.  
  622.     var dockMenuEntry = actionsMenu?.EntryFirstMatchingRegexPattern("dock", RegexOptions.IgnoreCase);
  623.     var warpMenuEntry = actionsMenu?.EntryFirstMatchingRegexPattern(@"warp.*within.*m", RegexOptions.IgnoreCase);
  624.     var approachEntry = actionsMenu?.EntryFirstMatchingRegexPattern(@"approach", RegexOptions.IgnoreCase);
  625.  
  626.     var maneuverMenuEntry = dockMenuEntry ?? warpMenuEntry;
  627.  
  628.     if (null != maneuverMenuEntry)
  629.     {
  630.         Host.Log("initiating '" + maneuverMenuEntry.Text + "' on '" + destinationMenuEntry?.Text + "'");
  631.         Sanderling.MouseClickLeft(maneuverMenuEntry);
  632.         return false;
  633.     }
  634.  
  635.     if (null != approachEntry)
  636.     {
  637.         Host.Log("found menu entry '" + approachEntry.Text + "'. Assuming we are already there.");
  638.         return false;
  639.     }
  640.  
  641.     Host.Log("no suitable menu entry found on '" + destinationMenuEntry?.Text + "'");
  642.     return true;
  643. }
  644.  
  645. IWindowDroneView    WindowDrones    =>
  646.     Measurement?.WindowDroneView?.FirstOrDefault();
  647.  
  648. DroneViewEntryGroup DronesInBayListEntry =>
  649.     WindowDrones?.ListView?.Entry?.OfType<DroneViewEntryGroup>()?.FirstOrDefault(Entry => null != Entry?.Caption?.Text?.RegexMatchIfSuccess(@"Drones in bay", RegexOptions.IgnoreCase));
  650.  
  651. DroneViewEntryGroup DronesInSpaceListEntry =>
  652.     WindowDrones?.ListView?.Entry?.OfType<DroneViewEntryGroup>()?.FirstOrDefault(Entry => null != Entry?.Caption?.Text?.RegexMatchIfSuccess(@"Drones in Local Space", RegexOptions.IgnoreCase));
  653.  
  654. int?    DronesInSpaceCount => DronesInSpaceListEntry?.Caption?.Text?.AsDroneLabel()?.Status?.TryParseInt();
  655. int?    DronesInBayListEntryCount => DronesInBayListEntry?.Caption?.Text?.AsDroneLabel()?.Status?.TryParseInt();
  656.  
  657. void DroneEnsureInBay()
  658. {
  659.     if(0 == DronesInSpaceCount)
  660.         return;
  661.  
  662.     DroneReturnToBay();
  663.    
  664.     Host.Delay(4444);
  665. }
  666.  
  667. void DroneReturnToBay()
  668. {
  669.     Host.Log("return drones to bay.");
  670.     Sanderling.MouseClickRight(DronesInSpaceListEntry);
  671.     Sanderling.MouseClickLeft(Menu?.FirstOrDefault()?.EntryFirstMatchingRegexPattern("return.*bay", RegexOptions.IgnoreCase));
  672.     Sanderling.KeyboardPressCombined(new[]{VirtualKeyCode.SHIFT, VirtualKeyCode.VK_R});
  673. }
  674.  
  675. void DroneLaunch()
  676. {
  677.     Host.Log("launch drones.");
  678.     Sanderling.MouseClickRight(DronesInBayListEntry);
  679.     Sanderling.MouseClickLeft(Menu?.FirstOrDefault()?.EntryFirstMatchingRegexPattern("launch", RegexOptions.IgnoreCase));
  680. }
  681.  
  682. void Undock()
  683. {
  684.     while(Measurement?.IsDocked ?? true)
  685.     {
  686.         Sanderling.MouseClickLeft(Measurement?.WindowStation?.FirstOrDefault()?.UndockButton);
  687.         Host.Log("waiting for undocking to complete.");
  688.         Host.Delay(8000);
  689.     }
  690.  
  691.     Host.Delay(4444);
  692.     Sanderling.InvalidateMeasurement();
  693. }
  694.  
  695.  
  696. void ModuleMeasureAllTooltip()
  697. {
  698.     Host.Log("measure tooltips of all modules.");
  699.    
  700.         var shieldBoostersCount = Sanderling.MemoryMeasurementAccu?.Value?.ShipUiModule.Count(m => m?.TooltipLast?.Value?.IsShieldBooster ?? false);
  701.         var armorRapairCount = Sanderling.MemoryMeasurementAccu?.Value?.ShipUiModule.Count(m => m?.TooltipLast?.Value?.IsArmorRepairer ?? false);
  702.         var miningLasersCount = Sanderling.MemoryMeasurementAccu?.Value?.ShipUiModule.Count(m => m?.TooltipLast?.Value?.IsMiner ?? false);
  703.  
  704.     while( (shieldBoostersCount <  ShieldBoostersCount) ||  (armorRapairCount < ArmorRepairsCount) || (miningLasersCount <  MinerLasersCount)   )
  705.     {
  706.         if(Sanderling.MemoryMeasurementParsed?.Value?.IsDocked ?? false)
  707.             break;
  708.         foreach(var NextModule in Sanderling.MemoryMeasurementAccu?.Value?.ShipUiModule)
  709.         {
  710.             if(null == NextModule)
  711.                 break;
  712.    
  713.             Host.Log("measure module.");
  714.             //  take multiple measurements of module tooltip to reduce risk to keep bad read tooltip.
  715.             Sanderling.MouseMove(NextModule);
  716.             Sanderling.WaitForMeasurement();
  717.             Sanderling.MouseMove(NextModule);
  718.         }      
  719.    
  720.         shieldBoostersCount = Sanderling.MemoryMeasurementAccu?.Value?.ShipUiModule.Count(m => m?.TooltipLast?.Value?.IsShieldBooster ?? false);
  721.         armorRapairCount = Sanderling.MemoryMeasurementAccu?.Value?.ShipUiModule.Count(m => m?.TooltipLast?.Value?.IsArmorRepairer ?? false);
  722.         miningLasersCount = Sanderling.MemoryMeasurementAccu?.Value?.ShipUiModule.Count(m => m?.TooltipLast?.Value?.IsMiner ?? false);
  723.    
  724.         Host.Log("Shield Boosters count = " + shieldBoostersCount + ", Armor Repair count = " + armorRapairCount + ", Mining Lasers Count = " + miningLasersCount );
  725.  
  726.     }
  727. }
  728.  
  729. void ActivateHardenerExecute()
  730. {
  731.     var SubsetModuleHardener =
  732.         Sanderling.MemoryMeasurementAccu?.Value?.ShipUiModule
  733.         ?.Where(module => module?.TooltipLast?.Value?.IsHardener ?? false);
  734.  
  735.     var SubsetModuleToToggle =
  736.         SubsetModuleHardener
  737.         ?.Where(module => !(module?.RampActive ?? false));
  738.  
  739.     foreach (var Module in SubsetModuleToToggle.EmptyIfNull())
  740.         ModuleToggle(Module);
  741. }
  742.  
  743. void ModuleToggle(Sanderling.Accumulation.IShipUiModule Module)
  744. {
  745.     var ToggleKey = Module?.TooltipLast?.Value?.ToggleKey;
  746.  
  747.     Host.Log("toggle module using " + (null == ToggleKey ? "mouse" : Module?.TooltipLast?.Value?.ToggleKeyTextLabel?.Text));
  748.  
  749.     if(null == ToggleKey)
  750.         Sanderling.MouseClickLeft(Module);
  751.     else
  752.         Sanderling.KeyboardPressCombined(ToggleKey);
  753. }
  754.  
  755. void EnsureOverviewTypeSelectionLoaded()
  756. {
  757.     if(null == OverviewPresetTabActive || null == WindowOverview || null == OverviewPreset)
  758.         return;
  759.  
  760.     if(string.Equals(OverviewTypeSelectionName, OverviewPreset, StringComparison.OrdinalIgnoreCase))
  761.         return;
  762.  
  763.     Host.Log("loading preset '" + OverviewPreset + "' to overview (current selection is '" + OverviewTypeSelectionName + "').");
  764.     Sanderling.MouseClickRight(OverviewPresetTabActive);
  765.     Sanderling.MouseClickLeft(Menu?.FirstOrDefault()?.EntryFirstMatchingRegexPattern("load.*preset", RegexOptions.IgnoreCase));
  766.     var PresetMenuEntry = Menu?.ElementAtOrDefault(1)?.EntryFirstMatchingRegexPattern(@"^\s*" + Regex.Escape(OverviewPreset) + @"\s*$", RegexOptions.IgnoreCase);
  767.  
  768.     if(null == PresetMenuEntry)
  769.     {
  770.         Host.Log("error: menu entry '" + OverviewPreset + "' not found");
  771.         return;
  772.     }
  773.  
  774.     Sanderling.MouseClickLeft(PresetMenuEntry);
  775. }
  776.  
  777. void DelayWhileUpdatingMemory(int delayAmountMilli)
  778. {
  779.     var beginTimeMilli = Host.GetTimeContinuousMilli();
  780.  
  781.     while(true)
  782.     {
  783.         var remainingTimeMilli = beginTimeMilli + delayAmountMilli - Host.GetTimeContinuousMilli();
  784.         if(remainingTimeMilli < 0)
  785.             break;
  786.  
  787.         Host.Delay(Math.Min(1000, (int)remainingTimeMilli));
  788.         Sanderling.InvalidateMeasurement();
  789.         MemoryUpdate();
  790.     }
  791. }
  792.  
  793. void MemoryUpdate()
  794. {
  795.     RetreatUpdate();
  796.     JammedLastTimeUpdate();
  797.     OffloadCountUpdate();
  798.     UpdateLocationRecord();
  799.     TrackTotalMinedOre();
  800. }
  801.  
  802. void UpdateLocationRecord()
  803. {
  804.     //  I am not interested in locations which are only close during warp.
  805.     if(Measurement?.ShipUi?.Indication?.ManeuverType == ShipManeuverTypeEnum.Warp)
  806.         return;
  807.  
  808.     // Purpose of recording locations is to prioritize our next destination when warping to mining site or docking to station.
  809.     // For this purpose, I will compare the recorded locations with the menu entries in the system menu.
  810.     // Therefore I want the format of the recorded location to be the same as it appears in the menu entries in the system menu.
  811.  
  812.     var currentSystemLocationLabelText =
  813.         Measurement?.InfoPanelCurrentSystem?.ExpandedContent?.LabelText
  814.         ?.OrderByCenterVerticalDown()?.FirstOrDefault()?.Text;
  815.  
  816.     if(currentSystemLocationLabelText == null)
  817.         return;
  818.  
  819.     // 2018-03 observed label text: <url=showinfo:15//40088644 alt='Nearest'>Amsen V - Asteroid Belt 1</url>
  820.  
  821.     var currentLocationName = RegexExtension.RemoveXmlTag(currentSystemLocationLabelText)?.Trim();
  822.  
  823.     var lastRecordedLocation = visitedLocations.LastOrDefault();
  824.  
  825.     if(lastRecordedLocation == currentLocationName)
  826.         return;
  827.  
  828.     visitedLocations.Enqueue(currentLocationName);
  829.     Host.Log("Recorded transition from location '" + lastRecordedLocation + "' to location '" + currentLocationName + "'");
  830.  
  831.     if(100 < visitedLocations.Count)
  832.         visitedLocations.Dequeue();
  833. }
  834.  
  835. /*
  836. 2018-03 Observation: Station name containing reference to moon appears different between system menu and system info panel.
  837. In the info panel 'Moon 17' was used while in the system menu it was 'M17'.
  838. */
  839. public bool StationFromSystemInfoPanelEqualsStationFromSystemMenu(
  840.     string stationNameInCurrentSystemInfoPanel,
  841.     string stationNameInSystemMenu)
  842. {
  843.     //  Copied from https://github.com/botengine-de/Optimat.EO/blob/6c19e8f36e30d5468e94d627eb16dcb78bb47d12/src/Optimat.EveOnline.Bot/Sonst/AgentUndMission.Aktualisiire.cs#L1888-L1893
  844.  
  845.     var representationPattern =
  846.         Regex.Replace(
  847.         stationNameInCurrentSystemInfoPanel,
  848.         "Moon\\s*",
  849.         "M([\\w]*\\s*)",
  850.         RegexOptions.IgnoreCase);
  851.  
  852.     return
  853.         stationNameInSystemMenu.RegexMatchSuccessIgnoreCase(representationPattern);
  854. }
  855.  
  856. void JammedLastTimeUpdate()
  857. {
  858.     if(Jammed)
  859.         JammedLastTime  = Host.GetTimeContinuousMilli();
  860. }
  861.  
  862. bool MeasurementEmergencyWarpOutEnter =>
  863.     !(Measurement?.IsDocked ?? false) && !(EmergencyWarpOutHitpointPercent < ShieldHpPercent);
  864.  
  865. void RetreatUpdate()
  866. {
  867.     RetreatReasonTemporary = (RetreatOnNeutralOrHostileInLocal && hostileOrNeutralsInLocal) ? "hostile or neutral in local" : null;
  868.  
  869.     if (!MeasurementEmergencyWarpOutEnter)
  870.         return;
  871.  
  872.     //  measure multiple times to avoid being scared off by noise from a single measurement.
  873.     Sanderling.InvalidateMeasurement();
  874.  
  875.     if (!MeasurementEmergencyWarpOutEnter)
  876.         return;
  877.  
  878.     RetreatReasonPermanent = "shield hp";
  879. }
  880.  
  881. void OffloadCountUpdate()
  882. {
  883.     var OreContainerFillPercentSynced   = OreContainerFillPercent;
  884.  
  885.     if(!OreContainerFillPercentSynced.HasValue)
  886.         return;
  887.  
  888.     if(0 == OreContainerFillPercentSynced && OreContainerFillPercentSynced < LastCheckOreContainerFillPercent)
  889.         ++OffloadCount;
  890.  
  891.     LastCheckOreContainerFillPercent = OreContainerFillPercentSynced;
  892. }
  893.  
  894. bool IsNeutralOrEnemy(IChatParticipantEntry participantEntry) =>
  895.    !(participantEntry?.FlagIcon?.Any(flagIcon =>
  896.      new[] { "good standing", "excellent standing", "Pilot is in your (fleet|corporation)", }
  897.      .Any(goodStandingText =>
  898.         flagIcon?.HintText?.RegexMatchSuccessIgnoreCase(goodStandingText) ?? false)) ?? false);
  899.  
  900. bool? IsExpanded(IInventoryTreeViewEntryShip shipEntryInInventory) =>
  901.     shipEntryInInventory == null ? null :
  902.     (bool?)((shipEntryInInventory.IsExpanded ?? false) || 0 < (shipEntryInInventory.Child?.Count() ?? 0));
  903.  
  904. void TrackTotalMinedOre()
  905. {
  906.     var currentTimeMilli = Sanderling.MemoryMeasurement?.End;
  907.  
  908.     // Host.Log("TrackTotalMinedOre called at " + currentTimeMilli);
  909.  
  910.     if(!currentTimeMilli.HasValue)
  911.         return;
  912.  
  913.     if(Sanderling.MemoryMeasurementParsed?.Value?.IsDocked ?? false)
  914.         return;
  915.  
  916.     if(SetModuleMiner?.Any(module => module?.RampActive ?? false) ?? false)
  917.         miningModuleLastActiveTime = currentTimeMilli.Value;
  918.  
  919.     var containerCurrentUsedVolumeMilli = OreContainerCapacityMilli?.Used;
  920.  
  921.     if(!containerCurrentUsedVolumeMilli.HasValue)
  922.         return;
  923.  
  924.     var lastRecordingAgeMilli = currentTimeMilli - efficiencyRawMeasurements.LastOrDefault().timeMilli;
  925.  
  926.     if(lastRecordingAgeMilli < 500)
  927.         return;
  928.  
  929.     efficiencyRawMeasurements.Enqueue(
  930.         new StatisticsMeasurementSnapshot{ timeMilli = currentTimeMilli.Value, volumeMilli = containerCurrentUsedVolumeMilli.Value });
  931.  
  932.     while(2 < efficiencyRawMeasurements.Count)
  933.         efficiencyRawMeasurements.Dequeue();
  934.  
  935.     if(efficiencyRawMeasurements.Select(measurement => measurement.volumeMilli).Distinct().Count() == 1)
  936.         efficiencyDebouncedMeasurements.Enqueue(efficiencyRawMeasurements.Last());
  937.  
  938.     while(2 < efficiencyDebouncedMeasurements.Count)
  939.         efficiencyDebouncedMeasurements.Dequeue();
  940.  
  941.     if(1 < efficiencyDebouncedMeasurements.Count)
  942.     {
  943.         var lastMeasurement = efficiencyDebouncedMeasurements.Last();
  944.         var secondLastMeasurement = efficiencyDebouncedMeasurements.Reverse().ElementAt(1);
  945.  
  946.         var usedVolumeIncreaseMilli = lastMeasurement.volumeMilli - secondLastMeasurement.volumeMilli;
  947.         var secondLastMeasurementAgeMilli = currentTimeMilli - secondLastMeasurement.timeMilli;
  948.  
  949.         if(0 < usedVolumeIncreaseMilli)
  950.         {
  951.             Host.Log("Inventory used volume increased by " + (usedVolumeIncreaseMilli / 1000) + " m³");
  952.  
  953.             var miningModuleActiveLastAge = (currentTimeMilli.Value - miningModuleLastActiveTime) / 1000;
  954.  
  955.             if(10 * 1000 < miningModuleActiveLastAge)
  956.                 Host.Log("Measuring Statistics: Ignored volume increase because miningModuleActiveLastAge was " + miningModuleActiveLastAge + " s.");
  957.             else
  958.             {
  959.                 if(10 * 1000 < secondLastMeasurementAgeMilli)
  960.                     Host.Log("Measuring Statistics: Ignored volume increase because timespan was " + secondLastMeasurementAgeMilli + " ms.");
  961.                 else
  962.                 {
  963.                     totalMinedOreVolumeMilli += usedVolumeIncreaseMilli;
  964.                     Host.Log("Total_mined_ore_in_cubic_meters: " + (totalMinedOreVolumeMilli / 1000));
  965.                 }
  966.             }
  967.         }
  968.     }
  969. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top