lib/mnit: introduce mnit_fps so each app does not need to play with clocks
[nit.git] / lib / mnit / mnit_fps.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Frame-rate control for applications
16 module mnit_fps
17
18 import mnit_app
19 private import realtime
20
21 redef class App
22 # Limit the frame-rate to a given frequency
23 # This basically limits how much `frame_core` is called per second.
24 # Zero (or a negative value) means no limit.
25 #
26 # Applications can modify this value even during the main-loop.
27 var maximum_fps writable = 60
28
29 redef fun full_frame
30 do
31 super
32 limit_fps
33 end
34
35 # The clock for limit_fps
36 private var clock = new Clock
37
38 # Check and sleep to maitain a frame-rate bellow `maximum_fps`
39 # Is automatically called at the end of `full_frame`.
40 fun limit_fps
41 do
42 var mfps = maximum_fps
43 if mfps <= 0 then return
44 var dt = clock.lapse
45 var target_dt = 1000000000 / mfps
46 var sec = dt.sec
47 var nanosec = dt.nanosec
48 if sec == 0 and nanosec < target_dt then
49 var sleep_t = target_dt - nanosec
50 sys.nanosleep(0, sleep_t)
51 dt = clock.lapse
52 end
53 end
54 end