Debian Codegraph @

CorsixTH/Lua/world.lua

raw
1 --[[ Copyright (c) 2009 Peter "Corsix" Cawley
2
3 Permission is hereby granted, free of charge, to any person obtaining a copy of
4 this software and associated documentation files (the "Software"), to deal in
5 the Software without restriction, including without limitation the rights to
6 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
7 of the Software, and to permit persons to whom the Software is furnished to do
8 so, subject to the following conditions:
9
10 The above copyright notice and this permission notice shall be included in all
11 copies or substantial portions of the Software.
12
13 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19 SOFTWARE. --]]
20
21 local TH = require("TH")
22 local ipairs, _G, table_remove
23 = ipairs, _G, table.remove
24
25 corsixth.require("entities.humanoids.patient")
26 corsixth.require("entities.humanoids.staff.doctor")
27 corsixth.require("entities.humanoids.staff.nurse")
28 corsixth.require("entities.humanoids.staff.handyman")
29 corsixth.require("entities.humanoids.staff.receptionist")
30 corsixth.require("entities.humanoids.vip")
31 corsixth.require("entities.humanoids.grim_reaper")
32 corsixth.require("entities.humanoids.inspector")
33 corsixth.require("staff_profile")
34 corsixth.require("hospital")
35 corsixth.require("hospitals.player_hospital")
36 corsixth.require("hospitals.ai_hospital")
37 corsixth.require("cheats")
38 corsixth.require("epidemic")
39 corsixth.require("calls_dispatcher")
40 corsixth.require("research_department")
41 corsixth.require("entity_map")
42 corsixth.require("date")
43 corsixth.require("announcer")
44 corsixth.require("endconditions")
45 corsixth.require("earthquake")
46
47 --! Manages entities, rooms, and the date.
48 class "World"
49
50 ---@type World
51 local World = _G["World"]
52
53 function World:World(app, free_build_mode)
54 self.app = app
55 self.free_build_mode = free_build_mode
56 self.map = app.map
57 self.wall_types = app.walls
58 self.object_types = app.objects
59 self.anims = app.anims
60 self.pathfinder = TH.pathfinder()
61 self.pathfinder:setMap(app.map.th)
62 self.entities = {} -- List of entities in the world.
63 self.dispatcher = CallsDispatcher(self)
64 self.objects = {}
65 self.objects_notify_occupants = {}
66 self.rooms = {} -- List that can have gaps when a room is deleted, so use pairs to iterate.
67 self.entity_map = EntityMap(self.map)
68
69 -- Time
70 self.hours_per_tick = 1
71 self.tick_rate = 3
72 self.tick_timer = 0
73 self.game_date = Date() -- Current date in the game.
74
75 self.room_information_dialogs = app.config.room_information_dialogs
76 -- This is false when the game is paused.
77 self.user_actions_allowed = true
78
79 -- If set, do not create salary raise requests.
80 self.debug_disable_salary_raise = self.free_build_mode
81 self.idle_cache = {} -- Cached queue standing positions for all queues.
82 self.delayed_map_objects = {} -- Initial objects in the map for parcels without owner.
83 self.room_remove_callbacks = {--[[a set rather than a list]]}
84 self.room_built = {} -- List of room types that have been built
85 self.hospitals = {}
86 self.floating_dollars = {}
87 self.game_log = {} -- saves list of useful debugging information
88 self.savegame_version = app.savegame_version -- Savegame version number
89 self.release_version = app:getReleaseString() -- Savegame release version (e.g. 0.60), or Trunk
90 -- Also preserve this throughout future updates.
91 self.original_savegame_version = app.savegame_version
92
93 -- Initialize available rooms.
94 local avail_rooms = self:getAvailableRooms()
95 self.available_rooms = {} -- Both a list and a set, use ipairs to iterate through the available rooms.
96 for _, avail_room in ipairs(avail_rooms) do
97 local room = avail_room.room
98 self.available_rooms[#self.available_rooms + 1] = room
99 self.available_rooms[room.id] = room
100 end
101
102 -- Initialize available diseases and winning conditions.
103 self:initLevel(app, avail_rooms)
104
105 -- Construct hospitals.
106 self.hospitals[1] = PlayerHospital(self, avail_rooms, app.config.player_name)
107
108 -- Add computer players
109 -- TODO: Right now they're only names
110 local level_config = self.map.level_config
111 for key, value in pairs(level_config.computer) do
112 if value.Playing == 1 then
113 self.hospitals[#self.hospitals + 1] = AIHospital(tonumber(key) + 1,
114 self, avail_rooms, value.Name)
115 end
116 end
117
118 -- Setup research.
119 for _, hospital in ipairs(self.hospitals) do
120 hospital.research:setResearchConcentration()
121 end
122
123 self:updateInitialsCache()
124 -- TODO: Add (working) AI and/or multiplayer hospitals
125 -- TODO: Needs to be changed for multiplayer support
126 self.hospitals[1]:initStaff()
127
128 self:initWallTypes()
129
130 self.object_id_by_thob = {}
131 for _, object_type in ipairs(self.object_types) do
132 self.object_id_by_thob[object_type.thob] = object_type.id
133 end
134 self:makeAvailableStaff(0)
135 self.spawn_points = self:calculateSpawnTiles()
136
137 -- Next Events dates
138 -- emergencies
139 -- The emergency control level data starts with an array of 0
140 self.next_emergency_no = 0
141 self:nextEmergency()
142
143 -- Earthquakes
144 self.earthquake = Earthquake(self)
145
146 -- vip
147 self.next_vip_date = self:_generateNextVipDate()
148
149 -- Set initial spawn rate in people per month.
150 -- Assumes that the first entry is always the first month.
151 self.spawn_rate = self.map.level_config.popn[0].Change
152 self.monthly_spawn_increase = self.spawn_rate
153
154 self.spawn_hours = {}
155 self.spawn_dates = {}
156 self:updateSpawnDates()
157
158 self.cheat_announcements = {
159 "cheat001.wav", "cheat002.wav", "cheat003.wav",
160 }
161
162 self:gameLog("Created game with savegame version " .. self.savegame_version .. ".")
163 end
164
165 --! Register key shortcuts for controlling the world (game speed, etc.)
166 function World:setUI(ui)
167 self.ui = ui
168
169 self.ui:addKeyHandler("ingame_pause", self, self.pauseOrUnpause, "Pause")
170 self.ui:addKeyHandler("ingame_gamespeed_slowest", self, self.setSpeed, "Slowest")
171 self.ui:addKeyHandler("ingame_gamespeed_slower", self, self.setSpeed, "Slower")
172 self.ui:addKeyHandler("ingame_gamespeed_normal", self, self.setSpeed, "Normal")
173 self.ui:addKeyHandler("ingame_gamespeed_max", self, self.setSpeed, "Max speed")
174 self.ui:addKeyHandler("ingame_gamespeed_thensome", self, self.setSpeed, "And then some more")
175
176 self.ui:addKeyHandler("ingame_zoom_in", self, self.adjustZoom, 1)
177 self.ui:addKeyHandler("ingame_zoom_in_more", self, self.adjustZoom, 5)
178 self.ui:addKeyHandler("ingame_zoom_out", self, self.adjustZoom, -1)
179 self.ui:addKeyHandler("ingame_zoom_out_more", self, self.adjustZoom, -5)
180 self.ui:addKeyHandler("ingame_reset_zoom", self, self.resetZoom)
181 end
182
183 function World:adjustZoom(delta)
184 local scr_w = self.ui.app.config.width
185 local factor = self.ui.app.config.zoom_speed
186 local virtual_width = scr_w / (self.ui.zoom_factor or 1)
187
188 -- The modifier is a normal distribution to make it more difficult to zoom at the extremes
189 local modifier = math.exp(-((self.ui.zoom_factor - 1) ^ 2) / 2) / math.sqrt(2 * math.pi)
190
191 if modifier < 0.05 or modifier > 1 then
192 modifier = 0.05
193 end
194
195 virtual_width = virtual_width - delta * factor * modifier
196 if virtual_width < 200 then
197 return false
198 end
199
200 return self.ui:setZoom(scr_w / virtual_width)
201 end
202
203 function World:resetZoom()
204 return self.ui:setZoom(1)
205 end
206
207 --! Initialize the game level (available diseases, winning conditions).
208 --!param app Game application.
209 --!param avail_rooms (list) Available rooms in the level.
210 function World:initLevel(app, avail_rooms)
211 local existing_rooms = {}
212 for _, avail_room in ipairs(avail_rooms) do
213 existing_rooms[avail_room.room.id] = true
214 end
215
216 -- Determine available diseases
217 self.available_diseases = {}
218 local level_config = self.map.level_config
219 local visual = level_config.visuals
220 local non_visual = level_config.non_visuals
221 for _, disease in ipairs(app.diseases) do
222 if not disease.pseudo then
223 local vis_id = disease.visuals_id
224 local nonvis_id = disease.non_visuals_id
225
226 local vis = 1
227 if visual and (visual[vis_id] or non_visual[nonvis_id]) then
228 vis = vis_id and visual[vis_id].Value or non_visual[nonvis_id].Value
229 end
230 if vis ~= 0 then
231 for _, room_id in ipairs(disease.treatment_rooms) do
232 if existing_rooms[room_id] == nil then
233 print("Warning: Removing disease \"" .. disease.id ..
234 "\" due to missing treatment room \"" .. room_id .. "\".")
235 vis = 0 -- Missing treatment room, disease cannot be treated. Remove it.
236 break
237 end
238 end
239 end
240 -- TODO: Where the value is greater that 0 should determine the frequency of the patients
241 if vis ~= 0 then
242 self.available_diseases[#self.available_diseases + 1] = disease
243 self.available_diseases[disease.id] = disease
244 end
245 end
246 end
247 -- Apply level-defined pricing to diseases on new game:
248 self:applyLevelStartPrices()
249 if #self.available_diseases == 0 and self.map.level_number ~= "MAP EDITOR" then
250 -- No diseases are needed if we're actually in the map editor!
251 print("Warning: This level does not contain any diseases")
252 end
253
254 self:determineWinningConditions()
255 end
256
257 -- Apply level-defined pricing to all available diseases.
258 function World:applyLevelStartPrices()
259 local config = self.map and self.map.level_config
260 if not (config and config.expertise and self.available_diseases) then return end
261
262 for _, disease in ipairs(self.available_diseases) do
263 local expertise = disease.expertise_id and config.expertise[disease.expertise_id]
264 if expertise and expertise.StartPrice then
265 disease.cure_price = expertise.StartPrice
266 end
267 end
268 end
269
270 function World:toggleInformation()
271 self.room_information_dialogs = not self.room_information_dialogs
272 end
273
274 --! In EndConditions, collect and test the win and lose conditions of the level.
275 function World:determineWinningConditions()
276 self.endconditions = EndConditions(self.map.level_config,
277 self.map.level_number, self.free_build_mode)
278 end
279
280 --! Find the rooms available at the level.
281 --!return (list) Available rooms, with discovery state at start, and build_cost.
282 function World:getAvailableRooms()
283 local avail_rooms = {}
284
285 local cfg_objects = self.map.level_config.objects
286 local cfg_rooms = self.map.level_config.rooms
287 for _, room in ipairs(TheApp.rooms) do
288 -- Add build cost based on level files for all rooms.
289 -- For now, sum it up so that the result is the same as before.
290 -- TODO: Change the whole build process so that this value is
291 -- the room cost only? (without objects)
292 local build_cost = cfg_rooms[room.level_config_id].Cost
293 local available = true
294 local is_discovered = true
295 -- Make sure that all objects needed for this room are available
296 for name, no in pairs(room.objects_needed) do
297 local spec = cfg_objects[TheApp.objects[name].thob]
298 if spec.AvailableForLevel == 0 then
299 -- It won't be possible to build this room at all on the level.
300 available = false
301 elseif spec.StartAvail == 0 then
302 -- Ok, it will be available at some point just not from the beginning.
303 is_discovered = false
304 end
305 -- Add cost for this object.
306 build_cost = build_cost + cfg_objects[TheApp.objects[name].thob].StartCost * no
307 end
308
309 if available then
310 avail_rooms[#avail_rooms + 1] = {room = room, is_discovered = is_discovered, build_cost = build_cost}
311 end
312 end
313 return avail_rooms
314 end
315
316 --! Get the hospital controlled by the (single) player.
317 --!return (Hospital) The hospital controlled by the (single) player.
318 function World:getLocalPlayerHospital()
319 -- NB: UI code can get the hospital to use via ui.hospital
320 -- TODO: Make this work in multiplayer?
321 return self.hospitals[1]
322 end
323
324 --! Identify the tiles on the map suitable for spawning `Humanoid`s from.
325 --!return (table) 0-8 spawn points of the map.
326 function World:calculateSpawnTiles()
327 local spawn_points = {}
328 local w, h = self.map.width, self.map.height
329 local directions = {
330 {direction = "north", origin = {1, 1}, step = { 1, 0}},
331 {direction = "east" , origin = {w, 1}, step = { 0, 1}},
332 {direction = "south", origin = {w, h}, step = {-1, 0}},
333 {direction = "west" , origin = {1, h}, step = { 0, -1}},
334 }
335 for _, edge in ipairs(directions) do
336 -- Find all possible spawn points on the edge
337 local xs = {}
338 local ys = {}
339 local x, y = edge.origin[1], edge.origin[2]
340 while not (x < 1 or x > w or y < 1 or y > h) do
341 if self.pathfinder:isReachableFromHospital(x, y) then
342 xs[#xs + 1] = x
343 ys[#ys + 1] = y
344 end
345 x = x + edge.step[1]
346 y = y + edge.step[2]
347 end
348
349 -- Choose at most 8 points for the edge
350 local num = math.min(8, #xs)
351 for i = 1, num do
352 local index = math.floor((i - 0.5) / num * #xs + 1)
353 spawn_points[#spawn_points + 1] = {x = xs[index], y = ys[index], direction = edge.direction}
354 end
355 end
356 return spawn_points
357 end
358
359 --! Function to determine whether a given disease is available for new patients.
360 --!param self (World) World object.
361 --!param disease (disease) Disease to test.
362 --!param hospital (Hospital) Hospital that needs a new patient.
363 --!return (boolean) Whether the disease is usable for new spawned patients.
364 local function isDiseaseUsableForNewPatient(self, disease, hospital)
365 if disease.only_emergency then return false end
366 local level_config = self.map.level_config
367 if disease.visuals_id then
368 -- level files can delay visuals to a given month
369 -- and / or until a given number of patients have arrived
370 local hold_visual_months = level_config.gbv.HoldVisualMonths
371 local hold_visual_peep_count = level_config.gbv.HoldVisualPeepCount
372
373 -- if the month is greater than either of these values then visuals will not appear in the game
374 if (hold_visual_months and hold_visual_months > self.game_date:monthOfGame()) or
375 (hold_visual_peep_count and hold_visual_peep_count > hospital.num_visitors) then
376 return false
377 end
378
379 -- The value against #visuals_available determines from which month a disease can appear.
380 -- 0 means it can show up anytime.
381 return level_config.visuals_available[disease.visuals_id].Value < self.game_date:monthOfGame()
382 elseif disease.non_visuals_id then
383 -- Non-visual disease. Simply check the month it can appear from has passed
384 -- 0 means it can show up anytime.
385 return level_config.non_visuals_available[disease.non_visuals_id].Value < self.game_date:monthOfGame()
386 end
387 error("disease has neither visuals_id or non_visuals_id")
388 end
389
390 --! Private function to assess the shortest path between all spawn points and desks
391 --!param staffed_desks (table) All staffed reception desks
392 --!param spawns (table) All available spawn points
393 --!return Optimal spawn point to the nearest reception desk or false on failure
394 function World:_findClosestSpawnToDesk(staffed_desks, spawns)
395 local best_spawn_point, distance
396 local function testNewSpawnPath(desk, spawn)
397 local new_dist = self:getPathDistance(desk.tile_x, desk.tile_y, spawn.x, spawn.y)
398 if not new_dist then return end
399 if not distance or new_dist < distance then
400 distance = new_dist
401 best_spawn_point = spawn
402 end
403 end
404
405 for _, spawn in ipairs(spawns) do
406 for _, desk in ipairs(staffed_desks) do
407 testNewSpawnPath(desk, spawn)
408 end
409 end
410
411 if not best_spawn_point then
412 local msg =
413 "Warning: Path not found between any spawn point and staffed desk. " ..
414 "Humanoid will still likely find its own way."
415 self:gameLog(msg)
416 return false
417 end
418 return best_spawn_point
419 end
420
421 --! Spawn a patient from a spawn point for the given hospital.
422 --!param hospital (Hospital) Hospital that the new patient should visit.
423 --!return (Patient entity) The spawned patient, or 'nil' if no patient spawned.
424 function World:spawnPatient(hospital)
425 if not hospital then
426 hospital = self:getLocalPlayerHospital()
427 end
428
429 -- The level might not contain any diseases
430 if #self.available_diseases < 1 then
431 self.ui:addWindow(UIInformation(self.ui, {"There are no diseases on this level! Please add some to your level."}))
432 return
433 end
434 if #self.spawn_points == 0 then
435 self.ui:addWindow(UIInformation(self.ui, {"Could not spawn patient because no spawn points are available. Please place walkable tiles on the edge of your level."}))
436 return
437 end
438
439 if not hospital:hasReceptionDesk(true) then return nil end
440
441 -- Construct disease, take a random guess first, as a quick clear-sky attempt.
442 local disease = self.available_diseases[math.random(1, #self.available_diseases)]
443 if not isDiseaseUsableForNewPatient(self, disease, hospital) then
444 -- Lucky shot failed, do a proper calculation.
445 local usable_diseases = {}
446 for _, d in ipairs(self.available_diseases) do
447 if isDiseaseUsableForNewPatient(self, d, hospital) then
448 usable_diseases[#usable_diseases + 1] = d
449 end
450 end
451
452 if #usable_diseases == 0 then return nil end
453
454 disease = usable_diseases[math.random(1, #usable_diseases)]
455 end
456
457 -- Construct patient.
458 local spawns = self.spawn_points
459 -- Let the first patient to the player use the shortest path to a reception desk
460 local spawn_point = hospital:isPlayerHospital() and not hospital:hadPatients() and
461 self:_findClosestSpawnToDesk(hospital:getReceptionDesks(true), spawns) or
462 spawns[math.random(1, #spawns)]
463
464 local patient = self:newEntity("Patient", 2, 1)
465 patient:setDisease(disease)
466 patient:setNextAction(SpawnAction("spawn", spawn_point))
467 patient:setHospital(hospital)
468 return patient
469 end
470
471 --A VIP is invited (or he invited himself) to the player hospital.
472 --!param name Name of the VIP
473 function World:spawnVIP(name)
474 local hospital = self:getLocalPlayerHospital()
475
476 local vip = self:newEntity("Vip", 2, 2)
477 vip:setType("VIP")
478 vip.name = name
479 vip.enter_deaths = hospital.num_deaths
480 vip.enter_visitors = hospital.num_visitors
481 vip.enter_cures = hospital.num_cured
482 vip.enter_patients = #hospital.patients
483 -- VIP's room visit chance is 50% if total rooms in hospital is less than 80 (makes a math.random with 0 and 1 possibilities).
484 -- Else decided by total rooms / 40 (0, 1, 2 [33%]; 0, 1, 2, 3 [25%] etc)
485 local rooms_threshold = 79
486 if #self.rooms > rooms_threshold then
487 vip.room_visit_chance = math.floor(#self.rooms / 40)
488 end
489
490 local spawn_point = self.spawn_points[math.random(1, #self.spawn_points)]
491 vip:setNextAction(SpawnAction("spawn", spawn_point))
492 vip:setHospital(hospital)
493 vip:updateDynamicInfo()
494 hospital:onSpawnVIP()
495 vip:queueAction(SeekReceptionAction())
496 end
497
498 --! Enable or disable salary raise events.
499 --!param mode (boolean) If true, do not create salary raise events.
500 function World:debugDisableSalaryRaise(mode)
501 self.debug_disable_salary_raise = mode
502 end
503
504 local staff_to_make = {
505 {class = "Doctor", name = "doctor", conf = "Doctors" },
506 {class = "Nurse", name = "nurse", conf = "Nurses" },
507 {class = "Handyman", name = "handyman", conf = "Handymen" },
508 {class = "Receptionist", name = "receptionist", conf = "Receptionists"},
509 }
510 function World:makeAvailableStaff(month)
511 local conf_entry = 0
512 local cfg_staff_levels = self.map.level_config.staff_levels
513 while cfg_staff_levels[conf_entry + 1] and cfg_staff_levels[conf_entry + 1].Month <= month do
514 conf_entry = conf_entry + 1
515 end
516 self.available_staff = {}
517 for _, info in ipairs(staff_to_make) do
518 local num
519 local ind = conf_entry
520 while not num do
521 assert(ind >= 0, "Staff amount " .. info.conf .. " not existent (should at least be given by base_config).")
522 num = cfg_staff_levels[ind][info.conf]
523 ind = ind - 1
524 end
525 local group = {}
526 for i = 1, num do
527 group[i] = StaffProfile(self, info.class, _S.staff_class[info.name])
528 group[i]:randomise(month)
529 end
530 self.available_staff[info.class] = group
531 end
532 end
533
534 --[[ Register a callback for when `Humanoid`s enter or leave a given tile.
535 ! Note that only one callback may be registered to each tile.
536 !param x (integer) The 1-based X coordinate of the tile to monitor.
537 !param y (integer) The 1-based Y coordinate of the tile to monitor.
538 !param object (Object) Something with an `onOccupantChange` method, which will
539 be called whenever a `Humanoid` enters or leaves the given tile. The method
540 will receive one argument (after `self`), which will be `1` for an enter event
541 and `-1` for a leave event.
542 ]]
543 function World:notifyObjectOfOccupants(x, y, object)
544 local idx = (y - 1) * self.map.width + x
545 self.objects_notify_occupants[idx] = object or nil
546 end
547
548 function World:getObjectToNotifyOfOccupants(x, y)
549 local idx = (y - 1) * self.map.width + x
550 return self.objects_notify_occupants[idx]
551 end
552
553 --! Place objects from a map file onto the map.
554 --!param objects Objects to place.
555 function World:createMapObjects(objects)
556 self.delayed_map_objects = {}
557
558 for _, object in ipairs(objects) do
559 self:_createMapObject(object)
560 end
561 end
562
563 local flag_cache = {}
564 --! Internal function for placing an object from the map file.
565 --!param object Object to place.
566 function World:_createMapObject(object)
567 local x, y, thob, flags = unpack(object)
568 local object_id = self.object_id_by_thob[thob]
569 if not object_id then
570 print("Warning: Map contained object with unrecognised THOB (" .. thob
571 .. ") at " .. x .. "," .. y)
572 return
573 end
574
575 local object_type = self.object_types[object_id]
576 if not object_type or not object_type.supports_creation_for_map then
577 print("Warning: Unable to create map object " .. object_id .. " at "
578 .. x .. "," .. y)
579 return
580 end
581
582 local map = self.map.th
583 local parcel = map:getCellFlags(x, y, flag_cache).parcelId
584 if parcel ~= 0 and map:getPlotOwner(parcel) == 0 then
585 -- Delay making objects which are on plots which haven't been purchased yet
586 self.delayed_map_objects[{object_id, x, y, flags, "map object"}] = parcel
587
588 else
589 self:newObject(object_id, x, y, flags, "map object")
590 end
591 end
592
593 --! Change owner of a plot.
594 --!param parcel (int) Plot to change.
595 --!param owner (int) New owner (may be 0).
596 function World:setPlotOwner(parcel, owner)
597 self.map:setPlotOwner(parcel, owner)
598 if owner ~= 0 and self.delayed_map_objects then
599 for info, p in pairs(self.delayed_map_objects) do
600 if p == parcel then
601 self:newObject(unpack(info))
602 self.delayed_map_objects[info] = nil
603 end
604 end
605 end
606 self.map.th:updateShadows()
607 end
608
609 -- Register a function to be called whenever a room has been deactivated (crashed or edited).
610 --!param callback (function) A function taking one argument: a `Room`.
611 function World:registerRoomRemoveCallback(callback)
612 self.room_remove_callbacks[callback] = true
613 end
614
615 -- Unregister a function from being called whenever a room has been deactivated (crashed or edited).
616 --!param callback (function) A function previously passed to
617 -- `registerRoomRemoveCallback`.
618 function World:unregisterRoomRemoveCallback(callback)
619 self.room_remove_callbacks[callback] = nil
620 end
621
622 function World:newRoom(x, y, w, h, room_info, ...)
623 local id = #self.rooms + 1
624 -- Note: Room IDs will be unique, but they may not form continuous values
625 -- from 1, as IDs of deleted rooms may not be re-issued for a while
626 local class = room_info.class and _G[room_info.class] or Room
627 local hospital = self:getHospital(x, y)
628 local room = class(x, y, w, h, id, room_info, self, hospital, ...)
629
630 self.rooms[id] = room
631 self:clearCaches()
632 return room
633 end
634
635 --! Called when a room has been completely built and is ready to use.
636 --!param room (Room) The new room.
637 function World:markRoomAsBuilt(room)
638 room:roomFinished()
639 local hosp = room.hospital
640 local diag_disease = hosp.disease_casebook["diag_" .. room.room_info.id]
641 if diag_disease and not diag_disease.discovered then
642 hosp.disease_casebook["diag_" .. room.room_info.id].discovered = true
643 end
644 for _, entity in ipairs(self.entities) do
645 if entity.notifyNewRoom then
646 entity:notifyNewRoom(room)
647 end
648 end
649 end
650
651 --! Called when a room has been deactivated (crashed or edited)
652 function World:notifyRoomRemoved(room)
653 self.dispatcher:dropFromQueue(room)
654 for callback in pairs(self.room_remove_callbacks) do
655 callback(room)
656 end
657 end
658
659 --! Clear all internal caches which are dependent upon map state / object position
660 function World:clearCaches()
661 self.idle_cache = {}
662 end
663
664 function World:initWallTypes()
665 self.wall_id_by_block_id = {}
666 for _, wall_type in ipairs(self.wall_types) do
667 for _, set in ipairs({"inside_tiles", "outside_tiles", "window_tiles"}) do
668 for _, id in pairs(wall_type[set]) do
669 self.wall_id_by_block_id[id] = wall_type.id
670 end
671 end
672 end
673 self.wall_set_by_block_id = {}
674 for _, wall_type in ipairs(self.wall_types) do
675 for _, set in ipairs({"inside_tiles", "outside_tiles", "window_tiles"}) do
676 for _, id in pairs(wall_type[set]) do
677 self.wall_set_by_block_id[id] = set
678 end
679 end
680 end
681 self.wall_dir_by_block_id = {}
682 for _, wall_type in ipairs(self.wall_types) do
683 for _, set in ipairs({"inside_tiles", "outside_tiles", "window_tiles"}) do
684 for name, id in pairs(wall_type[set]) do
685 self.wall_dir_by_block_id[id] = name
686 end
687 end
688 end
689 end
690
691 function World:getWallIdFromBlockId(block_id)
692 -- Remove the transparency flag if present.
693 if self.ui.transparent_walls then
694 block_id = block_id - 1024
695 end
696 return self.wall_id_by_block_id[block_id]
697 end
698
699 function World:getWallSetFromBlockId(block_id)
700 -- Remove the transparency flag if present.
701 if self.ui.transparent_walls then
702 block_id = block_id - 1024
703 end
704 return self.wall_set_by_block_id[block_id]
705 end
706
707 function World:getWallDirFromBlockId(block_id)
708 -- Remove the transparency flag if present.
709 if self.ui.transparent_walls then
710 block_id = block_id - 1024
711 end
712 return self.wall_dir_by_block_id[block_id]
713 end
714
715
716 -- Game speeds. The second value is the number of world clicks that pass for each
717 -- in-game tick and the first is the number of hours to progress when this
718 -- happens.
719 local tick_rates = {
720 ["Pause"] = {0, 1},
721 ["Slowest"] = {1, 56}, -- 1 hour per s
722 ["Slower"] = {1, 12}, -- 1 hour per 216ms
723 ["Normal"] = {1, 3}, -- 1 hour per 54 ms
724 ["Max speed"] = {1, 2}, -- 1 hour per 36 ms
725 ["And then some more"] = {1, 1}, -- 1 hour per 18ms
726 ["Speed Up"] = {8, 1},
727 }
728
729 function World:speedUp()
730 self:setSpeed("Speed Up")
731 end
732
733 function World:previousSpeed()
734 if self:isCurrentSpeed("Speed Up") then
735 self:setSpeed(self.prev_speed)
736 end
737 end
738
739 --! Return true if the given speed the same as the current speed.
740 function World:isCurrentSpeed(speed)
741 local hours_per_tick, tick_rate = unpack(tick_rates[speed])
742 return self.hours_per_tick == hours_per_tick and self.tick_rate == tick_rate
743 end
744
745 --! Return the name of the current speed, relating to a key in tick_rates.
746 function World:getCurrentSpeed()
747 for name, rate in pairs(tick_rates) do
748 if rate[1] == self.hours_per_tick and rate[2] == self.tick_rate then
749 return name
750 end
751 end
752 end
753
754 -- Set the (approximate) number of seconds per tick.
755 --!param new_speed (string) New speed to set.
756 -- One of: "Pause", "Slowest", "Slower", "Normal",
757 -- "Max speed", or "And then some more".
758 function World:setSpeed(new_speed)
759 if self:isCurrentSpeed(new_speed) then return end
760 if self:mustPause() and new_speed ~= "Pause" then return end -- "Must pause" takes precedence
761 tracy.Message("Changing speed to " .. new_speed)
762
763 if new_speed == "Pause" then
764 self.ui.hospital:tickEarthquake("pause")
765 end
766
767 local old_speed = self:getCurrentSpeed()
768 if old_speed ~= "Pause" and old_speed ~= "Speed Up" then
769 self.prev_speed = old_speed
770 end
771
772 local was_paused = old_speed == "Pause"
773 local old_tick_rate = self.tick_rate or 1
774 local new_hours_per_tick, new_tick_rate = unpack(tick_rates[new_speed])
775
776 if was_paused then
777 TheApp.audio:onEndPause()
778 self.tick_timer = new_tick_rate
779 else
780 self.tick_timer = math.ceil((self.tick_timer or 0) / old_tick_rate * new_tick_rate)
781 end
782
783 self.hours_per_tick = new_hours_per_tick
784 self.tick_rate = new_tick_rate
785
786 self:updateUserActionsAllowed()
787 self:updateScreenBlueFilter()
788
789 return false
790 end
791
792 function World:mustPauseWindowAdd()
793 self:setSpeed("Pause")
794 end
795
796 function World:mustPauseWindowRemoved()
797 if self:isCurrentSpeed("Pause") then
798 self:pauseOrUnpause()
799 end
800 end
801
802 --! Check if "Must Pause" mode enabled
803 --!return (bool) returns true if "Must Pause" mode enabled
804 function World:mustPause()
805 return self.ui:anyMustPauseWindowOpen()
806 end
807
808 function World:isPaused()
809 return self:isCurrentSpeed("Pause")
810 end
811
812 --! Set the "actions allowed" flag according to whether the user can do some actions with UI or not.
813 function World:updateUserActionsAllowed()
814 -- Actions are not allowed when the game in "Must Pause" mode.
815 self.user_actions_allowed = not self:mustPause() and
816 (not self:isCurrentSpeed("Pause") or TheApp.config.allow_user_actions_while_paused)
817 end
818
819 --! Set the blue filter according to whether the user can build or not.
820 function World:updateScreenBlueFilter()
821 TheApp.video:setBlueFilterActive(not self.user_actions_allowed and not self:mustPause())
822 end
823
824 --! Dedicated function to allow unpausing by pressing 'p' again
825 function World:pauseOrUnpause()
826 if self:mustPause() then return end -- "Must Pause" takes precedence
827 if not self:isCurrentSpeed("Pause") then
828 self:setSpeed("Pause")
829 elseif self.prev_speed then
830 self:setSpeed(self.prev_speed)
831 end
832 end
833
834 --! Function to check if player can perform actions when paused
835 --!return (bool) Returns true if player hasn't allowed editing while paused
836 function World:isUserActionProhibited()
837 if self:mustPause() then return true end
838 return self:isCurrentSpeed("Pause") and not self.user_actions_allowed
839 end
840
841 -- Outside (air) temperatures based on climate data for Oxford, taken from
842 -- Wikipedia. For scaling, 0 degrees C becomes 0 and 50 degrees C becomes 1
843 local outside_temperatures = {
844 4.1 / 50, -- January
845 4.4 / 50, -- February
846 6.3 / 50, -- March
847 8.65 / 50, -- April
848 11.95 / 50, -- May
849 15 / 50, -- June
850 16.95 / 50, -- July
851 16.55 / 50, -- August
852 14.15 / 50, -- September
853 10.5 / 50, -- October
854 6.8 / 50, -- November
855 4.75 / 50, -- December
856 }
857
858 local start_date = Date()
859
860 --! World ticks (every 18ms) are translated to game ticks (or hours) depending
861 -- on the current speed of the game. There are 50 hours in a TH day.
862 function World:onTick()
863 if self.map.level_number == "MAP EDITOR" then return end
864
865 if self.tick_timer == 0 then
866 if self.autosave_next_tick then
867 self:_executeAutosave()
868 self.autosave_next_tick = false
869 end
870 if self.game_date == start_date then
871 if not self.ui.start_tutorial then
872 self.ui:addWindow(UIWatch(self.ui, "initial_opening"))
873 end
874 self.ui:showBriefing()
875 end
876 self.tick_timer = self.tick_rate
877
878 -- If the game is not paused then an earthquake may be taking place
879 if not self:isCurrentSpeed("Pause") then
880 self.earthquake:tick()
881 end
882
883 local new_game_date = self.game_date:plusHours(self.hours_per_tick)
884 -- End of day/month/year
885 if self.game_date:dayOfMonth() ~= new_game_date:dayOfMonth() then
886 for _, hospital in ipairs(self.hospitals) do
887 hospital:onEndDay()
888 end
889 self:onEndDay()
890 if self.game_date:isLastDayOfMonth() then
891 for _, hospital in ipairs(self.hospitals) do
892 hospital:onEndMonth()
893 end
894 -- Let the hospitals do what they need to do at end of month first.
895 if self:onEndMonth() then
896 -- Bail out as the game has already been ended.
897 return
898 end
899
900 if self.game_date:isLastDayOfYear() then
901 -- It is crucial that the annual report gets to initialize before onEndYear is called.
902 -- Yearly statistics are reset there.
903 self.ui:addWindow(UIAnnualReport(self.ui, self))
904 self:onEndYear()
905 end
906 end
907 end
908 self.game_date = new_game_date
909
910 for i = 1, self.hours_per_tick do
911 self.anims:tick()
912 for _, hospital in ipairs(self.hospitals) do
913 hospital:tick()
914 end
915 -- A patient might arrive to the player hospital.
916 -- TODO: Multiplayer support.
917 local spawn_count = self.spawn_hours[self.game_date:hourOfDay() + i - 1]
918 if spawn_count and self.hospitals[1].opened then
919 for _ = 1, spawn_count do
920 self:spawnPatient()
921 end
922 end
923 for _, entity in ipairs(self.entities) do
924 if entity.ticks then
925 self.current_tick_entity = entity
926 entity:tick()
927 end
928 end
929 self.current_tick_entity = nil
930 self.map:onTick()
931 self.map.th:updateTemperatures(outside_temperatures[self.game_date:monthOfYear()],
932 0.25 + self.hospitals[1].heating.radiator_heat * 0.3)
933 if self.ui then
934 self.ui:onWorldTick()
935 end
936 self.dispatcher:onTick()
937 end
938 end
939 if self.hours_per_tick > 0 and self.floating_dollars then
940 for obj in pairs(self.floating_dollars) do
941 obj:tick()
942 if obj:isDead() then
943 obj:setTile(nil)
944 self.floating_dollars[obj] = nil
945 end
946 end
947 end
948 self.tick_timer = self.tick_timer - 1
949 end
950
951 --! Creates a save file in the "Autosaves" folder, using the "Autosave-mm-dd.sav" name template for filename.
952 -- If the "Autosaves" folder does not exist, folder will be created.
953 function World:_executeAutosave()
954 local pathsep = package.config:sub(1, 1)
955 local dir = TheApp.savegame_dir
956 if dir:sub(-1, -1) ~= pathsep then
957 dir = dir .. pathsep
958 end
959 if not lfs.attributes(dir .. "Autosaves", "modification") then
960 lfs.mkdir(dir .. "Autosaves")
961 end
962 local month = string.format("%02d", self.game_date:monthOfYear())
963 local day = string.format("%02d", self.game_date:dayOfMonth())
964 local filename = "Autosave" .. "-" .. month .. "-" .. day .. ".sav"
965 local status, err = pcall(TheApp.save, TheApp, dir .. "Autosaves" .. pathsep .. filename)
966 if not status then
967 print("Error while autosaving game: " .. err)
968 end
969 end
970
971 --! Change the date of the game to the last hour of this month.
972 function World:setEndMonth()
973 local previous_date = self.game_date
974 local first_day_of_next_month = Date(self.game_date:year(), self.game_date:monthOfYear() + 1)
975 self.game_date = first_day_of_next_month:plusHours(-1)
976 -- Has the date jump caused an emergency to be missed?
977 if self:wasEmergencySkipped(previous_date, self.game_date) then
978 self:nextEmergency()
979 end
980 end
981
982 --! Change the date of the game to the last hour of this year.
983 function World:setEndYear()
984 local previous_date = self.game_date
985 local first_day_of_next_year = Date(self.game_date:year() + 1)
986 self.game_date = first_day_of_next_year:plusHours(-1)
987 -- Has the date jump caused an emergency to be missed?
988 if self:wasEmergencySkipped(previous_date, self.game_date) then
989 self:nextEmergency()
990 end
991 end
992
993 --! Checks if a time jump caused an emergency to be missed
994 --!param prev_date (Date) Original game date before jump
995 --!param new_date (Date) Game date after time jump
996 --!return (boolean) true if emergency has been skipped
997 function World:wasEmergencySkipped(prev_date, new_date)
998 local emer_date = self.next_emergency_date
999 return emer_date and emer_date < new_date and prev_date < emer_date
1000 end
1001
1002
1003 -- Called immediately prior to the ingame day changing.
1004 function World:onEndDay()
1005 local local_hospital = self:getLocalPlayerHospital()
1006 for _, entity in ipairs(self.entities) do
1007 if entity.ticks and class.is(entity, Humanoid) then
1008 self.current_tick_entity = entity
1009 entity:tickDay()
1010 elseif class.is(entity, Plant) then
1011 entity:tickDay()
1012 end
1013 end
1014 self.current_tick_entity = nil
1015
1016 --check if it's time for a VIP visit
1017 if self.game_date:isSameDay(self.next_vip_date) then
1018 if #self.rooms > 0 and local_hospital:hasReceptionDesk(true) then
1019 local_hospital:createVip()
1020 else
1021 self.next_vip_date = self:_generateNextVipDate()
1022 end
1023 end
1024
1025 -- See if its time for an earthquake
1026 self.earthquake:onEndDay()
1027
1028 -- Maybe it's time for an emergency?
1029 if self.game_date:monthOfGame() == self.next_emergency_month and
1030 self.game_date:dayOfMonth() == self.next_emergency_day then
1031 -- Postpone it if anything clock related is already underway.
1032 if self.ui:getWindow(UIWatch) then
1033 self.next_emergency_month = self.next_emergency_month + 1
1034 local month_of_year = 1 + ((self.next_emergency_month - 1) % 12)
1035 self.next_emergency_day = math.random(1, Date(1, month_of_year):lastDayOfMonth())
1036 else
1037 -- Do it only for the player hospital for now. TODO: Multiplayer
1038 local control = self.map.level_config.emergency_control
1039 if control[0].Mean or control[0].Random then
1040 -- The level uses random emergencies, so just create one.
1041 local_hospital:createEmergency()
1042 else
1043 local next_em = self.next_emergency
1044 -- Find out which disease the emergency patients have.
1045 local disease
1046 for _, dis in ipairs(self.available_diseases) do
1047 if dis.expertise_id == next_em.Illness then
1048 disease = dis
1049 break
1050 end
1051 end
1052 if not disease then
1053 -- Unknown disease! Create a random one instead.
1054 local_hospital:createEmergency()
1055 else
1056 local emergency = {
1057 disease = disease,
1058 victims = math.random(next_em.Min, next_em.Max),
1059 bonus = next_em.Bonus,
1060 percentage = next_em.PercWin/100,
1061 killed_emergency_patients = 0,
1062 cured_emergency_patients = 0,
1063 }
1064 local_hospital:createEmergency(emergency)
1065 end
1066 end
1067 end
1068 end
1069 -- Any patients tomorrow?
1070 self.spawn_hours = {}
1071 local day = self.game_date:dayOfMonth()
1072 if self.spawn_dates[day] then
1073 for _ = 1, self.spawn_dates[day] do
1074 local hour = math.random(1, Date.hoursPerDay())
1075 self.spawn_hours[hour] = self.spawn_hours[hour] and self.spawn_hours[hour] + 1 or 1
1076 end
1077 end
1078
1079 -- Autosave
1080 if self.app.config.autosave_frequency == 3 then
1081 -- Daily autosave
1082 self.autosave_next_tick = true
1083 elseif self.app.config.autosave_frequency == 2 then
1084 if day == self.game_date:lastDayOfMonth() or day == 6 or day == 13 or day == 20 or day == 27 then
1085 -- Weekly autosave
1086 self.autosave_next_tick = true
1087 end
1088 elseif self.app.config.autosave_frequency == 1 then
1089 if day == self.game_date:lastDayOfMonth() then
1090 -- Monthly autosave
1091 self.autosave_next_tick = true
1092 end
1093 end
1094 end
1095
1096 function World:checkIfGameWon()
1097 for i, hosp in ipairs(self.hospitals) do
1098 if self.endconditions:checkEndGame(hosp) == "win" then
1099 self:winGame(i)
1100 end
1101 end
1102 end
1103
1104 -- Called immediately prior to the ingame month changing.
1105 -- returns true if the game was killed due to the player losing
1106 function World:onEndMonth()
1107 local local_hospital = self:getLocalPlayerHospital()
1108 local_hospital.population = 0.25
1109 if self.game_date:monthOfGame() >= self.map.level_config.gbv.AllocDelay then
1110 local_hospital.population = local_hospital.population * self:getReputationImpact(local_hospital)
1111 end
1112
1113 -- Also possibly change world spawn rate according to the level configuration.
1114 local index = 0
1115 local popn = self.map.level_config.popn
1116 while popn[index] do
1117 if popn[index].Month == self.game_date:monthOfGame() then
1118 self.monthly_spawn_increase = popn[index].Change
1119 break
1120 end
1121 index = index + 1
1122 end
1123 -- Now set the new spawn rate
1124 self.spawn_rate = self.spawn_rate + self.monthly_spawn_increase
1125 self:updateSpawnDates()
1126
1127 self:makeAvailableStaff(self.game_date:monthOfGame())
1128 for _, entity in ipairs(self.entities) do
1129 if entity.checkForDeadlock then
1130 self.current_tick_entity = entity
1131 entity:checkForDeadlock()
1132 end
1133 end
1134 self.current_tick_entity = nil
1135 end
1136
1137 -- Called when a month ends. Decides on which dates patients arrive
1138 -- during the coming month.
1139 -- TODO: Requires adjustment for AIHospital spawns; see PR 1986 for progress.
1140 function World:updateSpawnDates()
1141 local local_hospital = self:getLocalPlayerHospital()
1142
1143 -- Decide on number of visitors
1144 local no_of_spawns = self.spawn_rate * local_hospital.population
1145 -- If Roujin's Challenge is on, add a fixed bonus to the spawn pool for this player.
1146 if local_hospital.hosp_cheats:isCheatActive("spawn_rate_cheat") then
1147 local roujin_bonus = 40
1148 no_of_spawns = no_of_spawns + roujin_bonus
1149 end
1150 -- Compute expected number of patients that arrive while forcing an arrival
1151 -- if feasible.
1152 self.spawn_dates = {}
1153
1154 if local_hospital.population > 0 then
1155 local day, last_day = 1, self.game_date:lastDayOfMonth()
1156 local force_arrival = true -- Ensure a patient arrives.
1157 local interval = last_day / no_of_spawns -- Lower interval = more visits.
1158 while day <= last_day do
1159 local x = math.p_random(interval)
1160 day = day + x
1161 if day <= last_day then
1162 local count = self.spawn_dates[day]
1163 self.spawn_dates[day] = count and count + 1 or 1
1164 force_arrival = false
1165 end
1166 end
1167
1168 -- Give the poor user a patient this month anyway.
1169 if force_arrival then
1170 self.spawn_dates[math.floor(1 + math.random() * last_day)] = 1
1171 end
1172 end
1173 end
1174
1175 --! Computes the impact of hospital reputation on the spawn rate.
1176 --! The relation between reputation and its impact is linear.
1177 --! Returns a percentage (as a float):
1178 --! 1% if reputation < 253
1179 --! 60% if reputation == 400
1180 --! 100% if reputation == 500
1181 --! 140% if reputation == 600
1182 --! 180% if reputation == 700
1183 --! 300% if reputation == 1000
1184 --!param hospital (hospital): the hospital used to compute the
1185 --! reputation impact
1186 function World:getReputationImpact(hospital)
1187 local result = 1 + ((hospital.reputation - 500) / 250)
1188
1189 -- The result must be positive
1190 if result <= 0 then
1191 return 0.01
1192 else
1193 return result
1194 end
1195 end
1196
1197 -- Called when it is time to determine when the next emergency should happen
1198 function World:nextEmergency()
1199 local control = self.map.level_config.emergency_control
1200 -- Does this level use random emergencies?
1201 if control[0].Random or control[0].Mean then
1202 self:scheduleRandomEmergency(control)
1203 return
1204 end
1205
1206 -- Find the next valid emergency entry
1207 local valid_emergency = false
1208 while not valid_emergency do
1209 local emer_num = self.next_emergency_no
1210 -- First, handle the missing Level 3 emergency[5]
1211 if not control[emer_num] and control[emer_num + 1] then
1212 emer_num = emer_num + 1
1213 self.next_emergency_no = emer_num
1214 end
1215 local emergency = control[emer_num]
1216
1217 -- No more emergencies?
1218 if not emergency then
1219 self.next_emergency_month = 0
1220 self.next_emergency_date = nil
1221 self.next_emergency = nil
1222 return
1223 end
1224
1225 -- Test the emergency's validity
1226 self.next_emergency = emergency
1227 self.next_emergency_no = self.next_emergency_no + 1
1228 valid_emergency = self:computeNextEmergencyDates(emergency)
1229 end
1230 end
1231
1232 --! If a level file specifies random emergencies we make the next one as defined by the mean/variance given
1233 --!param control (table) Contains emergency information from level file
1234 function World:scheduleRandomEmergency(control)
1235 -- Support standard values for mean and variance
1236 local mean = control[0].Mean or 180
1237 local variance = control[0].Variance or 30
1238 -- How many days until next emergency?
1239 local days = math.round(math.n_random(mean, variance))
1240 days = days > 1 and days or 1 -- Don't schedule in the past
1241 local emergency_date = self.game_date:plusDays(days)
1242
1243 -- Make it the same format as for "controlled" emergencies
1244 self.next_emergency_month = emergency_date:monthOfGame()
1245 self.next_emergency_day = emergency_date:dayOfMonth()
1246 self.next_emergency_date = Date(1, self.next_emergency_month, self.next_emergency_day) -- TODO: Make more use of this
1247 end
1248
1249 --! Generate the dates for the next emergency
1250 --!param emergency The next scheduled emergency to take place
1251 --!return (boolean) true if emergency successfully scheduled
1252 function World:computeNextEmergencyDates(emergency)
1253 -- Generate the next month and day the emergency should occur at.
1254 -- Make sure it doesn't happen in the past.
1255 local start = math.max(emergency.StartMonth, self.game_date:monthOfGame())
1256 if (emergency.EndMonth < start) then
1257 return false
1258 end
1259 local next_month = math.random(start, emergency.EndMonth)
1260 self.next_emergency_month = next_month
1261 local day_start = 1
1262 if start == emergency.EndMonth then
1263 day_start = self.game_date:dayOfMonth()
1264 end
1265 local day_end = Date(1, next_month):lastDayOfMonth()
1266 self.next_emergency_day = math.random(day_start, day_end)
1267 self.next_emergency_date = Date(1, self.next_emergency_month, self.next_emergency_day) -- TODO: Make more use of this
1268 return self.game_date <= self.next_emergency_date
1269 end
1270
1271 -- Called when it is time to have another VIP
1272 function World:nextVip()
1273 self.next_vip_date = self:_generateNextVipDate()
1274 end
1275
1276 -- PRIVATE method to generate the next VIP date
1277 -- Note: it is important we ensure this date always is in the future
1278 function World:_generateNextVipDate()
1279 -- Support standard values for mean and bound
1280 local mean, bound = math.max(self.map.level_config.gbv.MayorLaunch, 1), 30
1281 -- How many days until next vip?
1282 local lower, upper = math.max(mean - bound, 1), mean + bound
1283 local days = math.round(math.t_random(lower, mean, upper))
1284 return self.game_date:plusDays(days)
1285 end
1286
1287 --! Process that the given player number won the game.
1288 --!param player_no (integer) Number of the player who just won.
1289 function World:winGame(player_no)
1290 if player_no == 1 then -- Player won. TODO: Needs to be changed for multiplayer
1291 local text = {}
1292 local choice_text, choice
1293 local bonus_rate = math.random(4,9)
1294 local with_bonus = self.ui.hospital.cheated and 0 or (self.ui.hospital.player_salary * bonus_rate) / 100
1295 self.ui.hospital.salary_offer = math.floor(self.ui.hospital.player_salary + with_bonus)
1296 if self:isCampaign() then
1297 text, choice_text, choice = self:getCampaignWinningText(player_no)
1298 else
1299 local level_info = TheApp:readLevelFile(self.map.level_number)
1300 text[1] = _S.letter.dear_player:format(self.hospitals[player_no].name)
1301 text[2] = level_info.end_praise and level_info.end_praise or _S.letter.custom_level_completed
1302 text[3] = _S.letter.return_to_main_menu
1303 choice_text = _S.fax.choices.return_to_main_menu
1304 choice = "return_to_main_menu"
1305 end
1306 local message = {
1307 {text = text[1]},
1308 {text = text[2]},
1309 {text = text[3]},
1310 choices = {
1311 {text = choice_text, choice = choice},
1312 {text = _S.fax.choices.decline_new_level, choice = "stay_on_level"},
1313 },
1314 }
1315 local --[[persistable:world_win_game_message_close_callback]] function callback ()
1316 local world = self.ui.app.world
1317 if world then
1318 world.hospitals[player_no].game_won = false
1319 if world:isCurrentSpeed("Pause") then
1320 world:setSpeed(world.prev_speed)
1321 end
1322 end
1323 end
1324 self.hospitals[player_no].game_won = true
1325 self:previousSpeed()
1326 self.ui.bottom_panel:queueMessage("information", message, nil, 0, 2, callback)
1327 self.ui.bottom_panel:openLastMessage()
1328 end
1329 end
1330
1331 --! Finds what text the winning fax should contain, and which choices the player has.
1332 --!param player_no (integer) Which player that will see the message.
1333 --!return (string, string, string) Text to show in the fax, text that accompanies
1334 --! the "continue"-choice the player has, and whether it is the "return_to_main_menu"
1335 --! choice or the "accept_new_level" choice.
1336 function World:getCampaignWinningText(player_no)
1337 local text = {}
1338 local choice_text, choice
1339 local hosp = self:getLocalPlayerHospital()
1340 local repeated_offer = hosp.win_declined
1341 local has_next = false
1342 if type(self.map.level_number) == "number" then
1343 local no = tonumber(self.map.level_number)
1344 has_next = no < 12 and not TheApp.using_demo_files
1345 -- Standard letters 1-4: normal
1346 -- Standard letters 5-8: repeated offer
1347 -- Standard letters 9-12: last level
1348 local letter_idx = math.random(1, 4) + (not has_next and 8 or repeated_offer and 4 or 0)
1349 for key, value in ipairs(_S.letter[letter_idx]) do
1350 text[key] = value
1351 end
1352 text[1] = text[1]:format(self.hospitals[player_no].name)
1353 text[2] = text[2]:format(self.hospitals[player_no].salary_offer)
1354 text[3] = text[3]:format(_S.level_names[self.map.level_number + 1])
1355 else
1356 local campaign_info = self.campaign_info
1357 local next_level_name, next_level_info
1358 if campaign_info then
1359 for i, level in ipairs(campaign_info.levels) do
1360 local filename = self.map.level_filename or self.map.level_number
1361 if filename == level then
1362 has_next = i < #campaign_info.levels
1363 if has_next then
1364 next_level_info = TheApp:readLevelFile(campaign_info.levels[i + 1], campaign_info.folder)
1365 if not next_level_info then
1366 return {_S.letter.campaign_level_missing:format(campaign_info.levels[i + 1]), "", ""},
1367 _S.fax.choices.return_to_main_menu,
1368 "return_to_main_menu"
1369 end
1370 next_level_name = next_level_info.name
1371 end
1372 break
1373 end
1374 end
1375 end
1376 local level_info = TheApp:readLevelFile(self.map.level_filename or self.map.level_number,
1377 campaign_info.folder)
1378 text[1] = _S.letter.dear_player:format(self.hospitals[player_no].name)
1379 if has_next then
1380 if level_info and level_info.end_praise then
1381 text[2] = level_info.end_praise:format(next_level_name)
1382 else
1383 text[2] = _S.letter.campaign_level_completed:format(next_level_name)
1384 end
1385 else
1386 text[2] = campaign_info.winning_text and campaign_info.winning_text or _S.letter.campaign_completed
1387 end
1388 text[3] = ""
1389 end
1390 if has_next then
1391 choice_text = _S.fax.choices.accept_new_level
1392 choice = "accept_new_level"
1393 else
1394 choice_text = _S.fax.choices.return_to_main_menu
1395 choice = "return_to_main_menu"
1396 end
1397 return text, choice_text, choice
1398 end
1399
1400 --! Cause the player with the player number player_no to lose.
1401 --!param player_no (number) The number of the player which should lose.
1402 --!param reason (string) [optional] The name of the criterion the player lost to.
1403 --!param limit (number) [optional] The number the player went over/under which caused him to lose.
1404 function World:loseGame(player_no, reason, limit)
1405 if player_no == 1 then -- TODO: Multiplayer
1406 self.ui.app.moviePlayer:playLoseMovie()
1407 local message = {_S.information.level_lost[1]}
1408 if reason then
1409 message[2] = _S.information.level_lost[2]
1410 message[3] = _S.information.level_lost[reason]:format(limit)
1411 else
1412 message[2] = _S.information.level_lost["cheat"]
1413 end
1414 self.ui.app:loadMainMenu(message)
1415 end
1416 end
1417
1418 -- Called immediately prior to the ingame year changing.
1419 function World:onEndYear()
1420 for _, hospital in ipairs(self.hospitals) do
1421 hospital:onEndYear()
1422 end
1423
1424 -- This is done here instead of in onEndMonth so that the player gets
1425 -- the chance to receive money or reputation from trophies and awards first.
1426 for i, hosp in ipairs(self.hospitals) do
1427 local reason, limit = self.endconditions:checkEndGame(hosp)
1428 if limit then
1429 self:loseGame(i, reason, limit)
1430 if i == 1 then
1431 return true
1432 end
1433 end
1434 end
1435 end
1436
1437 -- Calculate the distance of the shortest path (along passable tiles) between
1438 -- the two given map tiles. This operation is commutative (swapping (x1, y1)
1439 -- with (x2, y2) has no effect on the result) if both tiles are passable.
1440 --!param x1 (integer) X-cordinate of first tile's Lua tile coordinates.
1441 --!param y1 (integer) Y-cordinate of first tile's Lua tile coordinates.
1442 --!param x2 (integer) X-cordinate of second tile's Lua tile coordinates.
1443 --!param y2 (integer) Y-cordinate of second tile's Lua tile coordinates.
1444 --!return (integer, boolean) The distance of the shortest path, or false if
1445 -- there is no path.
1446 function World:getPathDistance(x1, y1, x2, y2)
1447 return self.pathfinder:findDistance(x1, y1, x2, y2)
1448 end
1449
1450 function World:getPath(x, y, dest_x, dest_y)
1451 return self.pathfinder:findPath(x, y, dest_x, dest_y)
1452 end
1453
1454 -- Find an tile for idling.
1455 -- !param x X coordinate of the queue position.
1456 -- !param y Y coordinate of the queue position.
1457 -- !param idx Randomization factor for the idle tile, returns Nth candidate tile.
1458 -- !param parcel_id Optional parcel of the indoor returned idling tile.
1459 -- !return Position of an idle tile if it exists.
1460 function World:getIdleTile(x, y, idx, parcel_id)
1461 local cache_idx = (y - 1) * self.map.width + x
1462 local cache = self.idle_cache[cache_idx]
1463 if not cache then
1464 cache = {
1465 x = {},
1466 y = {},
1467 }
1468 self.idle_cache[cache_idx] = cache
1469 end
1470 if not cache.x[idx] then
1471 local ix, iy = self.pathfinder:findIdleTile(x, y, idx, parcel_id or 0)
1472 if not ix then
1473 return ix, iy
1474 end
1475 cache.x[idx] = ix
1476 cache.y[idx] = iy
1477 end
1478 return cache.x[idx], cache.y[idx]
1479 end
1480
1481 --[[
1482 This function checks if a tile has no entity on it and (optionally) if it is not
1483 in a room.
1484 !param x (integer) the queried tile's x coordinate.
1485 !param y (integer) the queried tile's y coordinate.
1486 !param not_in_room (boolean) If set, also check the tile is not in a room.
1487 !return (boolean) whether all checks hold.
1488 --]]
1489 function World:isTileEmpty(x, y, not_in_room)
1490 if self:atLeastOneHumanoidLocatedAtTile(x, y) or
1491 self:atLeastOneObjectLocatedAtTile(x, y) then
1492 return false
1493 end
1494 if not_in_room then
1495 return self:getRoom(x, y) == nil
1496 end
1497 return true
1498 end
1499
1500 --! Checks if any object is located on a tile.
1501 --!param x (integer) the queried tile's x coordinate.
1502 --!param y (integer) the queried tile's y coordinate.
1503 --!return (boolean) true if any object is located on a tile.
1504 function World:atLeastOneObjectLocatedAtTile(x, y)
1505 return #self.entity_map:getObjectsAtCoordinate(x, y) ~= 0
1506 end
1507
1508 --! Checks if any humanoid is located on a tile.
1509 --!param x (integer) the queried tile's x coordinate.
1510 --!param y (integer) the queried tile's y coordinate.
1511 --!return (boolean) true if any humanoid is located on a tile.
1512 function World:atLeastOneHumanoidLocatedAtTile(x, y)
1513 return #self.entity_map:getHumanoidsAtCoordinate(x, y) ~= 0
1514 end
1515
1516 --! Сhecks whether a tile is occupied by any humanoid.
1517 --!param x (integer) the queried tile's x coordinate.
1518 --!param y (integer) the queried tile's y coordinate.
1519 --!return (boolean) true if any humanoid is occupy the tile.
1520 function World:anyHumanoidObscuringArea(x, y)
1521 -- Search for humanoids on the given tile and all neighboring tiles, but not diagonal ones
1522 local humanoids = self.entity_map:getHumanoidsInSquareAndInAdjacentSquares(x, y)
1523 for _, humanoid in ipairs(humanoids) do
1524 if humanoid:isObscuringArea(x - 1, x + 1, y - 1, y + 1) then
1525 return true
1526 end
1527 end
1528 return false
1529 end
1530
1531 function World:getFreeBench(x, y, distance)
1532 local bench, rx, ry, bench_distance
1533 local object_type = self.object_types.bench
1534 x, y, distance = math.floor(x), math.floor(y), math.ceil(distance)
1535 self.pathfinder:findObject(x, y, object_type.thob, distance, function(xpos, ypos, d, dist)
1536 local b = self:getObject(xpos, ypos, "bench", true)
1537 if b and not b.user and not b.reserved_for and not b.picked_up then
1538 local orientation = object_type.orientations[b.direction]
1539 if orientation.pathfind_allowed_dirs[d] then
1540 rx = xpos + orientation.use_position[1]
1541 ry = ypos + orientation.use_position[2]
1542 bench = b
1543 bench_distance = dist
1544 return true
1545 end
1546 end
1547 end)
1548 return bench, rx, ry, bench_distance
1549 end
1550
1551 --! Checks whether the given tile is part of a nearby object (walkable tiles
1552 -- count as part of the object)
1553 --!param x X position of the given tile.
1554 --!param y Y position of the given tile.
1555 --!param distance The number of tiles away from the tile to search.
1556 --!return (boolean) Whether the tile is part of a nearby object.
1557 function World:isTilePartOfNearbyObject(x, y, distance)
1558 for o in pairs(self:findAllObjectsNear(x, y, distance)) do
1559 for _, xy in ipairs(o:getWalkableTiles()) do
1560 if xy[1] == x and xy[2] == y then
1561 return true
1562 end
1563 end
1564 end
1565 return false
1566 end
1567
1568 -- Returns a set of all objects near the given position but if supplied only of the given object type.
1569 --!param x The x-coordinate at which to originate the search
1570 --!param y The y-coordinate
1571 --!param distance The number of tiles away from the origin to search
1572 --!param object_type_name The name of the objects that are being searched for
1573 function World:findAllObjectsNear(x, y, distance, object_type_name)
1574 if not distance then
1575 -- Note that regardless of distance, only the room which the humanoid is in
1576 -- is searched (or the corridor if the humanoid is not in a room).
1577 distance = 2^30
1578 end
1579 local objects = {}
1580 local thob = 0
1581 if object_type_name then
1582 local obj_type = self.object_types[object_type_name]
1583 if not obj_type then
1584 error("Invalid object type name: " .. object_type_name)
1585 end
1586 thob = obj_type.thob
1587 end
1588
1589 local callback = function(xpos, ypos)
1590 local obj = self:getObject(xpos, ypos, object_type_name)
1591 if obj then
1592 objects[obj] = true
1593 end
1594 end
1595 self.pathfinder:findObject(x, y, thob, distance, callback)
1596 return objects
1597 end
1598
1599 --[[ Find all objects of the given type near the humanoid.
1600 Note that regardless of distance, only the room which the humanoid is in
1601 is searched (or the corridor if the humanoid is not in a room).
1602
1603 When no callback is specified then the first object found is returned,
1604 along with its usage tile position. This may return an object already being
1605 used - if you want to find an object not in use (in order to use it),
1606 then call findFreeObjectNearToUse instead.
1607
1608 !param humanoid The humanoid to search around
1609 !param object_type_name The objects to search for
1610 !param distance Maximum L1 distance to search from humanoid. If nil then
1611 everywhere in range will be searched.
1612 !param only_usable Bool If true the object must be permitted for use
1613 !param callback Function to call for each result. If it returns true then
1614 the search will be ended.
1615 --]]
1616 function World:findObjectNear(humanoid, object_type_name, distance, only_usable, callback)
1617 if not distance then
1618 distance = 2^30
1619 end
1620 local obj, ox, oy
1621 if not callback then
1622 -- The default callback returns the first object found
1623 callback = function(x, y, d)
1624 obj = self:getObject(x, y, object_type_name, only_usable)
1625 if obj then
1626 local orientation = obj.object_type.orientations
1627 if orientation then
1628 orientation = orientation[obj.direction]
1629 if not orientation.pathfind_allowed_dirs[d] then
1630 return
1631 end
1632 x = x + orientation.use_position[1]
1633 y = y + orientation.use_position[2]
1634 end
1635 ox = x
1636 oy = y
1637 return true
1638 end
1639 end
1640 end
1641 local thob = 0
1642 if type(object_type_name) == "table" then
1643 local original_callback = callback
1644 callback = function(x, y, ...)
1645 local cb_obj = self:getObject(x, y, object_type_name, only_usable)
1646 if cb_obj then
1647 return original_callback(x, y, ...)
1648 end
1649 end
1650 elseif object_type_name ~= nil then
1651 local obj_type = self.object_types[object_type_name]
1652 if not obj_type then
1653 error("Invalid object type name: " .. object_type_name)
1654 end
1655 thob = obj_type.thob
1656 end
1657 self.pathfinder:findObject(humanoid.tile_x, humanoid.tile_y, thob, distance,
1658 callback)
1659 -- These return values are only relevant for the default callback - are nil
1660 -- for custom callbacks
1661 return obj, ox, oy
1662 end
1663
1664 function World:findFreeObjectNearToUse(humanoid, object_type_name, which, current_object)
1665 -- If which == nil or false, then the nearest object is taken.
1666 -- If which == "far", then the furthest object is taken.
1667 -- If which == "near", then the nearest object is taken with 50% probability, the second nearest with 25%, and so on
1668 -- Other values for which may be added in the future.
1669 -- Specify current_object if you want to exclude the currently used object from the search
1670 local object, ox, oy
1671 self:findObjectNear(humanoid, object_type_name, nil, true, function(x, y, d)
1672 local obj = self:getObject(x, y, object_type_name)
1673 if obj.user or obj.picked_up or (obj.reserved_for and obj.reserved_for ~= humanoid) or (current_object and obj == current_object) then
1674 return
1675 end
1676 local orientation = obj.object_type.orientations
1677 if orientation then
1678 orientation = orientation[obj.direction]
1679 if not orientation.pathfind_allowed_dirs[d] then
1680 return
1681 end
1682 x = x + orientation.use_position[1]
1683 y = y + orientation.use_position[2]
1684 end
1685 object = obj
1686 ox = x
1687 oy = y
1688 if which == "far" then -- luacheck: ignore 542
1689 -- just take the last found object, so don't ever abort
1690 elseif which == "near" then
1691 -- abort at each item with 50% probability
1692 local chance = math.random(1, 2)
1693 if chance == 1 then
1694 return true
1695 end
1696 else
1697 -- default: return at the first found item
1698 return true
1699 end
1700 end)
1701 return object, ox, oy
1702 end
1703
1704 --! Finds the most desirable room of a given room type for the provided humanoid.
1705 --!param humanoid The queried NPC (start point)
1706 --!param room_type_id (string) The room we are looking for
1707 --!param max_distance (number) The maximum distance away a room will be considered from the humanoid
1708 --!param mode (string) "nearest"/nil returns the nearest room, while
1709 --! "advanced" prefers a near room but also takes into account queue size/staffing
1710 --!return The best room for the huamnoid or nil if no room exists within the maximum distance
1711 function World:findRoomNear(humanoid, room_type_id, max_distance, mode)
1712 assert(type(room_type_id) == "string", "Room type id given is not a string!")
1713 local room
1714 local score
1715 if not mode then
1716 mode = "nearest" -- default mode
1717 end
1718 if not max_distance then
1719 max_distance = 2^30
1720 end
1721
1722 for _, r in pairs(self.rooms) do
1723 if r.built and r.room_info.id == room_type_id and r.is_active then
1724 local x, y = r:getEntranceXY(false)
1725 local d = self:getPathDistance(humanoid.tile_x, humanoid.tile_y, x, y)
1726
1727 if d and d <= max_distance then
1728 local this_score = d
1729
1730 if mode == "advanced" then
1731 this_score = this_score + r:getUsageScore()
1732 end
1733
1734 if not score or this_score < score then
1735 score = this_score
1736 room = r
1737 end
1738 end
1739 end
1740 end
1741 return room
1742 end
1743
1744 --! Setup an animated floating money amount above a patient.
1745 --!param patient Patient to float above.
1746 --!param amount Amount of money to display.
1747 function World:newFloatingDollarSign(patient, amount)
1748 if self.free_build_mode or patient.hospital ~= self:getLocalPlayerHospital() then
1749 return
1750 end
1751 if not self.floating_dollars then
1752 self.floating_dollars = {}
1753 end
1754 local spritelist = TH.spriteList()
1755 spritelist:setPosition(-17, -60)
1756 spritelist:setSpeed(0, -1):setLifetime(100)
1757 spritelist:setSheet(TheApp.gfx:loadSpriteTable("Data", "Money01V"))
1758 spritelist:setUseIntermediateBuffer()
1759 spritelist:append(1, 0, 0)
1760 local len = #("%i"):format(amount)
1761 local xbase = math.floor(10.5 + (20 - 5 * len) / 2)
1762 for i = 1, len do
1763 local digit = amount % 10
1764 amount = (amount - digit) / 10
1765 spritelist:append(2 + digit, xbase + 5 * (len - i), 5)
1766 end
1767 spritelist:setTile(self.map.th, patient.tile_x, patient.tile_y,
1768 DrawingLayers.FloatingDollars)
1769
1770 self.floating_dollars[spritelist] = true
1771 end
1772
1773 --! Create a new entity.
1774 --!param class Class to use for the new entity.
1775 --!param animation (int)Initial animation to use.
1776 --!param mood_marker (int) Whether to use the first (default), or the second marker.
1777 function World:newEntity(class, animation, mood_marker)
1778 mood_marker = mood_marker and mood_marker or 1
1779 assert(mood_marker == 1 or mood_marker == 2, "mood_marker is neither 1 nor 2.")
1780
1781 local th = TH.animation()
1782 th:setAnimation(self.anims, animation)
1783 local entity = _G[class](th)
1784 if not table_contains(self.entities, entity) then
1785 self.entities[#self.entities + 1] = entity
1786 end
1787 entity.world = self
1788 entity.mood_marker = mood_marker
1789 return entity
1790 end
1791
1792 function World:destroyEntity(entity)
1793 for i, e in ipairs(self.entities) do
1794 if e == entity then
1795 table.remove(self.entities, i)
1796 break
1797 end
1798 end
1799 entity:onDestroy()
1800 end
1801
1802 function World:newObjectType(new_object)
1803 self.object_types[new_object.id] = new_object
1804 end
1805
1806 --! Creates a new object by finding the object_type from the "id" variable and
1807 -- calls its class constructor.
1808 --!param id (string) The unique id of the object to be created.
1809 --!param x X position of the new object.
1810 --!param y Y position of the new object.
1811 --!param flags Flags of the new object.
1812 --!param name Name of the new object.
1813 --!return The created object.
1814 function World:newObject(id, x, y, flags, name)
1815 local object_type = self.object_types[id]
1816 local hospital = self:getLocalPlayerHospital()
1817
1818 local entity
1819 if object_type.class then
1820 entity = _G[object_type.class](hospital, object_type, x, y, flags, name)
1821 elseif object_type.default_strength then
1822 entity = Machine(hospital, object_type, x, y, flags, name)
1823 -- Tell the player if there is no handyman to take care of the new machinery.
1824 if hospital:countStaffOfCategory("Handyman", 1) == 0 then
1825 hospital:giveAdvice({_A.staff_advice.need_handyman_machines})
1826 end
1827 else
1828 entity = Object(hospital, object_type, x, y, flags, name)
1829 end
1830 self:objectPlaced(entity, id)
1831 return entity
1832 end
1833
1834 -- Checks whether object can be spawned at some coordinates.
1835 -- For example, when searching for a suitable placement for "gates_to_hell".
1836 -- 'NonSideObject' is a object that do occupy the tile entirely, not only one side of it.
1837 function World:canNonSideObjectBeSpawnedAt(x, y, objects_id, orientation, spawn_rooms_id, player_id)
1838 local object = self.object_types[objects_id]
1839 local objects_footprint = object.orientations[orientation].footprint
1840 for _, tile in ipairs(objects_footprint) do
1841 local tiles_world_x = x + tile[1]
1842 local tiles_world_y = y + tile[2]
1843 if not self:isOnMap(tiles_world_x, tiles_world_y) then
1844 return false
1845 end
1846
1847 if not self:willObjectsFootprintTileBeWithinItsAllowedRoomIfLocatedAt(x, y, object, spawn_rooms_id).within_room then
1848 return false
1849 end
1850
1851 if not self:isFootprintTileBuildableOrPassable(x, y, tile, objects_footprint, "buildable", player_id) then
1852 return false
1853 end
1854 end
1855 return not self:wouldNonSideObjectBreakPathfindingIfSpawnedAt(x, y, object, orientation, spawn_rooms_id)
1856 end
1857
1858 --! Test whether the given coordinate is on the map.
1859 --!param x (int) X position of the coordinate to test.
1860 --!param y (int) Y position of the coordinate to test.
1861 --!return (boolean) Whether the provided position is on the map.
1862 function World:isOnMap(x, y)
1863 return x >= 1 and x <= self.map.width and y >= 1 and y <= self.map.height
1864 end
1865
1866 ---
1867 -- @param allowed_rooms_id_parameter Should be nil when the object is allowed to be placed in any room.
1868 -- @return {within_room, roomId}
1869 ---
1870 function World:willObjectsFootprintTileBeWithinItsAllowedRoomIfLocatedAt(x, y, object, allowed_rooms_id_parameter)
1871 local xy_rooms_id = self.map.th:getCellFlags(x, y, {}).roomId
1872
1873 if allowed_rooms_id_parameter then
1874 return {within_room = allowed_rooms_id_parameter == xy_rooms_id, roomId = allowed_rooms_id_parameter}
1875 elseif xy_rooms_id == 0 then
1876 return {within_room = object.corridor_object ~= nil, roomId = xy_rooms_id}
1877 else
1878 for _, additional_objects_name in pairs(self.rooms[xy_rooms_id].room_info.objects_additional) do
1879 if TheApp.objects[additional_objects_name].thob == object.thob then
1880 return {within_room = true, roomId = xy_rooms_id}
1881 end
1882 end
1883 for needed_objects_name, _ in pairs(self.rooms[xy_rooms_id].room_info.objects_needed) do
1884 if TheApp.objects[needed_objects_name].thob == object.thob then
1885 return {within_room = true, roomId = xy_rooms_id}
1886 end
1887 end
1888 return {within_room = false, roomId = xy_rooms_id}
1889 end
1890 end
1891
1892 ---
1893 -- A footprint tile will either need to be buildable or passable so this function
1894 -- checks if its buildable/passable using the tile's appropriate flag and then returns this
1895 -- flag's boolean value or false if the tile isn't valid.
1896 ---
1897 function World:isFootprintTileBuildableOrPassable(x, y, tile, footprint, requirement_flag, player_id)
1898 local function isTileValid(xpos, ypos, complete_cell, flags, flag_name, need_side)
1899 if complete_cell or need_side then
1900 return flags[flag_name]
1901 end
1902 for _, fp_tile in ipairs(footprint) do
1903 if fp_tile[1] == xpos and fp_tile[2] == ypos then
1904 return flags[flag_name]
1905 end
1906 end
1907 return true
1908 end
1909
1910 local direction_parameters = {
1911 north = { x = 0, y = -1, buildable_flag = "buildableNorth", passable_flag = "travelNorth", needed_side = "need_north_side"},
1912 east = { x = 1, y = 0, buildable_flag = "buildableEast", passable_flag = "travelEast", needed_side = "need_east_side"},
1913 south = { x = 0, y = 1, buildable_flag = "buildableSouth", passable_flag = "travelSouth", needed_side = "need_south_side"},
1914 west = { x = -1, y = 0, buildable_flag = "buildableWest", passable_flag = "travelWest", needed_side = "need_west_side"}
1915 }
1916 local flags = {}
1917 local requirement_met = self.map.th:getCellFlags(x, y, flags)[requirement_flag] and
1918 (player_id == 0 or player_id == flags.owner)
1919
1920 if requirement_met then
1921 -- For each direction check that the tile is valid:
1922 for _, direction in pairs(direction_parameters) do
1923 local x1, y1 = tile[1] + direction["x"], tile[2] + direction["y"]
1924 if not isTileValid(x1, y1, tile.complete_cell, flags, direction["buildable_flag"], tile[direction["needed_side"]]) then
1925 return false
1926 end
1927 end
1928 return true
1929 else
1930 return false
1931 end
1932 end
1933
1934 --! Check that pathfinding still works, i.e. that placing the object
1935 --! wouldn't disconnect one part of the hospital from another. To do
1936 --! this, we provisionally mark the footprint as unpassable (as it will
1937 --! become when the object is placed), and then check that the cells
1938 --! surrounding the footprint have not had their connectedness changed.
1939 --!param x (integer) target tile x coordinate.
1940 --!param y (integer) target tile y coordinate.
1941 --!param object (object) target object for placing.
1942 --!param objects_orientation (table) object orientations description with footprints.
1943 --!param room_id (integer) target room for placing the object.
1944 --!return (bool) will this placement break path finding.
1945 function World:wouldNonSideObjectBreakPathfindingIfSpawnedAt(x, y, object, objects_orientation, room_id)
1946 local objects_footprint = object.orientations[objects_orientation].footprint
1947 local map = self.map.th
1948
1949 local function setFootprintTilesPassable(passable)
1950 for _, tile in ipairs(objects_footprint) do
1951 if not tile.only_passable then
1952 map:setCellFlags(x + tile[1], y + tile[2], {passable = passable})
1953 end
1954 end
1955 end
1956
1957 local function isIsolated(xpos, ypos)
1958 setFootprintTilesPassable(false)
1959 local result = not self.pathfinder:isReachableFromHospital(xpos, ypos)
1960 setFootprintTilesPassable(true)
1961 return result
1962 end
1963
1964 local pathfinding_success = true
1965
1966 --1. Find out which footprint tiles are passable now before this function makes some unpassable
1967 --during its test:
1968 local tiles_passable_flags = {}
1969 for _, tile in ipairs(objects_footprint) do
1970 table.insert(tiles_passable_flags, map:getCellFlags(x + tile[1], y + tile[2], {}).passable)
1971 end
1972
1973 --2. Find out which tiles adjacent to the footprint would become isolated:
1974 setFootprintTilesPassable(false)
1975 local prev_x, prev_y
1976 for _, tile in ipairs(object.orientations[objects_orientation].adjacent_to_solid_footprint) do
1977 local xpos = x + tile[1]
1978 local ypos = y + tile[2]
1979 local flags = {}
1980 if map:getCellFlags(xpos, ypos, flags).roomId == room_id and flags.passable then
1981 if prev_x then
1982 if not self.pathfinder:findDistance(xpos, ypos, prev_x, prev_y) then
1983 -- There is no route between the two map nodes. In most cases,
1984 -- this means that connectedness has changed, though there is
1985 -- one rare situation where the above test is insufficient. If
1986 -- (xpos, ypos) is a passable but isolated node outside the hospital
1987 -- and (prev_x, prev_y) is in the corridor, then the two will
1988 -- not be connected now, but critically, neither were they
1989 -- connected before.
1990 if not isIsolated(xpos, ypos) then
1991 if not isIsolated(prev_x, prev_y) then
1992 pathfinding_success = false
1993 break
1994 end
1995 else
1996 xpos = prev_x
1997 ypos = prev_y
1998 end
1999 end
2000 end
2001 prev_x = xpos
2002 prev_y = ypos
2003 end
2004 end
2005
2006 -- 3. For each footprint tile passable flag set to false by step 2 undo this change:
2007 for tiles_index, tile in ipairs(objects_footprint) do
2008 map:setCellFlags(x + tile[1], y + tile[2], {passable = tiles_passable_flags[tiles_index]})
2009 end
2010
2011 return not pathfinding_success
2012 end
2013
2014 --! Check that pathfinding between object and room door still works,
2015 --! i.e. that placing the object wouldn't disconnect it from the world.
2016 --! For that it mark the footprint as unpassable (as it will
2017 --! become when the object is placed), and then check that the
2018 --! "use_position" cells have path to the room door.
2019 --!param object_x (integer) target tile x coordinate.
2020 --!param object_y (integer) target tile y coordinate.
2021 --!param room (object) target room for placing the object.
2022 --!param object_layout (table) object orientation description with footprint.
2023 --!return (bool) will this placement break path finding.
2024 function World:wouldNonSideObjectsNotHaveAccessToRoomDoor(object_x, object_y, room, object_layout)
2025 if not room.door or not room.door.tile_x or not room.door.tile_y then return true end
2026
2027 local door_x, door_y = room:getEntranceXY(true)
2028 local object_footprint = object_layout.footprint
2029 local map = self.map.th
2030
2031 -- To switch the tiles passability
2032 local function setFootprintTilesPassable(passable)
2033 for _, tile in ipairs(object_footprint) do
2034 if not tile.only_passable then
2035 map:setCellFlags(object_x + tile[1], object_y + tile[2], {passable = passable})
2036 end
2037 end
2038 end
2039
2040 local function _isIsolated(tile_x, tile_y, poi_x, poi_y)
2041 -- Make footprint tiles unpassable except only_passable ones
2042 setFootprintTilesPassable(false)
2043 -- And check is there is a valid path
2044 local getPathDistance = self:getPathDistance(tile_x, tile_y, poi_x, poi_y)
2045 setFootprintTilesPassable(true)
2046
2047 -- Let's also check that there is a path even without the footprint apply.
2048 -- This will help to avoid cases where the path starts on an inaccessible tile.
2049 -- For some reason, "getPathDistance" successfully constructs a path from inaccessible tiles.
2050 -- So filtering such cases there.
2051 getPathDistance = getPathDistance and self:getPathDistance(tile_x, tile_y, poi_x, poi_y)
2052 return not getPathDistance
2053 end
2054
2055 -- 1. Let's simulate it as if we've already placed the object and make some tiles unpassable.
2056 -- Find out which footprint tiles are passable now before this function makes some unpassable
2057 -- during its test:
2058 local tiles_passable_flags = {}
2059 for _, tile in ipairs(object_footprint) do
2060 table.insert(tiles_passable_flags, map:getCellFlags(object_x + tile[1], object_y + tile[2], {}).passable)
2061 end
2062
2063 -- 2. Find out which use position tiles would become isolated:
2064 local pathfinding_success = true
2065 local usage_tiles = {}
2066 local object_use_positions_names = Object:usePositionNames()
2067 for _, usage_position_type in ipairs(object_use_positions_names) do
2068 local more_usage_tiles = Object:getXYforUsePosition(object_x, object_y, object_layout, usage_position_type)
2069 usage_tiles = table_merge(usage_tiles, more_usage_tiles)
2070 end
2071
2072 for _, usage_tile in ipairs(usage_tiles) do
2073 pathfinding_success = pathfinding_success and not _isIsolated(usage_tile[1], usage_tile[2], door_x, door_y)
2074 if not pathfinding_success then break end
2075 end
2076
2077 -- 3. For each footprint tile passable flag set to false by step 2 undo this change:
2078 for tiles_index, tile in ipairs(object_footprint) do
2079 map:setCellFlags(object_x + tile[1], object_y + tile[2], {passable = tiles_passable_flags[tiles_index]})
2080 end
2081
2082 return not pathfinding_success
2083 end
2084
2085 --! Check that pathfinding between already placed in the room objects
2086 --! and room door still works. i.e. that placing the target object
2087 --! wouldn't disconnect the existing objects from the world.
2088 --! For 'NonSideObject' it mark the footprint as unpassable
2089 --! (as it will become when the object is placed).
2090 --! For 'SideObject' this function expects that mark the footprint
2091 --! as unpassable will be executed outside of this function.
2092 --! And then this function check that the "use_position" cells
2093 --! of existing objects have path to the room door.
2094 --!param object_x (integer) target tile x coordinate.
2095 --!param object_y (integer) target tile y coordinate.
2096 --!param room (object) target room for placing the object.
2097 --!param object_layout (table) object orientation description with footprint.
2098 --!param is_side_object (bool) is that object is side object.
2099 --!return (bool) will this placement break path finding.
2100 function World:wouldObjectBreakRoomObjectsAccessToTheRoomDoor(object_x, object_y, room, object_layout, is_side_object)
2101 if not room.door or not room.door.tile_x or not room.door.tile_y then return true end
2102
2103 local object_footprint
2104 local door_x, door_y = room:getEntranceXY(true)
2105 local map = self.map.th
2106 if not is_side_object then
2107 object_footprint = object_layout.footprint
2108 end
2109
2110 -- To switch the tiles passability
2111 local function setFootprintTilesPassable(passable) -- not used for SideObjects
2112 for _, tile in ipairs(object_footprint) do
2113 if not tile.only_passable then
2114 map:setCellFlags(object_x + tile[1], object_y + tile[2], {passable = passable})
2115 end
2116 end
2117 end
2118
2119 local function _isIsolated(tile_x, tile_y, poi_x, poi_y)
2120 local getPathDistance = self:getPathDistance(tile_x, tile_y, poi_x, poi_y)
2121 return not getPathDistance
2122 end
2123
2124 --1. Find out which footprint tiles are passable now before this function makes some unpassable
2125 --during its test:
2126 local tiles_passable_flags = {}
2127 if not is_side_object then
2128 for _, tile in ipairs(object_footprint) do
2129 table.insert(tiles_passable_flags, map:getCellFlags(object_x + tile[1], object_y + tile[2], {}).passable)
2130 end
2131 end
2132
2133 --2. Make footprint tiles unpassable except only_passable ones
2134 if not is_side_object then
2135 setFootprintTilesPassable(false)
2136 end
2137
2138 --3. Find out which use position tiles would become isolated:
2139 local pathfinding_success = true
2140 for room_object, _ in pairs(room.objects) do
2141 -- check that for each already placed object there is a valid path to the door
2142 local object_usage_tiles = room_object:getAllUsageTiles()
2143 for _, usage_tile in pairs(object_usage_tiles) do
2144 local use_x, use_y = usage_tile[1], usage_tile[2]
2145 -- 'SideObject' somehow has 'use_position', even though they don't have it in the footprint.
2146 -- We don't need to check that 'use_position' for 'SideObjects',
2147 -- because these 'use_position' are not actually used in the game, so skip them.
2148 if (room_object.object_type.class ~= "SideObject") and use_x and use_y then
2149 -- check that the placing object itself does not occupy 'use_position'
2150 local tile_overlap = (object_x == use_x) and (object_y == use_y)
2151 pathfinding_success = pathfinding_success and not tile_overlap
2152 -- also check that the placing object does not break the path from 'use_position' to the room door.
2153 pathfinding_success = pathfinding_success and not _isIsolated(use_x, use_y, door_x, door_y)
2154 end
2155 if not pathfinding_success then break end
2156 end
2157 if not pathfinding_success then break end
2158 end
2159
2160 -- 4. For each footprint tile passable flag set to false by step 2 undo this change:
2161 if not is_side_object then
2162 setFootprintTilesPassable(true)
2163 for tiles_index, tile in ipairs(object_footprint) do
2164 map:setCellFlags(object_x + tile[1], object_y + tile[2], {passable = tiles_passable_flags[tiles_index]})
2165 end
2166 end
2167
2168 return not pathfinding_success
2169 end
2170
2171 --! Notifies the world that an object has been placed, notifying
2172 -- interested entities in the vicinity of the new arrival.
2173 --!param entity (Entity) The entity that was just placed.
2174 --!param id (optional string) That entity's id.
2175 function World:objectPlaced(entity, id)
2176 -- If id is not supplied, we can use the entities internal id if it exists
2177 -- This is so the bench check below works
2178 -- see place_object.lua:UIPlaceObjects:placeObject for call w/o id --cgj
2179 if not id and entity.object_type.id then
2180 id = entity.object_type.id
2181 end
2182
2183 if not table_contains(self.entities, entity) then
2184 self.entities[#self.entities + 1] = entity
2185 end
2186
2187 -- Warn a hospital if that is possible.
2188 if not entity.tile_x or not entity.tile_y then return end
2189 local hosp = self:getHospital(entity.tile_x, entity.tile_y)
2190 if hosp then hosp:objectPlaced(entity, id) end
2191 end
2192
2193 --! Notify the world of an object being removed from a tile
2194 --! See also `World:addObjectToTile`
2195 --!param object (Object) The object being removed.
2196 --!param x (integer) The X-coordinate of the tile which the object was on
2197 --!param y (integer) The Y-coordinate of the tile which the object was on
2198 function World:removeObjectFromTile(object, x, y)
2199 local index = (y - 1) * self.map.width + x
2200 local objects = self.objects[index]
2201 local thob = object.object_type.thob
2202 if objects then
2203 for k, v in ipairs(objects) do
2204 if v == object then
2205 table_remove(objects, k)
2206 self.map.th:removeObjectType(x, y, thob)
2207 object.hospital:removeTileObject(object.object_type.count_category)
2208 return true
2209 end
2210 end
2211 end
2212 return false
2213 end
2214
2215 --! Notify the world of a new object being placed somewhere in the world
2216 --! See also `World:removeObjectFromTile`
2217 --!param object (Object) The object being placed
2218 --!param x (integer) The X-coordinate of the tile being placed upon
2219 --!param y (integer) The Y-coordinate of the tile being placed upon
2220 function World:addObjectToTile(object, x, y)
2221 local index = (y - 1) * self.map.width + x
2222 local objects = self.objects[index]
2223 if objects then
2224 self.map.th:setCellFlags(x, y, {thob = object.object_type.thob})
2225 objects[#objects + 1] = object
2226 else
2227 objects = {object}
2228 self.objects[index] = objects
2229 self.map.th:setCellFlags(x, y, {thob = object.object_type.thob})
2230 end
2231 object.hospital:addTileObject(object.object_type.count_category)
2232 return true
2233 end
2234
2235 --! Retrieve all objects from a given position.
2236 --!param x (int) X position of the object to retrieve.
2237 --!param y (int) Y position of the object to retrieve.
2238 function World:getObjects(x, y)
2239 local index = (y - 1) * self.map.width + x
2240 return self.objects[index]
2241 end
2242
2243 --! Retrieve one object from a given position.
2244 --!param x (int) X position of the object to retrieve.
2245 --!param y (int) Y position of the object to retrieve.
2246 --!param id Id to search, nil gets first object, string gets first object with
2247 --!param only_usable (bool) If true the object must be permitted for use
2248 --! that id, set of strings gets first object that matches an entry in the set.
2249 --!return (Object or nil) The found object, or nil if the object is not found.
2250 function World:getObject(x, y, id, only_usable)
2251 local objects = self:getObjects(x, y)
2252 if objects then
2253 if not id then
2254 if not only_usable or not objects[1].picked_up then
2255 return objects[1]
2256 end
2257 elseif type(id) == "table" then
2258 for _, obj in ipairs(objects) do
2259 if id[obj.object_type.id] and (not only_usable or not obj.picked_up) then
2260 return obj
2261 end
2262 end
2263 else
2264 for _, obj in ipairs(objects) do
2265 if obj.object_type.id == id and (not only_usable or not obj.picked_up) then
2266 return obj
2267 end
2268 end
2269 end
2270 end
2271 return -- nil
2272 end
2273
2274 --! Remove all cleanable litter from a given tile.
2275 --!param x (int) X position of the tile to clean.
2276 --!param y (int) Y position of the tile to clean.
2277 function World:removeAllLitter(x, y)
2278 local litters = {}
2279 local objects = self:getObjects(x, y)
2280 if not objects then return end
2281
2282 for _, obj in ipairs(objects) do
2283 if obj.object_type.id == "litter" and obj:isCleanable() then
2284 litters[#litters + 1] = obj
2285 end
2286 end
2287 for _, litter in ipairs(litters) do litter:remove() end
2288 end
2289
2290 --! Prepare all tiles of the footprint for build of an object.
2291 --!param object_footprint Footprint of the object being build.
2292 --!param x (int) X position of the object
2293 --!param y (int) Y position of the object
2294 function World:prepareFootprintTilesForBuild(object_footprint, x, y)
2295 local hospital = self:getLocalPlayerHospital()
2296
2297 for _, tile in ipairs(object_footprint) do
2298 if tile.complete_cell or not (tile.passable or tile.only_passable) then
2299 self:removeAllLitter(x + tile[1], y + tile[2])
2300 hospital:removeRatholeXY(x + tile[1], y + tile[2])
2301 end
2302 end
2303 end
2304
2305 --! Prepare all tiles in the given rectangle for building a room.
2306 --!param x (int) Start x position of the area.
2307 --!param y (int) Start y position of the area.
2308 --!param w (int) Number of tiles in x direction.
2309 --!param h (int) Number of tiles in y direction.
2310 function World:prepareRectangleTilesForBuild(x, y, w, h)
2311 local hospital = self:getLocalPlayerHospital()
2312
2313 x = x - 1
2314 y = y - 1
2315 for dx = 1, w do
2316 for dy = 1, h do
2317 self:removeAllLitter(x + dx, y + dy)
2318 if dx == 1 or dx == w or dy == 1 or dy == h then hospital:removeRatholeXY(x + dx, y + dy) end
2319 end
2320 end
2321 end
2322
2323 --! Get the room at a given tile location.
2324 --!param x (int) X position of the queried tile.
2325 --!param y (int) Y position of the queried tile.
2326 --!return (Room) Room of the tile, or 'nil'.
2327 function World:getRoom(x, y)
2328 return self.rooms[self.map:getRoomId(x, y)]
2329 end
2330
2331 --! Get the hospital at a given tile location.
2332 --!param x (int) X position of the queried tile.
2333 --!param y (int) Y position of the queried tile.
2334 --!return (Hospital) Hospital at the given location or 'nil'.
2335 function World:getHospital(x, y)
2336 local th = self.map.th
2337
2338 local flags = th:getCellFlags(x, y)
2339 if not flags.hospital then return nil end
2340 return self.hospitals[flags.owner]
2341 end
2342
2343 --! Returns localized name of the room, internal required staff name
2344 -- and localized name of staff required.
2345 function World:getRoomNameAndRequiredStaffName(room_id)
2346 local room_name, required_staff
2347 for _, room in ipairs(TheApp.rooms) do
2348 if room.id == room_id then
2349 room_name = room.long_name
2350 required_staff = room.required_staff
2351 end
2352 end
2353
2354 local staff_name
2355 for key, _ in pairs(required_staff) do
2356 staff_name = key -- This is the "programmatic" name of the staff.
2357 end
2358 return room_name, staff_name, StaffProfile.translateStaffClass(staff_name)
2359 end
2360
2361 --! Gets a list of all the machines in the player's hospital.
2362 function World:getPlayerMachines()
2363 local world = self
2364 local hosp = world:getLocalPlayerHospital()
2365 local playerMachines = {}
2366
2367 for _, entity in ipairs(world.entities) do
2368 -- is entity a machine and not a slave (e.g. operating_table_b)
2369 if class.is(entity, Machine) and not entity.master then
2370 -- check if machine belongs to player hospital
2371 if entity.hospital == hosp then
2372 playerMachines[#playerMachines + 1] = entity
2373 end
2374 end
2375 end
2376 return playerMachines
2377 end
2378
2379 --! Append a message to the game log.
2380 --!param message (string) The message to add.
2381 function World:gameLog(message)
2382 self.game_log[#self.game_log + 1] = message
2383 -- If in debug mode also show it in the command prompt
2384 if TheApp.config.debug then
2385 print(message)
2386 end
2387 end
2388
2389 --! Dump the contents of the game log into a file.
2390 -- This is automatically done on each error.
2391 function World:dumpGameLog()
2392 local gamelog_path = TheApp.gamelog_path
2393 local fi = self.app:writeToFileOrTmp(gamelog_path)
2394 -- Start the gamelog file with the system information
2395 local sysinfo = TheApp:gamelogHeader()
2396 fi:write(sysinfo)
2397 for _, str in ipairs(self.game_log) do
2398 fi:write(str .. "\n")
2399 end
2400 fi:close()
2401 end
2402
2403 --! Because the save file only saves one thob per tile if they are more that information
2404 -- will be lost. To solve this after a load we need to set again all the thobs on each tile.
2405 function World:resetAnimations()
2406 -- Erase entities from the map if they want.
2407 for _, entity in ipairs(self.entities) do
2408 entity:eraseObject()
2409 end
2410 -- Add them again.
2411 for _, entity in ipairs(self.entities) do
2412 entity:resetAnimation()
2413 end
2414 end
2415
2416 strict_declare_global "staff_initials_cache"
2417 staff_initials_cache = {}
2418
2419 local function our_concat(t)
2420 -- The standard table.concat function doesn't like our userdata strings :(
2421 local result = ""
2422 for _, s in ipairs(t) do
2423 result = result .. s
2424 end
2425 return result
2426 end
2427
2428 --! Refresh cache of letters in current language to be used for staff member's initials
2429 function World:updateInitialsCache()
2430 local parts = tostring(our_concat(_S.humanoid_name_starts)
2431 .. our_concat(_S.humanoid_name_ends)):sub(33)
2432 local initials = {}
2433 for uchar in parts:gmatch("([%z\1-\127\194-\244][\128-\191]*)") do
2434 initials[#initials + 1] = uchar
2435 end
2436 initials[0] = initials[#initials]
2437 staff_initials_cache.initials = initials
2438 end
2439
2440 --! Change the staff name first letter to one from the current language
2441 -- from the seed (generated here or in staff_profile.lua)
2442 --!param profile (table) The profile of the staff member
2443 function World:localiseInitial(profile)
2444 if not profile.name_seed then
2445 profile.name_seed = math.random(1, 1009)
2446 end
2447 if profile.initial and profile.name_lang == TheApp.config.language then return end
2448 -- Staff member doesn't have an initial in the current language
2449 local num = profile.name_seed % #staff_initials_cache.initials
2450 profile.initial = staff_initials_cache.initials[num]
2451 profile.name_lang = TheApp.config.language
2452 end
2453
2454 --! Let the world react to and old save game. First it gets the chance to
2455 -- do things for itself, and then it calls corresponding functions for
2456 -- the hospitals, entities and rooms in that order.
2457 --!param old (integer) The old version of the save game.
2458 --!param new (integer) The current version of the save game format.
2459 function World:afterLoad(old, new)
2460 self:setUI(self.ui)
2461 -- Re-apply level-defined pricing when loading saves:
2462 self:applyLevelStartPrices()
2463 -- insert global compatibility code here
2464 if old < 4 then
2465 self.room_built = {}
2466 end
2467 if old < 6 then
2468 -- Calculate hospital value
2469
2470 -- Initial value
2471 local value = self.map.parcelTileCounts[self.hospitals[1]:getPlayerIndex()] * 25 + 20000
2472
2473 -- Add room values
2474 for _, room in pairs(self.rooms) do
2475 local valueChange = room.room_info.build_cost
2476
2477 -- Subtract values of objects in rooms to avoid calculating those object values twice
2478 for obj, num in pairs(room.room_info.objects_needed) do
2479 valueChange = valueChange - num * TheApp.objects[obj].build_cost
2480 end
2481 value = value + valueChange
2482 end
2483
2484 -- Add up all object values
2485 for _, object in ipairs(self.entities) do
2486 if class.is(object, Object) and object.object_type.build_cost then
2487 value = value + object.object_type.build_cost
2488 end
2489 end
2490
2491 self.hospitals[1].value = value
2492 end
2493
2494 if old < 10 then
2495 self.object_counts = {
2496 extinguisher = 0,
2497 radiator = 0,
2498 plant = 0,
2499 general = 0,
2500 }
2501 for _, obj_list in pairs(self.objects) do
2502 for _, obj in ipairs(obj_list) do
2503 local count_cat = obj.object_type.count_category
2504 if count_cat then
2505 self.object_counts[count_cat] = self.object_counts[count_cat] + 1
2506 end
2507 end
2508 end
2509 end
2510 if old < 43 then
2511 self.object_counts.reception_desk = 0
2512 for _, obj_list in pairs(self.objects) do
2513 for _, obj in ipairs(obj_list) do
2514 local count_cat = obj.object_type.count_category
2515 if count_cat and count_cat == "reception_desk" then
2516 self.object_counts[count_cat] = self.object_counts[count_cat] + 1
2517 end
2518 end
2519 end
2520 end
2521 if old < 47 then
2522 self.object_counts.bench = 0
2523 for _, obj_list in pairs(self.objects) do
2524 for _, obj in ipairs(obj_list) do
2525 local count_cat = obj.object_type.count_category
2526 if count_cat and count_cat == "bench" then
2527 self.object_counts[count_cat] = self.object_counts[count_cat] + 1
2528 end
2529 end
2530 end
2531 end
2532 if old < 12 then
2533 self.animation_manager = TheApp.animation_manager
2534 self.anim_length_cache = nil
2535 end
2536 if old < 17 then
2537 -- Added another object
2538 local pathsep = package.config:sub(1, 1)
2539 local _, shield = pcall(corsixth.require, "objects" .. pathsep .. "radiation_shield")
2540 local _, shield_b = pcall(corsixth.require, "objects" .. pathsep .. "radiation_shield_b")
2541 shield.slave_type = shield_b
2542 shield.slave_type.master_type = shield
2543 Object.processTypeDefinition(shield)
2544 Object.processTypeDefinition(shield_b)
2545
2546 self.object_id_by_thob[shield.thob] = shield.id
2547 self.object_id_by_thob[shield_b.thob] = shield_b.id
2548 self.object_types[shield.id] = shield
2549 self.object_types[shield_b.id] = shield_b
2550 self.ui.app.objects[shield.id] = shield
2551 self.ui.app.objects[shield_b.id] = shield_b
2552 self.ui.app.objects[#self.ui.app.objects + 1] = shield
2553 self.ui.app.objects[#self.ui.app.objects + 1] = shield_b
2554 end
2555 if old < 27 then
2556 -- Add callsDispatcher
2557 self.dispatcher = CallsDispatcher(self)
2558 end
2559 if old < 30 then
2560 self:nextEmergency()
2561 end
2562 if old < 31 then
2563 self.hours_per_day = 50
2564 self:setSpeed("Normal")
2565 end
2566 if old < 37 then
2567 -- Spawn rate is taken from level files now.
2568 -- Make sure that all config values are present.
2569 if not self.map.level_config.popn then
2570 self.map.level_config.popn = {
2571 [0] = {Change = 3, Month = 0},
2572 [1] = {Change = 1, Month = 1},
2573 }
2574 end
2575 if not self.map.level_config.gbv.AllocDelay then
2576 self.map.level_config.gbv.AllocDelay = 3
2577 end
2578 local index = 0
2579 local popn = self.map.level_config.popn
2580 self.spawn_rate = popn[index].Change
2581 self.monthly_spawn_increase = self.spawn_rate
2582
2583 -- Bring the spawn rate "up to speed".
2584 for month = 1, self.month + (self.year-1)*12 do
2585 -- Check if the next entry should be used.
2586 while popn[index + 1] and month >= popn[index + 1].Month do
2587 index = index + 1
2588 end
2589 self.monthly_spawn_increase = popn[index].Change
2590 self.spawn_rate = self.spawn_rate + self.monthly_spawn_increase
2591 end
2592 self.spawn_hours = {}
2593 self.spawn_dates = {}
2594 self:updateSpawnDates()
2595 end
2596 if old < 45 then
2597 self:nextVip()
2598 end
2599 if old < 52 then
2600 -- Litter was not properly removed from the world.
2601 for i = #self.entities, 1, -1 do
2602 if class.is(self.entities[i], Litter) then
2603 if not self.entities[i].tile_x then
2604 self:destroyEntity(self.entities[i])
2605 end
2606 end
2607 end
2608 end
2609 if old < 57 then
2610 self.user_actions_allowed = true
2611 end
2612 if old < 61 then
2613 -- room remove callbacks added
2614 self.room_remove_callbacks = {}
2615 end
2616 if old < 64 then
2617 -- added reference to world for staff profiles
2618 for _, group in pairs(self.available_staff) do
2619 for _, profile in ipairs(group) do
2620 profile.world = self
2621 end
2622 end
2623 end
2624 if old < 66 then
2625 -- Unreserve objects which are not actually reserved for real in the staff room.
2626 -- This is a special case where reserved_for could be set just as a staff member was leaving
2627 for _, room in pairs(self.rooms) do
2628 if room.room_info.id == "staff_room" then
2629 -- Find all objects in the room
2630 local fx, fy = room:getEntranceXY(true)
2631 for obj, _ in pairs(self:findAllObjectsNear(fx, fy)) do
2632 if obj.reserved_for then
2633 local found = false
2634 for _, action in ipairs(obj.reserved_for.action_queue) do
2635 if action.name == "use_object" then
2636 if action.object == obj then
2637 found = true
2638 break
2639 end
2640 end
2641 end
2642 if not found then
2643 self:gameLog("Unreserved an object: " .. obj.object_type.id .. " at " .. obj.tile_x .. ":" .. obj.tile_y)
2644 obj.reserved_for = nil
2645 end
2646 end
2647 end
2648 end
2649 end
2650 end
2651
2652 if old < 103 then
2653 -- If a room has patients who no longer exist in its
2654 -- humanoids_enroute table because of #133 remove them:
2655 for _, room in pairs(self.rooms) do
2656 for patient, _ in pairs(room.humanoids_enroute) do
2657 if patient.tile_x == nil then
2658 room.humanoids_enroute[patient] = nil
2659 end
2660 end
2661 end
2662 end
2663 if old < 124 then
2664 self.game_date = Date(self.year, self.month, self.day, self.hour)
2665 -- self.next_vip_month is number of months since the game start
2666 self.next_vip_date = Date(1, self.next_vip_month, self.next_vip_day)
2667 end
2668
2669 -- Now let things inside the world react.
2670 for _, cat in pairs({self.hospitals, self.entities, self.rooms}) do
2671 for _, obj in pairs(cat) do
2672 obj:afterLoad(old, new)
2673 end
2674 end
2675
2676 if old >= 87 then
2677 self:playLoadedEntitySounds()
2678 end
2679
2680 if old < 88 then
2681 --Populate the entity map
2682 self.entity_map = EntityMap(self.map)
2683 for _, e in ipairs(self.entities) do
2684 local x, y = e.tile_x, e.tile_y
2685 if x and y then
2686 self.entity_map:addEntity(x,y,e)
2687 end
2688 end
2689 end
2690 if old < 108 then
2691 self.room_build_callbacks = nil
2692 end
2693 if old < 113 then -- Make cleanable littered tiles buildable.
2694 for x = 1, self.map.width do
2695 for y = 1, self.map.height do
2696 local litter = self:getObject(x, y, "litter")
2697 if litter and litter:isCleanable() then self.map:setCellFlags(x, y, {buildable=true}) end
2698 end
2699 end
2700 end
2701 if old < 120 then
2702 -- Issue #1105 updates to fix any broken saves with travel<dir> flags for side objects
2703 self:resetSideObjects()
2704 end
2705
2706 if old < 132 then
2707 self.app = self.ui.app
2708 end
2709 if old < 153 then
2710 -- Set the new variable next_emergency_date
2711 -- Also set the new variable next_emergency
2712 -- In previous code month == 0 meant emergencies were over
2713 if self.next_emergency_month ~= 0 then
2714 self.next_emergency_date = Date(1, self.next_emergency_month, self.next_emergency_day)
2715 local control = self.map.level_config.emergency_control
2716 self.next_emergency = control[self.next_emergency_no]
2717 -- Complementary afterLoad to see if emergencies got stuck in the level.
2718 -- There's no guarantee we can unstick the level, however.
2719 local next_emer_date = Date(1, self.next_emergency_month, self.next_emergency_day)
2720 --[[ UIWatch's emergency timer is 52 days but this is local.
2721 The emergency fax also is held for 16 days.
2722 Add one extra day to this for compensation = 69. (Unavoidable magic number)]]--
2723 if self.game_date > next_emer_date:plusDays(69) then
2724 -- The date the emergency should've finished by has passed.
2725 -- Next check if the emergency could still be happening.
2726 local watch = self.ui:getWindow(UIWatch)
2727 if not watch or watch.count_type ~= "emergency" then
2728 -- The emergency is likely stuck
2729 self:nextEmergency()
2730 end
2731 end
2732 end
2733 end
2734
2735 if old < 165 and new >= 165 then -- Add 'KnockDoorAction.humanoid' field.
2736 for _, entity in ipairs(self.entities) do
2737 if entity.action_queue and class.is(entity, Humanoid) then
2738 for _, action in ipairs(entity.action_queue) do
2739 if class.is(action, KnockDoorAction) then action.humanoid = entity end
2740 end
2741 end
2742 end
2743 end
2744
2745 if old < 167 then
2746 self.object_counts = nil -- Moved to Hospital.tile_object_counts
2747 end
2748 if old < 171 then
2749 self.wall_types = nil
2750 self.wall_id_by_block_id = nil
2751 self.wall_set_by_block_id = nil
2752 self.wall_dir_by_block_id = nil
2753 end
2754 if old < 174 then
2755 -- Originally 172, bumping afterLoad to correct a typo
2756 self.wall_types = self.app.walls
2757 self:initWallTypes()
2758 end
2759 if old < 185 then
2760 -- Fix any missing initial in staff names
2761 self:updateInitialsCache()
2762 for _, staff_category in pairs(self.available_staff) do
2763 for _, staff in pairs(staff_category) do
2764 if not staff.initial then
2765 self:localiseInitial(staff)
2766 end
2767 end
2768 end
2769 for _, staff in ipairs(self:getLocalPlayerHospital().staff) do
2770 if not staff.profile.initial then
2771 self:localiseInitial(staff.profile)
2772 end
2773 end
2774 end
2775 if old < 188 then
2776 self.level_criteria = nil
2777 self.goals = nil
2778 self:determineWinningConditions()
2779 end
2780 if old < 189 then
2781 -- Move existing and future earthquakes to the Earthquake class
2782 self.earthquake = Earthquake(self, true)
2783 end
2784 if old < 208 then -- Adjust game speed and tick rates
2785 local old_tick_rates
2786 if old < 183 then
2787 -- Save is using tick rates before 0.68.0 (PR2494)
2788 old_tick_rates = {
2789 ["Pause"] = {0, 1},
2790 ["Slowest"] = {1, 9},
2791 ["Slower"] = {1, 5},
2792 ["Normal"] = {1, 3},
2793 ["Max speed"] = {1, 1},
2794 ["And then some more"] = {3, 1},
2795 ["Speed Up"] = {8, 1},
2796 }
2797 else
2798 -- Save is using tick rates introduced during development post 0.68.0 (PR2688)
2799 old_tick_rates = {
2800 ["Pause"] = {0, 1},
2801 ["Slowest"] = {1, 28},
2802 ["Slower"] = {1, 6},
2803 ["Normal"] = {2, 3},
2804 ["Max speed"] = {1, 1},
2805 ["And then some more"] = {2, 1},
2806 ["Speed Up"] = {4, 1},
2807 }
2808 end
2809 local found_speed = false
2810 for name, rate in pairs(old_tick_rates) do
2811 if rate[1] == self.hours_per_tick and rate[2] == self.tick_rate then
2812 found_speed = true
2813 -- Do not call setSpeed as the values below are mapped to old tick rates.
2814 -- Instead, update manually.
2815 self.hours_per_tick = tick_rates[name][1]
2816 self.tick_rate = tick_rates[name][2]
2817 -- There is also no need to run it afterward either
2818 break
2819 end
2820 end
2821 -- No conversion available; reset instead
2822 if not found_speed then
2823 self.hours_per_tick = tick_rates["Pause"][1]
2824 self.tick_rate = tick_rates["Pause"][2]
2825 self:setSpeed("Normal")
2826 end
2827 end
2828 if old < 214 then
2829 self.animation_manager = nil -- Use TheApp.animation_manager instead.
2830 end
2831 if old < 239 then
2832 for _, entity in ipairs(self.entities) do
2833 if class.is(entity, Humanoid) then
2834 entity:setIfHoverMoodsVisible()
2835 end
2836 end
2837 end
2838 if old < 245 then
2839 self.system_pause = nil
2840 end
2841
2842 -- Fix the initial of staff names
2843 self:updateInitialsCache()
2844 for _, staff_category in pairs(self.available_staff) do
2845 for _, staff in pairs(staff_category) do
2846 self:localiseInitial(staff)
2847 end
2848 end
2849 for _, staff in ipairs(self:getLocalPlayerHospital().staff) do
2850 self:localiseInitial(staff.profile)
2851 end
2852
2853 -- Fix if game was saved with Speed Up
2854 self:previousSpeed()
2855
2856 self.earthquake:afterLoad(old, new)
2857
2858 -- Savegame version housekeeping
2859 if not self.original_savegame_version then
2860 self.original_savegame_version = old
2861 end
2862 -- If the original save game version is considerably lower than the current, ask
2863 -- the player if they want to restart the level.
2864 if TheApp:compareVersions(new, old, "release") > 2 then
2865 TheApp:restart(_S.confirmation.very_old_save)
2866 end
2867 self.savegame_version = new
2868 self.release_version = TheApp:getReleaseString(new)
2869 end
2870
2871 function World:playLoadedEntitySounds()
2872 for _, entity in pairs(self.entities) do
2873 entity:playAfterLoadSound()
2874 end
2875 end
2876
2877 --[[ There is a problem with room editing in that it resets all the partial passable flags
2878 (travelNorth, travelSouth etc.) in the corridor, a workaround is calling this function
2879 after the room was edited so that all edge only objects, that set partial passable flags set
2880 those flags again]]
2881 function World:resetSideObjects()
2882 for _, objects in pairs(self.objects) do
2883 for _, obj in ipairs(objects) do
2884 if obj.object_type.class == "SideObject" then
2885 obj:setTile(obj.tile_x, obj.tile_y)
2886 end
2887 end
2888 end
2889 end
2890
2891 --[[ When placing doors and objects the passable tiles need to be checked for overlapping
2892 passable tiles. This presents problems with objects like Bench where the passable tile
2893 is not for exclusive use of the Bench (another object can share that same tile)
2894 the footprint.shareable differentiates shareable passable tiles, and exclusive use
2895 passable tiles (the norm for most objects)]]
2896 --!param x (int) x map tile position
2897 --!param y (int) y map tile position
2898 --!param distance (int) searchable distance for nearby objects
2899 --!return (boolean) indicating if exclusively passable or not
2900 function World:isTileExclusivelyPassable(x, y, distance)
2901 for o in pairs(self:findAllObjectsNear(x, y, distance)) do
2902 if o and not o.picked_up and o.footprint then
2903 for _, footprint in pairs(o.footprint) do
2904 if footprint[1] + o.tile_x == x and footprint[2] + o.tile_y == y and footprint.only_passable and not footprint.shareable then
2905 return false
2906 end
2907 end
2908 else
2909 -- doors don't have a footprint but objects can't be built blocking them either
2910 for _, footprint in pairs(o:getWalkableTiles()) do
2911 -- 62 is a litter thob
2912 if not o.picked_up and o.object_type and o.object_type.thob ~= 62 and footprint[1] == x and footprint[2] == y then
2913 return false
2914 end
2915 end
2916 end
2917 end
2918 return true
2919 end
2920
2921 --! Get todays date.
2922 --!return (Date) Current game date.
2923 function World:date()
2924 return self.game_date:clone()
2925 end
2926
2927 --! Collect the settings that should be reused in the next world
2928 --!return (table) world and hospital campaign data
2929 function World:getCampaignData()
2930 local world = {
2931 room_built = self.room_built,
2932 campaign_info = self.campaign_info,
2933 debug_disable_salary_raise = self.debug_disable_salary_raise,
2934 }
2935 return { world = world, hospital = self:getLocalPlayerHospital():getCampaignData() }
2936 end
2937
2938 --! Restore the settings from the previous world
2939 --!param campaign_data (table) world and hospital campaign data
2940 function World:setCampaignData(campaign_data)
2941 for key, value in pairs(campaign_data.world) do
2942 self[key] = value
2943 end
2944 self:getLocalPlayerHospital():setCampaignData(campaign_data.hospital)
2945 end
2946
2947 --! Perform validity tests on the map in world
2948 --!return (string) The message relating to the first failed check
2949 function World:validateMap()
2950 self.map.th:updatePathfinding()
2951 local spawn_points = self:calculateSpawnTiles()
2952 -- Do any passable tiles on the edge of the map have a path of
2953 -- passable tiles to the hospital
2954 if not spawn_points[1] then
2955 return _S.map_editor_window.checks.spawn_points_and_path
2956 end
2957 end
2958
2959 --! Returns whether the level being played is part of a campaign or not
2960 function World:isCampaign()
2961 return type(self.map.level_number) == "number" or self.campaign_info
2962 end