1 ! Copyright (C) 2009 Joe Groff.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors calendar continuations destructors kernel
4 math math.order system timers ui ui.gadgets.worlds vocabs.loader ;
8 { tick-interval-nanos integer read-only }
18 GENERIC: tick* ( delegate -- )
19 GENERIC: draw* ( tick-slice delegate -- )
23 TUPLE: game-loop-error-state error game-loop ;
25 : ?ui-error ( error -- )
26 ui-running? [ ui-error ] [ rethrow ] if ;
28 : game-loop-error ( error game-loop -- )
29 [ nip stop-loop ] [ \ game-loop-error-state boa ?ui-error ] 2bi ;
31 : fps ( fps -- nanos )
32 [ 1,000,000,000 ] dip /i ; inline
36 : last-tick-percent-offset ( loop -- float )
37 [ draw-timer>> next-nanos>> nano-count - ]
38 [ tick-interval-nanos>> ] bi /f 1.0 swap -
41 GENERIC#: record-benchmarking 1 ( loop quot -- )
43 M: object record-benchmarking
49 [ last-tick-percent-offset ] [ draw-delegate>> ] bi
51 ] record-benchmarking ;
54 [ tick-delegate>> tick* ] record-benchmarking ;
56 : increment-tick ( loop -- )
62 :: when-running ( loop quot -- )
65 dup running?>> quot [ drop ] if
70 : tick-iteration ( loop -- )
71 [ [ tick ] [ increment-tick ] bi ] when-running ;
73 : frame-iteration ( loop -- )
74 [ redraw ] when-running ;
76 : start-loop ( loop -- )
80 [ '[ _ tick-iteration ] f ]
81 [ tick-interval-nanos>> nanoseconds ] bi <timer> >>tick-timer
83 dup '[ _ frame-iteration ] f 1 milliseconds <timer> >>draw-timer
85 [ tick-timer>> ] [ draw-timer>> ] bi [ start-timer ] bi@ ;
87 : stop-loop ( loop -- )
89 [ tick-timer>> ] [ draw-timer>> ] bi [ stop-timer ] bi@ ;
91 : <game-loop*> ( tick-interval-nanos tick-delegate draw-delegate -- loop )
92 f 0 0 f f f game-loop boa ;
94 : <game-loop> ( tick-interval-nanos delegate -- loop )
95 dup <game-loop*> ; inline
100 { "game.loop" "prettyprint" } "game.loop.prettyprint" require-when
101 { "game.loop" "tools.memory" } "game.loop.benchmark" require-when