module Waterfall.Offset 
( offset
) where 

import Waterfall.Internal.Solid (Solid (..))
import qualified OpenCascade.BRepOffsetAPI.MakeOffsetShape as MakeOffsetShape
import Control.Monad.IO.Class (liftIO)
import OpenCascade.Inheritance (SubTypeOf(upcast), unsafeDowncast)
import qualified OpenCascade.BRepBuilderAPI.MakeShape as MakeShape
import qualified OpenCascade.BRepOffset.Mode as Mode
import qualified OpenCascade.GeomAbs.JoinType as GeomAbs.JoinType
import qualified OpenCascade.BRepBuilderAPI.MakeSolid as MakeSolid
import Linear.Epsilon (nearZero)

-- | Expand or contract a `Solid` by a certain amount.
-- 
-- This seems to be relatively fragile on Sweeps/Prisms
-- (as in, may fail to produce a result)
offset :: Double    -- ^ Amount to offset by, positive values expand, negative values contract
    -> Double       -- ^ Tolerance, this can be relatively small
    -> Solid        -- ^ the `Solid` to offset 
    -> Solid
offset :: Double -> Double -> Solid -> Solid
offset Double
value Double
tolerance (Solid Acquire (Ptr Shape)
run)
    | Double -> Bool
forall a. Epsilon a => a -> Bool
nearZero Double
value = Acquire (Ptr Shape) -> Solid
Solid Acquire (Ptr Shape)
run
    | Bool
otherwise = 
  Acquire (Ptr Shape) -> Solid
Solid (Acquire (Ptr Shape) -> Solid) -> Acquire (Ptr Shape) -> Solid
forall a b. (a -> b) -> a -> b
$ do


    Ptr MakeOffsetShape
builder <- Acquire (Ptr MakeOffsetShape)
MakeOffsetShape.new
    Ptr Shape
s <- Acquire (Ptr Shape)
run 
    --liftIO $ MakeOffsetShape.performBySimple builder s value
    IO () -> Acquire ()
forall a. IO a -> Acquire a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> Acquire ()) -> IO () -> Acquire ()
forall a b. (a -> b) -> a -> b
$ Ptr MakeOffsetShape
-> Ptr Shape
-> Double
-> Double
-> Mode
-> Bool
-> Bool
-> JoinType
-> Bool
-> IO ()
MakeOffsetShape.performByJoin Ptr MakeOffsetShape
builder Ptr Shape
s Double
value Double
tolerance Mode
Mode.Skin Bool
False Bool
False JoinType
GeomAbs.JoinType.Arc Bool
False 
    Ptr Shape
shell <- Ptr MakeShape -> Acquire (Ptr Shape)
MakeShape.shape (Ptr MakeOffsetShape -> Ptr MakeShape
forall a b. SubTypeOf a b => Ptr b -> Ptr a
upcast Ptr MakeOffsetShape
builder)
    Ptr MakeSolid
shellBuilder <- Acquire (Ptr MakeSolid)
MakeSolid.new
    IO () -> Acquire ()
forall a. IO a -> Acquire a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> Acquire ()) -> IO () -> Acquire ()
forall a b. (a -> b) -> a -> b
$ Ptr MakeSolid -> Ptr Shell -> IO ()
MakeSolid.add Ptr MakeSolid
shellBuilder (Ptr Shell -> IO ()) -> IO (Ptr Shell) -> IO ()
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< Ptr Shape -> IO (Ptr Shell)
forall a b. DiscriminatedSubTypeOf a b => Ptr a -> IO (Ptr b)
unsafeDowncast Ptr Shape
shell
    Ptr MakeShape -> Acquire (Ptr Shape)
MakeShape.shape (Ptr MakeSolid -> Ptr MakeShape
forall a b. SubTypeOf a b => Ptr b -> Ptr a
upcast Ptr MakeSolid
shellBuilder)