Debian Codegraph @

dokidoki/kernel.lua

raw symbols SCIP
1 --- dokidoki.kernel
2 --- ===============
3 ---
4 --- `dokidoki.kernel` handles initialization and the core loop. It takes an
5 --- abstract scene object which provides implementations of updating, drawing,
6 --- and event-handling functions.
7 ---
8 --- A scene must implement:
9 ---
10 --- - `scene.update()`
11 --- - `scene.draw()`
12 --- - `scene.handle_event(event)`
13 ---
14 --- where none of the callbacks has a return value.
15 ---
16 --- For the `handle_event(event)` callback, `event` has one of the following
17 --- forms:
18 ---
19 --- - `{type = 'close'}`
20 --- - `{type = 'resize', width = ?, height = ?}`
21 --- - `{type = 'key', key = ?, is_down = ?}` (`key` is a GLFW key constant)
22
23 --- Implementation
24 --- --------------
25
26 require "dokidoki.module"
27 [[ set_fps, set_max_frameskip, get_width, get_height, get_ratio,
28 set_fullscreen, set_video_mode, set_ratio, start_main_loop, abort_main_loop,
29 switch_scene, get_framerate ]]
30
31 require "glfw"
32
33 local mixer = require "mixer"
34 local log = require "log"
35
36 import(require "gl")
37
38 import(require "dokidoki.base")
39
40 ---- Constants ----------------------------------------------------------------
41
42 max_frameskip = 6
43 fps = 60
44 max_sample_frames = 16
45
46 -- Never sleep for less than this amount. This has to be bigger on systems with
47 -- really lame timers, like Windows.
48 min_sleep_time = 0.002
49 -- Allow for this much inaccuracy in the OS sleep operation
50 sleep_allowance = 0.002
51
52 ---- State Variables ----------------------------------------------------------
53
54 running = false
55 use_fullscreen = false
56
57 width = nil
58 height = nil
59 ratio = nil
60
61 frame_times = {}
62
63 next_scene = nil
64
65 ---- Public Interface ---------------------------------------------------------
66
67 --- ### `set_max_frameskip(max_frameskip)`
68 --- Sets the maximum number of updates to run before forcing a draw.
69 ---
70 --- If more than this number of updates are queued to happen before a redraw,
71 --- the rest will be discared.
72 function set_max_frameskip(new_max_frameskip)
73 assert(type(new_max_frameskip == 'number') and new_max_frameskip >= 1)
74 max_frameskip = new_max_frameskip
75 end
76
77 --- ### `set_fps(fps)`
78 --- Sets the target frames-per-second.
79 function set_fps(new_fps)
80 assert(type(new_fps == 'number') and fps > 0)
81 fps = new_fps
82 end
83
84 --- ### `get_width()`
85 --- Returns the current total window width in pixels. This includes borders
86 --- when the ratio doesn't match the window size. Returns nil if called before
87 --- the main loop and the width has never been set with `set_size()`.
88 function get_width () return width end
89
90 --- ### `get_height()`
91 --- Returns the current total window height in pixels. This includes borders
92 --- when the ratio doesn't match the window size. Returns nil if called before
93 --- the main loop and the height has never been set with `set_size()`.
94 function get_height () return height end
95
96 --- ### `set_fullscreen(fullscreen)`
97 --- Sets whether or not a fullscreen window should be opened. This must be
98 --- called before entering the main loop.
99 ---
100 --- The default is to open in a window.
101 function set_fullscreen(fullscreen)
102 assert(not running, 'set_fullscreen must be called before the main loop')
103 use_fullscreen = fullscreen
104 end
105
106 --- ### `set_video_mode(width, height)`
107 --- Sets the desired width/height of the window in pixels.
108 ---
109 --- If the main loop hasn't yet been started, it will immediately change
110 --- the window size (or change video modes in fullscreen). If called before
111 --- entering the main loop, this sets the initial video mode, but has no
112 --- immediate effect.
113 ---
114 --- This does not set the desired ratio, so unless you set that as well you may
115 --- end up with borders.
116 function set_video_mode (w, h)
117 assert(w > 0)
118 assert(h > 0)
119 width = w
120 height = h
121 if running then
122 glfw.SetWindowSize(w, h)
123 update_viewport()
124 end
125 end
126
127 --- ### `get_ratio()`
128 --- Returns the screen ratio used within the window for the active area. See
129 --- also `set_ratio()`. Returns nil if called before the main loop and no ratio
130 --- has been set with `set_ratio()`.
131 function get_ratio () return ratio end
132
133 --- ### `set_ratio(ratio)`
134 --- Sets the desired screen ratio.
135 ---
136 --- If the window size doesn't match this ratio, then the ratio is used to set
137 --- the opengl viewport shape within the window.
138 ---
139 --- This must be set manually if a ratio other than 4/3 is wanted, since calls
140 --- to `set_video_mode()` have no effect on it.
141 function set_ratio (r)
142 assert(r > 0)
143 ratio = r
144 if running then update_viewport() end
145 end
146
147 --- ### `start_main_loop(scene)`
148 --- Initializes stuff and begins the main loop. `scene` is used as described in
149 --- the introduction above.
150 function start_main_loop (scene)
151 -- glfw.Terminate() needs to be called even if there is an error, since
152 -- otherwise it may not return the screen to its original resolution.
153 local success, message = xpcall(function ()
154 log.log_message "initializing glfw. . ."
155 if glfw.Init() == GL_FALSE then
156 error("glfw initialization failed")
157 end
158 log.log_message "initializing mixer. . ."
159 assert(mixer.init())
160
161 running = true
162
163 log.log_message "detected video modes:"
164 for _, mode in ipairs(glfw.GetVideoModes()) do
165 log.log_message(' ' .. mode.Width .. 'x' .. mode.Height .. ' R' ..
166 mode.RedBits .. ' G' .. mode.GreenBits .. ' B' ..
167 mode.BlueBits)
168 end
169 if width == nil then
170 log.log_message('using desktop video mode')
171 local mode = glfw.GetDesktopMode()
172 width = mode.Width
173 height = mode.Height
174 end
175 if ratio == nil then
176 ratio = width / height
177 end
178 log.log_message("setting video mode to " .. width .. "x" .. height .. ". . .")
179 glfw.OpenWindow(width, height, 8, 8, 8, 8, 24, 0,
180 use_fullscreen and glfw.FULLSCREEN or glfw.WINDOW)
181 set_video_mode(width, height)
182
183 log.log_message "starting main loop"
184
185 next_scene = scene
186 while next_scene do
187 scene = next_scene
188 next_scene = nil
189 main_loop(scene)
190 if next_scene then
191 running = true
192 end
193 end
194 end, get_stack_trace)
195
196 log.log_message "shutting down"
197 glfw.Terminate()
198
199 if not success then error(message, 0) end
200 end
201
202 --- ### `get_framerate()`
203 --- Returns a running average of the number of `draw()` calls per second.
204 --- Since multiple updates can happen per draw, this isn't the same as the
205 --- number of updates per second, which should usually stay constant.
206 function get_framerate ()
207 if #frame_times >= 2 then
208 return (#frame_times - 1) / (frame_times[#frame_times] - frame_times[1])
209 else
210 return 1
211 end
212 end
213
214 --- ### `abort_main_loop()`
215 --- Sets a flag to terminate the main loop at the next opportunity.
216 ---
217 --- This function should be called from one of the scene callbacks; the loop
218 --- will be aborted when the callback returns.
219 function abort_main_loop ()
220 assert(running)
221 running = false
222 end
223
224 --- ### `switch_scene(scene)`
225 --- Queues up a scene to switch to.
226 ---
227 --- This function should be called from one of the scene callbacks; the scenes
228 --- will be switched when the callback returns.
229 function switch_scene(scene)
230 assert(running)
231 next_scene = scene
232 running = false
233 end
234
235 ---- Utility Functions --------------------------------------------------------
236
237 function get_stack_trace(err)
238 return debug.traceback(err, 2)
239 end
240
241 function set_callback(name, callback)
242 local set = glfw['Set' .. name .. 'Callback']
243 assert(set, 'invalid callback name given')
244 local varname = '__kernel_callback_' .. name
245
246 rawset(_G, varname, callback)
247
248 if(callback) then
249 set(varname)
250 else
251 set()
252 end
253 end
254
255 function main_loop (scene)
256 local last_update_time = get_current_time()
257
258 -- filled in callbacks whenever glfw.SwapBuffers is called
259 local events = {}
260
261 set_callback('WindowClose', function ()
262 table.insert(events, {type = 'quit'})
263 return glfw.FALSE
264 end)
265
266 set_callback('WindowSize', function (width, height)
267 table.insert(events,
268 {type = 'resize', width = width, height = height})
269 end)
270
271 set_callback('Key', function (key, action)
272 table.insert(events,
273 {type = 'key', key = key, is_down = action == glfw.PRESS})
274 end)
275
276 while true do
277 ---- handle events
278 local new_width, new_height
279 for i, event in ipairs(events) do
280 if event.type == 'resize' then
281 new_width = event.width
282 new_height = event.height
283 end
284 scene.handle_event(event)
285 if not running then return end
286 end
287 if new_width and (new_width ~= width or new_height ~= height) then
288 set_video_mode(new_width, new_height)
289 end
290
291 while #events ~= 0 do events[#events] = nil end
292
293 ---- update
294 do
295 -- wait until it's time to update at least once
296 local update_time = 1/fps
297 sleep_until(last_update_time + update_time)
298 local current_time = get_current_time()
299 log_frame_time(current_time)
300 -- if we would have to update for more than max_update_time, skip forward
301 local max_update_time = max_frameskip / fps + 0.001
302 local total_update_time = current_time - last_update_time
303 if max_update_time < total_update_time then
304 log.log_message(
305 "warning: underrun of " ..
306 math.ceil(1000 * (total_update_time - max_update_time)) ..
307 "ms")
308 last_update_time = current_time - max_update_time
309 end
310 -- update the right number of times
311 while last_update_time + update_time <= current_time do
312 last_update_time = last_update_time + update_time
313 scene.update(update_time)
314 if not running then return end
315 end
316 end
317
318 ---- draw
319 scene.draw()
320
321 local err = glGetError()
322 if err ~= 0 then error('OpenGL error ' .. err) end
323
324 if not running then return end
325 glfw.SwapBuffers()
326 end
327 end
328
329 function get_current_time ()
330 return glfw.GetTime()
331 end
332
333 function sleep_until (time)
334 local time_to_sleep = time - get_current_time() - sleep_allowance
335 if time_to_sleep > min_sleep_time then
336 glfw.Sleep(time_to_sleep)
337 end
338 -- Floating point inaccuracy can cause this to pass here but not in the main
339 -- loop, making us do iterations of 0 updates, which is stupid because it
340 -- will render the same thing as last time. Making this condition slightly
341 -- stricter fixes it.
342 while time + 0.0001 > get_current_time() do end
343 end
344
345 function update_viewport ()
346 if width / height > ratio then
347 -- pillarbox
348 local inner_width = math.floor(height * ratio + 0.5)
349 glViewport(math.floor((width - inner_width) / 2), 0, inner_width, height)
350 else
351 -- letterbox
352 local inner_height = math.floor(width / ratio + 0.5)
353 glViewport(0, math.floor((height - inner_height) / 2), width, inner_height)
354 end
355 end
356
357 function log_frame_time(time)
358 table.insert(frame_times, time)
359 if #frame_times > max_sample_frames then
360 table.remove(frame_times, 1)
361 end
362 end
363
364 return get_module_exports()