-- GENERATED by C->Haskell Compiler, version 0.16.0 Crystal Seed, 24 Jan 2009 (Haskell)
-- Edit the ORIGNAL .chs file instead!


{-# LINE 1 "./Algebra/Geometric/Strip.chs" #-}{-# LANGUAGE ForeignFunctionInterface #-}

-- Strip.chs

-- hgeometric: A geometric library with bindings to GPC.
-- Strip.chs is part of hgeometric.

-- Copyright 2007, 2009 Marco TĂșlio Gontijo e Silva
-- Copyright 2007, 2009 Rafael Cunha de Almeida

-- See LICENSE


-- | 'Strip' data type and convertions.
module Algebra.Geometric.Strip (
        -- * Data Type
        Strip (StripC, stripSet),
        -- * Convertion
        safePolygonToStrip, polygonToStrip)
    where

import Data.Set hiding (map)
import Control.Monad
import Foreign
import Foreign.C

import Algebra.Geometric.Contour
import Algebra.Geometric.Polygon


{-# LINE 31 "./Algebra/Geometric/Strip.chs" #-}

type CContour = Ptr (Contour)
{-# LINE 33 "./Algebra/Geometric/Strip.chs" #-}
type CPolygon = Ptr (Polygon)
{-# LINE 34 "./Algebra/Geometric/Strip.chs" #-}
type CStrip = Ptr (Strip)
{-# LINE 35 "./Algebra/Geometric/Strip.chs" #-}

-- | A 'Strip' is an alternative form of representing a 'Polygon' composed
-- by 'Contour's that are not holes. It's a good idea to use it to draw filled
-- figures, and to use 'Polygon' to draw the 'Contour's.
newtype Strip = StripC {stripSet :: Set Contour} deriving Show

instance Storable Strip where
    sizeOf _ = 8
{-# LINE 43 "./Algebra/Geometric/Strip.chs" #-}

    alignment _ = alignment (undefined :: Int)

    peek cStrip =
        (StripC . fromList) `liftM`
        do
        numStrips <-
            fromIntegral `liftM` (\ptr -> do {peekByteOff ptr 0 ::IO CInt}) cStrip
        (\ptr -> do {peekByteOff ptr 4 ::IO (CContour)}) cStrip >>= peekArray numStrips

    poke cStrip (StripC strip) =
        (\ptr val -> do {pokeByteOff ptr 0 (val::CInt)}) cStrip (fromIntegral $ size strip) >>

        newArray (toList strip) >>= (\ptr val -> do {pokeByteOff ptr 4 (val::(CContour))}) cStrip

-- | An 'IO' version of 'polygonToStrip', which does not use 'unsafePerformIO'.
safePolygonToStrip :: Polygon -> IO Strip
safePolygonToStrip polygon =
    alloca $
    \cStrip -> alloca $
    \cPolygon ->
    do
    poke cPolygon polygon

    gpc_polygon_to_tristrip cPolygon cStrip
    result <- peek cStrip

    gpc_free_polygon cPolygon
    gpc_free_tristrip cStrip

    return result

-- | Converts a 'Polygon' to a 'Strip'.
polygonToStrip :: Polygon -> Strip
polygonToStrip = unsafePerformIO . safePolygonToStrip

foreign import ccall unsafe "Algebra/Geometric/Strip.chs.h gpc_polygon_to_tristrip"
  gpc_polygon_to_tristrip :: ((CPolygon) -> ((CStrip) -> (IO ())))

foreign import ccall unsafe "Algebra/Geometric/Strip.chs.h gpc_free_polygon"
  gpc_free_polygon :: ((CPolygon) -> (IO ()))

foreign import ccall unsafe "Algebra/Geometric/Strip.chs.h gpc_free_tristrip"
  gpc_free_tristrip :: ((CStrip) -> (IO ()))