packages feed

mischief-live (empty) → 0.1.0.0

raw patch · 12 files changed

+946/−0 lines, 12 filesdep +basedep +containersdep +directory

Dependencies added: base, containers, directory, exceptions, fsnotify, hint, mischief-assets, mischief-ecs, mischief-live, mischief-math, mischief-render, primitive, stm, text

Files

+ CHANGELOG.md view
@@ -0,0 +1,5 @@+# Revision history for mischief-live ++## 0.1.0.0 ++* First version. Released on an unsuspecting world.
+ LICENSE view
@@ -0,0 +1,29 @@+Copyright (c) 2026, Damon+++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++    * Redistributions of source code must retain the above copyright+      notice, this list of conditions and the following disclaimer.++    * Redistributions in binary form must reproduce the above+      copyright notice, this list of conditions and the following+      disclaimer in the documentation and/or other materials provided+      with the distribution.++    * Neither the name of the copyright holder nor the names of its+      contributors may be used to endorse or promote products derived+      from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ README.md view
@@ -0,0 +1,4 @@+# mischief-live++This is a lightweight library that adds live coding capabilities to the Mischief game engine. Read the +`Live` module above for more information.  
+ examples/shader/common/ShaderCommon.hs view
@@ -0,0 +1,28 @@+module ShaderCommon where++import Mischief.Materials+import Mischief.Materials.Sprite (SpriteMaterial)+import Mischief.Materials.Sprite qualified as Sprite+import Mischief.Materials.Time (TimeMaterial)+import Prelude ()++data CustomMaterial++data Bindings f = Bindings deriving (Generic, Bindable)++instance Material CustomMaterial where+  type VI CustomMaterial = Sprite.VertexInput+  type VO CustomMaterial = Sprite.VertexOutput+  type B CustomMaterial = Bindings++  type Extends CustomMaterial = '[SpriteMaterial, TimeMaterial]++  vertex = liftExt . vertex @SpriteMaterial+  fragment = liftExt . fragment @SpriteMaterial+  fetch = FetchBindings (const $ pure ()) (const $ pure ()) (const $ const Bindings)++newtype Input = Input (VO SpriteMaterial GPU)++newtype Output = Output (Vec4 Float)++newtype ShaderOutput = ShaderOutput (Shader CustomMaterial Output)
+ examples/shader/live/Live.hs view
@@ -0,0 +1,39 @@+module Live where++import Mischief.Materials+import Mischief.Materials.Sprite+import Mischief.Materials.Time (getTime)+import Mischief.Render.Camera (Camera, CameraZoom (CameraZoom))+import ShaderCommon (CustomMaterial)+import Prelude ()++customFrag :: Vec2 Float -> Shader CustomMaterial (Vec4 Float)+customFrag uv = do+  col <- liftExt $ sampleSprite uv++  s <- extension @SpriteMaterial+  let dim = s.sprite.size++  uv <- var $ floor (uv * dim) / dim+  i <- var $ floor (uv.y / uv.x * 5) / 5++  time <- liftExt getTime+  i <- var $ i + time+  t <- trans $ cast i % 5++  pure $ col * t++trans :: Int -> Shader CustomMaterial (Vec4 Float)+trans i =+  (+: 1)+    . (^/ 256)+    <$> pick+      [ (i == 0, pure $ vec3 91 207 250),+        (i == 1, pure $ vec3 245 171 185),+        (i == 2, pure $ vec3 255 255 255),+        (i == 3, pure $ vec3 245 171 185)+      ]+      (pure $ vec3 91 207 250)++zoom :: System ()+zoom = query_ $ qinsert (const $ CameraZoom 10) [q|E / With Camera|]
+ examples/shader/main/Main.hs view
@@ -0,0 +1,74 @@+module Main where++import Data.Foldable+import Mischief.Animation+import Mischief.Assets+import Mischief.ECS+import Mischief.Live+import Mischief.Materials.Sprite qualified as S+import Mischief.Math+import Mischief.Render+import Mischief.Render.Camera (CameraBackground (..), CameraZoom (..))+import Mischief.Render.Material.Pipeline (updateFragment)+import ShaderCommon (CustomMaterial)++main :: IO ()+main = do+  app <- newApp+  setAssetSource "assets/" app+  attachLive "./mischief-live/examples/shader/live" ["Live.hs"] def app+  addPlugin @P app+  runApp app++data P++instance Plugin P where+  init = do+    schedule @Startup $ systems setup+    schedule @Update $ systems update+    schedule @RenderUpdate $ systems $ renderSortedMaterial @CustomMaterial def {defaultSampler = sampler @PixelSampler} pickY++  deps = [dep @RenderPlugin, dep @AnimationPlugin]++pickY :: Entity -> Query System Float+pickY e = do+  t <- qget e [Mischief.ECS.qd|Transform|]+  pure (-t.translation.y)++setup :: System ()+setup = do+  window <- spawn Window+  spawn_ (Camera, Rel {comp = OutputTo, target = window}, CameraZoom 8, CameraBackground 0.01, def {translation = V3 0 7 0})+  spawn_ (Animator RatAnimator, WithMaterial @CustomMaterial)+  spawn_ (Animator RatAnimator, WithMaterial @CustomMaterial, def {translation = V3 (-7) 17 0}, SpriteFlip {x = False, y = True})+  spawn_ (Animator RatAnimator, WithMaterial @CustomMaterial, def {translation = V3 23 (-10) 0})+  spawn_ (Animator RatAnimator, WithMaterial @CustomMaterial, def {translation = V3 (-15) (-12) 0}, SpriteFlip {x = False, y = True})+  spawn_ (Animator RatAnimator, WithMaterial @CustomMaterial, def {translation = V3 (-25) 5 0}, SpriteFlip {x = False, y = True})+  spawn_ (Animator RatAnimator, WithMaterial @CustomMaterial, def {translation = V3 18 10 0})++  query_ $ do+    e <- [q|E / With Animator|]+    qlift $ insert (Anchor $ V2 0.5 1) e++update :: System ()+update = do+  x <- liveIfChanged "Live" "customFrag"+  for_ x $ \x -> updateFragment @CustomMaterial $ \i -> do x i.uv++  -- [q|CameraZoom|] & qinsert (const $ CameraZoom 15) & query_++  s <- liveIfChanged @(System ()) "Live" "zoom"+  for_ s id++-- for_ y $ \y -> [q|CameraZoom|] & qinsert (const $ CameraZoom y) & query_++data RatAnimator = RatAnimator++instance AnimatorTag RatAnimator where+  data State RatAnimator = State+  data Input RatAnimator = Input deriving (Generic, Default)+  data Shift RatAnimator = Shift++  animation State = selAnim "rats/rat-animations.kdl" "rat3"++  start = State
+ examples/simple/common/Common.hs view
@@ -0,0 +1,7 @@+module Common where++import Mischief.ECS++newtype Health = Health Int+  deriving stock (Show)+  deriving anyclass (Component)
+ examples/simple/live/Live.hs view
@@ -0,0 +1,7 @@+module Live where++import Common (Health (..))+import Mischief.ECS++y :: System ()+y = insertRes $ Health 10
+ examples/simple/main/Main.hs view
@@ -0,0 +1,26 @@+module Main where++import Common (Health (Health))+import Data.Text qualified as T+import Mischief.ECS+import Mischief.Live++main :: IO ()+main = do+  app <- newApp+  attachLive "./mischief-live/examples/simple/live" ["Live.hs"] def app+  addPlugin @P app+  runApp app++data P++instance Plugin P where+  init =+    schedule @Update $ systems (update, showHealth)++update :: System ()+update = do+  unwrap =<< live "Live" "y"++showHealth :: System ()+showHealth = info . T.show =<< res @Health
+ mischief-live.cabal view
@@ -0,0 +1,335 @@+cabal-version: 3.0+-- The cabal-version field refers to the version of the .cabal specification,+-- and can be different from the cabal-install (the tool) version and the+-- Cabal (the library) version you are using. As such, the Cabal (the library)+-- version used must be equal or greater than the version stated in this field.+-- Starting from the specification version 2.2, the cabal-version field must be+-- the first thing in the cabal file.+-- Initial package description 'mischief' generated by+-- 'cabal init'. For further documentation, see:+--   http://haskell.org/cabal/users-guide/+--+-- The name of the package.+name: mischief-live+-- The package version.+-- See the Haskell package versioning policy (PVP) for standards+-- guiding when and how versions should be incremented.+-- https://pvp.haskell.org+-- PVP summary:     +-+------- breaking API changes+--                  | | +----- non-breaking API additions+--                  | | | +--- code changes with no API change+version: 0.1.0.0+-- A short (one-line) description of the package.+-- synopsis:+-- A longer description of the package.+-- description:+-- The license under which the package is released.+license: BSD-3-Clause+-- The file containing the license text.+license-file: LICENSE+-- The package author(s).+author: Damon+-- An email address to which users can send suggestions, bug reports, and patches.+maintainer: pvdoriginal2019@gmail.com+homepage: https://codeberg.org/mischief/mischief+synopsis: Live Coding for the Mischief Game Engine.+-- A copyright notice.+-- copyright:+build-type: Simple+-- Extra doc files to be distributed with the package, such as a CHANGELOG or a README.+extra-doc-files:+  CHANGELOG.md+  README.md++-- Extra source files to be distributed with the package, such as examples, or a tutorial module.+-- extra-source-files:+common warnings+  ghc-options:+    "-Wall,"+    -Wno-name-shadowing++library+  -- Import common warning flags.+  import: warnings+  -- Modules exported by the library.+  exposed-modules:+    Mischief.Live++  -- Modules included in this library but not exported.+  -- other-modules:+  other-modules:+    Mischief.Live.Interpreter++  -- LANGUAGE extensions used by modules in this package.z+  default-extensions:+    DefaultSignatures+    DeriveAnyClass+    DuplicateRecordFields+    FunctionalDependencies+    ImportQualifiedPost+    MagicHash+    NoFieldSelectors+    OverloadedRecordDot+    OverloadedStrings+    QuasiQuotes+    RequiredTypeArguments+    TemplateHaskell+    TypeFamilyDependencies+    UndecidableInstances++  -- other-extensions:+  -- Other library packages from which modules are imported.+  build-depends:+    base >=4.21.0 && <4.22,+    containers >=0.7 && <0.8,+    directory >=1.3.9 && <1.4,+    exceptions >=0.10.9 && <0.11,+    fsnotify >=0.4.4 && <0.5,+    hint >=0.9.0 && <0.10,+    mischief-ecs >=0.2.1 && <0.3,+    primitive >=0.9.1 && <0.10,+    stm >=2.5.3 && <2.6,+    text >=2.1.2 && <2.2,++  -- Directories containing source files.+  hs-source-dirs:+    src++  -- Base language which the package is written in.+  default-language:+    GHC2024++  ghc-options: -fno-omit-yields++library example-simple-common+  -- Import common warning flags.+  import: warnings+  -- Modules exported by the library.+  exposed-modules:+    Common++  -- Modules included in this library but not exported.+  -- other-modules:+  other-modules:+  -- LANGUAGE extensions used by modules in this package.z+  default-extensions:+    DefaultSignatures+    DeriveAnyClass+    DuplicateRecordFields+    FunctionalDependencies+    ImportQualifiedPost+    MagicHash+    NoFieldSelectors+    OverloadedRecordDot+    OverloadedStrings+    QuasiQuotes+    RequiredTypeArguments+    TemplateHaskell+    TypeFamilyDependencies+    UndecidableInstances++  -- other-extensions:+  -- Other library packages from which modules are imported.+  build-depends:+    base >=4.21.0 && <4.22,+    mischief-ecs,++  -- Directories containing source files.+  hs-source-dirs:+    examples/simple/common++  -- Base language which the package is written in.+  default-language:+    GHC2024++  ghc-options: -fno-omit-yields++executable example-simple+  -- .hs or .lhs file containing the Main module.+  main-is: Main.hs+  -- Modules included in this executable, other than Main.+  other-modules:+    -- OtherModule.hs+  -- LANGUAGE extensions used by modules in this package.+  default-extensions:+    DeriveAnyClass+    DerivingStrategies+    DuplicateRecordFields+    ImportQualifiedPost+    MultiWayIf+    NoFieldSelectors+    OverloadedRecordDot+    OverloadedStrings+    QuasiQuotes+    TypeFamilyDependencies++  -- Other library packages from which modules are imported.+  build-depends:+    base ^>=4.21,+    directory,+    hint,+    mischief-ecs,+    mischief-live,+    mischief-live:example-simple-common,+    text,+    -- mischief-assets ^>=0.1,+    -- mischief-input ^>=0.1,+    -- mischief-math ^>=0.1,+    -- mischief-render ^>=0.1,++  -- Directories containing source files.+  hs-source-dirs: examples/simple/main+  -- Base language which the package is written in.+  default-language: GHC2024++library example-simple-live+  exposed-modules:+    Live++  -- LANGUAGE extensions used by modules in this package.+  default-extensions:+    DeriveAnyClass+    DerivingStrategies+    DuplicateRecordFields+    ImportQualifiedPost+    MultiWayIf+    NoFieldSelectors+    OverloadedRecordDot+    OverloadedStrings+    QuasiQuotes+    TypeFamilyDependencies++  -- Other library packages from which modules are imported.+  build-depends:+    base ^>=4.21,+    mischief-ecs,+    mischief-live:example-simple-common,+    text,+    -- mischief-assets ^>=0.1,+    -- mischief-input ^>=0.1,+    -- mischief-math ^>=0.1,+    -- mischief-render ^>=0.1,++  -- Directories containing source files.+  hs-source-dirs: examples/simple/live+  -- Base language which the package is written in.+  default-language: GHC2024++library example-shader-common+  -- Import common warning flags.+  import: warnings+  -- Modules exported by the library.+  exposed-modules:+    ShaderCommon++  -- Modules included in this library but not exported.+  -- other-modules:+  other-modules:+  -- LANGUAGE extensions used by modules in this package.z+  default-extensions:+    DefaultSignatures+    DeriveAnyClass+    DuplicateRecordFields+    FunctionalDependencies+    ImportQualifiedPost+    MagicHash+    NoFieldSelectors+    OverloadedRecordDot+    OverloadedStrings+    QuasiQuotes+    RequiredTypeArguments+    TemplateHaskell+    TypeFamilyDependencies+    UndecidableInstances++  -- other-extensions:+  -- Other library packages from which modules are imported.+  build-depends:+    base ^>=4.21,+    mischief-ecs,+    mischief-render,++  -- Directories containing source files.+  hs-source-dirs:+    examples/shader/common++  -- Base language which the package is written in.+  default-language:+    GHC2024++  ghc-options: -fno-omit-yields++executable example-shader+  -- .hs or .lhs file containing the Main module.+  main-is: Main.hs+  -- Modules included in this executable, other than Main.+  other-modules:+    -- OtherModule.hs+  -- LANGUAGE extensions used by modules in this package.+  default-extensions:+    DeriveAnyClass+    DerivingStrategies+    DuplicateRecordFields+    ImportQualifiedPost+    MultiWayIf+    NoFieldSelectors+    OverloadedRecordDot+    OverloadedStrings+    QuasiQuotes+    TypeFamilyDependencies++  -- Other library packages from which modules are imported.+  build-depends:+    base ^>=4.21,+    directory,+    hint,+    mischief-assets,+    mischief-ecs,+    mischief-live,+    mischief-live:example-shader-common,+    mischief-math,+    mischief-render,+    text,+    -- mischief-assets ^>=0.1,+    -- mischief-input ^>=0.1,+    -- mischief-math ^>=0.1,+    -- mischief-render ^>=0.1,++  -- Directories containing source files.+  hs-source-dirs: examples/shader/main+  -- Base language which the package is written in.+  default-language: GHC2024++library example-shader-live+  exposed-modules:+    Live++  -- LANGUAGE extensions used by modules in this package.+  default-extensions:+    DeriveAnyClass+    DerivingStrategies+    DuplicateRecordFields+    ImportQualifiedPost+    MultiWayIf+    NoFieldSelectors+    OverloadedRecordDot+    OverloadedStrings+    QuasiQuotes+    TypeFamilyDependencies++  -- Other library packages from which modules are imported.+  build-depends:+    base ^>=4.21,+    mischief-ecs,+    mischief-live:example-shader-common,+    mischief-render,+    text,+    -- mischief-assets ^>=0.1,+    -- mischief-input ^>=0.1,+    -- mischief-math ^>=0.1,+    -- mischief-render ^>=0.1,++  -- Directories containing source files.+  hs-source-dirs: examples/shader/live+  -- Base language which the package is written in.+  default-language: GHC2024
+ src/Mischief/Live.hs view
@@ -0,0 +1,321 @@+{-# LANGUAGE AllowAmbiguousTypes #-}++module Mischief.Live+  ( -- * Mischief Live+    -- $intro++    -- * Project Structure+    -- $structure++    -- * How to Run+    -- $run++    -- * How to Use+    -- $how++    -- * Extensions+    -- $extensions++    -- * Preparing for Release+    -- $release+    attachLive,+    live,+    LiveExtensions (..),+    Extension,+    OnLiveLoad,+    liveIfChanged,+    ghc2024Extensions,+  )+where++import Control.Concurrent+import Control.Concurrent.STM+import Control.Monad+import Data.Data (Proxy (Proxy), TypeRep, Typeable, typeRep)+import Data.Foldable (for_)+import Data.Map (Map)+import Data.Map qualified as Map+import Language.Haskell.Interpreter+import Mischief.ECS+import Mischief.ECS.App (App (..))+import Mischief.ECS.Resources (modifyRes')+import Mischief.ECS.World (SystemAny (systemAny), World (..), runSystem)+import Mischief.Live.Interpreter+import System.Directory+import System.FSNotify+import Unsafe.Coerce++newtype LiveExtensions = LiveExtensions [Extension] deriving newtype (Semigroup)++instance Default LiveExtensions where+  def =+    ghc2024Extensions+      <> LiveExtensions+        [ DeriveAnyClass,+          UnknownExtension "DerivingStrategies",+          DuplicateRecordFields,+          UnknownExtension "ImportQualifiedPost",+          MultiWayIf,+          UnknownExtension "NoFieldSelectors",+          UnknownExtension "OverloadedRecordDot",+          OverloadedStrings,+          QuasiQuotes,+          TypeFamilyDependencies+        ]++ghc2024Extensions :: LiveExtensions+ghc2024Extensions =+  LiveExtensions+    [ BangPatterns,+      BinaryLiterals,+      ConstrainedClassMethods,+      ConstraintKinds,+      DataKinds,+      DeriveDataTypeable,+      DeriveFoldable,+      DeriveFunctor,+      DeriveGeneric,+      DeriveLift,+      DeriveTraversable,+      UnknownExtension "DerivingStrategies",+      DisambiguateRecordFields,+      DoAndIfThenElse,+      EmptyCase,+      EmptyDataDecls,+      UnknownExtension "EmptyDataDeriving",+      ExistentialQuantification,+      ExplicitForAll,+      ExplicitNamespaces,+      UnknownExtension "FieldSelectors",+      FlexibleContexts,+      FlexibleInstances,+      ForeignFunctionInterface,+      GADTs,+      GADTSyntax,+      UnknownExtension "GeneralisedNewtypeDeriving",+      UnknownExtension "HexFloatLiterals",+      ImplicitPrelude,+      UnknownExtension "ImportQualifiedPost",+      InstanceSigs,+      KindSignatures,+      LambdaCase,+      MonoLocalBinds,+      MonomorphismRestriction,+      MultiParamTypeClasses,+      NamedFieldPuns,+      NamedWildCards,+      UnknownExtension "NumericUnderscores",+      PatternGuards,+      PolyKinds,+      PostfixOperators,+      RankNTypes,+      RelaxedPolyRec,+      RoleAnnotations,+      ScopedTypeVariables,+      StandaloneDeriving,+      UnknownExtension "StandaloneKindSignatures",+      UnknownExtension "StarIsType",+      TraditionalRecordSyntax,+      TupleSections,+      TypeApplications,+      TypeOperators,+      TypeSynonymInstances+    ]++attachLive :: FilePath -> [FilePath] -> LiveExtensions -> App -> IO ()+attachLive path files (LiveExtensions ext) app = do+  path <- makeAbsolute path+  -- paths <- getFilesRecursively path+  chanReq <- newBroadcastTChanIO++  chanReqRead <- atomically $ dupTChan chanReq++  runSystem (insertRes $ InterpreterChan chanReq) app.world+  -- runSystem (insertRes $ LivePaths $ path :| paths) app.world++  runSystem (insertRes $ LiveRegistry Map.empty) app.world++  void $ forkIO $ withCurrentDirectory path $ interpreterInit files ext chanReqRead+  void $ forkIO $ withManager $ watcher app.world path++watcher :: World -> FilePath -> WatchManager -> IO ()+watcher World {deferredAsync} dir mgr = do+  void $ watchTree mgr dir (const True) $ const $ atomically $ do+    modifyTVar' deferredAsync (++ [resetLiveCode])++  forever $ threadDelay 10000000000000000++resetLiveCode :: System ()+resetLiveCode = do+  Just (InterpreterChan chanReq) <- res+  -- reset <- liftIO $ atomically $ do+  --   p <- peekTChan chanReq+  --   case p of+  --     Reset -> pure False+  --     _ -> True <$ writeTChan chanReq Reset++  -- when reset $ do+  liftIO $ atomically $ writeTChan chanReq Reset+  insertRes $ LiveRegistry Map.empty+  trigger OnLiveLoad++data LiveKey = LiveKey+  { moduleName :: String,+    valName :: String,+    valType :: TypeRep+  }+  deriving (Eq, Ord)++data LiveValue where+  LiveValue :: (Typeable a) => a -> LiveValue++newtype LiveRegistry = LiveRegistry (Map LiveKey LiveValue) deriving anyclass (Component)++live :: forall a m w. (Typeable a, MonadSystem w m) => ModuleName -> String -> m (Maybe a)+live m f = do+  Just (InterpreterChan chanReq) <- res++  Just (LiveRegistry reg) <- res++  let key = LiveKey {moduleName = m, valName = f, valType = typeRep $ Proxy @a}++  case Map.lookup key reg of+    Just (LiveValue val) -> pure $ Just $ unsafeCoerce val+    Nothing -> do+      a <- liftIO $ do+        t <- newTMVarIO AwaitingResult+        atomically $ writeTChan chanReq (Request m f t)+        waitForResult t++      for_ a $ \a -> do+        let s = modifyRes' $ \(LiveRegistry m) -> LiveRegistry $ Map.insert key (LiveValue a) m+        systemAny s (defer s)++      pure a++liveIfChanged :: forall a m w. (Typeable a, MonadSystem w m) => ModuleName -> String -> m (Maybe a)+liveIfChanged m f = do+  Just (InterpreterChan chanReq) <- res++  Just (LiveRegistry reg) <- res++  let key = LiveKey {moduleName = m, valName = f, valType = typeRep $ Proxy @a}++  case Map.lookup key reg of+    Just _ -> pure Nothing+    Nothing -> do+      a <- liftIO $ do+        t <- newTMVarIO AwaitingResult+        atomically $ writeTChan chanReq (Request m f t)+        waitForResult t++      for_ a $ \a -> do+        let s = modifyRes' $ \(LiveRegistry m) -> LiveRegistry $ Map.insert key (LiveValue a) m+        systemAny s (defer s)++      pure a++waitForResult :: TMVar (Result a) -> IO (Maybe a)+waitForResult t = do+  x <- atomically $ readTMVar t+  case x of+    Result a -> pure $ Just $ unsafeCoerce a+    NoResult -> pure Nothing+    AwaitingResult -> waitForResult t++data OnLiveLoad = OnLiveLoad deriving (Mischief.ECS.Event)++-- $intro+-- This library is a lightweight, yet powerful, addition to the core ECS library. It enables a form of live coding+-- by running a background interpreter over the code from a chosen target, letting you modify the functions from it+-- during the runtime of your main compiled library.++-- $structure+-- I will be describing the general recommended structure of a mischief app that uses this library. It is also recommended to+-- look at or clone one of the @-live@ branches in the [template repository](https://codeberg.org/mischief/template) for a more concrete example+-- or starting point.+--+-- In order to properly use this library, you will need at least one library besides your executable (the main \"library\" that you're running). You can define+-- it in your @.cabal@ file. In the template, this library is generally named @live@, with it's starting point in a @Live.hs@ module.+--+-- In this live library you can write any code that you wish to be able to freely change at runtime. Systems, shaders, and so on.+--+-- Your executable cannot depend on the live library, and the live library cannot depend on your executable. Because of this restriction, it is+-- recommended to create a third library, containing the /common/ logic and definitions that you wish both the executable and the live library to see.+-- You'll generally define types, such as components and materials in this common library.++-- $run+-- In order to run your executable, you should use the following command:+--+-- @+-- cabal run --write-ghc-environment-files=always --enable-shared --enable-executable-dynamic+-- @+--+-- The first flag will write an environment file which the interpreter can read to see all dependencies. The other two+-- ensure your local libraries are compiled dynamically so that the interpreter can access them. These are very important! GHC+-- is likely to be stuck in the linking phase if you depend on @mischief-live@ and don't compile your code dynamically!+--+-- On windows you may also need to add the @-fthreaded@ flag, as this library uses [fsnotify](https://hackage.haskell.org/package/fsnotify) for reacting to file changes.++-- $how+-- This library's API is really simple! It only has two functions you need to be aware of.+--+-- First, you need to use @attachLive@ to attach the interpreter to your app before running it:+--+-- @+-- app <- 'newApp'+-- 'attachLive' \".\/live\/" [\"Live.hs\"] 'def' app+-- @+--+-- The first parameter is the directory where your live library is located. The second is a list of+-- files to load when initializing the interpreter, relative to the previous path. There is also+-- a list of extensions you need to pass, but more on that later, @def@ is usually enough.+--+-- Second, there is the main primitive introduces by this library, @live@:+--+-- @+-- x <- 'live' \@'Int' \"Live\" \"myInt\"+-- @+--+-- The @live@ function takes a module name and a top-level function from that module, and produces its latest value. In this case,+-- the @Live@ module is expected to look something like this:+--+-- @+-- module Live where+--+--   myInt :: 'Int'+--   myInt = 3+-- @+--+-- The @\@Int@ type hint is optional, @live@ usually infers the value.+--+-- This function is smart. It caches the functions you've already requested, so it only interprets them the first time you ask for them, at the+-- start of the app or after you made a change to the live library.+--+-- There is also the @'liveIfChanged'@ function which will return a value only if this is the first time you're asking for it since the last change in the live library.+--+-- The @'OnLiveLoad'@ event is triggered each time a change in the live library is detected and the interpreter is reset.++-- $extenions+-- A list of language extensions that are applied when interpreting the live library need to be provided. The Default instance+-- adds all the extensions enabled by default by @ghc2024@, as well as the set of extensions recommended by Mischief. You can see+-- the exact list in the source of this file!+--+-- In order to customize the list of extensions, you can use the 'ghc2024Extensions' and the 'def' as a starting point, adding more extensions on top. For instance:+--+-- @+-- myExtensions :: 'LiveExtensions'+-- myExtensions = 'ghc2024Extensions' <> LiveExtensions ['UndecidableInstances']+-- @+--+-- You should set these to match the extensions listed under your live library in the @.cabal@ file.++-- $release+-- When releasing your app, you'll want to comment out the @mischief-live@ dependencies in your @.cabal@ file, and compile your+-- app normally, without the dynamic flags.+--+-- The simplest approach to ensure your app still works as expected with minimal refactoring is to have your executable depend on the+-- live library and import it, replacing all the @live@ calls with actual calls to the relevant functions.+--+-- Options are being considered for streamlining this process, such as a macro that can smartly switch between @live@ and the+-- direct calls. Your feedback and ideas are appreciated!
+ src/Mischief/Live/Interpreter.hs view
@@ -0,0 +1,71 @@+module Mischief.Live.Interpreter where++import Control.Concurrent+import Control.Concurrent.STM+import Control.Monad+import Control.Monad.Catch+import Data.Data (Proxy (..))+import Data.Foldable (for_)+import Data.Typeable (Typeable)+import Language.Haskell.Interpreter+import Mischief.ECS+import System.Directory (withCurrentDirectory)++data Request where+  Request :: forall a. (Typeable a) => ModuleName -> String -> TMVar (Result a) -> Request+  Reset :: Request++data Result a = Result a | NoResult | AwaitingResult++newtype InterpreterChan = InterpreterChan (TChan Request) deriving anyclass (Component)++interpreterInit :: [FilePath] -> [Extension] -> TChan Request -> IO ()+interpreterInit files ext req = do+  result <- runInterpreter $ do+    set [languageExtensions := ext]+    loadModules files+    interpreterLoop req++  case result of+    Right _ -> do+      putStrLn "Reloading Live Code.."+      interpreterInit files ext req+    Left e -> do+      putStrLn $ "Live Code Error: " ++ show e+      interpreterInit files ext req++interpreterLoop :: TChan Request -> Interpreter ()+interpreterLoop req = do+  request <- liftIO $ atomically $ readTChan req++  case request of+    Request mod f (v :: TMVar (Result a)) -> do+      -- liftIO $ putStrLn "received request"+      result <- tryRequest @a mod f+      liftIO $ atomically $ writeTMVar v result++      interpreterLoop req+    Reset -> liftIO $ atomically $ tryConsumeResets req++tryConsumeResets :: TChan Request -> STM ()+tryConsumeResets t = do+  reset <- tryPeekTChan t+  case reset of+    Just Reset -> do+      void $ readTChan t+      tryConsumeResets t+    _ -> pure ()++tryRequest :: forall a. (Typeable a) => ModuleName -> String -> Interpreter (Result a)+tryRequest mod f = do+  catch+    (Result <$> handleRequest mod f)+    ( \(e :: InterpreterError) -> do+        liftIO $ putStrLn $ "Live Code Error: " ++ show e+        pure NoResult+    )++handleRequest :: forall a. (Typeable a) => ModuleName -> String -> Interpreter a+handleRequest mod f = do+  setTopLevelModules [mod]+  interpret f (as :: a)