-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
nafl.lua
544 lines (461 loc) · 15 KB
/
nafl.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
-- NPad's Advanced Frame Limiter
--
-- Copyright (c) 2022 Miku AuahDark
--
-- Permission is hereby granted, free of charge, to any person obtaining a
-- copy of this software and associated documentation files (the "Software"),
-- to deal in the Software without restriction, including without limitation
-- the rights to use, copy, modify, merge, publish, distribute, sublicense,
-- and/or sell copies of the Software, and to permit persons to whom the
-- Software is furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-- DEALINGS IN THE SOFTWARE.
local love = require("love")
local nafl = {
_VERSION = "1.0.1",
_AUTHOR = "MikuAuahDark",
_LICENSE = "MIT"
}
local var = {
value = nil,
mode = "sleep",
accumulator = 0,
time = 0,
canvas = nil,
redraw = false,
queuedValue = nil,
queuedMode = "sleep",
displayRateDelay = 4,
refreshRate = 0,
monkeypatch = true,
loveRun = love.run,
loveErrhand = love.errorhandler or love.errhand
}
local loveGetCanvas = love.graphics.getCanvas
local loveSetCanvas = love.graphics.setCanvas
local loveReset = love.graphics.reset
---@param value? integer
---@param mode? '"sleep"' | '"lockstep"' | '"vblank"'
local function setLimit(value, mode)
-- vblank 1 is no-op
if mode == "vblank" and value == 1 then
value, mode = nil, nil
end
var.queuedValue = value
var.queuedMode = mode
end
local function needBackbuffer()
return var.mode == "vblank" or var.mode == "lockstep"
end
local function applyMonkeypatch()
love.graphics.reset = nafl.reset
love.graphics.getCanvas = nafl.getCanvas
love.graphics.setCanvas = nafl.setCanvas
end
local function revertMonkeypatch()
love.graphics.reset = loveReset
love.graphics.getCanvas = loveGetCanvas
love.graphics.setCanvas = loveSetCanvas
end
local function initSleep()
var.frameTime = 1 / var.value
var.time = love.timer.getTime()
end
local function initLockstep()
var.frameTime = 1 / var.value
var.accumulator = 0
var.firstTime = true
var.runDraw = false
var.forceDraw = false
nafl.resize()
if var.monkeypatch then
applyMonkeypatch()
end
end
local function initVblank()
nafl.resize()
if var.monkeypatch then
applyMonkeypatch()
end
end
---@param dt number
local function updateSleep(dt)
var.time = love.timer.getTime()
return true, dt
end
---@param dt number
local function updateLockstep(dt)
var.runDraw = false
-- Always draw the 1st frame regardless
if var.firstTime then
var.firstTime = false
var.runDraw = true
return true, dt
end
-- Prevent spiral of death by not lockstepping
-- if dt is larger than the intended frame time
if dt > var.frameTime then
var.runDraw = true
return true, dt
end
-- If force draw is issued, allow update and empty
-- out the accumulator.
if var.forceDraw then
dt = dt + var.accumulator
var.accumulator = 0
return true, dt
end
var.accumulator = var.accumulator + dt
if var.accumulator >= var.frameTime then
var.accumulator = var.accumulator - var.frameTime
var.runDraw = true
return true, var.frameTime
end
return false, dt
end
local function drawSleep()
return true
end
local function drawLockstep()
love.graphics.push("all")
if var.runDraw or var.forceDraw then
love.graphics.setCanvas(var.canvas)
love.graphics.clear(love.graphics.getBackgroundColor())
var.forceDraw = false
return true
end
return false
end
local function drawVblank()
love.graphics.push("all")
love.graphics.setCanvas(var.canvas)
love.graphics.clear(love.graphics.getBackgroundColor())
return true
end
local function postDrawSleep()
love.graphics.flushBatch()
end
local function postDrawLockstep()
love.graphics.pop()
love.graphics.setBlendMode("alpha", "premultiplied")
love.graphics.draw(var.canvas)
love.graphics.setBlendMode("alpha", "alphamultiply")
end
local function decideSleep()
local t = love.timer.getTime() - var.time
local sleepFor = math.max(var.frameTime - t - 0.0005, 0)
if sleepFor > 0 then
love.timer.sleep(sleepFor)
end
end
local function decideLockstep()
end
local function decideVblank()
for i = 1, var.value - 1 do
if love.graphics.isActive() then
love.graphics.clear()
love.graphics.setBlendMode("alpha", "premultiplied")
love.graphics.draw(var.canvas)
love.graphics.setBlendMode("alpha", "alphamultiply")
love.graphics.present()
end
end
end
local initMode = {
["sleep"] = initSleep,
["lockstep"] = initLockstep,
["vblank"] = initVblank,
}
local updateMode = {
["sleep"] = updateSleep,
["lockstep"] = updateLockstep,
["vblank"] = updateSleep,
}
local drawMode = {
["sleep"] = drawSleep,
["lockstep"] = drawLockstep,
["vblank"] = drawVblank,
}
local postDrawMode = {
["sleep"] = postDrawSleep,
["lockstep"] = postDrawLockstep,
["vblank"] = postDrawLockstep
}
local decideMode = {
["sleep"] = decideSleep,
["lockstep"] = decideLockstep,
["vblank"] = decideVblank
}
local function shouldPerform()
return var.value and (var.refreshRate == 0 or var.refreshRate > var.value)
end
--====================================--
--===== Public API Listing Below =====--
--====================================--
---Get screen refresh rate. Equivalent to `select(3, love.window.getMode()).refreshrate`
---@return integer
function nafl.getRefreshRate()
return select(3, love.window.getMode()).refreshrate
end
---Activate FPS limiter.
---
---There are 3 `mode`s that user can choose from, with the expected `value` parameter:
---* `"sleep"` - Sleeps the CPU until it reaches the desired FPS. `value` is the target FPS.
--- **Caveat**: Target FPS may not be 100% guaranteed.
---* `"lockstep"` - Run the game in lock-step fashion. `love.update` will see at least `1/value`
--- seconds but _can be higher_. `value` is the target FPS. **Caveat**: `love.timer.getFPS()`
--- reading will be inaccurate.
---* `"vblank"` - Wait for specified amount of vblank (which is `1/screen refresh rate` seconds).
--- `value` is number of vblank to wait (so value of `2` will wait for `2/screen refresh rate`
--- seconds). **Caveat**: Does not limit FPS fully when vsync is (forcefully) turned off.
---
---Calling this function without any parameter turns off the FPS limiter.
---@param mode? '"sleep"' | '"lockstep"' | '"vblank"'
---@param value? integer
function nafl.limit(mode, value)
if mode and value then
assert(mode == "sleep" or mode == "lockstep" or mode == "vblank", "invalid mode")
setLimit(value, mode)
else
setLimit()
end
end
---Return the internal backbuffer Canvas used on lockstep or vblank mode.
---@return love.Canvas?
function nafl.getBackbufferCanvas()
return var.canvas
end
---This function must be called when the window is resized. The default `nafl.run`
---calls this, but if you're using your own `love.run`, make sure to call this.
---
---**NOTE**: This is for advanced users. See implementation of `nafl.run`
---in nafl.lua for more information about this function!
function nafl.resize()
if needBackbuffer() then
var.canvas = love.graphics.newCanvas()
if var.mode == "lockstep" then
var.forceDraw = true
end
end
end
---Start NAFL routines on this frame.
---
---**NOTE**: This is for advanced users. See implementation of `nafl.run`
---in nafl.lua for more information about this function!
function nafl.start()
local changed = var.value ~= var.queuedValue or var.mode ~= var.queuedMode
var.value = var.queuedValue
var.mode = var.queuedMode
if changed then
revertMonkeypatch()
end
if var.value then
if changed then
initMode[var.mode]()
end
end
var.displayRateDelay = var.displayRateDelay + 1
if var.displayRateDelay >= 5 then
var.displayRateDelay = 0
var.refreshRate = nafl.getRefreshRate()
end
end
---Update NAFL routines and determine if update logic should be called on
---this frame. `dt` must be value of `love.timer.step()`, without modifications!
---
---**NOTE**: This is for advanced users. See implementation of `nafl.run`
---in nafl.lua for more information about this function!
---@param dt number `love.timer.step()`
---@return boolean call call update routine?
---@return number dt actual `dt` that should be passed to `love.update`
function nafl.update(dt)
if shouldPerform() then
return updateMode[var.mode](dt)
end
return true, dt
end
---Determine if render logic should be called on this frame.
---
---**NOTE**: This is for advanced users. See implementation of `nafl.run`
---in nafl.lua for more information about this function!
---@return boolean @call draw routine?
function nafl.draw()
if shouldPerform() then
return drawMode[var.mode]()
end
return true
end
---Post-`love.update` function that must be called. Call this just before
---`love.graphics.present`.
---
---**NOTE**: This is for advanced users. See implementation of `nafl.run`
---in nafl.lua for more information about this function!
function nafl.postDraw()
if shouldPerform() then
return postDrawMode[var.mode]()
end
end
---Final function that must be called just before the game loop code finishes.
---
---**NOTE**: This is for advanced users. See implementation of `nafl.run`
---in nafl.lua for more information about this function!
function nafl.decide()
if shouldPerform() then
decideMode[var.mode]()
end
end
---This is the default NAFL-integrated game loop, based on `love.run`.
---
---**NOTE**: This is for advanced users. Please see
---[`love.run` Wiki page](https://love2d.org/wiki/love.run) for more
---information about LOVE game loop!
---
---If you're writing your own game loop, take a note where to place the NAFL-specific
---functions. Otherwise you may get errors.
---@return function
function nafl.run()
---@diagnostic disable-next-line: undefined-field
if love.load then love.load(love.arg.parseGameArguments(arg), arg) end
-- We don't want the first frame's dt to include time taken by love.load.
if love.timer then love.timer.step() end
local dt = 0
-- Main loop time.
return function()
nafl.start() -- NAFL: Put this before processing events.
-- Process events.
if love.event then
love.event.pump()
for name, a,b,c,d,e,f in love.event.poll() do
if name == "quit" then
---@diagnostic disable-next-line: undefined-field
if not love.quit or not love.quit() then
return a or 0
end
-- NAFL: Handle resize event!
elseif name == "resize" then
nafl.resize()
end
---@diagnostic disable-next-line: undefined-field
love.handlers[name](a,b,c,d,e,f)
end
end
-- Update dt, as we'll be passing it to update
local update update, dt = nafl.update(love.timer.step())
-- NAFL: Only run `love.update` if `update` is `true`.
-- Call update and draw
---@diagnostic disable-next-line: undefined-field
if update and love.update then love.update(dt) end
if love.graphics and love.graphics.isActive() then
love.graphics.origin()
love.graphics.clear(love.graphics.getBackgroundColor())
if nafl.draw() then -- NAFL: `nafl.draw` returns boolean whetever to call `love.draw` or not.
---@diagnostic disable-next-line: undefined-field
if love.draw then love.draw() end
end
nafl.postDraw() -- NAFL: Call this just before `love.graphics.present` is called.
love.graphics.present()
end
if love.timer then love.timer.sleep(0.001) end
nafl.decide() -- NAFL: Call this at the end of game loop.
end
end
---If you written custom error handler, call this on top of your `love.errorhandler`
---function. This function ensure Canvas are unset and restores monkeypatched LOVE
---functions.
---
---**NOTE**: This is for advanced users. Please see
---[`love.errorhandler` Wiki page](https://love2d.org/wiki/love.errorhandler) for more
---information about LOVE error handler loop!
function nafl.errorHandler()
if nafl.getBackbufferCanvas() and love.graphics.isActive() then
loveSetCanvas()
end
revertMonkeypatch()
end
---Equivalent to `love.graphics.getCanvas` but returns the default canvas when needed.
function nafl.getCanvas()
local c = loveGetCanvas()
if shouldPerform() and needBackbuffer() and (not c) then
c = var.canvas
end
return c
end
---Equivalent to `love.graphics.setCanvas` but sets the default canvas when needed.
function nafl.setCanvas(c)
if shouldPerform() and needBackbuffer() and c == nil then
c = var.canvas
end
return loveSetCanvas(c)
end
---Equivalent to `love.graphics.reset` but sets the default canvas when needed.
function nafl.reset()
loveReset()
if shouldPerform() and needBackbuffer() then
loveSetCanvas(var.canvas)
end
end
---Do not monkeypatch `love.graphics.getCanvas`, `love.graphics.setCanvas`,
---and `love.graphics.reset` when using "**lockstep**" or "**vblank**" limiter
---mode.
---
---If you don't monkeypatch those LOVE functions, then you must replace all
---calls to:
---* `love.graphics.getCanvas` to `nafl.getCanvas`
---* `love.graphics.setCanvas` to `nafl.setCanvas`
---* `love.graphics.reset` to `nafl.reset`
---
---**CAUTION**: This is one-time function. Once disabled, it can't be enabled
---again. This function should be called at your main.lua, before `love.load`
---is called, otherwise the behavior of this function is undefined.
function nafl.disableMonkeypatch()
var.monkeypatch = false
end
---Do not replace `love.run` with NAFL-written `nafl.run`. Useful if
---you already written your own `love.run` before loading this library.
---
---**CAUTION**: This is one-time function. Once disabled, it can't be enabled
---again. This function should be called at your main.lua, before `love.load`
---is called, otherwise the behavior of this function is undefined.
---
---**NOTE**: Please read `nafl.lua` if you implemented your own `love.run`
---and want to integrate this library into your game loop!
function nafl.disableNAFLRun()
love.run = var.loveRun
end
---Do not replace `love.errorhandler` with NAFL-written `nafl.errorHandler`.
---Maybe useful if you have written your own `love.errorhandler`, but NAFL
---error handler only unsets canvas then calls the original LOVE error handler
---(or the one you wrote if overridden before loading this library)
---
---**CAUTION**: This is one-time function. Once disabled, it can't be enabled
---again. This function should be called at your main.lua, before `love.load`
---is called, otherwise the behavior of this function is undefined.
---
---**NOTE**: Please read `nafl.lua` if you implemented your own `love.run`
---and want to integrate this library into your game error handler!
function nafl.disableErrorHandler()
love.errorhandler = var.loveErrhand
end
love.run = nafl.run
function love.errorhandler(msg)
nafl.errorHandler()
return var.loveErrhand(msg)
end
return nafl
--[[
Changelog:
vM.m.p: YYYY-MM-DD
v1.0.1: 2022-09-13
> Override love.errorhandler to unset Canvas and revert monkeypatch.
v1.0.0: 2022-09-09
> Initial release.
]]