1 ! Copyright (C) 2009 Joe Groff.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors calendar continuations destructors fry kernel
4 locals math math.order system timers ui ui.gadgets.worlds
9 { tick-interval-nanos integer read-only }
19 GENERIC: tick* ( delegate -- )
20 GENERIC: draw* ( tick-slice delegate -- )
24 TUPLE: game-loop-error-state error game-loop ;
26 : ?ui-error ( error -- )
27 ui-running? [ ui-error ] [ rethrow ] if ;
29 : game-loop-error ( error game-loop -- )
30 [ nip stop-loop ] [ \ game-loop-error-state boa ?ui-error ] 2bi ;
32 : fps ( fps -- nanos )
33 [ 1,000,000,000 ] dip /i ; inline
37 : last-tick-percent-offset ( loop -- float )
38 [ draw-timer>> next-nanos>> nano-count - ]
39 [ tick-interval-nanos>> ] bi /f 1.0 swap -
42 GENERIC#: record-benchmarking 1 ( loop quot -- )
44 M: object record-benchmarking
50 [ last-tick-percent-offset ] [ draw-delegate>> ] bi
52 ] record-benchmarking ;
55 [ tick-delegate>> tick* ] record-benchmarking ;
57 : increment-tick ( loop -- )
63 :: when-running ( loop quot -- )
66 dup running?>> quot [ drop ] if
71 : tick-iteration ( loop -- )
72 [ [ tick ] [ increment-tick ] bi ] when-running ;
74 : frame-iteration ( loop -- )
75 [ redraw ] when-running ;
77 : start-loop ( loop -- )
81 [ '[ _ tick-iteration ] f ]
82 [ tick-interval-nanos>> nanoseconds ] bi <timer> >>tick-timer
84 dup '[ _ frame-iteration ] f 1 milliseconds <timer> >>draw-timer
86 [ tick-timer>> ] [ draw-timer>> ] bi [ start-timer ] bi@ ;
88 : stop-loop ( loop -- )
90 [ tick-timer>> ] [ draw-timer>> ] bi [ stop-timer ] bi@ ;
92 : <game-loop*> ( tick-interval-nanos tick-delegate draw-delegate -- loop )
93 f 0 0 f f f game-loop boa ;
95 : <game-loop> ( tick-interval-nanos delegate -- loop )
96 dup <game-loop*> ; inline
101 { "game.loop" "prettyprint" } "game.loop.prettyprint" require-when
102 { "game.loop" "tools.memory" } "game.loop.benchmark" require-when