Debian Codegraph @

CorsixTH/Lua/room.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 class "Room"
22
23 ---@type Room
24 local Room = _G["Room"]
25
26 local COST_RECOVERY = 0.40 -- Percentage cost recovery of destroyed room items
27
28 function Room:Room(x, y, w, h, id, room_info, world, hospital, door, door2)
29 self.id = id
30 self.world = world
31 self.hospital = hospital
32
33 -- Serving staff in single occupancy rooms (like GD, Pharmacy and etc)
34 self.staff_member = nil
35 -- Serving staff list in multi-occupancy rooms (like Operating Theatre)
36 -- Only set this for multi-occupancy, otherwise single occupancy rooms break
37 self.staff_member_set = nil -- Override with {} in derived class
38
39 self.room_info = room_info
40 self:initRoom(x, y, w, h, door, door2)
41 end
42
43 --! Initialises primary components of the room.
44 -- Additionally, if there is already a room, e.g. it is being moved,
45 -- we can just reinit it by calling this, not make a new one.
46 --!param x (coordinate) starting tile
47 --!param y (coordinate) starting tile
48 --!param w (num) width of room
49 --!param h (num) height of room
50 --!param door (object) primary door for room
51 --!param door2 (object) optional secondary door (e.g. swing doors)
52 function Room:initRoom(x, y, w, h, door, door2)
53 self.x = x
54 self.y = y
55 self.width = w
56 self.height = h
57 self.maximum_patients = 1 -- A good default for most rooms
58
59 -- setup new door and new queue
60 local new_door = door
61 local old_door = self.door
62 new_door:setupDoor(self, old_door)
63 self.door = new_door
64
65 -- If it's a swing door we have two doors
66 self.door2 = door2
67 if not self:hasQueueDialog() then
68 door:setDynamicInfo('text', {
69 self.room_info.name
70 })
71 else
72 door:setDynamicInfo('text', {
73 self.room_info.name,
74 _S.dynamic_info.object.queue_size:format(0),
75 _S.dynamic_info.object.queue_expected:format(0)
76 })
77 end
78 self.built = false
79 self.crashed = false
80
81 self.world.map.th:markRoom(x, y, w, h, self.room_info.floor_tile, self.id)
82
83 self.humanoids = {--[[a set rather than a list]]}
84 self.objects = {--[[a set rather than a list]]}
85 -- the set of humanoids walking to this room
86 self.humanoids_enroute = {--[[a set rather than a list]]}
87
88 self.world:prepareRectangleTilesForBuild(self.x, self.y, self.width, self.height)
89 end
90
91 --! Get the tile next to the door.
92 --!param inside (bool) If set, get the tile inside the room, else get the tile outside.
93 --!return x,y (tile coordinates) of the tile next to the door.
94 function Room:getEntranceXY(inside)
95 local door = self.door
96 local x, y = door.tile_x, door.tile_y
97 if (inside and self.world:getRoom(x, y) ~= self) or (not inside and self.world:getRoom(x, y) == self) then
98 if door.direction == "north" then
99 y = y - 1
100 elseif door.direction == "west" then
101 x = x - 1
102 end
103 end
104 return x, y
105 end
106
107 --! Construct an 'walk' action to the tile next to the door, just outside the room.
108 --!return Action to move to the tile just outside the room.
109 function Room:createLeaveAction()
110 local x, y = self:getEntranceXY(false)
111 return WalkAction(x, y):setIsLeaving(true):truncateOnHighPriority()
112 end
113
114 function Room:createEnterAction(humanoid_entering, callback)
115 local x, y = self:getEntranceXY(true)
116 if not callback then
117 if class.is(humanoid_entering, Patient) then
118 callback = --[[persistable:room_patient_enroute_cancel]] function()
119 humanoid_entering:setNextAction(SeekRoomAction(self.room_info.id))
120 end
121 elseif class.is(humanoid_entering, Vip) then
122 callback = --[[persistable:room_vip_enroute_cancel]] function()
123 humanoid_entering:setNextAction(IdleAction())
124 humanoid_entering.waiting = 1
125 end
126 else
127 callback = --[[persistable:room_humanoid_enroute_cancel]] function()
128 local room = humanoid_entering:getRoom()
129 -- if the room is one we should 'cycle' in, resume that
130 -- otherwise staff member will meander in room incorrectly again
131 if room and room.doStaffUseCycle and humanoid_entering.user_of ~= room.door then
132 room:commandEnteringStaff(humanoid_entering)
133 else
134 humanoid_entering:setNextAction(MeanderAction())
135 end
136 end
137 end
138 end
139 if self.is_active then
140 self.door.queue:expect(humanoid_entering, {callback = callback})
141 end
142
143 return WalkAction(x, y):setIsEntering(true)
144 end
145
146 --! Get a table of all patients using the room
147 --! A room usually only has one patient, however in the ward can have multiple
148 --! patients at once.
149 --!return patients (table) All patients actively using the room
150 function Room:getPatients()
151 local patients = {}
152 -- Are there patients using the room?
153 if self:getPatientCount() == 0 then return patients end
154 for humanoid in pairs(self.humanoids) do
155 if class.is(humanoid, Patient) then
156 patients[#patients + 1] = humanoid
157 end
158 end
159 return patients
160 end
161
162 --! Get any patient in the room.
163 --!return A patient (humanoid) if there is a patient, nil otherwise.
164 function Room:getPatient()
165 for humanoid in pairs(self.humanoids) do
166 if class.is(humanoid, Patient) then
167 return humanoid
168 end
169 end
170 end
171
172 --! Count the number of patients in the room.
173 --!return Number of patients in the room.
174 function Room:getPatientCount()
175 local count = 0
176 for humanoid in pairs(self.humanoids) do
177 if class.is(humanoid, Patient) then
178 count = count + 1
179 end
180 end
181 return count
182 end
183
184 -- function that sets a given attribute to a given value for all staff members.
185 -- Should be overridden for rooms that have more than one staff member.
186 function Room:setStaffMembersAttribute(attribute, value)
187 if self.staff_member then
188 self.staff_member[attribute] = value
189 end
190 end
191
192 function Room:dealtWithPatient(patient)
193 patient = patient or self:getPatient()
194 -- If the patient was sent home while in the room, don't
195 -- do anything apart from removing any leading idle action.
196 if not patient.hospital or patient.going_home then
197 if patient:getCurrentAction().name == "idle" then
198 patient:finishAction()
199 end
200 return
201 end
202 patient:setNextAction(self:createLeaveAction())
203 patient:addToTreatmentHistory(self.room_info)
204 if self.staff_member then
205 self:setStaffMembersAttribute("dealing_with_patient", false)
206 end
207
208 if patient.disease then
209 if not patient.diagnosed then
210 -- Patient not yet diagnosed, hence just been in a diagnosis room.
211 -- Increment diagnosis_progress, and send patient back to GP.
212
213 patient:completeDiagnosticStep(self)
214 self.hospital:receiveMoneyForTreatment(patient)
215 if patient:agreesToPay("diag_gp") then
216 patient:queueAction(SeekRoomAction("gp"))
217 else
218 patient:goHome("over_priced", "diag_gp")
219 end
220 else
221 -- Patient just been in a cure room, so either patient now cured, or needs
222 -- to move onto next cure room.
223 patient.cure_rooms_visited = patient.cure_rooms_visited + 1
224 local next_room = patient.disease.treatment_rooms[patient.cure_rooms_visited + 1]
225 if next_room then
226 -- Do not say that it is a treatment room here, since that check should already have been made.
227 patient:queueAction(SeekRoomAction(next_room))
228 else
229 -- Patient is "done" at the hospital
230 patient:treatDisease()
231 end
232 end
233 else
234 patient:queueAction(MeanderAction():setCount(2))
235 patient:queueAction(IdleAction())
236 end
237
238 end
239
240 local profile_attributes = {
241 Psychiatrist = "is_psychiatrist",
242 Surgeon = "is_surgeon",
243 Researcher = "is_researcher",
244 }
245
246 -- Given any type of staff criteria (required/maximum), subtract the staff in the room and return the result
247 function Room:getMissingStaff(criteria)
248 local result = {}
249 for attribute, count in pairs(criteria) do
250 for humanoid in pairs(self.humanoids) do
251 -- check state of humanoid is appropriate for room
252 -- check they are staff and meet requirements for the room
253 -- ensure not leaving (going to staff room) or fired
254 -- check if answering a call to another room
255 if class.is(humanoid, Staff) and humanoid:fulfillsCriterion(attribute) and
256 not humanoid:isLeaving() and not humanoid.fired and
257 not (humanoid.on_call and humanoid.on_call.object ~= self) and
258 not humanoid.going_to_staffroom then
259 count = count - 1
260 end
261 end
262 if count <= 0 then
263 count = nil
264 end
265 result[attribute] = count
266 end
267 return result
268 end
269
270 function Room:testStaffCriteria(criteria, extra_humanoid)
271 -- criteria should be required_staff or maximum_staff table.
272 -- if extra_humanoid is nil, then returns true if the humanoids in the room
273 -- meet the given criteria, and false otherwise.
274 -- if extra_humanoid is not nil, then returns true if the given humanoid
275 -- would assist in satisfying the given criteria, and false if they would not.
276 local missing = self:getMissingStaff(criteria)
277
278 if extra_humanoid then
279 local class = extra_humanoid.humanoid_class
280 if class == "Surgeon" then
281 class = "Doctor"
282 end
283 if missing[class] then
284 return true
285 end
286 if class == "Doctor" then
287 -- check for special proficiencies
288 for attribute, profile_attribute in pairs(profile_attributes) do
289 if extra_humanoid.profile and extra_humanoid.profile[profile_attribute] == 1.0 and missing[attribute] then
290 return true
291 end
292 end
293 end
294 return false
295 else
296 return next(missing) == nil
297 end
298 end
299
300 local no_staff = {} -- Constant denoting 'no staff at all' in a room.
301
302 --! Get the type and number of maximum staff for the room.
303 --!return (table) Type and number of maximum staff.
304 function Room:getMaximumStaffCriteria()
305 -- Some rooms have dynamic criteria (i.e. dependent upon the number of items
306 -- in the room), so this method is provided for such rooms to override it.
307 return self.room_info.maximum_staff or self.room_info.required_staff or no_staff
308 end
309
310 --! Get the type and number of required staff for the room.
311 --!return (table) Type and number of required staff.
312 function Room:getRequiredStaffCriteria()
313 return self.room_info.required_staff or no_staff
314 end
315
316 function Room:onHumanoidEnter(humanoid)
317 assert(not self.humanoids[humanoid], "Humanoid entering a room that they are already in")
318
319 humanoid.in_room = self
320 humanoid.last_room = self -- Remember where the staff was for them to come back after staffroom rest
321 -- Do not set humanoids[humanoid] here, because it affect staffFitsInRoom test
322
323 -- If this humanoid for some strange reason happens to enter a non-active room,
324 -- just leave.
325 if not self.is_active then
326 print('Warning: humanoid entering non-active room')
327 self.humanoids[humanoid] = true
328 if class.is(humanoid, Patient) then
329 self:makeHumanoidLeave(humanoid)
330 humanoid:queueAction(SeekRoomAction(self.room_info.id))
331 else
332 humanoid:setNextAction(self:createLeaveAction())
333 humanoid:queueAction(MeanderAction())
334 end
335 return
336 end
337 if class.is(humanoid, Handyman) then
338 -- Handymen can always enter a room (to repair stuff, water plants, etc.)
339 self.humanoids[humanoid] = true
340 -- Check for machines which need repair or plants which need watering if
341 -- the handyman didn't arrive as a part of a job
342 if humanoid.on_call then
343 assert(humanoid.on_call.object:getRoom() == self, "Handyman arrived is on call but not arriving to the designated room")
344 local machine = self:getRoomMachine()
345 if machine then
346 local handyman = machine.repairing
347 if humanoid == handyman then
348 -- The handyman arrived to fix the machine. Should lock the room to keep patients out.
349 self:lockRoomOnRepair()
350 end
351 end
352 else
353 -- If the handyman was not assigned for the job (e.g. drop by manual pickup), do answer a call
354 humanoid:setNextAction(AnswerCallAction())
355 end
356 self:tryAdvanceQueue()
357 return
358 end
359 local researcher_desks = {
360 (_A.warnings.researcher_needs_desk_1),
361 (_A.warnings.researcher_needs_desk_2),
362 (_A.warnings.researcher_needs_desk_3),
363 }
364 local nurse_desks = {
365 (_A.warnings.nurse_needs_desk_1),
366 (_A.warnings.nurse_needs_desk_2),
367 }
368 if class.is(humanoid, Staff) then
369 -- If the room is already full of staff, or the staff member isn't relevant
370 -- to the room, then make them leave. Otherwise, take control of them.
371 local staff_entered = humanoid
372 if not self:staffFitsInRoom(staff_entered) then
373 if self:getStaffMember() and self:staffMeetsRoomRequirements(staff_entered) then
374 local staff_in_room = self:getStaffMember()
375 self.humanoids[staff_entered] = true
376 if staff_in_room.profile.is_researcher and self.room_info.id == "research" then
377 self.hospital:giveAdvice(researcher_desks)
378 end
379 if class.is(staff_in_room, Nurse) and self.room_info.id == "ward" then
380 self.hospital:giveAdvice(nurse_desks)
381 end
382 if not staff_in_room.dealing_with_patient or staff_in_room:isMeandering() then
383 -- Previous staff in the room not currently occupied by serving patient in room.
384 -- Send out the previous staff and appoint new one.
385 staff_in_room:setNextAction(self:createLeaveAction())
386 staff_in_room:queueAction(MeanderAction())
387 self.staff_member = staff_entered
388 staff_entered:setCallCompleted()
389 self:commandEnteringStaff(staff_entered)
390 else
391 -- Previous staff in the room currently occupied by serving patient in room.
392 -- Send out the entered staff. It's not needed here.
393 staff_entered:setNextAction(self:createLeaveAction())
394 staff_entered:queueAction(MeanderAction())
395 end
396 else
397 -- Inappropriate staff for this room
398 self.humanoids[staff_entered] = true
399 staff_entered:setNextAction(self:createLeaveAction())
400 staff_entered:queueAction(MeanderAction())
401 staff_entered:adviseWrongPersonForThisRoom()
402 end
403 else
404 self.humanoids[staff_entered] = true
405 staff_entered:setCallCompleted()
406 self:commandEnteringStaff(staff_entered)
407 end
408 self:tryAdvanceQueue()
409 return
410 end
411 self.humanoids[humanoid] = true
412 self:tryAdvanceQueue()
413 if class.is(humanoid, Patient) then
414 -- An infect patient's disease may have changed so they might have
415 -- been sent to an incorrect diagnosis room, they should leave and go
416 -- back to the gp for redirection
417 local patient_entered = humanoid
418 if patient_entered.infected and not patient_entered.diagnosed and
419 not self:isDiagnosisRoomForPatient(patient_entered) then
420 patient_entered:queueAction(self:createLeaveAction())
421 patient_entered.needs_redirecting = true
422 patient_entered:queueAction(SeekRoomAction("gp"))
423 return
424 end
425 -- Check if the staff requirements are still fulfilled (the staff might have left / been picked up meanwhile)
426 if self:testStaffCriteria(self:getRequiredStaffCriteria()) then
427 if self.staff_member then
428 self:setStaffMembersAttribute("dealing_with_patient", true)
429 end
430 self:commandEnteringPatient(patient_entered)
431 else
432 patient_entered:setNextAction(self:createLeaveAction())
433 patient_entered:queueAction(self:createEnterAction(patient_entered))
434 end
435 end
436 end
437
438 --! Get the current staff member.
439 -- In multi-occupancy rooms this returns the staff member with the minimum service quality
440 --!return (staff) The current staff member.
441 function Room:getStaffMember()
442 if not self.staff_member_set then return self.staff_member end
443
444 local staff
445 for staff_member, _ in pairs(self.staff_member_set) do
446 if not staff_member.fired and not staff_member:hasLeavingAction() then
447 if not staff or staff:getServiceQuality() > staff_member:getServiceQuality() then
448 staff = staff_member
449 end
450 end
451 end
452 return staff
453 end
454
455 --! Set the current staff member.
456 --!param staff (staff) Staff member to denote as current staff.
457 function Room:setStaffMember(staff)
458 self.staff_member = staff
459 end
460
461 --! Does the given staff member fit in the room?
462 -- Returns false if the room is already full of staff or if the given member of staff cannot help out.
463 -- Otherwise returns true.
464 --!return (bool) True if the staff member can work in the room, else False.
465 function Room:staffFitsInRoom(staff)
466 local criteria = self:getMaximumStaffCriteria()
467 if self:testStaffCriteria(criteria) or not self:testStaffCriteria(criteria, staff) then
468 return false
469 end
470 return true
471 end
472
473 --! Returns true if the humanoid meets (one of) the required staff criteria of the room
474 function Room:staffMeetsRoomRequirements(humanoid)
475 local criteria = self:getRequiredStaffCriteria()
476 for attribute, _ in pairs(criteria) do
477 if humanoid:fulfillsCriterion(attribute) then
478 return true
479 end
480 end
481 return false
482 end
483
484 --! When a valid member of staff enters the room this function is called.
485 -- Can be extended in derived classes.
486 --!param staff (object) The staff in question
487 --!param already_initialized (bool) If true, this means that the staff has already got order
488 -- what to do.
489 function Room:commandEnteringStaff(staff, already_initialized)
490 if not already_initialized then
491 self.staff_member = staff
492 staff:setNextAction(MeanderAction())
493 end
494 self:tryToFindNearbyPatients()
495 staff:setDynamicInfoText("")
496 -- This variable is used to avoid multiple calls for staff (sound played only)
497 self.sound_played = nil
498 if self:testStaffCriteria(self:getRequiredStaffCriteria()) then
499 self.world.dispatcher:dropFromQueue(self)
500 end
501 end
502
503 --! Activates and deactivates the staff waiting for patient mood icon
504 -- and dynamic info text
505 --!param activate (bool) - true to activate, false or nil to deactivate
506 function Room:_staffWaitToggle(activate)
507 if not self.staff_member and not self.staff_member_set then
508 return -- No staff in room
509 end
510
511 local state = "deactivate"
512 local dynamic_text = ""
513
514 if activate then
515 dynamic_text = _S.dynamic_info.staff.actions.waiting_for_patient
516 state = "activate"
517 end
518
519 if not self.staff_member_set and self.staff_member then
520 -- single occupancy rooms (like GD, Pharmacy and etc)
521 self.staff_member:setMood("staff_wait", state)
522 self.staff_member:setDynamicInfoText(dynamic_text)
523 else
524 -- multi-occupancy rooms (like Operating Theatre)
525 for staff_member in pairs(self.staff_member_set) do
526 staff_member:setMood("staff_wait", state)
527 staff_member:setDynamicInfoText(dynamic_text)
528 end
529 end
530 end
531
532 --! Check the target room for a staff wait toggle is not staff room/training/toilets,
533 --! and the front humanoid is a patient.
534 function Room:_checkWaitToggleValidTarget()
535 return self:hasQueueDialog() and self.room_info.id ~= "toilets" and
536 class.is(self.door.queue:front(), Patient)
537 end
538
539 --! Handle the patient coming into the room
540 --! To be extended in derived classes.
541 --!param humanoid The patient entering
542 function Room:commandEnteringPatient(humanoid)
543 self.door.queue.visitor_count = self.door.queue.visitor_count + 1
544 humanoid:updateDynamicInfo("")
545
546 self:_staffWaitToggle(false) -- Staff no longer waiting
547 end
548
549 function Room:tryAdvanceQueue()
550 if self.door.queue and self.door.queue:size() > 0 and not self.door.user and not self.door.reserved_for then
551 local front = self.door.queue:front()
552 -- These two conditions differ by the waiting symbol
553
554 if self:canHumanoidEnter(front) then
555 self.door.queue:pop()
556 self.door:updateDynamicInfo()
557 if self:_checkWaitToggleValidTarget() then
558 self:_staffWaitToggle(true) -- Staff are now waiting
559 end
560 elseif self.humanoids[front] then
561 self.door.queue:pop()
562 self.door:updateDynamicInfo()
563 end
564 end
565 end
566
567 --! Handles the departure of a humanoid from the room
568 --!param humanoid The subject entity
569 function Room:onHumanoidLeave(humanoid)
570 if self.staff_member == humanoid then
571 self.staff_member = nil
572 end
573 humanoid.in_room = nil
574 if not self.humanoids[humanoid] then
575 print("Warning: Humanoid leaving a room that they are not in")
576 return
577 end
578 self.humanoids[humanoid] = nil
579 local staff_leaving = false -- used only for staff leaving immediately after a patient
580
581 if class.is(humanoid, Patient) then
582 -- Some staff member in the room might be waiting to get to the staffroom.
583 for room_humanoid in pairs(self.humanoids) do
584 -- A patient leaving allows doctors/nurses inside to go to staffroom, if needed
585 -- In a rare case a handyman that just decided he wants to go to the staffroom
586 -- could be in the room at the same time as a patient leaves.
587 if class.is(room_humanoid, Staff) and not class.is(room_humanoid, Handyman) then
588 if room_humanoid.staffroom_needed then
589 room_humanoid.staffroom_needed = nil
590 room_humanoid:goToStaffRoom()
591 staff_leaving = true
592 end
593 end
594 end
595 -- There might be other similar rooms with patients queueing
596 if self.door.queue and self.door.queue:reportedSize() == 0 and self.is_active then
597 self:tryToFindNearbyPatients()
598 end
599 end
600 if not staff_leaving then
601 self:tryAdvanceQueue()
602 else
603 -- Staff is leaving. If there is still a need for this room (people are in the queue) then call
604 -- someone new.
605 if self.active and self.door.queue:patientSize() > 0 then
606 -- This call might not be effective, if the doctor last action is
607 -- walking/must_happen but is_leaving not set (psych likes to walk around in the room)
608 -- hence testStaffCriteria still pass.
609 -- This is guarded by onHumanoidLeave(Staff)
610 self.world.dispatcher:callForStaff(self)
611 end
612 end
613
614 if class.is(humanoid, Staff) then
615 -- Make patients leave the room (except wards) if there are no longer enough staff
616 if not self:testStaffCriteria(self:getRequiredStaffCriteria()) or self:getStaffMember() == nil then
617 local call_for_new_staff = self.door.queue:patientSize() > 0
618 for room_humanoid in pairs(self.humanoids) do
619 if class.is(room_humanoid, Patient) and self:shouldHavePatientReenter(room_humanoid) then
620 call_for_new_staff = true
621 if self.room_info.id ~= "ward" then
622 self:makeHumanoidLeave(room_humanoid)
623 room_humanoid:queueAction(self:createEnterAction(room_humanoid))
624 end
625 end
626 end
627 -- Call for staff if needed
628 if self.is_active and call_for_new_staff then
629 self.world.dispatcher:callForStaff(self)
630 end
631 end
632 -- Remove any unwanted moods the staff member might have
633 humanoid:setMood("staff_wait", "deactivate")
634 end
635
636 if class.is(humanoid, Handyman) then
637 local machine = self:getRoomMachine()
638 if machine then
639 local handyman = machine.repairing
640 if humanoid == handyman and not self.manual_repair then
641 -- The handyman arrived to fix the machine was grabbed from the room before repair finished.
642 self:unlockRoomOnRepair()
643 self:tryAdvanceQueue()
644 end
645 end
646 end
647
648 -- The player might be waiting to edit this room
649 if not self.is_active then
650 local people_in_room = 0
651 for _ in pairs(self.humanoids) do
652 people_in_room = people_in_room + 1
653 end
654 if people_in_room == 0 then
655 self:enterEditMode()
656 end
657 end
658 end
659
660 function Room:enterEditMode()
661 local ui = self.world.ui
662
663 -- If we have the window for this room machine open, close it
664 local window = ui:getWindow(UIMachine)
665 if window and window.machine and window.machine:getRoom() == self then
666 window:close()
667 end
668
669 ui:addWindow(UIEditRoom(ui, self))
670 ui:setCursor(ui.default_cursor)
671 end
672
673 function Room:shouldHavePatientReenter(patient)
674 return not patient:hasLeavingAction()
675 end
676
677 local tile_factor = 10 -- how many tiles further are we willing to walk for 1 person fewer in the queue
678 local readiness_bonus = 50 -- how many tiles further are we willing to walk if the room has all the required staff
679
680 --! Score function to decide how desirable a room is for a patient.
681 --!return (int) The score, lower is better.
682 function Room:getUsageScore()
683 local queue = self.door.queue
684 local score = queue:patientSize() + self:getPatientCount() - self.maximum_patients
685 score = score * tile_factor
686 if self:testStaffCriteria(self:getRequiredStaffCriteria()) then
687 score = score - readiness_bonus
688 end
689 -- Add constant penalty if queue is full
690 if queue:isFull() then
691 score = score + 1000
692 end
693 return score
694 end
695
696 function Room:canHumanoidEnter(humanoid)
697 -- If the room is not active nobody can enter
698 if not self.is_active then
699 return false
700 end
701 -- By default, staff can always enter
702 if class.is(humanoid, Staff) then
703 return true
704 end
705 -- By default, patients can only enter if there are sufficient staff and not
706 -- too many patients.
707 if class.is(humanoid, Patient) and not self.needs_repair then
708 return self:testStaffCriteria(self:getRequiredStaffCriteria()) and self:getPatientCount() < self.maximum_patients
709 end
710 -- By default, other classes of humanoids cannot enter
711 return false
712 end
713
714 -- Function stub for rooms to implement. Called when the final confirm
715 -- button has been pressed when building/editing a room.
716 function Room:roomFinished()
717 -- True once the room has been finished after initial construction, and then
718 -- as long as the user doesn't edit it and go back beyond the first phase (place objects)
719 self.built = true
720 -- Only true when not editing the room at all.
721 self.is_active = true
722 -- Some rooms should not have the door cursor for the queue dialog
723 if not self:hasQueueDialog() then
724 self.door.hover_cursor = TheApp.gfx:loadMainCursor("default")
725 end
726 -- Show information about the room if not already shown.
727 -- Also only show them if the player is playing the original campaign.
728 if tonumber(self.world.map.level_number) and self.world.room_information_dialogs then
729 if not self.world.room_built[self.room_info.id] then
730 self.world.ui:addWindow(UIInformation(self.world.ui, _S.room_descriptions[self.room_info.id]))
731 self.world.room_built[self.room_info.id] = true
732 end
733 end
734 self:tryToFindNearbyPatients()
735 -- It may also happen that there are patients queueing for this room already (e.g after editing)
736 if self.door.queue:patientSize() > 0 then
737 self.world.dispatcher:callForStaff(self)
738 end
739 self:tryAdvanceQueue()
740 self:calculateHappinessFactor()
741 end
742
743 --! Private function to check for any patients outside the door queueing,
744 --! or about to come in
745 --!return (boolean) true if any patient wants to come in
746 function Room:_arePatientsWantingToEnter()
747 local door = self.door
748 return (door.queue and door.queue:patientSize() > 0) or
749 (door.reserved_for and class.is(door.reserved_for, Patient)) or
750 (door.user and class.is(door.user, Patient) and door.user:getCurrentAction().is_entering)
751 end
752
753 --! Check if a room is actively required by patients
754 --! A room is deemed in demand should any patient be in a state of using, or
755 --! wanting to use the room.
756 --!return (boolean) true if the room is currently needed
757 function Room:isRoomInDemand()
758 if self:getPatientCount() > 0 then
759 -- Maybe a patient is using the room right now?
760 for _, patient in ipairs(self:getPatients()) do
761 if not patient:isLeaving() then return true end
762 end
763 end
764 return self:_arePatientsWantingToEnter()
765 end
766
767 --! Try to move a patient from the old room to the new room.
768 --!param old_room (Room) Room that currently has the patient in the queue.
769 --!param new_room (Room) Room that wants the patient in the queue.
770 --!param patient (Humanoid) Patient to move.
771 --!return (boolean) Whether we are done with the old room (no more patients will come from it).
772 local function tryMovePatient(old_room, new_room, patient)
773 local world = new_room.world
774
775 local px, py = patient.tile_x, patient.tile_y
776 -- Don't reroute the patient if he just decided to go to the toilet or is going home
777 if patient.going_to_toilet ~= "no" or patient.going_home or patient.going_to_die then
778 return false
779 end
780
781 local new_x, new_y = new_room:getEntranceXY(true)
782 local old_x, old_y = old_room:getEntranceXY(true)
783 local new_distance = world:getPathDistance(px, py, new_x, new_y)
784 if not new_distance then return true end -- Patient cannot reach us, quit trying
785
786 local new_score = new_room:getUsageScore() + new_distance
787 local old_score
788 local old_distance = world:getPathDistance(px, py, old_x, old_y)
789 if old_distance then
790 old_score = old_room:getUsageScore() + old_distance
791 else
792 old_score = new_score + 1 -- Make condition below fail.
793 end
794 if new_score >= old_score then return true end
795
796 -- Update the queues
797 local old_queue = old_room.door.queue
798 old_queue:removeValue(patient)
799
800 -- Rewrite the action queue
801 for i, action in ipairs(patient.action_queue) do
802 if i ~= 1 then
803 action.todo_interrupt = true
804 end
805 -- The patient will most likely have a queue action for the other
806 -- room that must be cancelled. To prevent the after_use callback
807 -- of the drinks machine to enqueue the patient in the other queue
808 -- again, is_in_queue is set to false so the callback won't run
809 if action.name == 'queue' then
810 action.is_in_queue = false
811 elseif action.name == "walk" and action.x == old_x and action.y == old_y then
812 patient:queueAction(new_room:createEnterAction(patient), i)
813 break
814 end
815 end
816
817 -- next_room_to_visit is guarded in checks in WalkAction from being incorrectly
818 -- interrupted, there is possibility walk above isn't found and there is no new
819 -- room to go to, but this remains mostly safe, see #1561
820 patient.next_room_to_visit = new_room
821 new_room.door:updateDynamicInfo()
822 old_room.door:updateDynamicInfo()
823
824 local interrupted = patient:getCurrentAction()
825 local on_interrupt = interrupted.on_interrupt
826 if on_interrupt then
827 interrupted.on_interrupt = nil
828 on_interrupt(interrupted, patient, false)
829 end
830 return false
831 end
832
833 --! Try to find new patients for this room by 'stealing' them from other rooms nearby.
834 function Room:tryToFindNearbyPatients()
835 if not self.door.queue then
836 return
837 end
838
839 for _, old_room in pairs(self.world.rooms) do
840 if old_room.hospital == self.hospital and old_room ~= self and
841 old_room.room_info == self.room_info and old_room.door.queue and
842 old_room.door.queue:reportedSize() >= 2 then
843 local old_queue = old_room.door.queue
844 local pat_number = old_queue:reportedSize()
845 while pat_number > 1 do
846 local patient = old_queue:reportedHumanoid(pat_number)
847 if tryMovePatient(old_room, self, patient) then break end
848 -- tryMovePatient may have just removed patient 'pat_number', but it does
849 -- not change the queue in front of it. 'pat_number - 1' thus still exists.
850 pat_number = pat_number - 1
851 end
852 end
853 end
854 end
855
856 --! Explode the room.
857 function Room:crashRoom()
858 self.door:closeDoor()
859 if self.door2 then
860 self.door2.hover_cursor = nil
861 end
862
863 -- A patient might be about to use the door (staff are dealt with elsewhere):
864 if self.door.reserved_for then
865 local person = self.door.reserved_for
866 if not person:isLeaving() then
867 if class.is(person, Patient) then
868 --Delay so that room is destroyed before the SeekRoom search.
869 person:setNextAction(IdleAction():setCount(1))
870 person:queueAction(SeekRoomAction(self.room_info.id))
871 end
872 end
873 person:finishAction()
874 self.door.reserved_for = nil
875 end
876
877 local remove_humanoid = function(humanoid)
878 humanoid:queueAction(IdleAction(), 1)
879 humanoid.user_of = nil
880 -- Make sure any emergency list is not messed up.
881 -- Note that these humanoids might just have been kicked. (No hospital set)
882 if humanoid.is_emergency then
883 table.remove(self.world:getLocalPlayerHospital().emergency_patients, humanoid.is_emergency)
884 end
885 humanoid:die()
886 humanoid:despawn()
887 self.world:destroyEntity(humanoid)
888 end
889
890 -- Remove all humanoids in the room
891 for humanoid, _ in pairs(self.humanoids) do
892 remove_humanoid(humanoid)
893 end
894 self.humanoids = {}
895 -- There might also be someone using the door, even if that person is just about to exit
896 -- he/she is killed too.
897 local walker = self.door.user
898 if walker then
899 self.door:removeUser(walker)
900 remove_humanoid(walker)
901 end
902
903 -- Remove all objects in the room
904 local fx, fy = self:getEntranceXY(true)
905 for object, _ in pairs(self.world:findAllObjectsNear(fx, fy)) do
906 -- Machines (i.e. objects with strength) are already done.
907 if object.object_type.class == "Plant" then
908 local index = self.hospital:getIndexOfTask(object.tile_x, object.tile_y, "watering")
909 if index ~= -1 then
910 self.hospital:removeHandymanTask(index, "watering")
911 end
912 object.unreachable = true
913 end
914 if object.object_type.id ~= "door" and not object.strength and
915 object.object_type.class ~= "SwingDoor" then
916 object.user = nil
917 object.user_list = nil
918 object.reserved_for = nil
919 object.reserved_for_list = nil
920 self.world:destroyEntity(object)
921 end
922 end
923
924 local map = self.world.map.th
925 -- TODO: Explosion, animations: 4612, 3280
926
927 -- Make every floor tile have soot on them
928 for x = self.x, self.x + self.width - 1 do
929 for y = self.y, self.y + self.height - 1 do
930 local soot = self.world:newObject("litter", x, y)
931 soot:setLitterType("soot_floor", 0)
932 end
933 end
934 -- Make walls have soot on them too
935 local ty = self.y
936 local soot_type, soot, block
937 for x = self.x, self.x + self.width - 1 do
938 block = map:getCell(x, ty, 2)
939 soot_type = "soot_wall"
940 if self.world:getWallSetFromBlockId(block) == "window_tiles" then
941 soot_type = "soot_window"
942 end
943 soot = self.world:newObject("litter", x, ty)
944 soot:setLitterType(soot_type, 1)
945 end
946 local x = self.x
947 for y = self.y, self.y + self.height - 1 do
948 block = map:getCell(x, y, 3)
949 soot_type = "soot_wall"
950 if self.world:getWallSetFromBlockId(block) == "window_tiles" then
951 soot_type = "soot_window"
952 end
953 soot = self.world:newObject("litter", x, y)
954 soot:setLitterType(soot_type, 0)
955 end
956
957 self.hospital.num_explosions = self.hospital.num_explosions + 1
958
959 local value_change = self.hospital.research.research_progress[self.room_info].build_cost
960 self.hospital:changeValue(value_change * -1)
961 self.hospital:changeReputation("room_crash")
962 self.crashed = true
963 self:deactivate()
964 end
965
966 -- Tells a humanoid in the room to leave it. This can be overridden for special
967 -- handling, e.g. if the humanoid needs to change before leaving the room.
968 function Room:makeHumanoidLeave(patient)
969 local leave = self:createLeaveAction():setMustHappen(true)
970 patient:setNextAction(leave)
971 end
972
973 function Room:makeHumanoidDressIfNecessaryAndThenLeave(humanoid)
974 if not humanoid:isLeaving() then
975 local leave = self:createLeaveAction():setMustHappen(true)
976
977 if not string.find(humanoid.humanoid_class, "Stripped") then
978 --The humanoid is dressed
979 humanoid:setNextAction(leave)
980 return
981 end
982
983 local screen, sx, sy = self.world:findObjectNear(humanoid, "screen")
984 local use_screen = UseScreenAction(screen):setMustHappen(true):setIsLeaving(true)
985
986 --Make old saved game action queues compatible with the changes made by the #293 fix commit:
987 for actions_index, action in ipairs(humanoid.action_queue) do
988 if action.name == "use screen" or (action.name == "walk" and action.x == sx and action.y == sy) then
989 if not action.is_leaving then
990 humanoid.humanoid_actions[actions_index].is_leaving = true
991 end
992 if action.name == "walk" and action.must_happen then
993 action.must_happen = false
994 end
995 end
996 end
997
998 if humanoid:getCurrentAction().name == "use_screen" then
999 --The humanoid must be using the screen to undress because this isn't a leaving action:
1000 if not humanoid:hasDressingAndLeavingAction() then
1001 humanoid:getCurrentAction().after_use = nil
1002 humanoid:setNextAction(use_screen)
1003 end
1004 else
1005 --The humanoid undressed but not using use_screen
1006 humanoid:setNextAction(WalkAction(sx, sy):setMustHappen(true):disableTruncate():setIsLeaving(true))
1007 humanoid:queueAction(use_screen)
1008 end
1009
1010 humanoid:queueAction(leave)
1011 end
1012 end
1013
1014 --! Deactivate the room from the world.
1015 function Room:deactivate()
1016 self.is_active = false -- So that no more patients go to it.
1017 self.world:notifyRoomRemoved(self)
1018
1019 -- crashRoom might have deactivated the door already
1020 if self.door.queue then
1021 self.door.queue:rerouteAllPatients(self.room_info.id)
1022 end
1023
1024 self.hospital:removeRatholesAroundRoom(self)
1025 end
1026
1027 function Room:tryToEdit()
1028 self:deactivate()
1029 local people_in_room = 0
1030 -- Tell all humanoids that they should leave
1031 -- If someone is entering the room right now they are also counted.
1032 if self.door.user and self.door.user:getCurrentAction().is_entering then
1033 people_in_room = 1
1034 end
1035 for humanoid, _ in pairs(self.humanoids) do
1036 if not humanoid:isLeaving() then
1037 if class.is(humanoid, Patient) then
1038 self:makeHumanoidLeave(humanoid)
1039 humanoid:queueAction(SeekRoomAction(self.room_info.id))
1040 else
1041 humanoid:setNextAction(self:createLeaveAction())
1042 humanoid:queueAction(MeanderAction())
1043 end
1044 end
1045 people_in_room = people_in_room + 1
1046 end
1047 -- If there were no people inside we're ready to edit the room
1048 if people_in_room == 0 then
1049 self:enterEditMode()
1050 end
1051 end
1052
1053 function Room:hasQueueDialog()
1054 return not self.room_info.has_no_queue_dialog
1055 end
1056
1057 --! Stub to be extended in subclasses, if needed.
1058 function Room:afterLoad(old, new)
1059 if old < 46 then
1060 self.humanoids_enroute = {--[[a set rather than a list]]}
1061 end
1062 if old < 137 then
1063 if self.door.queue then
1064 -- reset expected count so we can recalculate it
1065 self.door.queue.expected = {}
1066 self.door.queue.expected_count = 0
1067 for enroute, callback in pairs(self.humanoids_enroute) do -- Go through all registered callbacks
1068 local clear_this_callback = true -- Presume the callback must be cleared
1069 for _, action in pairs(enroute.action_queue) do -- Go through the action queue
1070 if action.name == "walk" then -- Only look at walk actions
1071 if self == self.world:getRoom(action.x, action.y) and -- This walk action leads into the room
1072 self ~= enroute:getRoom() then -- The entity is not already in the room
1073 clear_this_callback = false -- Assume the callback is valid, don't clear
1074 end
1075 end
1076 end
1077 if not clear_this_callback then
1078 -- still expecting
1079 self.door.queue:expect(enroute, callback)
1080 end
1081 end
1082 self.door:updateDynamicInfo()
1083 end
1084 -- no longer using this so empty it
1085 self.humanoids_enroute = {}
1086 end
1087 if old < 186 then
1088 self:calculateHappinessFactor()
1089 end
1090 if old < 233 then
1091 if self.waiting_staff_member then
1092 -- Cancel delayed replace existing staff member in room
1093 self.waiting_staff_member:setNextAction(self:createLeaveAction())
1094 self.waiting_staff_member:queueAction(MeanderAction())
1095 self.waiting_staff_member.waiting_on_other_staff = nil
1096 end
1097 self.waiting_staff_member = nil
1098 self.dealt_patient_callback = nil
1099 end
1100 -- Patch the saves post 233 that labelled all rooms as having a staff_member_set
1101 if old >= 233 and old < 235 then
1102 local room_name = self.room_info.id
1103 if room_name ~= "ward" and room_name ~= "operating_theatre" and
1104 room_name ~= "research" then
1105 self.staff_member_set = nil
1106 end
1107 end
1108 end
1109
1110 --[[ Is the room one of the diagnosis rooms for the patient?
1111 -- This used for epidemics when the disease and therefore the diagnosis
1112 -- rooms of a patient may change.
1113 -- @param patient (Patient) patient to verify if treatment room ]]
1114 -- @return result (boolean) true if is suitable diagnosis room, false otherwise
1115 function Room:isDiagnosisRoomForPatient(patient)
1116 if self.room_info.id ~= "gp" then
1117 for _, room_name in ipairs(patient.disease.diagnosis_rooms) do
1118 if self.room_info.id == room_name then
1119 return true
1120 end
1121 end
1122 return false
1123 else
1124 return true
1125 end
1126 end
1127
1128 --! Get the average service quality of the staff members in the room.
1129 --!return (float) [0-1] Average staff service quality.
1130 function Room:getStaffServiceQuality()
1131 local quality = 0.5
1132
1133 if self.staff_member_set then
1134 -- For rooms with multiple staff member (like operating theatre)
1135 quality = 0
1136 local count = 0
1137 for member, _ in pairs(self.staff_member_set) do
1138 quality = quality + member:getServiceQuality()
1139 count = count + 1
1140 end
1141
1142 quality = quality / count
1143 elseif self.staff_member then
1144 -- For rooms with one staff member
1145 quality = self.staff_member:getServiceQuality()
1146 end
1147
1148 return quality
1149 end
1150
1151 local window_tile = list_to_set({116, 117, 118, 119, 120, 121, 124, 125, 126, 127})
1152 --! Count the number of windows in the room
1153 --!return (int) Number of windows
1154 function Room:countWindows()
1155 local map, count = self.world.ui.app.map.th, 0
1156 for x = self.x, self.x + self.width do
1157 for y = self.y, self.y + self.height do
1158 if window_tile[map:getCell(x, y, 2)] or window_tile[map:getCell(x, y, 3)] then
1159 count = count + 1
1160 end
1161 end
1162 end
1163 return count
1164 end
1165
1166 --! Get the removal cost
1167 --!return (int) cost of the room
1168 function Room:calculateRemovalCost()
1169 -- Charge double to clean it up
1170 local progress = self.hospital.research.research_progress
1171 local cost = math.floor(progress[self.room_info].build_cost * 2)
1172
1173 -- Recover some cost as scrap
1174 for obj, _ in pairs(self.room_info.objects_needed) do
1175 -- Get how much this item costs.
1176 local obj_cost = self.hospital:getObjectBuildCost(obj)
1177 -- recover a percentage of cost as scrap value
1178 cost = cost - math.floor(obj_cost * COST_RECOVERY)
1179 end
1180 return cost
1181 end
1182
1183 --! Calculate the effect the room has on humanoid happiness
1184 function Room:calculateHappinessFactor()
1185 -- The number of windows affects happiness
1186 local window_factor, space_factor, window_count = 0, 0, self:countWindows()
1187 if window_count > 0 then
1188 if self.room_info.id == "staff_room" then
1189 -- Staff are pleased to rest in a staff room with windows
1190 window_count = window_count * 2
1191 end
1192 -- More windows help but in smaller increments
1193 window_factor = math.round(math.log(window_count)) / 1000
1194 end
1195
1196 -- Extra space in the room affects happiness
1197 local extraspace = (self.width * self.height) / (self.room_info.minimum_size * self.room_info.minimum_size)
1198 if extraspace > 1 then
1199 -- Greater space helps but in smaller increments
1200 space_factor = math.round(math.log(extraspace)) / 1000
1201 end
1202
1203 self.happiness_factor = window_factor + space_factor
1204 end
1205
1206 --! Get this room machine, if it there
1207 --!return (object) machine object
1208 function Room:getRoomMachine()
1209 local fx, fy = self:getEntranceXY(true)
1210 for object, _ in pairs(self.world:findAllObjectsNear(fx, fy)) do
1211 if object.strength ~= nil then
1212 return object
1213 end
1214 end
1215 end
1216
1217 --! Locks the room to prevent patient from entering due to repair in room.
1218 function Room:lockRoomOnRepair()
1219 self.needs_repair = true
1220 end
1221
1222 --! Unlocks the room so repair no longer prevents patients from enter the room.
1223 function Room:unlockRoomOnRepair()
1224 self.needs_repair = false
1225 end
1226
1227 ----- BEGIN Save game compatibility -----
1228 -- These function are merely for save game compatibility.
1229 -- For 0.69.x gamesaves and below.
1230 -- And they does not participate in the current game logic.
1231 local --[[persistable:room_dealt_with_patient_callback]] function _(staff_humanoid) end
1232 ----- END Save game compatibility -----