Advertisement
Guest User

Untitled

a guest
Feb 21st, 2017
354
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 20.09 KB | None | 0 0
  1. package.path = package.path .. ";data/scripts/lib/?.lua"
  2. package.path = package.path .. ";data/scripts/?.lua"
  3. require ("oosproductionLib")
  4. require ("utility")
  5. require ("asteroidSpawningLib")
  6. require ("goodsindex")
  7.  
  8. --data\scripts\player\oosproduction.lua
  9. "[0.9_6b]"                           -- do not change
  10. SectorGenerator = require("SectorGenerator")--remove
  11. PlanGenerator = require ("plangenerator")--remove
  12. Placer = require("placer")
  13. local spawnAstroInThisSector = 0
  14. local usesRightversion = false
  15.  
  16. function initialize()
  17.     if onServer() then
  18.         print(OOSPVERSION.."[OOSP] ".."======oos initialising for Player "..Player().name.."======")
  19.         --unregister events to clear things up.
  20.         local unregisterOnSectorLeftValue = Player():unregisterCallback("onSectorLeft", "onSectorLeft")
  21.         local unregisterOnSectorEnteredValue = Player():unregisterCallback("onSectorEntered", "onSectorEntered")
  22.         local unregisterOnPlayerLogOffValue = Server():unregisterCallback("onPlayerLogOff", "onPlayerLogOff")
  23.        
  24.         print(OOSPVERSION.."[OOSP] ".."Event unregisteration: "..tostring(unregisterOnSectorLeftValue).." | "..tostring(unregisterOnSectorEnteredValue).." | "..tostring(unregisterOnPlayerLogOffValue))
  25.        
  26.        
  27.        
  28.        
  29.        
  30.         --begin registering events for a fresh start
  31.         Player():registerCallback("onSectorLeft", "onSectorLeft")
  32.         Player():registerCallback("onSectorEntered", "onSectorEntered")
  33.         Server():registerCallback("onPlayerLogOff", "onPlayerLogOff")
  34.     else
  35.         local isallowed = invokeServerFunction("processVersion", Player().index, OOSPVERSION)
  36.         if isallowed then
  37.        
  38.         else
  39.        
  40.         end
  41.         invokeServerFunction("onPlayerLogIn",Player().index)
  42.     end
  43.    
  44. end
  45.  
  46. function processVersion(playerIndex, version)
  47.     if onServer() then
  48.         if version ~= OOSPVERSION then    
  49.             print(OOSPVERSION.."[OOSP] ".."Player "..Player(playerIndex).name.."uses a different version of OOSP: "..version)
  50.             Player(playerIndex):sendChatMessage("Server", 2, "Update your Version ("..version..") to "..OOSPVERSION..". OOSP is deactivated for you! ")
  51.             return false
  52.         else
  53.             print(OOSPVERSION.."[OOSP][T] ".."Player "..Player(playerIndex).name.."Logged in with the correct version of OOSP: "..version)
  54.             usesRightversion = true
  55.             return true
  56.         end
  57.     end
  58.  end
  59.  
  60.  
  61. --When a Player logs in, the onSectorEntered-Event is not fired. This would cause the Sector to be ignored by the oosproduction-Script.
  62. function onPlayerLogIn(playerIndex)
  63.     if Player(playerIndex).name ~= Player().name then            --wrong player called
  64.         return
  65.     end
  66.     if usesRightversion == false then
  67.         Player(playerIndex):sendChatMessage("Server", 2, "Update your Version to "..OOSPVERSION..". OOSP is deactivated for you! ")
  68.         print(OOSPVERSION.."[OOSP] ".."Player "..Player(playerIndex).name.."uses a different version of OOSP")
  69.         local unregisterOnSectorLeftValue = Player():unregisterCallback("onSectorLeft", "onSectorLeft")
  70.         local unregisterOnSectorEnteredValue = Player():unregisterCallback("onSectorEntered", "onSectorEntered")
  71.         local unregisterOnPlayerLogOffValue = Server():unregisterCallback("onPlayerLogOff", "onPlayerLogOff")
  72.         print(OOSPVERSION.."[OOSP] ".."Event unregisteration: "..tostring(unregisterOnSectorLeftValue).." | "..tostring(unregisterOnSectorEnteredValue).." | "..tostring(unregisterOnPlayerLogOffValue))
  73.         sendMoreMessages()
  74.         onPlayerLogOff(playerIndex)
  75.         return
  76.     end
  77.    
  78.     --print(OOSPVERSION.."[OOSP] ".."onPlayerLogIn executed from Client")
  79.     local x,y = Sector():getCoordinates()
  80.     onSectorEntered(playerIndex, x, y)
  81. end
  82.  
  83. function sendMoreMessages(playerIndex)
  84.     Player(playerIndex):sendChatMessage("Server", 2, "Update your Version to "..OOSPVERSION..". OOSP is deactivated for you! ")
  85.     print(OOSPVERSION.."[OOSP] ".."Remembered "..Player(playerIndex).name.." that he is using the wrong version")
  86.     deferredCallback(10,"sendMoreMessages",playerIndex)
  87. end
  88.  
  89.  
  90. function onPlayerLogOff(playerIndex)--Initialize gets called on PlayerLogIn    
  91.     if Player(playerIndex).name ~= Player().name then            --wrong player called
  92.         print(OOSPVERSION.."[OOSP] ".."Wrong Player Logoff")
  93.         return
  94.     end
  95.     --unregister twice: better safe than sorry
  96.     local unregisterOnSectorLeftValue = Player():unregisterCallback("onSectorLeft", "onSectorLeft")
  97.     local unregisterOnSectorEnteredValue = Player():unregisterCallback("onSectorEntered", "onSectorEntered")
  98.     local unregisterOnPlayerLogOffValue = Server():unregisterCallback("onPlayerLogOff", "onPlayerLogOff")
  99.        
  100.     print(OOSPVERSION.."[OOSP] ".."Event unregisteration: "..tostring(unregisterOnSectorLeftValue).." | "..tostring(unregisterOnSectorEnteredValue).." | "..tostring(unregisterOnPlayerLogOffValue))
  101.        
  102.     print(OOSPVERSION.."[OOSP] ".."======oos unloading Player "..Player(playerIndex).name.."======")
  103.     local x,y = Sector():getCoordinates()
  104.     print(OOSPVERSION.."[OOSP] "..Player(playerIndex).name .. " " .. x .. ":" .. y)
  105.     onSectorLeft(playerIndex, x, y)
  106. end
  107.  
  108. --sets a Timestamp when the last player leaves the Sector
  109. function onSectorLeft(playerIndex, x, y)
  110.     if Player(playerIndex).name ~= Player().name then            --wrong player called
  111.         return
  112.     end
  113.     local numplayer = Sector().numPlayers      
  114.     local galaxyTickName = ("galaxyticks"..tostring(Server().seed))
  115.     --local mutexstr = ("MA"..Player(playerIndex).name)                                           --TODO
  116.    
  117.     if(numplayer <=1) then   -- we only need a new timestamp when an sector gets unloaded. The player is still in sector when the Hook calls, thus we check for 1 remaining player
  118.         local timestamp = Sector():getValue("oosTimestamp")
  119.         if timestamp ~= nil then --update Timestamp
  120.             timestamp = Server():getValue(galaxyTickName)
  121.             Sector():setValue("oosTimestamp", timestamp)
  122.             print(OOSPVERSION.."[OOSP] ".."timestamp: ".. timestamp .. " for Sector ".. x .. ":" .. y.." updated")
  123.         else        --sector was never timestamped
  124.             timestamp = Server():getValue(galaxyTickName)
  125.             Sector():setValue("oosTimestamp", timestamp)
  126.             print(OOSPVERSION.."[OOSP] ".."Sector get first timestamp: ".. timestamp .. " | ".. x .. ":" .. y)
  127.         end
  128.     end  
  129.    
  130. end
  131.  
  132. --Is there a timestamp on which we can work?-Then do so.
  133. function onSectorEntered(playerIndex, x, y)
  134.     if Player(playerIndex).name ~= Player().name then            --wrong player called
  135.         return
  136.     end
  137.     local sec = systemTimeMs()
  138.     local totaltime = 0
  139.     local timestamp = Sector():getValue("oosTimestamp")
  140.     print(OOSPVERSION.."[OOSP] ".."Player: "..Player().name.." entered sector with: "..(Sector().numPlayers-1).." more player(s)")
  141.    
  142.     if timestamp ~= nil then
  143.         if Sector().numPlayers <= 1 then
  144.             print(OOSPVERSION.."[OOSP] ".."timestamp aquired: " .. timestamp)
  145.             calculateOOSProductionForStations(Sector(),timestamp)
  146.         else
  147.             print(OOSPVERSION.."[OOSP] ".."Sector has been loaded already: "..Sector().numPlayers)
  148.         end
  149.     else
  150.         print(OOSPVERSION.."[OOSP] ".."no timestamp - no production!")
  151.     end
  152.    
  153.     print(OOSPVERSION.."[OOSP] ".."Sector: "..x..":"..y.. " needed " .. (systemTimeMs()- sec).."ms for Production catch-up")
  154.     totaltime = totaltime + (systemTimeMs()- sec)
  155.     sec = systemTimeMs()
  156.     --spawn Asteroids int the sector we just enetered
  157.     asteroidSpawning(playerIndex,x,y)
  158.     print(OOSPVERSION.."[OOSP][mOS] ".."Asteroid Construction/Spawning/resolving needed "..(systemTimeMs()- sec).."ms")
  159.     totaltime = totaltime + (systemTimeMs()- sec)
  160.     sec = systemTimeMs()
  161.     --especially needed after Serverrestarts and players relogging
  162.     activateAsteroidScripts(playerIndex)                
  163.     totaltime = totaltime + (systemTimeMs()- sec)
  164.     print(OOSPVERSION.."[OOSP][mOS] ".."Asteroid activation needed "..(systemTimeMs()- sec).."ms of the total "..totaltime.."ms")
  165. end
  166.  
  167. function asteroidSpawning(playerIndex, x, y)
  168.     local desc
  169.     local player = Player(playerIndex)
  170.     local hasToSpawn = (spawnAstroInThisSector > 0 )
  171.     if hasToSpawn then
  172.         player:sendChatMessage("Asteroid", 3, "Interact with Asteroid(s) to jump again.")
  173.         desc = createAsteroidPlan(x,y)
  174.         print(OOSPVERSION.."[OOSP][mOS] ".. "will spawn "..spawnAstroInThisSector.." Asteroids in Sector")
  175.     end
  176.     while spawnAstroInThisSector > 0 do
  177.         spawnAstroInThisSector = spawnAstroInThisSector -1
  178.         spawnClaimedAsteroid(playerIndex,x,y,desc)
  179.     end
  180.     if hasToSpawn then
  181.         local sec = systemTimeMs()
  182.         Placer.resolveIntersections()
  183.         print(OOSPVERSION.."[OOSP][mOS] ".."Asteroid resolving needed "..(systemTimeMs()- sec).."ms")
  184.     end
  185. end
  186.  
  187. function activateAsteroidScripts(playerIndex)
  188.     local MSSN = "isMarkedToMove"
  189.     local MAEI = "MAEI%s:%s|%s"
  190.     local x,y = Sector():getCoordinates()
  191.     local asteroidIndex = Server():getValue(string.format(MAEI, x, y, playerIndex))
  192.     --activateAllAstros(playerIndex)                                          --testfunction
  193.     if asteroidIndex ~= nil then       --most likely a player relogin or server restart
  194.         print(OOSPVERSION.."[OOSP][mOS] ".."activating Asteroid: "..asteroidIndex)
  195.         Entity(asteroidIndex):invokeFunction("data/scripts/entity/moveAsteroid.lua","initCallback",playerIndex)
  196.     end
  197. end
  198.  
  199. function activateAllAstros(playerIndex) --just testing
  200.     local MSSN = "isMarkedToMove"
  201.     local MAEI = "MAEI%s:%s|%s"
  202.     local astroList = {Sector():getEntitiesByScript("data/scripts/entity/moveAsteroid.lua")}
  203.     print(OOSPVERSION.."[OOSP][mOS] "..#astroList)
  204.     for i,astro in pairs(astroList) do
  205.         if astro.factionIndex == playerIndex then
  206.             if astro:getValue(MSSN) == nil or astro:getValue(MSSN) == false then
  207.                 astro:setValue(MSSN, true)
  208.                 --print(OOSPVERSION.."[OOSP][mOS] ".."Register Entity to extrajump: "..tostring(astro.index))
  209.             end
  210.             local x,y = Sector():getCoordinates()
  211.             if Server():getValue(string.format(MAEI, x, y, playerIndex)) == nil then
  212.                 print(OOSPVERSION.."[OOSP][mOS] ".."Callbackholder: "..tostring(astro.index))
  213.                 Server():setValue(string.format(MAEI, x, y, playerIndex),astro.index)
  214.             end
  215.         end
  216.     end
  217. end
  218.  
  219. function increaseSpawnAstroInNextSector(val)
  220.     if val then
  221.         print("+val")
  222.         spawnAstroInThisSector =  spawnAstroInThisSector + val
  223.     else
  224.         print("val++")
  225.         spawnAstroInThisSector = spawnAstroInThisSector + 1
  226.     end
  227. end
  228.  
  229.  
  230. --apply retro-production to factories and shipyards.
  231. function calculateOOSProductionForStations(sector,timestamp)
  232.     local stations = {sector:getEntitiesByType(EntityType.Station)}
  233.     for _, station in pairs(stations) do
  234.         if (station:hasScript("factory.lua")) then                      --normal factory
  235.             if (station:hasScript("turretfactory.lua")) then            --factory is a substring of turretfactory, but a turretfactory doesn't produce anything
  236.                 return
  237.             end
  238.             calculateOOSProductionForFactory(station, timestamp)
  239.         end
  240.         if (station:hasScript("shipyard.lua")) then                      --shipyard
  241.             print(OOSPVERSION.."[OOSP] ".."update shipyard: "..station.name)
  242.             calculateOOSProductionForShipyard(station,timestamp)
  243.            
  244.         end
  245.     end
  246.  
  247. end
  248.  
  249. function calculateOOSProductionForShipyard(shipyard,timestamp)
  250.     local galaxyTickName = ("galaxyticks"..tostring(Server().seed))
  251.     local currentTime = Server():getValue(galaxyTickName)
  252.     local timeDelta = currentTime - timestamp
  253.     timeDelta = timeDelta/20
  254.     if timeDelta <= 0 then
  255.         return
  256.     end
  257.     local dat = shipyard:invokeFunction("data/scripts/entity/merchants/shipyard.lua","update",timeDelta)
  258.     if(tostring(dat) == "0") then
  259.         print(OOSPVERSION.."[OOSP] ".."update shipyard +: "..timeDelta)
  260.     else
  261.         print(OOSPVERSION.."[OOSP] ".."Error updating shipyard: "..tostring(dat))
  262.        
  263.     end
  264. end
  265.  
  266. --calculate the production in absence
  267. function calculateOOSProductionForFactory(factory,timestamp)
  268.     local galaxyTickName = ("galaxyticks"..tostring(Server().seed))
  269.     local currentTime = Server():getValue(galaxyTickName)
  270.     if type(currentTime) ~= "number" then
  271.         print(OOSPVERSION.."[OOSP] ".."galaxyticks not found!")
  272.         return
  273.     end
  274.     local timeDelta = currentTime - timestamp
  275.     if timeDelta < 1 then
  276.         print(OOSPVERSION.."[OOSP] ".."There was a Jump back in time! Did the server crash previously?") --more likely : the Tickhandler restarted or could not load the Ticksfile
  277.         return
  278.     end
  279.     print(OOSPVERSION.."[OOSP] "..factory.title.. "    "..factory.name)
  280.     local status , factoryData = factory:invokeFunction("factory", "secure", nil)
  281.     print(OOSPVERSION.."[OOSP] ".."Status: " .. status)
  282.     local maxDuration = 0
  283.     local maxNumProductions = 0
  284.     local factorySize = 0
  285.     local production = {}
  286.     local currentProductions = {}
  287.     local tradingdata = {}
  288.     if status == 0 then
  289.         maxDuration = factoryData.maxDuration                 --Factory total cycle time
  290.         maxNumProductions = factoryData.maxNumProductions     --max. number simultainious Productions
  291.         factorySize = factoryData.maxNumProductions - 1       --self explained
  292.         production = factoryData.production                   -- *.ingredients, *.results, *.garbage
  293.         currentProductions = factoryData.currentProductions   --Table with the passed cycletime per running Production
  294.         tradingdata = factoryData.tradingData                 --All Information about stored Goods in a Station
  295.     else
  296.         print(OOSPVERSION.."[OOSP] "..factory.name..": konnte keine Daten erhalten")
  297.         return
  298.     end
  299.     if(maxDuration == 0) then
  300.         print(OOSPVERSION.."[OOSP] "..factory.name.."has a cycletime of 0. This is odd!")
  301.     end
  302.     local maximumProcesses = (timeDelta / (maxDuration * 20)) * maxNumProductions -- theoretical maximum we can produce ine the Timeframe. Might be corrected down later on.
  303.     local minimumProcess = maximumProcesses / 4    -- minimum guaranteed production, to takes into account traders moving goods as the player is away
  304.     print(OOSPVERSION.."[OOSP] ".."timeDelta: "..timeDelta)
  305.     print(OOSPVERSION.."[OOSP] ".."Starting with: "..maximumProcesses)
  306.     local spaceForExtraProcessesNeeded = 0     --since the currently running processes will be ended within the factory script, we need to make sure that they will still fit in.
  307.     for i,timepassed in pairs(currentProductions) do
  308.         if(maxDuration - timepassed) * 20 <= timeDelta then --20 ticks / Sec. ; timeDelta is in Ticks
  309.             print(OOSPVERSION.."[OOSP] ".."Current Process at: "..timepassed)
  310.             maximumProcesses = maximumProcesses - 1
  311.             spaceForExtraProcessesNeeded = spaceForExtraProcessesNeeded + 1
  312.             currentProductions[i] = maxDuration
  313.         else
  314.         -- we don't bother about this special case
  315.         end
  316.     end
  317.     print(OOSPVERSION.."[OOSP] ".."Current production reduces to: "..maximumProcesses)
  318.     if(maximumProcesses <= 0 )then
  319.         print(OOSPVERSION.."[OOSP] ".."no Production catch-up needed.")
  320.     end
  321.     --get max. amount of Processcycles we can have with our ressources
  322.     for _, ingredient in pairs(production.ingredients) do
  323.         if(ingredient.amount == 0) then
  324.             print(OOSPVERSION.."[OOSP] "..factory.name.." doesn't need "..ingredient.name.."for production.")
  325.         else
  326.             if ingredient.optional == 0 and math.floor(getNumGoods(factory, ingredient.name) / ingredient.amount) > 0 then
  327.                 print(OOSPVERSION.."[OOSP] "..ingredient.name..": "..getNumGoods(factory, ingredient.name).." | required: " .. ingredient.amount)
  328.                 maximumProcesses = math.min(math.floor(getNumGoods(factory, ingredient.name) / ingredient.amount), maximumProcesses)
  329.             end
  330.             if(ingredient.optional == 0 and getNumGoods(factory, ingredient.name) < ingredient.amount) then
  331.                 print(OOSPVERSION.."[OOSP] ".."can't do single process: "..ingredient.name)
  332.             end
  333.         end
  334.     end
  335.     print(OOSPVERSION.."[OOSP] ".."Ressources reduce to: "..maximumProcesses)
  336.    
  337.     -- only halve production if factory was stocked
  338.     minimumProcess = math.max(maximumProcesses/2, minimumProcess)
  339.    
  340.     --get max. amount of Processcycles we can have with our garbage capacity
  341.     for _, garbage in pairs(production.garbages) do
  342.         print(OOSPVERSION.."[OOSP] ".."Free space for "..garbage.name..": "..(getMaxGoods(factory, tradingdata, garbage.name) - getNumGoods(factory, garbage.name)).." | required: " .. garbage.amount)
  343.         maximumProcesses = math.min((getMaxGoods(factory, tradingdata, garbage.name) - getNumGoods(factory, garbage.name)), maximumProcesses)
  344.         if maximumProcesses == 0 then
  345.             print(OOSPVERSION.."[OOSP] ".."can't do single process: "..garbage.name)
  346.         end
  347.     end
  348.     print(OOSPVERSION.."[OOSP] ".."Garbage Storage Space reduces to: "..maximumProcesses)
  349.     --get max. amount of Processcycles we can have with our result capacity
  350.     for _, result in pairs(production.results) do
  351.         print(OOSPVERSION.."[OOSP] ".."Free space for "..result.name..": "..(getMaxGoods(factory, tradingdata, result.name) - getNumGoods(factory, result.name)).. " minus: "..spaceForExtraProcessesNeeded.. " | required: " .. result.amount)
  352.         maximumProcesses = math.min((getMaxGoods(factory, tradingdata, result.name) - getNumGoods(factory, result.name) - spaceForExtraProcessesNeeded), maximumProcesses)
  353.         if maximumProcesses == 0 then
  354.             print(OOSPVERSION.."[OOSP] ".."can't do single process: "..result.name)
  355.         end
  356.     end
  357.    
  358.     maximumProcesses = math.floor(math.max(maximumProcesses, minimumProcess))
  359.     if(maximumProcesses <= 0) then -- just in case. We wouldn't want negative Production right?
  360.         print(OOSPVERSION.."[OOSP] "..factory.name.." needs no Production catch-up.")
  361.         return
  362.     end
  363.     print(OOSPVERSION.."[OOSP] ".."The Factory is "..maximumProcesses.." processes behind.")
  364.    
  365.    
  366.     for _, ingredient in pairs(production.ingredients) do
  367.         print(OOSPVERSION.."[OOSP] ".."remove "..ingredient.amount * maximumProcesses.." of " .. ingredient.name)
  368.         decreaseGoods(factory, tradingdata, ingredient.name, math.max(ingredient.amount * maximumProcesses, getNumGoods(factory, ingredient.name)))
  369.     end
  370.    
  371.    
  372.     for i, result in pairs(production.results) do
  373.         print(OOSPVERSION.."[OOSP] ".."add "..result.amount * maximumProcesses.." of " .. result.name)
  374.         local excessProduction = result.amount * maximumProcesses - (getMaxGoods(factory, tradingdata, result.name) - getNumGoods(factory, result.name))
  375.         if excessProduction > 0 then
  376.             local f = Faction(factory.factionIndex)
  377.             if (f.isPlayer) then
  378.                local p = Player(factory.factionIndex)
  379.                local price = goods[result.name].price
  380.                print(OOSPVERSION.."[OOSP] ".."sending earnings "..(excessProduction * price / 5).." from " .. result.name)
  381.                p:receiveMoney( math.ceil((price * excessProduction)/5) )
  382.                p:sendChatMessage(factory.name, 0, "Sending Production Earnings...")
  383.             end
  384.         end
  385.         increaseGoods(factory, tradingdata, result.name, math.min(result.amount * maximumProcesses, getMaxGoods(factory, tradingdata, result.name) - getNumGoods(factory, result.name)))
  386.     end
  387.  
  388.     for i, garbage in pairs(production.garbages) do
  389.         print(OOSPVERSION.."[OOSP] ".."remove "..garbage.amount * maximumProcesses.." of " .. garbage.name)
  390.         increaseGoods(factory, tradingdata, garbage.name, math.min(garbage.amount * maximumProcesses, getMaxGoods(factory, tradingdata, garbage.name) - getNumGoods(factory, garbage.name)))
  391.     end
  392.                
  393.     --factory:invokeFunction("factory", "sync", nil)
  394. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement