-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathutil.lua
570 lines (485 loc) · 17.4 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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
local Constants = require("constants")
local UtilBitwise = require("util-bitwise")
local GridUtil = require("grid-util")
local GrahamScan = require("grahamscan")
local function calculateMaxRadius(centerPoint, circlePoints)
local maxRadiusSquared = 0
for _, point in ipairs(circlePoints) do
local dx = point.x - centerPoint.x
local dy = point.y - centerPoint.y
local distanceSquared = dx * dx + dy * dy
if distanceSquared > maxRadiusSquared then
maxRadiusSquared = distanceSquared
end
end
return math.sqrt(maxRadiusSquared)
end
local function addPadding(points, padding)
-- Calculate centroid
local centroid = {x = 0, y = 0}
for _, p in ipairs(points) do
centroid.x = centroid.x + p.x
centroid.y = centroid.y + p.y
end
centroid.x = centroid.x / #points
centroid.y = centroid.y / #points
-- Move points away from centroid
local paddedPoints = {}
for _, p in ipairs(points) do
local dx = p.x - centroid.x
local dy = p.y - centroid.y
local distance = math.sqrt(dx*dx + dy*dy)
local newDistance = distance + padding
local scale = newDistance / distance
table.insert(paddedPoints, {
x = math.floor(centroid.x + dx * scale),
y = math.floor(centroid.y + dy * scale)
})
end
return paddedPoints
end
local function approximateCircleAroundCity(city)
if city.surrounding_points_cache ~= nil and #city.surrounding_points_cache > 3 then
return city.surrounding_points_cache
end
local points = {}
local grid = city.grid
for y = 1, #grid do
for x = 1, #grid[y] do
local cell = GridUtil.safeGridAccess(city, {x=x, y=y})
if cell and cell.type ~= "unused" then
table.insert(points, {x=x, y=y})
end
end
end
local outerPoints = GrahamScan.approximate_circle(points)
local cornerList = addPadding(outerPoints, 5)
local mappedPoints = {}
for _, p in ipairs(cornerList) do
local mapped = GridUtil.translateCityGridToTileCoordinates(city, p)
table.insert(mappedPoints, mapped)
end
city.surrounding_points_cache = mappedPoints
return mappedPoints
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(storage.tycoon_cities) do
if city.id == cityId then
return city
end
end
return nil
end
local function findCityByTownHallUnitNumber(townHallUnitNumber)
for _, city in ipairs(storage.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 = storage.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 findCityNameByEntityUnitNumber(unitNumber)
local metaInfo = (storage.tycoon_entity_meta_info or {})[unitNumber]
if metaInfo == nil then
return "Unknown"
end
local cityId = metaInfo.cityId
local cityName = ((storage.tycoon_cities or {})[cityId] or {}).name
return cityName or "Unknown"
end
--- @param city City
--- @param name string
local function list_special_city_buildings(city, name)
local entities = {}
if city.special_buildings.other[name] ~= nil and #city.special_buildings.other[name] > 0 then
entities = city.special_buildings.other[name]
elseif city.special_buildings.other[name] == nil then
local radius = calculateMaxRadius(city.center, approximateCircleAroundCity(city))
entities = game.surfaces[city.surface_index].find_entities_filtered{
name=name,
position=city.center,
radius=radius,
}
city.special_buildings.other[name] = entities
end
local result = {}
for _, entity in ipairs(entities) do
if entity ~= nil and entity.valid then
table.insert(result, entity)
end
end
return result
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 | nil
local function addGlobalBuilding(unit_number, cityId, entity)
if storage.tycoon_city_buildings == nil then
storage.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
storage.tycoon_city_buildings[unit_number] = building
return building
end
--- @param unit_number number
local function removeGlobalBuilding(unit_number)
if storage.tycoon_city_buildings == nil or unit_number == nil then
return
end
storage.tycoon_city_buildings[unit_number] = nil
end
--- @param unit_number number
--- @return Building | nil
local function getGlobalBuilding(unit_number)
if storage.tycoon_city_buildings == nil or unit_number == nil then
return
end
return storage.tycoon_city_buildings[unit_number]
end
--- @param start Coordinates
--- @param map string[]
--- @param tileName string
--- @param dont_override_tiles string[] | nil
--- @param surface_index number
local function printTiles(start, map, tileName, surface_index, dont_override_tiles)
if dont_override_tiles == nil then
dont_override_tiles = {}
end
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
local can_print = true
if #dont_override_tiles > 0 then
local tile = game.surfaces[surface_index].get_tile(x, y)
can_print = indexOf(dont_override_tiles, tile.name) == nil
end
if can_print then
game.surfaces[surface_index or Constants.STARTING_SURFACE_ID].set_tiles({ { name = tileName, position = { x, y } } })
end
end
x = x + 1
end
x = start.x
y = y + 1
end
end
local function merge_items_by_name(items)
-- Creates a result table to store item counts by name.
local name_count_map = {}
-- Iterates through the input array of items.
for _, item in pairs(items) do
-- If the item name already exists in the result table, increment the count;
-- otherwise, initialize the count to the current item's count.
if name_count_map[item.name] then
name_count_map[item.name] = name_count_map[item.name] + item.count
else
name_count_map[item.name] = item.count
end
end
-- Converts the result table into an array format.
local sorted_array = {}
for name, count in pairs(name_count_map) do
table.insert(sorted_array, { name = name, count = count })
end
-- Sorts the array in descending order by count.
table.sort(sorted_array, function(a, b)
return a.count > b.count
end)
return sorted_array
end
local function aggregateSupplyBuildingResources(supplyBuildings)
local resources = {}
for _, entity in ipairs(supplyBuildings) do
local contents = entity.get_inventory(defines.inventory.chest).get_contents()
if contents and table_size(contents) > 0 then
--fixme now contents have a quality. see https://lua-api.factorio.com/latest/concepts/ItemWithQualityCounts.html
-- just merge quality items by name
for _, item in pairs(merge_items_by_name(contents)) do
resources[item.name] = (resources[item.name] or 0) + item.count
end
end
end
return resources
end
return {
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,
findCityNameByEntityUnitNumber = findCityNameByEntityUnitNumber,
addGlobalBuilding = addGlobalBuilding,
removeGlobalBuilding = removeGlobalBuilding,
getGlobalBuilding = getGlobalBuilding,
printTiles = printTiles,
aggregateSupplyBuildingResources = aggregateSupplyBuildingResources,
list_special_city_buildings = list_special_city_buildings,
calculateMaxRadius = calculateMaxRadius,
approximateCircleAroundCity = approximateCircleAroundCity,
}