-------------------------------------------------------------------------------
-- Layer 1 (imperative), as per
-- https://www.parsonsmatt.org/2018/03/22/three_layer_haskell_cake.html
-- 2019 Francesco Ariis GPLv3
-------------------------------------------------------------------------------

{-# Language ScopedTypeVariables #-}

module Terminal.Game.Layer.Imperative where

import Terminal.Game.Draw
import Terminal.Game.Layer.Object

import qualified Control.Concurrent as CC
import qualified Control.Exception as E
import qualified Control.Monad as CM
import qualified Data.Bool as B
import qualified Data.List as D
import qualified System.IO as SI

import Terminal.Game.Plane

-- | Game definition datatype, parametrised on your gamestate. The two most
-- important elements are the function dealing with logic and the drawing
-- one. Check @alone@ demo (@cabal run -f examples alone@) to see a simple
-- game in action.
data Game s =
        Game { forall s. Game s -> Integer
gTPS           :: TPS,
                    -- ^ Game speed in ticks per second. You do not
                    -- need high values, since the 2D canvas is coarse
                    -- (e.g. 13 TPS is enough for action games).
               forall s. Game s -> s
gInitState     :: s,   -- ^ Initial state of the game.
               forall s. Game s -> GEnv -> s -> Event -> s
gLogicFunction :: GEnv -> s -> Event -> s,
                         -- ^ Logic function.
               forall s. Game s -> GEnv -> s -> Plane
gDrawFunction  :: GEnv -> s -> Plane,
                         -- ^ Draw function. Just want to blit your game
                         -- in the middle? Check 'centerFull'.
               forall s. Game s -> s -> Bool
gQuitFunction  :: s -> Bool
                         -- ^ /Should I quit?/ function.
                                      }

-- | A blank plane as big as the terminal.
blankPlaneFull :: GEnv -> Plane
blankPlaneFull :: GEnv -> Plane
blankPlaneFull GEnv
e = forall a b c. (a -> b -> c) -> (a, b) -> c
uncurry Width -> Width -> Plane
blankPlane (GEnv -> Dimensions
eTermDims GEnv
e)

-- | Blits plane in the middle of terminal.
--
-- @
--   draw :: GEnv -> MyState -> Plane
--   draw ev s =
--       centerFull ev $
--         ⁝
-- @
centerFull :: GEnv -> Plane -> Plane
centerFull :: GEnv -> Plane -> Plane
centerFull GEnv
e Plane
p = GEnv -> Plane
blankPlaneFull GEnv
e Plane -> Plane -> Plane
*** Plane
p

-- | Entry point for the game execution, should be called in @main@.
--
-- You __must__ compile your programs with @-threaded@; if you do not do
-- this the game will crash at start-up. Just add:
--
-- @
-- ghc-options:      -threaded
-- @
--
-- in your @.cabal@ file and you will be fine!
--
-- Need to inspect state on exit? Check 'playGameS'.
playGame :: Game s -> IO ()
playGame :: forall s. Game s -> IO ()
playGame Game s
g = () forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ forall a. GameIO a -> IO a
runGIO (forall s (m :: * -> *). MonadGameIO m => Game s -> m s
runGameGeneral Game s
g)

-- | As 'playGame', but do not discard state.
playGameS :: Game s -> IO s
playGameS :: forall s. Game s -> IO s
playGameS Game s
g = forall a. GameIO a -> IO a
runGIO (forall s (m :: * -> *). MonadGameIO m => Game s -> m s
runGameGeneral Game s
g)

-- | Tests a game in a /pure/ environment. Aims to accurately emulate 'GEnv'
-- changes (screen size, FPS) too.
testGame :: Game s -> GRec -> s
testGame :: forall s. Game s -> GRec -> s
testGame Game s
g GRec
ts =
        case forall a. Test a -> GRec -> (Maybe a, [TestEvent])
runTest (forall s (m :: * -> *). MonadGameIO m => Game s -> m s
runGameGeneral Game s
g) GRec
ts of
            (Maybe s
Nothing, [TestEvent]
l) -> forall a. HasCallStack => [Char] -> a
error forall a b. (a -> b) -> a -> b
$ [Char]
"testGame, exception called: " forall a. [a] -> [a] -> [a]
++
                                    forall a. Show a => a -> [Char]
show [TestEvent]
l
                -- it is fine to use error here since in the end
                -- hspec can deal with it gracefully and we give
                -- more infos on a failed test
            (Just s
s, [TestEvent]
_) -> s
s

-- | As 'testGame', but returns 'Game' instead of a bare state.
-- Useful to fast-forward (e.g.: skip menus) before invoking 'playGame'.
setupGame :: Game s -> GRec -> Game s
setupGame :: forall s. Game s -> GRec -> Game s
setupGame Game s
g GRec
ts = let s' :: s
s' = forall s. Game s -> GRec -> s
testGame Game s
g GRec
ts
                 in Game s
g { gInitState :: s
gInitState = s
s' }
                 -- xx qua messi solo [Event]?

-- | Similar to 'testGame', runs the game given a 'GRec'. Unlike
-- 'testGame', the playthrough will be displayed on screen. Useful when a
-- test fails and you want to see how.
--
-- See this in action with  @cabal run -f examples alone-playback@.
--
-- Notice that 'GEnv' will be provided at /run-time/, and not
-- record-time; this can make emulation slightly inaccurate if — e.g. —
-- you replay the game on a smaller terminal than the one you recorded
-- the session on.
narrateGame :: Game s -> GRec -> IO s
narrateGame :: forall s. Game s -> GRec -> IO s
narrateGame Game s
g GRec
e = forall a. Narrate a -> GRec -> IO a
runReplay (forall s (m :: * -> *). MonadGameIO m => Game s -> m s
runGameGeneral Game s
g) GRec
e

-- | Play as in 'playGame' and write the session to @file@. Useful to
-- produce input for 'testGame' and 'narrateGame'. Session will be
-- recorded even if an exception happens while playing.
recordGame :: Game s -> FilePath -> IO ()
recordGame :: forall s. Game s -> [Char] -> IO ()
recordGame Game s
g [Char]
fp =
        forall a b c. IO a -> (a -> IO b) -> (a -> IO c) -> IO c
E.bracket
          (forall a. a -> IO (MVar a)
CC.newMVar GRec
igrec)
          (\MVar GRec
ve -> [Char] -> MVar GRec -> IO ()
writeRec [Char]
fp MVar GRec
ve)
          (\MVar GRec
ve -> () forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ forall a. Record a -> MVar GRec -> IO a
runRecord (forall s (m :: * -> *). MonadGameIO m => Game s -> m s
runGameGeneral Game s
g) MVar GRec
ve)

data Config = Config { Config -> MVar [Event]
cMEvents :: CC.MVar [Event],
                       Config -> Integer
cTPS     :: TPS }

runGameGeneral :: forall s m. MonadGameIO m =>
                  Game s -> m s
runGameGeneral :: forall s (m :: * -> *). MonadGameIO m => Game s -> m s
runGameGeneral (Game Integer
tps s
s GEnv -> s -> Event -> s
lf GEnv -> s -> Plane
df s -> Bool
qf) =
            -- init
            forall (m :: * -> *). MonadDisplay m => m ()
setupDisplay    forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>>
            forall (m :: * -> *). MonadInput m => Integer -> m InputHandle
startEvents Integer
tps forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \(InputHandle MVar [Event]
ve [ThreadId]
ts) ->
            forall (m :: * -> *).
(MonadDisplay m, MonadException m) =>
m Dimensions
displaySizeErr  forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \Dimensions
ds ->

            -- do it!
            let c :: Config
c = MVar [Event] -> Integer -> Config
Config MVar [Event]
ve Integer
tps in
            forall (m :: * -> *) a b. MonadException m => m a -> m b -> m a
cleanUpErr (MonadGameIO m => Config -> Dimensions -> m s
game Config
c Dimensions
ds)
                            -- this under will be run regardless
                       (forall (m :: * -> *). MonadInput m => [ThreadId] -> m ()
stopEvents [ThreadId]
ts forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>>
                        forall (m :: * -> *). MonadDisplay m => m ()
shutdownDisplay  )
    where
          game :: MonadGameIO m => Config -> Dimensions -> m s
          game :: MonadGameIO m => Config -> Dimensions -> m s
game Config
c Dimensions
wds = forall (m :: * -> *) s.
MonadGameIO m =>
Config
-> s
-> (GEnv -> s -> Event -> s)
-> (GEnv -> s -> Plane)
-> (s -> Bool)
-> Maybe Plane
-> Dimensions
-> FPSCalc
-> m s
gameLoop Config
c s
s GEnv -> s -> Event -> s
lf GEnv -> s -> Plane
df s -> Bool
qf
                                forall a. Maybe a
Nothing Dimensions
wds
                                (Integer -> FPSCalc
creaFPSCalc Integer
tps)

-- | Wraps an @IO@ computation so that any 'ATGException' or 'error' gets
-- displayed along with a @\<press any key to quit\>@ prompt.
-- Some terminals shut-down immediately upon program end; adding
-- @errorPress@ to 'playGame' makes it easier to beta-test games on those
-- terminals.
errorPress :: IO a -> IO a
errorPress :: forall a. IO a -> IO a
errorPress IO a
m = forall a. IO a -> [Handler a] -> IO a
E.catches IO a
m [forall a e. Exception e => (e -> IO a) -> Handler a
E.Handler forall a. ErrorCall -> IO a
errorDisplay,
                            forall a e. Exception e => (e -> IO a) -> Handler a
E.Handler forall a. ATGException -> IO a
atgDisplay]
    where
          errorDisplay :: E.ErrorCall -> IO a
          errorDisplay :: forall a. ErrorCall -> IO a
errorDisplay (E.ErrorCallWithLocation [Char]
cs [Char]
l) = forall a. IO () -> IO a
report forall a b. (a -> b) -> a -> b
$
              [Char] -> IO ()
putStrLn ([Char]
cs forall a. [a] -> [a] -> [a]
++ [Char]
"\n\n")        forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>>
              [Char] -> IO ()
putStrLn [Char]
"Stack trace info:\n" forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>>
              [Char] -> IO ()
putStrLn [Char]
l

          atgDisplay :: ATGException -> IO a
          atgDisplay :: forall a. ATGException -> IO a
atgDisplay ATGException
e = forall a. IO () -> IO a
report forall a b. (a -> b) -> a -> b
$ forall a. Show a => a -> IO ()
print ATGException
e

          report :: IO () -> IO a
          report :: forall a. IO () -> IO a
report IO ()
wm =
              [Char] -> IO ()
putStrLn [Char]
"ERROR REPORT\n"                forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>>
              IO ()
wm                                       forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>>
              [Char] -> IO ()
putStrLn [Char]
"\n\n <Press any key to quit>"  forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>>
              Handle -> BufferMode -> IO ()
SI.hSetBuffering Handle
SI.stdin BufferMode
SI.NoBuffering forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>>
              IO Char
getChar                                  forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>>
              forall a. [Char] -> a
errorWithoutStackTrace [Char]
"errorPress"


-----------
-- LOGIC --
-----------

-- from http://www.loomsoft.net/resources/alltut/alltut_lesson6.htm
gameLoop :: MonadGameIO m     =>
            Config            -> -- event source
            s                 -> -- state
            (GEnv ->
             s -> Event -> s) -> -- logic function
            (GEnv ->
             s -> Plane)      -> -- draw function
            (s -> Bool)       -> -- quit? function
            Maybe Plane       -> -- last blitted screen
            Dimensions        -> -- Term dimensions
            FPSCalc           -> -- calculate fps
            m s
gameLoop :: forall (m :: * -> *) s.
MonadGameIO m =>
Config
-> s
-> (GEnv -> s -> Event -> s)
-> (GEnv -> s -> Plane)
-> (s -> Bool)
-> Maybe Plane
-> Dimensions
-> FPSCalc
-> m s
gameLoop Config
c s
s GEnv -> s -> Event -> s
lf GEnv -> s -> Plane
df s -> Bool
qf Maybe Plane
opln Dimensions
td FPSCalc
fps =

        -- quit?
        forall (m :: * -> *) s. MonadLogic m => (s -> Bool) -> s -> m Bool
checkQuit s -> Bool
qf s
s forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \Bool
qb ->
        if Bool
qb
          then forall (m :: * -> *) a. Monad m => a -> m a
return s
s
        else

        -- fetch events (if any)
        forall (m :: * -> *). MonadInput m => MVar [Event] -> m [Event]
pollEvents (Config -> MVar [Event]
cMEvents Config
c) forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \[Event]
es ->

        -- no events? skip everything
        if forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Event]
es
          then forall (m :: * -> *). MonadTimer m => Integer -> m ()
sleepABit (Config -> Integer
cTPS Config
c)               forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>>
               forall (m :: * -> *) s.
MonadGameIO m =>
Config
-> s
-> (GEnv -> s -> Event -> s)
-> (GEnv -> s -> Plane)
-> (s -> Bool)
-> Maybe Plane
-> Dimensions
-> FPSCalc
-> m s
gameLoop Config
c s
s GEnv -> s -> Event -> s
lf GEnv -> s -> Plane
df s -> Bool
qf Maybe Plane
opln Dimensions
td FPSCalc
fps
        else

        forall (m :: * -> *).
(MonadDisplay m, MonadException m) =>
m Dimensions
displaySizeErr            forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \Dimensions
td' ->

        -- logic
        let ge :: GEnv
ge = Dimensions -> Integer -> GEnv
GEnv Dimensions
td' (FPSCalc -> Integer
calcFPS FPSCalc
fps)
            (Integer
i, s
s') = forall s. s -> (s -> Event -> s) -> [Event] -> (Integer, s)
stepsLogic s
s (GEnv -> s -> Event -> s
lf GEnv
ge) [Event]
es in

        -- no `Tick` events? You do not need to blit, just update state
        if Integer
i forall a. Eq a => a -> a -> Bool
== Integer
0
          then forall (m :: * -> *) s.
MonadGameIO m =>
Config
-> s
-> (GEnv -> s -> Event -> s)
-> (GEnv -> s -> Plane)
-> (s -> Bool)
-> Maybe Plane
-> Dimensions
-> FPSCalc
-> m s
gameLoop Config
c s
s' GEnv -> s -> Event -> s
lf GEnv -> s -> Plane
df s -> Bool
qf Maybe Plane
opln Dimensions
td FPSCalc
fps
        else

        -- FPS calc
        let fps' :: FPSCalc
fps' = Integer -> FPSCalc -> FPSCalc
addFPS Integer
i FPSCalc
fps in

        -- clear screen if resolution changed
        let resc :: Bool
resc = Dimensions
td forall a. Eq a => a -> a -> Bool
/= Dimensions
td' in
        forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
CM.when Bool
resc forall (m :: * -> *). MonadDisplay m => m ()
clearDisplay forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>>

        -- draw
        let opln' :: Maybe Plane
opln' | Bool
resc = forall a. Maybe a
Nothing -- res changed? restart double buffering
                  | Bool
otherwise = Maybe Plane
opln
            npln :: Plane
npln = GEnv -> s -> Plane
df GEnv
ge s
s' in

        forall (m :: * -> *).
MonadDisplay m =>
Maybe Plane -> Plane -> m ()
blitPlane Maybe Plane
opln' Plane
npln forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>>

        forall (m :: * -> *) s.
MonadGameIO m =>
Config
-> s
-> (GEnv -> s -> Event -> s)
-> (GEnv -> s -> Plane)
-> (s -> Bool)
-> Maybe Plane
-> Dimensions
-> FPSCalc
-> m s
gameLoop Config
c s
s' GEnv -> s -> Event -> s
lf GEnv -> s -> Plane
df s -> Bool
qf (forall a. a -> Maybe a
Just Plane
npln) Dimensions
td' FPSCalc
fps'

-- Int = number of `Tick` events
stepsLogic :: s -> (s -> Event -> s) -> [Event] -> (Integer, s)
stepsLogic :: forall s. s -> (s -> Event -> s) -> [Event] -> (Integer, s)
stepsLogic s
s s -> Event -> s
lf [Event]
es = let ies :: Integer
ies = forall i a. Num i => [a] -> i
D.genericLength forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. (a -> Bool) -> [a] -> [a]
filter Event -> Bool
isTick forall a b. (a -> b) -> a -> b
$ [Event]
es
                     in (Integer
ies, forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl s -> Event -> s
lf s
s [Event]
es)
    where
          isTick :: Event -> Bool
isTick Event
Tick = Bool
True
          isTick Event
_    = Bool
False

-------------------------------------------------------------------------------
-- Frame per Seconds

data FPSCalc = FPSCalc [Integer] TPS
    -- list with number of `Ticks` processed at each blit and expected
    -- FPS (i.e. TPS)

-- the size of moving average will be TPS (that simplifies calculations)
creaFPSCalc :: TPS -> FPSCalc
creaFPSCalc :: Integer -> FPSCalc
creaFPSCalc Integer
tps = [Integer] -> Integer -> FPSCalc
FPSCalc (forall i a. Integral i => i -> a -> [a]
D.genericReplicate Integer
tps {- (tps*2) -} Integer
1) Integer
tps
    -- tps*1: size of thw window in **blit actions** (not tick actions!)
    --        so keeping it small should be responsive and non flickery
    --        at the same time!

-- add ticks
addFPS :: Integer -> FPSCalc -> FPSCalc
addFPS :: Integer -> FPSCalc -> FPSCalc
addFPS Integer
nt (FPSCalc (Integer
_:[Integer]
fps) Integer
tps) = [Integer] -> Integer -> FPSCalc
FPSCalc ([Integer]
fps forall a. [a] -> [a] -> [a]
++ [Integer
nt]) Integer
tps
addFPS Integer
_ (FPSCalc [] Integer
_) = forall a. HasCallStack => [Char] -> a
error [Char]
"addFPS: empty list."

calcFPS :: FPSCalc -> Integer
calcFPS :: FPSCalc -> Integer
calcFPS (FPSCalc [Integer]
fps Integer
tps) =
        let ts :: Integer
ts = forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [Integer]
fps
            ds :: Integer
ds = forall i a. Num i => [a] -> i
D.genericLength [Integer]
fps
        in Integer -> Integer -> Integer
roundQuot (Integer
tps forall a. Num a => a -> a -> a
* Integer
ds) Integer
ts
    where
          roundQuot :: Integer -> Integer -> Integer
          roundQuot :: Integer -> Integer -> Integer
roundQuot Integer
a Integer
b = let (Integer
q, Integer
r) = forall a. Integral a => a -> a -> (a, a)
quotRem Integer
a Integer
b
                          in Integer
q forall a. Num a => a -> a -> a
+ forall a. a -> a -> Bool -> a
B.bool Integer
0 Integer
1 (Integer
r forall a. Ord a => a -> a -> Bool
> forall a. Integral a => a -> a -> a
div Integer
b Integer
2)