Debian Codegraph @

CorsixTH/Lua/announcer.lua

raw
1 --[[ Copyright (c) 2018 Rick "Feanathiel" Megens
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 corsixth.require("date")
22
23 --! Pr
24 local AnnouncementPriority = {
25 Critical = 1,
26 High = 2,
27 Normal = 3,
28 Low = 4
29 }
30
31 strict_declare_global "AnnouncementPriority"
32 _G["AnnouncementPriority"] = AnnouncementPriority
33
34 local default_announcement_priority = AnnouncementPriority.Normal
35 local hoursPerDay = Date.hoursPerDay()
36
37 local default_announcement_decay_hours = {
38 [AnnouncementPriority.Critical] = -1, -- never decay
39 [AnnouncementPriority.High] = 31 * hoursPerDay,
40 [AnnouncementPriority.Normal] = 7 * hoursPerDay,
41 [AnnouncementPriority.Low] = 3 * hoursPerDay
42 }
43
44 --! An announcement queue based on priority
45 class "AnnouncementQueue"
46
47 ---@type AnnouncementQueue
48 local AnnouncementQueue = _G["AnnouncementQueue"]
49
50 --! Creates an announcement queue: a collection of announcements with queue semantics.
51 function AnnouncementQueue:AnnouncementQueue()
52 -- might want to use a single table for this
53 self.priorities = {
54 [AnnouncementPriority.Critical] = {},
55 [AnnouncementPriority.High] = {},
56 [AnnouncementPriority.Normal] = {},
57 [AnnouncementPriority.Low] = {}
58 }
59
60 self.count = 0
61 end
62
63 --! Adds the announcement entry to the queue.
64 --!param priority (int) the priority of the announcement
65 --!param entry (AnnouncementEntry) the announcement entry
66 function AnnouncementQueue:push(priority, entry)
67 local entries = self.priorities[priority]
68 table.insert(entries, entry)
69 self.count = self.count + 1
70 end
71
72 --! Dequeues the announcement with the highest priority, nil if the queue is empty.
73 function AnnouncementQueue:pop()
74 for _, entries in ipairs(self.priorities) do
75 if entries[1] ~= nil then
76 local entry = table.remove(entries, 1)
77 self.count = self.count - 1
78 return entry
79 end
80 end
81
82 return nil
83 end
84
85 --! Returns true if the queue is empty, false otherwise.
86 function AnnouncementQueue:isEmpty()
87 return self.count == 0
88 end
89
90 --! Checks for duplicates in the announcement queue and refreshes the announcement's created_date
91 --!param sound the announcement to check
92 --!param date the date to use, usually the current date
93 function AnnouncementQueue:checkForDuplicates(sound, date)
94 for _, entries in ipairs(self.priorities) do
95 for _, entry in ipairs(entries) do
96 if entry.name == sound then
97 entry.created_date = date
98 return true
99 end
100 end
101 end
102 return false
103 end
104
105
106 --! An announcement.
107 class "AnnouncementEntry"
108
109 ---@type AnnouncementEntry
110 local AnnouncementEntry = _G["AnnouncementEntry"]
111
112 --! Creates an announcement
113 function AnnouncementEntry:AnnouncementEntry()
114 self.name = nil -- filename to play
115 self.priority = default_announcement_priority
116 self.created_date = nil -- when it has been created
117 self.decay_hours = nil -- how long until the announcement isn't relevant anymore
118 self.played_callback = nil -- call me whenever the sound was played, ...
119 self.played_callback_delay = nil -- but not until delay has passed
120 end
121
122 --! Announces audible messages to the player.
123 --! The announcer plays announcements based on their priority. If the caller requests an
124 -- announcement to be played, it will be played directly if there are no announcements
125 -- currently being announced. Note that announcements are only played if there is
126 -- a worker at the reception desk and announcements are enabled in the settings.
127 class "Announcer"
128
129 ---@type Announcer
130 local Announcer = _G["Announcer"]
131
132 --! Constructor.
133 --!param app (App) The CorsixTH app
134 function Announcer:Announcer(app)
135 self.app = app
136 self.entries = AnnouncementQueue()
137 self.playing = false
138 self.ticks_since_last_announcement = 0
139
140 self:_setRandomAnnouncementTarget()
141 end
142
143 --! Requests the announcer to play an announcement.
144 --!param name (string) The filename to play.
145 --!param priority (int | nil) The priority of the announcement. See AnnouncementPriority.
146 --!param decay_hours (float | nil) After this amount of hours the announcement should be considered irrelevant.
147 -- Provide nil for a decay time based on the provided priority.
148 --!param played_callback (function | nil) The callback to trigger when the announcement was successfully played.
149 --!param played_callback_delay (int | nil) Delay the callback with this amount of milliseconds.
150 function Announcer:playAnnouncement(name, priority, decay_hours, played_callback, played_callback_delay)
151 -- Announcements use the in-game time instead of ticks.
152 -- For example, if an employee is sacked, the announcement should
153 -- have played in a reasonable amount of time (on his way out).
154 -- We don't want the game to play the announcement if it took too long to
155 -- actually start it, as more important announcements must be played before that.
156 -- It doesn't make sense to play the sacked announcement when the employee
157 -- already has had several other jobs and has died already [joke].
158
159 -- Check for duplicate announcements, if there is we refresh the existing one
160 local created_date = self.app.world:date()
161 local duplicate_announcement = self.entries:checkForDuplicates(name, created_date)
162 if duplicate_announcement then
163 return
164 end
165
166 local new_priority = priority or default_announcement_priority
167
168 local new_decay_hours = decay_hours or default_announcement_decay_hours[new_priority]
169
170 local entry = AnnouncementEntry()
171 entry.name = name
172 entry.priority = new_priority
173 entry.created_date = created_date
174 entry.decay_hours = new_decay_hours
175 entry.played_callback = played_callback
176 entry.played_callback_delay = played_callback_delay
177
178 if self.app.world:getLocalPlayerHospital():hasReceptionDesk(true) or priority == AnnouncementPriority.Critical then
179 self.entries:push(new_priority, entry)
180 end
181 end
182
183 --! The announcer's (game) tick handler.
184 -- Plays the actual sound of the announcements, if available.
185 -- Also queues random announcements if no announcements have been played for a while.
186 function Announcer:onTick()
187 local staffedDesk = self.app.world:getLocalPlayerHospital():hasReceptionDesk(true)
188 local criticalAnnounces = #self.entries.priorities[AnnouncementPriority.Critical]
189 if not self.app.world:isCurrentSpeed("Pause") then
190 local ticks_since_last_announcement = self.ticks_since_last_announcement
191 if ticks_since_last_announcement >= self.random_announcement_ticks_target then
192 self:playAnnouncement("rand*.wav", AnnouncementPriority.Low)
193 self:_setRandomAnnouncementTarget()
194 else
195 self.ticks_since_last_announcement = ticks_since_last_announcement + 1
196 end
197
198 -- Wait for an occupied desk or announcement is critical
199 if staffedDesk or criticalAnnounces > 0 then
200 while not self.playing and not self.entries:isEmpty() do
201 local entry = self.entries:pop()
202 local game_date = self.app.world:date()
203
204 if entry.decay_hours == -1 or game_date <= entry.created_date:plusHours(entry.decay_hours) then
205 if self.app.config.play_announcements then
206 self:_play(entry)
207 end
208 -- Drain the queue otherwise
209 end
210 end
211 end
212 -- The game is paused
213 else
214 -- Only play critical announcements when paused
215 while not self.playing and not self.entries:isEmpty() and criticalAnnounces > 0 do
216 local entry = self.entries:pop()
217 if self.app.config.play_announcements then
218 self:_play(entry)
219 end
220 end
221 end
222 end
223
224 --! Private function. Sets the new time (in ticks) when a random announcement should be played.
225 function Announcer:_setRandomAnnouncementTarget()
226 -- Note that random announcement are measured in ticks.
227 -- This ensures that on fast game speeds random announcements aren't
228 -- spammed, or on lower game speeds random announcements are never played.
229
230 -- Every tick is 18ms, so ~3333 ticks is 1 minute at normal speed
231 local tick_chunk = 3333
232 -- Set a target of 4 - 6 minutes (chunks)
233 self.random_announcement_ticks_target = math.random(tick_chunk * 4, tick_chunk * 6)
234 end
235
236 --! Private function. Plays the actual sound of an announcement.
237 --!param entry (AnnouncementEntry) The announcement to play.
238 function Announcer:_play(entry)
239 self.playing = true
240 local name = self.app.audio:resolveFilenameWildcard(entry.name)
241 self.app.audio:playSound(name, nil, true, function () self:_onPlayed(entry) end, entry.played_callback_delay)
242 self.app.ui.subtitles:queueSubtitle(name)
243 self.ticks_since_last_announcement = 0
244 end
245
246 --! Private function. Handles the playSound completed event. Also calls the callback of the announcement.
247 --!param entry (AnnouncementEntry) The announcement that has been played.
248 function Announcer:_onPlayed(entry)
249 self.playing = false
250
251 if entry.played_callback ~= nil then
252 entry.played_callback()
253 end
254 end