Debian Codegraph @

CorsixTH/Lua/entities/machine.lua

raw
1 --[[ Copyright (c) 2009 Edvin "Lego3" Linge
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
23 --! An `Object` which needs occasional repair (to prevent explosion).
24 class "Machine" (Object)
25
26 ---@type Machine
27 local Machine = _G["Machine"]
28
29 function Machine:Machine(hospital, object_type, x, y, direction, etc)
30 self:Object(hospital, object_type, x, y, direction, etc)
31 self.mood_marker = 1 -- Machine reuses the patient marker.
32
33 if object_type.default_strength then
34 -- Only for the main object. The slave doesn't need any strength
35 local progress = self.hospital.research.research_progress[object_type]
36 self.strength = progress.start_strength
37 end
38
39 -- We actually don't want any dynamic info just yet
40 self:clearDynamicInfo()
41 -- Change hover cursor once the room has been finished.
42 self.waiting_for_finalize = true -- Waiting until the room is completed (reset by new-room callback).
43
44 self.total_usage = 0
45 self:setHandymanRepairPosition(direction)
46 end
47
48 --!param room (object) machine room
49 function Machine:notifyNewRoom(room)
50 if self.waiting_for_finalize and room.objects[self] then
51 self:finalize(room)
52 self.waiting_for_finalize = false
53 end
54 end
55
56 function Machine:setCrashedAnimation()
57 self:setAnimation(self.object_type.crashed_animation)
58 end
59
60 --! Calculates the number of times the machine can be used before crashing (unless repaired first)
61 --!return (int) remaining uses count
62 function Machine:getRemainingUses()
63 return self.strength - self.times_used
64 end
65
66 --! Returns true if a machine is smoking/needs repair
67 --!return (bool)
68 function Machine:isBreaking()
69 local threshold = self:getRemainingUses()
70 return threshold < 4
71 end
72
73 function Machine:isMachine()
74 return true
75 end
76
77 --! Return Tile position for smoke animation
78 --!return (map, int, int)
79 local function getSmokeTile(self)
80 local map, _, _ = self.th:getTile()
81 local x, y = self.tile_x, self.tile_y
82 local smoke_position = self.object_type.orientations[self.direction].smoke_position
83 if smoke_position then
84 x = x + smoke_position[1]
85 y = y + smoke_position[2]
86 end
87
88 return map, x, y
89 end
90
91 --! Set whether the smoke animation should be showing
92 local function setSmoke(self, isSmoking)
93 -- If turning smoke on for this machine
94 if isSmoking and self.object_type.smoke_animation then
95 -- If there is no smoke animation for this machine, make one
96 if not self.smokeInfo then
97 self.smokeInfo = TH.animation()
98 -- Note: Set the location of the smoke to that of the machine
99 -- rather than setting the machine to the parent so that the smoke
100 -- doesn't get hidden with the machine during use
101 local map, x, y = getSmokeTile(self)
102 self.smokeInfo:setTile(map, x, y, self:getSmokeDrawingLayer())
103 -- Always show the first smoke layer
104 self.smokeInfo:setLayer(10, 2)
105 -- tick to animate over all frames
106 self.ticks = true
107 end
108 local mirror = self.direction == "east" and 1 or 0
109 self.smokeInfo:setAnimation(self.world.anims, self.object_type.smoke_animation, mirror)
110 else -- Otherwise, turning smoke off
111 -- If there is currently a smoke animation, remove it
112 if self.smokeInfo then
113 self.smokeInfo:setTile(nil)
114 end
115 self.smokeInfo = nil
116 end
117 end
118
119 --! The function is called when an earthquake strike the machine.
120 --! Function defines the machine's reaction to an earthquake.
121 --! During an earthquake, this function is called one or several times.
122 --!param room (object) machine room
123 function Machine:earthquakeImpact(room)
124 self:machineUsed(room, true)
125 end
126
127 --! Call on machine use.
128 --!param room (object) machine room
129 --!param earthquake_activated (boolean) If true, machine was damaged by an active earthquake
130 --!return (bool) is room exploding after this use
131 function Machine:machineUsed(room, earthquake_activated)
132 earthquake_activated = not not earthquake_activated
133 -- Do nothing if the room has already crashed
134 if room.crashed then
135 return
136 end
137 local cheats = self.hospital.hosp_cheats
138 local is_invulnerable_machines_cheat_active = cheats:isCheatActive("invulnerable_machines")
139
140 self:incrementUsageCounts(is_invulnerable_machines_cheat_active, earthquake_activated)
141 -- Update dynamic info (machine strength & times used)
142 self:updateDynamicInfo()
143
144 -- If the cheat is active, the machine should not wear out or explode
145 local must_explode = not is_invulnerable_machines_cheat_active and self:calculateIsMachineMustExplode(room)
146 if must_explode then
147 -- Room failed to be saved, it must be explode
148 self:explodeMachine(room)
149 return true
150 else
151 self:callHandymanForRepairIfNecessary(room)
152 -- Update whether smoke gets displayed for this machine (and if so, how much)
153 self:updateSmokeDisplay(room)
154 end
155 end
156
157 --! Call after use of the machine.
158 function Machine:incrementUsageCounts(total_usage_only, is_earthquake)
159 if not is_earthquake then
160 self.total_usage = self.total_usage + 1
161 end
162
163 if not total_usage_only then
164 self.times_used = self.times_used + 1
165 end
166 end
167
168 --! Call on machine use.
169 --!param room (object) machine room
170 function Machine:callHandymanForRepairIfNecessary(room)
171 local repair_task_index = self.hospital:getIndexOfTask(self.tile_x, self.tile_y, "repairing")
172 local repair_task_does_not_exist = repair_task_index == -1
173 local remaining_use_count = self:getRemainingUses()
174 if remaining_use_count < 4 then
175 -- If the job of repairing the machine isn't queued, queue it now (higher priority)
176 if repair_task_does_not_exist then
177 local call = self.world.dispatcher:callForRepair(self, true, false)
178 self.hospital:addHandymanTask(self, "repairing", 2, self.tile_x, self.tile_y, call)
179 self.hospital:announceRepair(room)
180 else
181 -- Otherwise the task is already queued.
182 -- Increase the priority to above that of machines with at least 4 uses left
183 -- Upgrades task from low (1) priority to high (2) priority
184 if self.hospital:getHandymanTaskPriority(repair_task_index, "repairing") == 1 then
185 self.hospital:modifyHandymanTaskPriority(repair_task_index, 2, "repairing")
186 self.hospital:announceRepair(room)
187 end
188 end
189 elseif remaining_use_count < 6 and repair_task_does_not_exist then
190 -- Else if (low priority) repair is needed, make sure there is a handyman task for it.
191 local call = self.world.dispatcher:callForRepair(self)
192 self.hospital:addHandymanTask(self, "repairing", 1, self.tile_x, self.tile_y, call)
193 end
194 end
195
196 --! Call on machine use. Handles crashing the machine
197 function Machine:calculateIsMachineMustExplode(room)
198 -- Find a queued task for a handyman coming to repair this machine
199 local remaining_use_count = self:getRemainingUses()
200 local max_extinguishers_effective_count = 4
201 local num_extinguishers = 0
202 local explosion_chance
203 local must_explode = false
204 if remaining_use_count < 1 then
205 -- If a fire extinguisher in the room, room has chance not to explode
206 -- Calculate the number of extinguishers in the room.
207 for object, _ in pairs(room.objects) do
208 if object.object_type.id == "extinguisher" then
209 num_extinguishers = num_extinguishers + 1
210 end
211 if num_extinguishers == max_extinguishers_effective_count then
212 break
213 end
214 end
215 if num_extinguishers == 0 or remaining_use_count < -3 then
216 -- If not enough extinguishers in the room or machine is used 5 times over its strength, always explode.
217 must_explode = true
218 else
219 -- Explosion chance increases 20% with every use over strength, and reduced by 5% for every additional extinguisher (up to 3 extra) in the room bar the first one
220 explosion_chance = (2 / self.strength) + (remaining_use_count * -0.2) - (num_extinguishers * 0.05) + 0.05
221 explosion_chance = math.min(0.95, math.max(0.05, explosion_chance))
222 must_explode = math.random() < explosion_chance
223 end
224 end
225 return must_explode
226 end
227
228 --! Call on machine explode. Handles machine and room exploding
229 --!param room (object) machine room
230 function Machine:explodeMachine(room)
231 -- Clean up any task of handyman coming to repair the machine
232 self:removeHandymanRepairTask()
233
234 -- Blow up the room
235 room:crashRoom()
236 self:setCrashedAnimation()
237
238 -- No special cursor required when hovering over the crashed room
239 self.hover_cursor = nil
240
241 -- Clear dynamic info (tracks machine usage which is no longer required)
242 self:clearDynamicInfo()
243
244 -- Prevent the machine from smoking, it's now just a pile of rubble
245 setSmoke(self, false)
246
247 -- If we have the window for this machine open, close it
248 local window = self.world.ui:getWindow(UIMachine)
249 if window and window.machine == self then
250 window:close()
251 end
252
253 -- Clear gear icon
254 self:removeRepairingStatus()
255 end
256
257 --! Calculates whether smoke gets displayed for this machine (and if so, how much)
258 --!param room (object) machine room
259 function Machine:updateSmokeDisplay(room)
260 -- Do nothing if the room has already crashed
261 if room.crashed then
262 return
263 end
264
265 -- How many uses this machine has left until it explodes
266 local threshold = self:getRemainingUses()
267
268 -- Machines needing urgent repair show smoke
269 if threshold < 4 then
270 -- Display smoke, up to three animations per machine
271 -- i.e. < 4 one plume, < 3 two plumes or < 2 three plumes of smoke
272 setSmoke(self, true)
273 -- turn on additional layers of the animation for extra smoke plumes, depending on how damaged the machine is
274 if threshold < 3 then
275 self.smokeInfo:setLayer(11, 2)
276 end
277 if threshold < 2 then
278 self.smokeInfo:setLayer(12, 2)
279 end
280 end
281 end
282
283 --! Call on machine place.
284 --!param room (object) machine room
285 function Machine:placed(room)
286 -- Machines may have smoke, recalculate it to ensure the animation is in the correct state.
287 self:updateSmokeDisplay(room)
288 end
289
290 function Machine:getRepairTile()
291 local x = self.tile_x + self.handyman_position[1]
292 local y = self.tile_y + self.handyman_position[2]
293 return x, y
294 end
295
296 function Machine:createHandymanActions(handyman)
297 local ux, uy = self:getRepairTile()
298 local this_room = self:getRoom()
299 local handyman_room = handyman:getRoom()
300 assert(this_room, "machine should always in a room")
301
302 self.repairing = handyman
303
304 local --[[persistable:handyman_repair_after_use]] function repair_after_use()
305 handyman:setCallCompleted()
306 handyman:setDynamicInfoText("")
307 self:machineRepaired(self:getRoom())
308 end
309
310 local walk_action = WalkAction(ux, uy):setIsEntering(this_room and true or false)
311
312 local repair_action = UseObjectAction(self):setProlongedUsage(false)
313 :setAfterUse(repair_after_use)
314 repair_action.min_length = 20 -- Minimum number of frames needed for the action.
315
316 if handyman_room and handyman_room ~= this_room then
317 handyman:setNextAction(handyman_room:createLeaveAction())
318 handyman:queueAction(walk_action)
319 else
320 handyman:setNextAction(walk_action)
321 end
322
323 local meander_loop_callback = --[[persistable:handyman_meander_repair_loop_callback]] function()
324 -- Wait until the machine is not in use and not about to be used
325 local patient = self:getRoom():getPatient()
326 if not self.user and (not patient or patient:isLeaving()) then
327 -- The machine is ready to be repaired.
328 -- The following statement will finish the meander action in the handyman's
329 -- action queue.
330 handyman:finishAction()
331 end
332 -- Otherwise do nothing and let the meandering continue.
333 end
334
335 -- Before the actual repair action, insert a meander action to wait for the machine
336 -- to become free for use.
337 handyman:queueAction(MeanderAction():setLoopCallback(meander_loop_callback))
338
339 -- The last one is another walk action to the repair tile. If the handyman goes directly
340 -- to repair it will simply complete in an instant.
341 handyman:queueAction(walk_action)
342 handyman:queueAction(repair_action)
343 CallsDispatcher.queueCallCheckpointAction(handyman)
344 handyman:queueAction(AnswerCallAction())
345 handyman:setDynamicInfoText(_S.dynamic_info.staff.actions.going_to_repair
346 :format(self.object_type.name))
347 end
348
349 --! Replace this machine (make it pretend it's brand new)
350 --!param cost (int) Cost to replace the machine
351 function Machine:replaceMachine(cost)
352 -- Pay for the new machine
353 self.hospital:spendMoney(cost, _S.transactions.machine_replacement)
354
355 -- Reset usage stats
356 self.total_usage = 0
357 self.times_used = 0
358
359 -- Update strength to match the current level of research for it
360 self.strength = self.hospital.research.research_progress[self.object_type].start_strength
361
362 -- Remove any queued repair jobs
363 self:removeHandymanRepairTask()
364
365 -- Clear gear icon
366 self:removeRepairingStatus()
367 -- Clear smoke
368 setSmoke(self, false)
369 end
370
371 --! Call on machine repaired.
372 --!param room (object) machine room
373 --!param strength_reducible (bool) machine room
374 function Machine:machineRepaired(room, strength_reducible)
375 strength_reducible = strength_reducible or true
376 if strength_reducible then
377 self:reduceStrengthOnRepair()
378 end
379 room:unlockRoomOnRepair()
380 self:removeRepairingStatus()
381 setSmoke(self, false)
382 self:removeHandymanRepairTask()
383 self.times_used = 0
384 end
385
386 --! Call on machine repaired. Removes repair task for that machine.
387 function Machine:removeHandymanRepairTask()
388 -- Remove any queued repair jobs
389 local repair_task_index = self.hospital:getIndexOfTask(self.tile_x, self.tile_y, "repairing")
390 local repair_task_exist = repair_task_index ~= -1
391 if repair_task_exist then
392 self.hospital:removeHandymanTask(repair_task_index, "repairing")
393 end
394 end
395
396 --! Calculates if machine strength should be reduced as a result of repair
397 function Machine:reduceStrengthOnRepair()
398 local minimum_possible_strength = 2
399 if self.strength <= minimum_possible_strength then return end
400
401 local current_strength = self.strength
402 local used_out_rate = self.times_used / current_strength
403
404 -- calculate chance of strength reducing
405 local should_reduce_strength = math.random() < used_out_rate
406 if should_reduce_strength then
407 self.strength = current_strength - 1
408 end
409 end
410
411 --! Set the room's repair status manually. Lock room and show gear icon.
412 function Machine:setRepairingStatus()
413 local room = self:getRoom()
414 local anim = {icon = 4564} -- The only icon for machinery
415 room.manual_repair = true
416 -- put gear icon above machine
417 self:setMoodInfo(anim)
418 -- make gear icon animate
419 self.ticks = true
420 room:lockRoomOnRepair()
421 end
422
423 --! Remove the room's repair status. Unlock room and remove gear icon.
424 function Machine:removeRepairingStatus()
425 local room = self:getRoom()
426 room.manual_repair = false
427 self:setMoodInfo(nil)
428 room:unlockRoomOnRepair()
429 self.repairing = nil
430 self.ticks = self.object_type.ticks
431 self.world.dispatcher:dropFromQueue(self)
432 if not room.crashed then
433 self:updateDynamicInfo()
434 self:getRoom():tryAdvanceQueue()
435 end
436 end
437
438 function Machine.slaveMixinClass(class_method_table)
439 local slave_to_master, master_to_slave = Object.slaveMixinClass(class_method_table)
440 master_to_slave("finalize")
441 master_to_slave("setCrashedAnimation")
442 slave_to_master("createRepairAction")
443 slave_to_master("getRepairTile")
444 return slave_to_master, master_to_slave
445 end
446
447 -- Currently used to make the hover cursor of the machine be special
448 -- only if the room is active at the moment (e.g. not being edited)
449 --!param room (object) machine room
450 function Machine:finalize(room)
451 if room.is_active then
452 self.hover_cursor = TheApp.gfx:loadMainCursor("repair")
453 self:updateDynamicInfo()
454 else
455 self:clearDynamicInfo()
456 self.hover_cursor = nil
457 end
458 end
459
460 function Machine:updateDynamicInfo()
461 if self.strength then
462 local show_machine_max_available_strength_value = self.world.ui.app.config.new_machine_extra_info
463 if show_machine_max_available_strength_value then
464 local hosp = self.world:getLocalPlayerHospital()
465 self:setDynamicInfo("text", {
466 self.object_type.name,
467 _S.dynamic_info.object.strength_extra_info:format(self.strength, hosp.research.research_progress[self.object_type].start_strength),
468 _S.dynamic_info.object.times_used:format(self.times_used),
469 })
470 else
471 self:setDynamicInfo("text", {
472 self.object_type.name,
473 _S.dynamic_info.object.strength:format(self.strength),
474 _S.dynamic_info.object.times_used:format(self.times_used),
475 })
476 end
477 end
478 end
479
480 function Machine:onClick(ui, button)
481 local room = self:getRoom()
482 if button == "left" and room.is_active then
483 -- If the room is crashed is_active is false.
484 ui:addWindow(UIMachine(ui, self, room))
485 else
486 Object.onClick(self, ui, button)
487 end
488 end
489
490 function Machine:onDestroy()
491 local room = self:getRoom()
492 if room then
493 room:unlockRoomOnRepair()
494 end
495 self:removeHandymanRepairTask()
496
497 -- Stop this machine from smoking
498 setSmoke(self, false)
499
500 Object.onDestroy(self)
501 end
502
503 function Machine:afterLoad(old, new)
504 if old < 15 then
505 if self.object_type.id == "cardio" then
506 -- Fix THOB value being wrong
507 self.world.map.th:setCellFlags(self.tile_x, self.tile_y, {
508 thob = self.object_type.thob
509 })
510 end
511 end
512 if old < 54 then
513 local room = self:getRoom()
514 if room.crashed then
515 self:removeHandymanRepairTask()
516 end
517 end
518 self:updateDynamicInfo()
519 return Object.afterLoad(self, old, new)
520 end
521
522 function Machine:tick()
523 -- Tick any smoke animation
524 if self.smokeInfo then
525 self.smokeInfo:tick()
526 end
527
528 return Object.tick(self)
529 end
530
531 --[[ Gets the state of a machine
532
533 ! In addition to the object implementation this includes total_usage
534 !return (table) state
535 ]]
536 function Machine:getState()
537 local state = Object.getState(self)
538 state.total_usage = self.total_usage
539 state.strength = self.strength
540 return state
541 end
542
543 --[[ Sets the state of a machine
544
545 ! Adds total_usage
546 !param state (table) table holding the state
547 !return (void)
548 ]]
549 function Machine:setState(state)
550 Object.setState(self, state)
551 if state then
552 self.total_usage = state.total_usage
553 self.strength = state.strength
554 end
555 end
556
557 --[[ Sets the handyman use position of a machine
558
559 ! Calculate handyman use position based on object orientation
560 ! or the normal use position if one not available
561 !param direction (string) orientation of object
562 !return (void)
563 ]]
564 function Machine:setHandymanRepairPosition(direction)
565 local orientation = self.object_type.orientations[direction]
566 local handyman_position = orientation.handyman_position
567 if handyman_position then
568 -- If there are many possible handyman tiles, choose one that is accessible from the use_position.
569 if type(handyman_position[1]) == "table" then
570 for _, position in ipairs(handyman_position) do
571 local hx, hy = self.tile_x + position[1], self.tile_y + position[2]
572 local ux, uy = self.tile_x + orientation.use_position[1], self.tile_y + orientation.use_position[2]
573 if self.world.pathfinder:findDistance(hx, hy, ux, uy) then
574 -- Also make sure the tile is not in another room or in the corridor.
575 local room = self.world:getRoom(hx, hy)
576 if room and room == self:getRoom() then
577 self.handyman_position = {position[1], position[2]}
578 break
579 end
580 end
581 end
582 else
583 self.handyman_position = {handyman_position[1], handyman_position[2]}
584 end
585 else
586 self.handyman_position = {orientation.use_position[1], orientation.use_position[2]}
587 end
588 end
589
590 --! Access the dedicated DrawingLayer for the smoke animation attached to this machine
591 function Machine:getSmokeDrawingLayer()
592 return DrawingLayers.MachineSmoke
593 end
594
595 -- Dummy callbacks for savegame compatibility
596 local callbackNewRoom = --[[persistable:machine_build_callback]] function() end
597 local repair_loop_callback = --[[persistable:handyman_repair_loop_callback]] function() end