XRWS           ¸¯   K  ¸dext_01.cat ext_01.dat aiscripts/randommine.xml 47204 1640942137 f7e132d25d2b9ed9f0c7631ec922d10b
<?xml version="1.0" encoding="utf-8"?>
<!-- RandomSuply Ai, Created by Language. Version 122-->
<aiscript xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="randommine" xsi:noNamespaceSchemaLocation="aiscripts.xsd" version="122">
  <order id="RandomMine" name="RandomMine" description="Random miner logic." category="mining" infinite="true">
    <params>
      <!-- Define where the trader will base itself -->
      <param name="supplier" type="bool" default="true" text="Supplier" comment="Do we mine for our stations?"/>
      <param name="freeMiner" type="bool" default="false" text="Free Miner" comment="Do we mine for npc stations?"/>
      <param name="home" default="this.sector" type="object" text="MinerHome" comment="Home Sector/Station">
        <input_param name="class" value="[class.sector,class.station]"/>
      </param>
      <param name="homeBound" type="bool" default="false" text="HomeBound" comment="Trade only around home?"/>
      <!-- Some Range configurations -->
      <param name="maxMine" default="3" type="number" text="Mine Gate Distance" comment="Max gate distance to mine.">
        <input_param name="startvalue" value="0"/>
        <input_param name="min" value="0"/>
        <input_param name="max" value="@this.ship.pilot.skill.piloting * 2"/>
        <input_param name="step" value="1"/>
      </param>
      <param name="maxSell" default="3" type="number" text="{1041, 10057}" comment="Max gate distance to sell.">
        <input_param name="startvalue" value="0"/>
        <input_param name="min" value="0"/>
        <input_param name="max" value="@this.ship.pilot.skill.piloting * 2"/>
        <input_param name="step" value="1"/>
      </param>
      <param name="maxServe" default="@this.ship.pilot.skill.piloting * 2" type="number" text="Serve Gate Distance" comment="Max gate distance to serve stations.">
        <input_param name="startvalue" value="0"/>
        <input_param name="min" value="0"/>
        <input_param name="max" value="@this.ship.pilot.skill.piloting * 2"/>
        <input_param name="step" value="1"/>
      </param>

      <!-- What are we hauling? -->
      <param name="wareBasket" default="[]" type="list" text="{1041, 10146}" comment="Wares">
        <input_param name="type" value="'ware'"/>
        <input_param name="cancarry" value="this.ship"/>
      </param>

      <param name="allWares" type="bool" default="true" text="All Wares" comment="Enable all wares in the basket."/>
      
      <!--stockRatios while Station Trader mode-->
      <param name="stockRatioToMine" type="number" text="Mine before X% filled (Supplier)" default="90" comment="How many % of the needed wares for our home station should we keep filled?">
        <input_param name="min" value="10"/>
        <input_param name="max" value="90"/>
        <input_param name="step" value="5"/>
      </param>
      
      <!-- Allowed factions. -->
      <param name="allowAllFactions" type="bool" default="false" text="Allow all factions" comment="Allow all factions to trade with?"/>
      <param name="allowPlayer" type="bool" default="true" text="{20203,101}" comment="Allow this faction?"/>
      <!-- Argon Based Factions -->
      <param name="allowArgon" type="bool" default="true" text="{20203,201}" comment="Allow this faction?"/>
      <param name="allowAntigone" type="bool" default="true" text="{20203,301}" comment="Allow this faction?"/>
      <!-- Teladi Based Factions -->
      <param name="allowTeladi" type="bool" default="true" text="{20203,601}" comment="Allow this faction?"/>
      <param name="allowMinistry" type="bool" default="true" text="{20203,701}" comment="Allow this faction?"/>
      <!-- Paranid Based Factions -->
      <param name="allowParanid" type="bool" default="true" text="{20203,401}" comment="Allow this faction?"/>
      <param name="allowHolyOrder" type="bool" default="true" text="{20203,501}" comment="Allow this faction?"/>
      <param name="allowAlliance" type="bool" default="true" text="{20203,801}" comment="Allow this faction?"/>
      <!-- Split Based Factions (DLC)-->
      <param name="allowSplit" type="bool" default="true" text="{20203,2001}" comment="Allow this faction?"/>
      <param name="allowFreeSplit" type="bool" default="true" text="{20203,1601}" comment="Allow this faction?"/>
      <!-- Terran Factions (DLC)-->
      <param name="allowTerran" type="bool" default="true" text="{20203,3001}" comment="Allow this faction?"/>
      <param name="allowPioneers" type="bool" default="true" text="{20203,2901}" comment="Allow this faction?"/>
      <!-- Pirate Factions -->
      <param name="allowHatikvah" type="bool" default="true" text="{20203,901}" comment="Allow this faction?"/>
      <param name="allowScaleplate" type="bool" default="false" text="{20203,1001}" comment="Allow this faction?"/>
      <param name="allowYaki" type="bool" default="false" text="{20203,2801}" comment="Allow this faction?"/>
      <param name="updateSubordinates" type="bool" default="false" text="Update subordinates" comment="forcefully update settings of subordinate randomminers"/>
    </params>
    <skill min="20"/> <!-- Not any hotshot can be a randomminer, theres standards ye know? -->
    <requires primarypurpose="purpose.mine"/>
  </order>

  <interrupts>
    <handler ref="SectorChangeHandler"/>
    <handler ref="AttackHandler"/>
    <handler ref="MissileLockHandler"/>
    <handler ref="ScannedHandler"/>
    <handler ref="InspectedHandler"/>
    <handler ref="FoundAbandonedHandler"/>
    <handler ref="ResupplyHandler"/>
    <handler ref="JobRemoveRequestHandler"/>
    <handler ref="TargetInvalidHandler"/>
  </interrupts>

  <init>
    <substitute_text text="$debugFileName" source="''+this.ship.idcode">
      <replace string="'('" with="''"/>
      <replace string="')'" with="''"/>
    </substitute_text>
    <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'Starting Log File Version: 122'" append="false"/>
    
    <set_order_syncpoint_reached order="this.ship.order"/>

    <set_command_action commandaction="commandaction.searchingtrades"/>
    
    <!--which factions do we allow?-->
    <do_if value="$allowAllFactions">
      <set_value name="$allowedFactions" exact="[faction.player,faction.argon,faction.antigone,faction.paranid,faction.holyorder,faction.alliance,
                 faction.teladi,faction.ministry,faction.hatikvah,faction.scaleplate]"/>
      <do_if value="faction.split">
        <append_to_list name="$allowedFactions" exact="faction.split"/>
        <append_to_list name="$allowedFactions" exact="faction.freesplit"/>
      </do_if>
      <do_if value="faction.terran">
        <append_to_list name="$allowedFactions" exact="faction.terran"/>
        <append_to_list name="$allowedFactions" exact="faction.pioneers"/>
        <append_to_list name="$allowedFactions" exact="faction.yaki"/>
      </do_if>
    </do_if>
    <do_else>
      <create_list name="$allowedFactions"/>
      <do_if value="$allowPlayer">
        <append_to_list name="$allowedFactions" exact="faction.player"/>
      </do_if>
      <do_if value="$allowArgon">
        <append_to_list name="$allowedFactions" exact="faction.argon"/>
      </do_if>
      <do_if value="$allowAntigone">
        <append_to_list name="$allowedFactions" exact="faction.antigone"/>
      </do_if>
      <do_if value="$allowParanid">
        <append_to_list name="$allowedFactions" exact="faction.paranid"/>
      </do_if>
      <do_if value="$allowHolyOrder">
        <append_to_list name="$allowedFactions" exact="faction.holyorder"/>
      </do_if>
      <do_if value="$allowAlliance">
        <append_to_list name="$allowedFactions" exact="faction.alliance"/>
      </do_if>
      <do_if value="$allowTeladi">
        <append_to_list name="$allowedFactions" exact="faction.teladi"/>
      </do_if>
      <do_if value="$allowMinistry">
        <append_to_list name="$allowedFactions" exact="faction.ministry"/>
      </do_if>
      <do_if value="$allowHatikvah">
        <append_to_list name="$allowedFactions" exact="faction.hatikvah"/>
      </do_if>
      <do_if value="$allowSplit and faction.split">
        <append_to_list name="$allowedFactions" exact="faction.split"/>
      </do_if>
      <do_if value="$allowFreeSplit and faction.freesplit">
        <append_to_list name="$allowedFactions" exact="faction.freesplit"/>
      </do_if>
      <do_if value="$allowTerran and faction.terran">
        <append_to_list name="$allowedFactions" exact="faction.terran"/>
      </do_if>
      <do_if value="$allowPioneers and faction.pioneers">
        <append_to_list name="$allowedFactions" exact="faction.pioneers"/>
      </do_if>
      <do_if value="$allowYaki and faction.yaki">
        <append_to_list name="$allowedFactions" exact="faction.yaki"/>
      </do_if>
      <do_if value="$allowScaleplate">
        <append_to_list name="$allowedFactions" exact="faction.scaleplate"/>
      </do_if>
    </do_else>

    <!--some global variables-->
    <set_value name="$pilotSkill" exact="this.ship.pilot.skill.management"/>
    <!--minimum profit and maximum relative price while buying depend on management skill of pilot and profit scale - slider-->
    <set_value name="$maxBuyRelPrice" exact="(-0.325-0.025*($pilotSkill)f)"/>
    <set_value name="$buyRange" exact=" if $homeBound then $home else this.ship"/>
    <set_value name="$stepNr" exact="1"/>

    <!--initialize fleet inner communication (search interval on idling ships)-->
    <do_if value="this.ship.commander" negate="true">
      <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'Idling fleet: I am commander'"/>
      <set_value name="this.$randomXLastUpdated" exact="player.age"/>
      <set_value name="this.$randomXForceNext" exact="0"/>
    </do_if>

    <set_value name="this.$randomXLastMiningOrder" exact="-1.0f"/>
  </init>

  <attention min="unknown">
    <actions>

      <!--are ware presets used?-->
      <do_if value="$wareBasket.count == 0 and $allWares" negate="true"> <!--for presets to kick in, wareBasket must be empty and All Wares toggled-->
        <resume label="start"/>
      </do_if>
      
      <!-- ware preset lists -->
      <set_value name="$listCounter" exact="-1"/>
      <label name="wareLists"/>
      <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'detected presets'"/>
      <do_if value="this.ship.cargo.capacity.solid gt 0 and $listCounter lt 1">
        <set_value name="$waresToAdd" exact="[ware.ore, ware.silicon, ware.ice, ware.nividium]"/>
        <set_value name="$listCounter" exact="1"/>
        <resume label="addtoWaresToBasket"/>
      </do_if>
      <do_elseif value="this.ship.cargo.capacity.liquid gt 0 and $listCounter lt 1">
        <set_value name="$waresToAdd" exact="[ware.helium, ware.methane, ware.hydrogen]"/>
        <set_value name="$listCounter" exact="2"/>
        <resume label="addtoWaresToBasket"/>
      </do_elseif>

      <!--all lists done-->
      <remove_value name="$listCounter"/>
      <remove_value name="$waresToAdd"/>
      <resume label="start"/>
      
      <label name="addtoWaresToBasket"/> <!--labels inside if-statements, loops and init are not allowed-->
      <do_all exact="$waresToAdd.count" counter="$ware">
        <set_value name="$addingWare" exact="$waresToAdd.{$ware}"/>
        <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'scanning ware: '+$addingWare"/>
        <do_if value="$wareBasket.indexof.{$addingWare}" negate="true">
          <append_to_list name="$wareBasket" exact="$addingWare"/>
          <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'adding ware to basket'"/>
        </do_if>
        <wait min="1ms" max="3ms"/>
      </do_all>
      <resume label="wareLists"/>

      <label name="start"/>

      <!--here we want to copy settings to subordinates-->
      <set_value name="$subordinates" exact="this.ship.subordinates"/>
      <set_value name="$subNr" exact="$subordinates.count"/>
      <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'found subordinates: '+$subNr+', update them: '+$updateSubordinates"/>

      <do_if value="$subordinates and not $updateSubordinates">
        <set_value name="$elapsed" exact="player.age - this.$randomXLastUpdateSubordinates" />
        <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'      time since last subordinate update: ' + $elapsed"/>
        <do_if value="$elapsed gt 3600.0">
          <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'        => Automatic update subordinates'"/>
          <edit_order_param order="this.ship.defaultorder" param="'updateSubordinates'" value="true"/>
        </do_if>
      </do_if>

      <do_all exact="$subNr" counter="$nr">
        <set_value name="$subordinate" exact="$subordinates.{$nr}"/>
        <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'  '+$nr+' '+$subordinate.idcode"/>
        <do_if value="($subordinate.type == this.ship.type and $subordinate.defaultorder.id != this.ship.defaultorder.id) or
               ($subordinate.defaultorder.id == this.ship.defaultorder.id and $updateSubordinates)" negate="true">
          <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'    not same shiptype: '+$subordinate.type+' and '+this.ship.type
                         +', or not assigned to defend, assignment: '+$subordinate.assignment"/>
          <continue/>
        </do_if>
        <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'    copying default behavior'"/>
        <do_if value="$subordinate.defaultorder.id == this.ship.defaultorder.id">
          <set_value name="$updating" exact="true"/>
        </do_if>
        <create_order object="$subordinate" default="true" id ="'RandomMine'">
          <param name="supplier"           value="$supplier"/>
          <param name="freeMiner"          value="$freeMiner"/>
          <param name="home"               value="$home"/>
          <param name="homeBound"          value="$homeBound"/>
          <param name="maxMine"            value="[$maxMine, @$subordinate.pilot.skill.piloting * 2].min"/>
          <param name="maxSell"            value="[$maxSell, @$subordinate.pilot.skill.piloting * 2].min"/>
          <param name="maxServe"           value="[$maxServe, @$subordinate.pilot.skill.piloting * 2].min"/>
          <param name="wareBasket"         value="$wareBasket"/>
          <param name="allWares"           value="$allWares"/>
          <param name="stockRatioToMine"   value="$stockRatioToMine"/>
          <param name="allowAllFactions"   value="$allowAllFactions"/>
          <param name="allowPlayer"        value="$allowPlayer"/>
          <param name="allowArgon"         value="$allowArgon"/>
          <param name="allowAntigone"      value="$allowAntigone"/>
          <param name="allowTeladi"        value="$allowTeladi"/>
          <param name="allowMinistry"      value="$allowMinistry"/>
          <param name="allowParanid"       value="$allowParanid"/>
          <param name="allowHolyOrder"     value="$allowHolyOrder"/>
          <param name="allowSplit"         value="$allowSplit"/>
          <param name="allowFreeSplit"     value="$allowFreeSplit"/>
          <param name="allowAlliance"      value="$allowAlliance"/>
          <param name="allowHatikvah"      value="$allowHatikvah"/>
          <param name="allowTerran"        value="$allowTerran"/>
          <param name="allowPioneers"      value="$allowPioneers"/>
          <param name="allowScaleplate"    value="$allowScaleplate"/>
          <param name="allowYaki"          value="$allowYaki"/>
          <param name="updateSubordinates" value="$updateSubordinates"/>
        </create_order>
        <set_object_commander object="$subordinate" commander="this.ship" assignment="assignment.trade"/>
        <do_if value="@$updating" negate="true">
          <remove_value name="$updating"/>
          <wait min="5s" max="10s"/>
        </do_if>
      </do_all>
      <!--count idling ships in fleet-->
      <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'Idling fleet refresh start'"/>
      <do_if value="this.ship.commander" negate="true">
        <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'  I am commander'"/>
        <set_value name="this.$randomXLastUpdated" exact="player.age"/>
        <set_value name="this.$randomXIdleShips" exact="@this.$randomXIdling"/>
        <do_all exact="$subNr" counter="$nr">
          <set_value name="this.$randomXIdleShips" exact="@$subordinates.{$nr}.pilot.$randomXIdling" operation="add"/>
        </do_all>
        <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'  found '+($subNr+1)+' ships in fleet, '+@this.$randomXIdleShips+' are idling'"/>
      </do_if>
      <do_else>
        <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'  I am not commander'"/>
        <do_all exact="$subNr" counter="$nr">
          <set_object_commander object="$subordinates.{$nr}" commander="this.ship.commander" assignment="assignment.trade"/>
        </do_all>
        <set_value name="$rng" min="180f" max="200f"/>
        <set_value name="$lastUpdated" exact="player.age - this.ship.commander.pilot.$randomXLastUpdated"/>
        <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'  last update is '+$lastUpdated+
              ' ago, idling: '+@this.ship.commander.pilot.$randomXIdleShips+', chance to update: '+(100f / ((@this.ship.commander.pilot.$randomXIdleShips)f + 0.1) * ($lastUpdated / $rng))"/>
        <do_if value="$lastUpdated ge $rng" chance="100f / ((@this.ship.commander.pilot.$randomXIdleShips)f + 0.1) * ($lastUpdated / $rng)">
          <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'  updating'"/>
          <set_value name="this.ship.commander.pilot.$randomXLastUpdated" exact="player.age"/>
          <set_value name="this.ship.commander.pilot.$randomXIdleShips" exact="@this.ship.commander.pilot.$randomXIdling"/>
          <set_value name="$subordinates" exact="this.ship.commander.subordinates"/>
          <do_all exact="$subordinates.count" counter="$nr">
            <set_value name="this.ship.commander.pilot.$randomXIdleShips" exact="@$subordinates.{$nr}.pilot.$randomXIdling" operation="add"/>
          </do_all>
          <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'  found '+($subordinates.count+1)+' ships in fleet, '+@this.ship.commander.pilot.$randomXIdleShips+' are idling'"/>
        </do_if>
      </do_else>
      <remove_value name="$subordinates"/>
      <remove_value name="$subNr"/>
      <remove_value name="$subordinate"/>
      <do_if value="$updateSubordinates">
        <edit_order_param order="this.ship.defaultorder" param="'updateSubordinates'" value="false"/>
        <set_value name="this.$randomXLastUpdateSubordinates" exact="player.age"/>
      </do_if>

      <!-- Check stuck mining ships
      ================================================================================================
      ================================================================================================
      ================================================================================================-->
      <set_value name="this.$randomXLastMiningOrder" exact="-1.0f"/>

      <set_value name="$commander" exact="if this.ship.commander then this.ship.commander.pilot else this" />
      <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'Last stuck check: ' + $commander.$randomXLastStuckCheck"/>
      <do_if value="(player.age - $commander.$randomXLastStuckCheck)f gt 60.0">
        <set_value name="$commander.$randomXLastStuckCheck" exact="player.age" />
        <create_list name="$lstAllShips"/>
        <append_to_list name="$lstAllShips" exact="$commander"/>
        <do_all exact="$commander.ship.subordinates.count" counter="$idx">
          <append_to_list name="$lstAllShips" exact="$commander.ship.subordinates.{$idx}.pilot"/>
        </do_all>
        <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'List size: ' + $lstAllShips.count"/>
        <do_all exact="$lstAllShips.count" counter="$lstAllShipsIdx">
          <set_value name="$curShip" exact="$lstAllShips.{$lstAllShipsIdx}"/>
          <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'    check ship: ' + $curShip.ship.idcode + ' => ' + $curShip.ship.order.id"/>

          <do_if value="$curShip.ship.order.id == 'MiningCollect'">
            <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'      $randomXLastMiningOrder: ' + $curShip.$randomXLastMiningOrder"/>
            <do_if value="$curShip.$randomXLastMiningOrder gt 0.0" negate="true">
              <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'      setting timestamp'"/>
              <set_value name="$curShip.$randomXLastMiningOrder" exact="player.age"/>
            </do_if>
            <do_else>
              <set_value name="$elapsed" exact="player.age - $curShip.$randomXLastMiningOrder" />
              <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'      $elapsed: ' + $elapsed"/>
              <do_if value="$elapsed gt 1200.0">
                <write_to_logbook category="upkeep" title="'RandomMine: '+$curShip.ship.knownname+' ( '+$curShip.ship.idcode+' )'" interaction="showonmap"
                          object="$curShip.ship" text="'Cancelling mining order, because it took longer than 20 minutes.'"/>
                <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'        => Cancelling order'"/>
                <cancel_order order="$curShip.ship.order"/>
                <continue />
              </do_if>
            </do_else>
          </do_if>

          <do_if value="$curShip.$randomXLastMiningOrder gt 0.0">
            <set_value name="$elapsed" exact="player.age - $curShip.$randomXLastMiningOrder" />
            <do_if value="$elapsed gt 3600.0">
              <write_to_logbook category="upkeep" title="'RandomMine: '+$curShip.ship.knownname+' ( '+$curShip.ship.idcode+' )'" interaction="showonmap"
                          object="$curShip.ship" text="'Cancelling all orders, because it took longer than 60 minutes.'"/>
              <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'        Ship has been on the current order set for an hour => Cancelling all orders'"/>
              <cancel_all_orders object="$curShip.ship"/>
            </do_if>
          </do_if>
        </do_all>
        <remove_value name="$lstAllShips"/>
        <remove_value name="$curShip"/>
        <remove_value name="$elapsed"/>
      </do_if>
      
      <remove_value name="$commander"/>

      <!-- Mine logik
      ================================================================================================
      ================================================================================================
      ================================================================================================-->

      <!--do we have wares in cargo already? lets try to sell them-->
      <set_value name="$cargo" exact="this.ship.cargo.list"/>
      <shuffle_list list="$cargo"/>
      <set_value name="$searchStep" exact="(1.0-$maxBuyRelPrice)/4.0"/>

      <!--here search for player own buyers-->
      <label name="searchSellFromCargo"/>
      <do_all exact="$cargo.count" counter="$wareInCargo">
        <wait min="1ms" max="200ms" comment="Avoid performance peaks with find functions" />

        <set_value name="$currentWare" exact="$cargo.{$wareInCargo}"/>
        <set_value name="$amount" exact="this.ship.cargo.{$currentWare}.count"/>
        <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'trying to sell '+$currentWare+' from cargo to player'"/>

        <find_buy_offer space="player.galaxy" result="$buyOffer" wares="$currentWare" tradepartner="this.ship">
          <amount min="$amount"/>
          <match_buyer owner="this.ship.owner">
            <match_gate_distance max="100" object="$buyRange">
              <blacklist group="blacklistgroup.civilian" object="this.ship"/>
            </match_gate_distance>
            <match_parent>
              <match_parent>
                <match_use_blacklist group="blacklistgroup.civilian" type="blacklisttype.sectortravel" object="this.ship"/>
                <match_use_blacklist group="blacklistgroup.civilian" type="blacklisttype.sectoractivity" object="this.ship"/>
              </match_parent>
            </match_parent>
          </match_buyer>
        </find_buy_offer>
        
        <do_if value="$buyOffer == null">
          <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'  could not find player buyer.'"/>
          <continue/>
        </do_if>

        <resume label="createSellFromCargo"/>

      </do_all>

      <!--here search for npc buyers-->
      <do_all exact="$cargo.count" counter="$wareInCargo">
        <wait min="1ms" max="200ms" comment="Avoid performance peaks with find functions" />

        <set_value name="$currentWare" exact="$cargo.{$wareInCargo}"/>
        <set_value name="$amount" exact="this.ship.cargo.{$currentWare}.count"/>
        <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'trying to sell '+$amount+' '+$currentWare+' from cargo to npc'"/>
        
        <do_all exact="5" counter="$reduction">

          <!--searching suiting buy offer, will search 5 times reducing requirements each time by 20% (just want to get rid of that stuff at some point)-->
          <find_buy_offer space ="player.galaxy" result="$buyOffer" wares="$currentWare" tradepartner="this.ship">
            <match_buyer tradesknownto="this.owner" owner="$allowedFactions">
              <match_use_blacklist group="blacklistgroup.civilian" type="blacklisttype.objectactivity" object="this.ship"/>
              <match_gate_distance object="$buyRange" max="$maxSell+$reduction-1">
                <blacklist group="blacklistgroup.civilian" object="this.ship"/>
              </match_gate_distance>
              <match_relation_to object="this.ship" relation="neutral" comparison="ge"/><!--not selling to hostile buyers-->
              <match_parent><!--parent of buyer is zone (empty space)-->
                <match_relation_to object="this.ship" relation="neutral" comparison="ge"/><!--not selling to friendly buyers in hostile zones-->
                <match_parent>
                  <match_use_blacklist group="blacklistgroup.civilian" type="blacklisttype.sectortravel" object="this.ship"/>
                  <match_use_blacklist group="blacklistgroup.civilian" type="blacklisttype.sectoractivity" object="this.ship"/>
                </match_parent>
              </match_parent>
            </match_buyer>
            <relativeprice min="-$maxBuyRelPrice-(($reduction)f-1.0)*$searchStep-0.001"/>
            <amount min="$amount*(0.8^($reduction-1))"/>
          </find_buy_offer>
          <wait min="1ms" max="100ms" comment="Avoid performance peaks with find functions" />

          <do_if value="$buyOffer == null">
            <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'  could not find buyer for min amount: '+$amount*(0.8^($reduction-1))+
                           ' min relative price: '+(-$maxBuyRelPrice-(($reduction)f-1.0)*$searchStep-0.001)+', max gates :'+($maxSell+$reduction-1)"/>
            <continue/>
          </do_if>

          <resume label="createSellFromCargo"/>

        </do_all>
        <show_notification text="['RandomMine: '+this.ship.knownname+' ('+this.ship.idcode+')', '', 'can\'t empty cargo', [$amount+' '+$currentWare, 255, 192, 126]]" sound="notification_warning" />
        <write_to_logbook category="upkeep" title="'RandomMine: '+this.ship.knownname+' ( '+this.ship.idcode+' )'" interaction="showonmap"
                          object="this.ship" text="'can\'t get rid of '+$amount+' '+$currentWare+' from cargo, what should I do?'"/>
      </do_all>
      <remove_value name="$cargo"/>
      <remove_value name="$searchStep"/>

      <resume label="supply"/>

      <label name="createSellFromCargo"/>
      <set_value name="$amount" exact="[$amount,$buyOffer.amount].min"/>
      <debug_to_file name="$debugFileName" directory="'RandomMine'" text="
                       '  found buyer: ownername: '+$buyOffer.owner.knownname+'('+$buyOffer.owner.owner.knownname+'), unitprice: '+$buyOffer.unitprice+', amount: '+$buyOffer.amount+
                       ', relative price: '+$buyOffer.relativeprice+', totalprice: '+$buyOffer.price+', sector: '+$buyOffer.owner.sector.knownname+
                       ', gates from this ship: '+$buyOffer.owner.gatedistance.{this.ship}+', gates from home (from ship if not homebound): '+$buyOffer.owner.gatedistance.{$buyRange}+
                       '. selling amount: '+$amount"/>
      <do_if value="$buyOffer.available">
        <write_to_logbook category="upkeep" title="'RandomMine: '+this.ship.knownname+' ( '+this.ship.idcode+' )'" interaction="showonmap"
                          object="this.ship" money="$buyOffer.unitprice*$amount"
                          text="'Selling from cargo '+$amount+' '+$currentWare+' to '+$buyOffer.owner.knownname+', unitprice: '+$buyOffer.unitprice/100"/>
        <create_trade_order object="this.ship" amount="$amount" tradeoffer="$buyOffer"/>
        <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'  trade created'"/>
        <resume label="finish"/>
      </do_if>
      <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'  offer not available anymore'"/>
      <resume label="searchSellFromCargo"/>

      <label name="supply"/>

      <!--lets see if we actually have free space in cargo before trying to mine-->
      <do_if value="this.ship.cargo.free.all lt (this.ship.cargo.capacity.all/10)">
        <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'  cargo is full =('"/>
        <resume label="noTradesPossible"/>
      </do_if>

      <!-- lets see how many ships are idling in our fleet and decide if we want to seach based on that-->
      <do_if value="@this.$randomXIdling">
        <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'I was idling, lets see if I am allowed to attempt to wake up'"/>
        <do_if value="if this.ship.commander then this.ship.commander.pilot.$randomXForceNext else this.$randomXForceNext" negate="true">
          <do_all chance="100f - 100f / ((if @this.ship.commander then @this.ship.commander.pilot.$randomXIdleShips else @this.$randomXIdleShips)f + 0.1)">
            <resume label="noTradesPossible"/>
          </do_all>
          <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'  I was not allowed, but decided to do it anyway =)'"/>
        </do_if>
        <do_else>
          <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'  I was allowed to wake up'"/>
          <do_if value="this.ship.commander">
            <set_value name="this.ship.commander.pilot.$randomXForceNext" exact="0"/>
          </do_if>
          <do_else>
            <set_value name="this.$randomXForceNext" exact="0"/>
          </do_else>
        </do_else>
      </do_if>

      <!--======== all fine, ship is ready for randommining =======-->

      <!--lets get a list with possible sectors in which we can mine taking blacklists into account, sorted by gate distance-->
      <run_script name="'lib.find.sectors.inrange'" result="$sectors">
        <param name="refobject" value="$buyRange"/>
        <param name="maxgatedistance" value="$maxMine"/>
      </run_script>

      <remove_value name="$sectors.{$sectors.indexof.{this.sector}}"/>
      <set_value name="$sectors.{1}" exact="this.sector" operation="insert"/><!--put current sector at first place (highest priority)-->
      <!--remove hostile sectors-->
      <do_all exact="$sectors.count" counter="$nr" reverse="true">
        <do_if value="$sectors.{$nr}.relationto.{this.ship} lt -0.01">
          <remove_value name="$sectors.{$nr}"/>
        </do_if>
      </do_all>
      <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'found '+$sectors.count+' possible sectors for mining.'"/>

      <!--are we supplying our stations?-->
      <do_if value="$supplier" negate="true">
        <resume label="freeMiner"/>
      </do_if>
      <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'-starting supply mode-'"/>

      <set_value name="$searchStepBuy" exact="($stockRatioToMine)f/500.0"/>
      
      <!--<debug_to_file name="$debugFileName + '-stations'" directory="'RandomMine'" text="'Searching for stations with mining needs'" append="false"/>
      <find_buy_offer space="player.galaxy" result="$buyOffers" wares="$wareBasket" multiple="true" tradepartner="this.ship">
        <match_buyer class="class.station" owner="this.ship.owner">
          <match_gate_distance object="$buyRange" max="$maxServe">
            <blacklist group="blacklistgroup.civilian" object="this.ship"/>
          </match_gate_distance>
          <match_parent>
            <match_parent>
              <match_use_blacklist group="blacklistgroup.civilian" type="blacklisttype.sectortravel" object="this.ship"/>
              <match_use_blacklist group="blacklistgroup.civilian" type="blacklisttype.sectoractivity" object="this.ship"/>
            </match_parent>
          </match_parent>
        </match_buyer>
      </find_buy_offer>
      <do_all exact="$buyOffers.count" counter="$buyOffer">
        <set_value name="$currentBuyOffer" exact="$buyOffers.{$buyOffer}"/>
        <set_value name="$currentWare" exact="$currentBuyOffer.ware"/>
        <set_value name="$amount" exact="[this.ship.cargo.{$currentWare}.free,if $stationOrBuild==2 then $currentBuyOffer.desiredamount else $currentBuyOffer.amount].min"/>
        <debug_to_file name="$debugFileName + '-stations'" directory="'RandomMine'" text="'  searching for supply '+$currentBuyOffer.owner.knownname+
                       ': amount: '+$amount+', ware: '+$currentWare+', relativeprice: '+$currentBuyOffer.relativeprice"/>
      </do_all>-->

      <!--what do our stations need?-->
      <label name="stationBuys"/>

      <find_buy_offer space="player.galaxy" result="$buyOffers" wares="$wareBasket" multiple="true" tradepartner="this.ship">
        <match_buyer class="class.station" owner="this.ship.owner">
          <match_gate_distance object="$buyRange" max="$maxServe">
            <blacklist group="blacklistgroup.civilian" object="this.ship"/>
          </match_gate_distance>
          <match_parent>
            <match_parent>
              <match_use_blacklist group="blacklistgroup.civilian" type="blacklisttype.sectortravel" object="this.ship"/>
              <match_use_blacklist group="blacklistgroup.civilian" type="blacklisttype.sectoractivity" object="this.ship"/>
            </match_parent>
          </match_parent>
        </match_buyer>
        <relativeprice min="1.0-0.35*($stepNr)f" max="1.05-0.35*($stepNr-1)f"/>
      </find_buy_offer>
      <wait min="1ms" max="100ms" comment="Avoid performance peaks with find functions" />
      <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'  step: '+($stepNr)+', found '+$buyOffers.count+
                     ' buy offers from player stations'"/>
      <set_value name="$stepNr" operation="add"/>

      <!--search for mining possibilities-->
      <label name="searchMine"/>
      <shuffle_list list="$buyOffers"/>
      <do_all exact="$buyOffers.count" counter="$buyOffer">
        <wait min="1ms" max="100ms" comment="Avoid performance peaks with find functions" />
        <set_value name="$currentBuyOffer" exact="$buyOffers.{$buyOffer}"/>
        <set_value name="$currentWare" exact="$currentBuyOffer.ware"/>
        <set_value name="$amount" exact="[this.ship.cargo.{$currentWare}.free, $currentBuyOffer.desiredamount].min"/>
        <set_value name="$amountFactor" min="0.2f" max="5.0f" />
        <set_value name="$amountMineTarget" exact="$amount*$amountFactor"/>
        <set_value name="$sectors.{2}" exact="$currentBuyOffer.owner.sector" operation="insert"/><!--put sector of your station on second place-->
        <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'    searching for resources to supply '+$currentBuyOffer.owner.knownname+
                       ': amount: '+$amount+' * RND (' + $amountFactor + ') => amountMineTarget: '+ $amountMineTarget + ', ware: '+$currentWare+', relativeprice: '+$currentBuyOffer.relativeprice"/>
        
        <do_all exact="$sectors.count" counter="$nrs">
          <wait min="1ms" max="100ms" comment="Avoid performance peaks with find functions"/>
          <set_value name="$sector" exact="$sectors.{$nrs}"/>
          <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'      Scanning '+$sector.knownname"/>
          
          <set_value name="$yieldTarget" exact="'veryhigh'"/>
          <get_highest_resource_yield result="$yieldResult" sector="$sector" ware="$currentWare" yieldname="$yieldTarget" comment="see library/regionyield.xml" />
          <do_if value="$yieldResult lt $amountMineTarget">
            <set_value name="$yieldTarget" exact="'high'"/>
            <get_highest_resource_yield result="$yieldResult" sector="$sector" ware="$currentWare" yieldname="$yieldTarget" comment="see library/regionyield.xml" />
          </do_if>
          <do_if value="$yieldResult lt $amountMineTarget">
            <set_value name="$yieldTarget" exact="'medium'"/>
            <get_highest_resource_yield result="$yieldResult" sector="$sector" ware="$currentWare" yieldname="$yieldTarget" comment="see library/regionyield.xml" />
          </do_if>
          <do_if value="$yieldResult lt $amountMineTarget">
            <set_value name="$yieldTarget" exact="'low'"/>
            <get_highest_resource_yield result="$yieldResult" sector="$sector" ware="$currentWare" yieldname="$yieldTarget" comment="see library/regionyield.xml" />
          </do_if>
          <do_if value="$yieldResult lt $amountMineTarget">
            <set_value name="$yieldTarget" exact="'verylow'"/>
            <get_highest_resource_yield result="$yieldResult" sector="$sector" ware="$currentWare" yieldname="$yieldTarget" comment="see library/regionyield.xml" />
          </do_if>
          
          <do_if value="$yieldResult lt $amountMineTarget" comment="Ware not found">
            <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'        no '+$currentWare+' in '+$sector.knownname"/>
            <continue/>
          </do_if>

          <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'        '+$currentWare+' found in '+$sector.knownname + ' with ' + $yieldTarget + ' yield and amount: ' + $yieldResult"/>

          <set_value name="$searchAmount" min="$amountMineTarget" max="$yieldResult" />
          <find_closest_resource sector="$foundSector" refobject="$sector" minamount="$searchAmount" ware="$currentWare" position="$minePosition"/>
          <do_if value="$foundSector != $sector">
            <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'        didnt find resource location for ' + $sector.name"/>
            <remove_value name="$foundSector"/>
            <remove_value name="$searchAmount"/>
            <continue/>
          </do_if>
          <remove_value name="$foundSector"/>
          <remove_value name="$searchAmount"/>

          <do_if value="$minePosition==null">
            <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'        no '+$currentWare+' in '+$sector.knownname"/>
            <continue/>
          </do_if>

          <do_if value="$currentBuyOffer.available">
            <write_to_logbook category="upkeep" title="'RandomMine: '+this.ship.knownname+' ( '+this.ship.idcode+' )'" interaction="showonmap"
                              object="this.ship" text="'going to '+$sector.knownname+' to mine '+$currentWare+' for '+$currentBuyOffer.owner.knownname"/>
            <create_order object="this.ship" id="'MoveWait'">
              <param name="destination" value="[$sector, $minePosition]" />
              <param name="recallsubordinates" value="true" />
            </create_order>
            <create_order object="this.ship" id="'MiningCollect'">
              <param name="destination" value="[$sector, $minePosition]"/>
              <param name="ware" value="$currentWare"/>
            </create_order>
            <create_trade_order object="this.ship" amount="$amount" tradeoffer="$currentBuyOffer"/>
            <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'      orders created.'"/>
            <resume label="finish"/>
          </do_if>

          <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'      Buyoffer is not available anymore.'"/>
          <break/>

        </do_all>
        <remove_value name="$sectors.{2}"/>
        <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'-could not find mineable resources-'"/>
      </do_all>

      <do_if value="$stepNr le 5">
        <resume label="stationBuys"/>
      </do_if>
      <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'-could not find possibilities to supply player stations-'"/>
      <remove_value name="$buyOffers"/>
      <remove_value name="$stepNr"/>
      <remove_value name="$currentBuyOffer"/>
      <remove_value name="$currentWare"/>
      <remove_value name="$amount"/>

      <!--are we mining for NPCs?-->
      <label name="freeMiner"/>
      <do_if value="$freeMiner" negate="true">
        <resume label="noTradesPossible"/>
      </do_if>
      <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'-starting free mine mode-'"/>
      
      <do_all exact="$sectors.count" counter="$nrs">
        <wait min="1ms" max="100ms" comment="Avoid performance peaks with find functions" />
        <set_value name="$sector" exact="$sectors.{$nrs}"/>
        <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'  Scanning '+$sector.knownname"/>
        <find_closest_resource ware="$wareBasket" refobject="$sector" position="$position" minamount="750" sector="$dummy">
          <refposition value="position.[0, 0, 0]"/>
        </find_closest_resource>

        <do_if value="$position==null">
          <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'    no resources in '+$sector.knownname"/>
          <continue/>
        </do_if>

        <find_object space="$sector" name="$gates" multiple="true" class="[class.gate, class.highwayentrygate, class.highwayexitgate]"/>
        <set_value name="$x" exact="0.0"/>
        <set_value name="$z" exact="0.0"/>
        <do_all exact="$gates.count" counter="$nrg">
          <set_value name="$gate" exact="$gates.{$nrg}"/>
          <create_position name="$position" space="$sector" value="$gate.position" object="$gate.zone"/>
          <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'      gate nr: '+$nrg+', '+$gate.knownname+' '+@$gate.destination.parent.knownname+' '+$position"/>
          <set_value name="$x" exact="$position.x" operation="add"/>
          <set_value name="$z" exact="$position.z" operation="add"/>
        </do_all>
        <set_value name="$x" exact="$x/($gates.count)f"/>
        <set_value name="$z" exact="$z/($gates.count)f"/>
        <set_value name="$angle" min="0.0" max="6.283"/>
        <set_value name="$radius" min="0.0" max="$sector.size/2"/>
        <set_value name="$position" exact="position.[($x+$radius*cos($angle)), 0, ($z+$radius*sin($angle))]"/>

        <wait min="1ms" max="100ms" comment="Avoid performance peaks with find functions" />
        <find_closest_resource ware="$wareBasket" refobject="$sector" position="$minePosition" minamount="750" wares="$wares" sector="$dummy">
          <refposition value="$position"/>
        </find_closest_resource>
        <remove_value name="$position"/>
        <wait min="1ms" max="100ms" comment="Avoid performance peaks with find functions" />

        <do_if value="$minePosition==null">
          <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'    no resources at random position.'"/>
          <continue/>
        </do_if>

        <write_to_logbook category="upkeep" title="'RandomMine: '+this.ship.knownname+' ( '+this.ship.idcode+' )'" interaction="showonmap"
                          object="this.ship" text="'going to '+$sector.knownname+' to mine.'"/>
        <create_order object="this.ship" id="'MoveWait'">
          <param name="destination" value="[$sector, $minePosition]" />
          <param name="recallsubordinates" value="true" />
        </create_order>
        <create_order object="this.ship" id="'MiningCollect'">
          <param name="destination" value="[$sector, $minePosition]"/>
          <param name="ware" value="$wares.random"/>
        </create_order>
        <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'  orders created.'"/>
        <resume label="end"/>

      </do_all>


      <label name="noTradesPossible"/>
      <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'--- NO POSSIBLE TRADES FOUND ---'"/>
      <set_value name="this.$randomXIdling" exact="1"/>
      <!--I could not find any trade for the required min profit, maybe scale down (use slider)? visit more stations/deploy more sattelites-->
      <wait min="120s" max="200s"/>
      <resume label="end"/>

      <label name="finish"/>
      <do_if value="@this.$randomXIdling">
        <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'    I woke up from idle, allowing next ship in fleet to also wake up'"/>
        <set_value name="this.$randomXIdling" exact="0"/>
        <do_if value="this.ship.commander">
          <set_value name="this.ship.commander.pilot.$randomXForceNext" exact="1"/>
        </do_if>
        <do_else>
          <set_value name="this.$randomXForceNext" exact="1"/>
        </do_else>
      </do_if>

      <label name="end"/>
      <debug_to_file name="$debugFileName" directory="'RandomMine'" text="'end'"/>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<content id="" name="" description="" version="100" save="0" author="Faryu" date="2023-01-28" lastupdate="">
  <dependency version="250"/>
</content>
