forked from bahrmichael/factorio-tycoon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.lua
452 lines (384 loc) · 13.5 KB
/
util.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
local Constants = require("constants")
local UtilBitwise = require("util-bitwise")
--- useful shorthands to type less
-- NOTE: uncomment any print lines to debug
local global_once = {}
local function empty_once(t, k)
-- print("empty_once(): ".. tostring(k))
if rawget(t, k) == nil then rawset(t, k, {}) end
return rawget(t, k)
end
-- HACK: magic for the above to work...
local _mt = {}
_mt.__index = function(t, k)
-- print("global_once idx(): ".. tostring(k))
if rawget(global, k) == nil then rawset(global, k, {}) end
return rawget(global, k)
end
_mt.__newindex = function(t, k, v)
-- print("global_once new(): ".. tostring(k) .." v: ".. serpent.line(v))
if rawget(global, k) == nil then rawset(global, k, v) end
--return rawget(global, k) -- not used
end
setmetatable(global_once, _mt)
-- DEBUG: uncomment to hook wrapper onto the real "global" table
--setmetatable(global, _mt)
-- HACK: end
local function splitString(s, delimiter)
local parts = {}
for substring in s:gmatch("[^" .. delimiter .. "]+") do
table.insert(parts, substring)
end
return parts
end
-- Return the first index with the given value (or nil if not found).
--- @param array any[]
--- @param value any
--- @return number | nil Index The index of the element in the array, or nil if there's no match.
local function indexOf(array, value)
for i, v in ipairs(array) do
if v == value then
return i
end
end
return nil
end
--- @param p1 Coordinates
--- @param p2 Coordinates
--- @return number The distance between the two points.
local function calculateDistance(p1, p2)
local dx = p2.x - p1.x
local dy = p2.y - p1.y
return math.sqrt(dx * dx + dy * dy)
end
--- @param v number
--- @param min number
--- @param max number
--- @return number Clamped value to [min;max] range
local function clamp(v, min, max)
if v < min then
return min
elseif v > max then
return max
end
return v
end
--- @param v number
--- @param min number Lower bound of v
--- @param max number Upper bound of v
--- @return number Normalized value in [0;1] range
local function normalize(v, min, max)
return (v - min) / (max - min)
end
--- @param v number Normalized value in [0;1] range
--- @param min number
--- @param max number
--- @return number Linear interpolation of [min;max] range by v
local function lerp(v, min, max)
return min + (max - min)*v
end
--- Similar to lerp, but clamps v into [0;1] range
local function lerpClamped(v, min, max)
return lerp(clamp(v, 0, 1), min, max)
end
--- @param p Position
--- @return ChunkPosition
local function positionToChunk(p)
-- Factorio-Lua, // // // !
--return { x = p.x // Constants.CHUNK_SIZE, y = p.y // Constants.CHUNK_SIZE }
return { x = math.floor(p.x / Constants.CHUNK_SIZE), y = math.floor(p.y / Constants.CHUNK_SIZE) }
end
--- @param p Position
--- @param size number Region size
--- @return RegionPosition
local function positionToRegion(p, size)
return { x = math.floor(p.x / (Constants.CHUNK_SIZE * size)), y = math.floor(p.y / (Constants.CHUNK_SIZE * size)) }
end
--- @param ch ChunkPosition
--- @return Position
local function chunkToPosition(ch)
return { x = ch.x * Constants.CHUNK_SIZE, y = ch.y * Constants.CHUNK_SIZE }
end
--- @param ch ChunkPosition
--- @param size number Region size
--- @return Position
local function chunkToRegion(ch, size)
return { x = math.floor(ch.x / size), y = math.floor(ch.y / size) }
end
--- @param ch ChunkPosition
--- @param size number Size of array in one dimension
--- @return number Index in array
local function chunkToIndex2D(ch, size)
return math.floor(ch.y % size)*size + math.floor(ch.x % size)
end
--- @param index number Index in 2D-array
--- @param size number Size of array in one dimension
--- @return ChunkPosition Index in array
local function chunkFromIndex2D(index, size)
local y, x = math.modf(index / size)
x = math.floor(x * size)
return { x = x, y = y }
end
--- we could use string.format("%d;%d", p.x, p.y), but it looks slower
--- @param p ChunkPosition, only integers please! For floats use math.floor()
--- @return number Hash to be used for dictionary keys
local function chunkToHash(p)
-- WARN: only 16-bit signed values [-32768; 32767] are usable, uncomment assert to crash with message
--assert( (p.x >= -32768 and p.x <= 32767) and (p.y >= -32768 and p.y <= 32767) )
return UtilBitwise.pack2xInt16(p.x, p.y)
end
--- @param k Hash used for dictionary keys, as returned by chunkToHash()
--- @return ChunkPosition
local function chunkFromHash(k)
local p = UtilBitwise.unpack2xInt16(k)
return { x = p[1], y = p[2] }
end
--- @param v number Factorio slider value [0.16; 6.0] aka [17%; 600%] as in gui
--- @return number value in the [-1; 1] range
local function factorioSliderInverse(v)
-- formula is like e^((x-1)/3) for x==[-5;6], but can't find it. starting value 0 or 1?
-- x: -5 -4 -3 -2 -1 0 1 2 3 4 5 6
-- v: 0.16 0.25 0.33 0.50 0.75 1.00 1.33 1.50 2.00 3.00 4.00 6.00
if v < 1.0 then
return (1 - 1/v)/(6-1)
end
return normalize(v, 1, 6)
end
assert(factorioSliderInverse(1/6) == -1)
assert(factorioSliderInverse(1.0) == 0)
assert(factorioSliderInverse(6.0) == 1)
--- @param lowerTierBuildingCounts number
--- @param higherTierBuildingCounts number
--- @param houseRatio number
--- @return number Number of lower tier houses needed.
local function countPendingLowerTierHouses(lowerTierBuildingCounts, higherTierBuildingCounts, houseRatio)
-- or 0 is for simple houses that might not send anything
local higherTierExpectation = higherTierBuildingCounts * (houseRatio or 0)
if lowerTierBuildingCounts < higherTierExpectation then
return higherTierExpectation - lowerTierBuildingCounts
end
return 0
end
local lowerTierThreshold = {
highrise = 20,
residential = 20,
}
local function hasReachedLowerTierThreshold(city, currentHousingTier)
if currentHousingTier == "highrise" then
local residentialCount = ((city.buildingCounts or {})["residential"] or 0)
return residentialCount >= lowerTierThreshold[currentHousingTier]
elseif currentHousingTier == "residential" then
local simpleCount = ((city.buildingCounts or {})["simple"] or 0)
return simpleCount >= lowerTierThreshold[currentHousingTier]
else
return true
end
end
local function findCityById(cityId)
for _, city in ipairs(global.tycoon_cities) do
if city.id == cityId then
return city
end
end
return nil
end
local function findCityByTownHallUnitNumber(townHallUnitNumber)
for _, city in ipairs(global.tycoon_cities) do
if (city.special_buildings.town_hall or {}).valid
and (city.special_buildings.town_hall or {}).unit_number == townHallUnitNumber then
return city
end
end
return nil
end
--- @param surface LuaSurface
--- @param position MapPosition
--- @param radius number | nil
--- @param limit number | nil
--- @return Entity[] | {}
local function findTownHallsAtPosition(surface, position, radius, limit)
if surface == nil or position == nil then
return {}
end
return surface.find_entities_filtered{
position=position,
radius=radius or Constants.CITY_RADIUS,
name="tycoon-town-hall",
limit=limit or 1,
}
end
--- @param surface LuaSurface
--- @param position MapPosition
--- @param radius number | nil
--- @param limit number | nil
--- @return City
local function findCityAtPosition(surface, position, radius, limit)
local town_halls = findTownHallsAtPosition(surface, position, radius, limit)
if #town_halls < 1 then
return
end
-- can't use getGlobalBuilding(), it is declared below
local building = global.tycoon_city_buildings[town_halls[1].unit_number]
if building == nil then
log("ERROR: Found a town hall, but it has no city mapping.")
return
end
local city = findCityById(building.cityId)
if city == nil then
log("ERROR: Found a cityId, but there is no city for it.")
return
end
return city
end
--- tries harder to find city when surface_index is unknown and entity is invalid
local function findCityByBuilding(building)
if building == nil then return end
local city = nil
city = findCityById(building.cityId)
if city ~= nil then return city end
if building.entity ~= nil and building.entity.valid and building.entity.surface_index ~= nil then
city = findCityAtPosition(game.surfaces[building.entity.surface_index], building.position)
end
if city ~= nil then return city end
-- when there is no surface_index and no entity, try every surface
for _, surface in pairs(game.surfaces) do
city = findCityAtPosition(surface, building.position)
if city ~= nil then return city end
end
log("findCityByBuilding(): ERROR: unable to find city on any surface! building: ".. serpent.line(building))
end
local function isSupplyBuilding(entityName)
return Constants.CITY_SPECIAL_BUILDINGS[entityName] == true
end
local function isSpecialBuilding(entityName)
return Constants.CITY_SPECIAL_BUILDINGS[entityName] ~= nil
end
--- @param entityName string
--- @return boolean
local function isHouse(entityName)
return string.find(entityName, "tycoon-house-", 1, true) ~= nil
end
local function findCityByEntityUnitNumber(unitNumber)
local metaInfo = (global.tycoon_entity_meta_info or {})[unitNumber]
if metaInfo == nil then
return "Unknown"
end
local cityId = metaInfo.cityId
local cityName = ((global.tycoon_cities or {})[cityId] or {}).name
return cityName or "Unknown"
end
--- @class Building
--- @field cityId number
--- @field entity LuaEntity
--- @field entity_name string
--- @field position MapPosition | Coordinates
--- @field isSpecial boolean | nil
--- @param unit_number number
--- @param cityId number
--- @param entity LuaEntity | nil
--- @return Building
local function addGlobalBuilding(unit_number, cityId, entity)
if global.tycoon_city_buildings == nil then
global.tycoon_city_buildings = {}
end
if unit_number == nil then
return
end
local building = nil
if entity ~= nil and entity.valid then
building = {
cityId = cityId,
entity_name = entity.name,
entity = entity,
position = {
x = math.floor(entity.position.x),
y = math.floor(entity.position.y),
},
}
if isSpecialBuilding(entity.name) then
building.isSpecial = true
end
end
global.tycoon_city_buildings[unit_number] = building
return building
end
--- @param unit_number number
local function removeGlobalBuilding(unit_number)
if global.tycoon_city_buildings == nil or unit_number == nil then
return
end
global.tycoon_city_buildings[unit_number] = nil
end
--- @param unit_number number
--- @return Building
local function getGlobalBuilding(unit_number)
if global.tycoon_city_buildings == nil or unit_number == nil then
return
end
return global.tycoon_city_buildings[unit_number]
end
--- @param start Coordinates
--- @param map string[]
--- @param tileName string
--- @param surface_index number
local function printTiles(start, map, tileName, surface_index)
local x, y = start.x, start.y
for _, value in ipairs(map) do
for i = 1, #value do
local char = string.sub(value, i, i)
if char == "1" then
game.surfaces[surface_index or Constants.STARTING_SURFACE_ID].set_tiles({ { name = tileName, position = { x, y } } })
end
x = x + 1
end
x = start.x
y = y + 1
end
end
local function aggregateSupplyBuildingResources(supplyBuildings)
local resources = {}
for _, entity in ipairs(supplyBuildings) do
local contents = entity.get_inventory(defines.inventory.chest).get_contents()
for item, count in pairs(contents) do
resources[item] = (resources[item] or 0) + count
end
end
return resources
end
return {
global_once = global_once,
empty_once = empty_once,
countPendingLowerTierHouses = countPendingLowerTierHouses,
hasReachedLowerTierThreshold = hasReachedLowerTierThreshold,
lowerTierThreshold = lowerTierThreshold,
splitString = splitString,
indexOf = indexOf,
calculateDistance = calculateDistance,
clamp = clamp,
normalize = normalize,
lerp = lerp,
lerpClamped = lerpClamped,
positionToChunk = positionToChunk,
positionToRegion = positionToRegion,
chunkToPosition = chunkToPosition,
chunkToRegion = chunkToRegion,
chunkToIndex2D = chunkToIndex2D,
chunkFromIndex2D = chunkFromIndex2D,
chunkToHash = chunkToHash,
chunkFromHash = chunkFromHash,
factorioSliderInverse = factorioSliderInverse,
findCityByTownHallUnitNumber = findCityByTownHallUnitNumber,
findCityById = findCityById,
findTownHallsAtPosition = findTownHallsAtPosition,
findCityAtPosition = findCityAtPosition,
findCityByBuilding = findCityByBuilding,
isSupplyBuilding = isSupplyBuilding,
isSpecialBuilding = isSpecialBuilding,
isHouse = isHouse,
findCityByEntityUnitNumber = findCityByEntityUnitNumber,
addGlobalBuilding = addGlobalBuilding,
removeGlobalBuilding = removeGlobalBuilding,
getGlobalBuilding = getGlobalBuilding,
printTiles = printTiles,
aggregateSupplyBuildingResources = aggregateSupplyBuildingResources,
}