waterfall-cad 0.8.0.0 → 0.9.0.0
raw patch · 39 files changed
+2229/−933 lines, 39 filesdep +colourdep ~opencascade-hsPVP ok
version bump matches the API change (PVP)
Dependencies added: colour
Dependency ranges changed: opencascade-hs
API changes (from Hackage documentation)
- Waterfall.Colour: instance GHC.Generics.Generic Waterfall.Colour.Colour
- Waterfall.Colour: instance GHC.Show.Show Waterfall.Colour.Colour
- Waterfall.Diagram: diagramBoundingBox :: Diagram -> Maybe (V2 Double, V2 Double)
- Waterfall.Diagram: instance GHC.Base.Monoid Waterfall.Diagram.Diagram
- Waterfall.Diagram: instance GHC.Base.Semigroup Waterfall.Diagram.Diagram
- Waterfall.Diagram: instance GHC.Generics.Generic Waterfall.Diagram.Diagram
- Waterfall.Diagram: instance GHC.Show.Show Waterfall.Diagram.LineType
- Waterfall.Diagram: instance GHC.Show.Show Waterfall.Diagram.Visibility
- Waterfall.Error: instance GHC.Show.Show Waterfall.Error.WaterfallError
- Waterfall.IO: instance GHC.Exception.Type.Exception Waterfall.IO.WaterfallIOException
- Waterfall.IO: instance GHC.Show.Show Waterfall.IO.WaterfallIOException
- Waterfall.IO: instance GHC.Show.Show Waterfall.IO.WaterfallIOExceptionCause
- Waterfall.Internal.Edges: allSubShapesWithCopy :: ShapeEnum -> Ptr Shape -> Acquire [Ptr Shape]
- Waterfall.Internal.Path: instance GHC.Base.Monoid Waterfall.Internal.Path.Path
- Waterfall.Internal.Path: instance GHC.Base.Semigroup Waterfall.Internal.Path.Path
- Waterfall.Internal.Path.Common: instance GHC.Base.Monoid Waterfall.Internal.Path.Common.RawPath
- Waterfall.Internal.Path.Common: instance GHC.Base.Semigroup Waterfall.Internal.Path.Common.RawPath
- Waterfall.Internal.ShapeMap: instance Data.Foldable.Foldable Waterfall.Internal.ShapeMap.ShapeMap
- Waterfall.Internal.ShapeMap: instance Data.Traversable.Traversable Waterfall.Internal.ShapeMap.ShapeMap
- Waterfall.Internal.ShapeMap: instance GHC.Base.Functor Waterfall.Internal.ShapeMap.ShapeMap
- Waterfall.Internal.Solid: instance GHC.Base.Monoid Waterfall.Internal.Solid.Solid
- Waterfall.Internal.Solid: instance GHC.Base.Semigroup Waterfall.Internal.Solid.Solid
- Waterfall.Paint: instance GHC.Base.Monoid Waterfall.Paint.Paint
- Waterfall.Paint: instance GHC.Base.Semigroup Waterfall.Paint.Paint
- Waterfall.Paint: instance GHC.Generics.Generic Waterfall.Paint.Paint
- Waterfall.Paint: instance GHC.Show.Show Waterfall.Paint.DoubleSidedness
- Waterfall.Paint: instance GHC.Show.Show Waterfall.Paint.Paint
- Waterfall.Solids: box :: V3 Double -> Solid
- Waterfall.Solids: centerOfMass :: Solid -> V3 Double
- Waterfall.Solids: centeredCube :: Solid
- Waterfall.Solids: centeredCylinder :: Solid
- Waterfall.Solids: colourSolid :: Colour -> Solid -> Solid
- Waterfall.Solids: data Solid
- Waterfall.Solids: dodecahedron :: Solid
- Waterfall.Solids: emptySolid :: Solid
- Waterfall.Solids: icosahedron :: Solid
- Waterfall.Solids: momentOfInertia :: V3 Double -> V3 Double -> Solid -> Double
- Waterfall.Solids: octahedron :: Solid
- Waterfall.Solids: paintSolid :: Paint -> Solid -> Solid
- Waterfall.Solids: prism :: Double -> Shape -> Solid
- Waterfall.Solids: tetrahedron :: Solid
- Waterfall.Solids: torus :: Double -> Double -> Solid
- Waterfall.Solids: unitCone :: Solid
- Waterfall.Solids: unitCube :: Solid
- Waterfall.Solids: unitCylinder :: Solid
- Waterfall.Solids: unitSphere :: Solid
- Waterfall.Solids: volume :: Solid -> Double
- Waterfall.TwoD.Internal.Path2D: instance GHC.Base.Monoid Waterfall.TwoD.Internal.Path2D.Path2D
- Waterfall.TwoD.Internal.Path2D: instance GHC.Base.Semigroup Waterfall.TwoD.Internal.Path2D.Path2D
- Waterfall.TwoD.Internal.Shape: instance GHC.Base.Monoid Waterfall.TwoD.Internal.Shape.Shape
- Waterfall.TwoD.Internal.Shape: instance GHC.Base.Semigroup Waterfall.TwoD.Internal.Shape.Shape
- Waterfall.TwoD.Path2D: instance GHC.Show.Show Waterfall.TwoD.Path2D.Sense
+ Waterfall.BoundingBox.AxisAligned: class HasAxisAlignedBoundingBox a
+ Waterfall.BoundingBox.AxisAligned: instance Waterfall.BoundingBox.AxisAligned.HasAxisAlignedBoundingBox Waterfall.Internal.Path.Path
+ Waterfall.BoundingBox.AxisAligned: instance Waterfall.BoundingBox.AxisAligned.HasAxisAlignedBoundingBox Waterfall.Internal.Solid.Solid
+ Waterfall.BoundingBox.Oriented: class HasOrientedBoundingBox a
+ Waterfall.BoundingBox.Oriented: instance Waterfall.BoundingBox.Oriented.HasOrientedBoundingBox Waterfall.Internal.Path.Path
+ Waterfall.BoundingBox.Oriented: instance Waterfall.BoundingBox.Oriented.HasOrientedBoundingBox Waterfall.Internal.Solid.Solid
+ Waterfall.Colour: fromDataColour :: Colour Double -> Colour
+ Waterfall.Colour: instance GHC.Internal.Generics.Generic Waterfall.Colour.Colour
+ Waterfall.Colour: instance GHC.Internal.Show.Show Waterfall.Colour.Colour
+ Waterfall.Colour: mixColours :: NonEmpty Colour -> Colour
+ Waterfall.Colour: sRGBComponents :: Colour -> V3 Double
+ Waterfall.Colour: toDataColour :: Colour -> Colour Double
+ Waterfall.Diagram: instance GHC.Internal.Base.Monoid Waterfall.Diagram.Diagram
+ Waterfall.Diagram: instance GHC.Internal.Base.Semigroup Waterfall.Diagram.Diagram
+ Waterfall.Diagram: instance GHC.Internal.Generics.Generic Waterfall.Diagram.Diagram
+ Waterfall.Diagram: instance GHC.Internal.Show.Show Waterfall.Diagram.LineType
+ Waterfall.Diagram: instance GHC.Internal.Show.Show Waterfall.Diagram.Visibility
+ Waterfall.Error: instance GHC.Internal.Show.Show Waterfall.Error.WaterfallError
+ Waterfall.IO: instance GHC.Internal.Exception.Type.Exception Waterfall.IO.WaterfallIOException
+ Waterfall.IO: instance GHC.Internal.Show.Show Waterfall.IO.WaterfallIOException
+ Waterfall.IO: instance GHC.Internal.Show.Show Waterfall.IO.WaterfallIOExceptionCause
+ Waterfall.Internal.Diagram: silhouetteShape :: Ptr Shape -> Acquire [Shape]
+ Waterfall.Internal.Edges: forwardWire :: Ptr Wire -> Acquire (Ptr Wire)
+ Waterfall.Internal.Edges: forwardWireAndStripZeroLengthEdges :: Ptr Wire -> Acquire (Maybe (Ptr Wire))
+ Waterfall.Internal.FromOpenCascade: class HasShapeKind a
+ Waterfall.Internal.FromOpenCascade: containsShapeKind :: ShapeEnum -> Ptr Shape -> Acquire Bool
+ Waterfall.Internal.FromOpenCascade: deduplicateTopoDSShapes :: (NFData a, NoPtr a) => (a -> Acquire (Ptr Shape)) -> [a] -> [a]
+ Waterfall.Internal.FromOpenCascade: instance Waterfall.Internal.FromOpenCascade.HasShapeKind OpenCascade.TopoDS.Types.Edge
+ Waterfall.Internal.FromOpenCascade: instance Waterfall.Internal.FromOpenCascade.HasShapeKind OpenCascade.TopoDS.Types.Face
+ Waterfall.Internal.FromOpenCascade: instance Waterfall.Internal.FromOpenCascade.HasShapeKind OpenCascade.TopoDS.Types.Shell
+ Waterfall.Internal.FromOpenCascade: instance Waterfall.Internal.FromOpenCascade.HasShapeKind OpenCascade.TopoDS.Types.Solid
+ Waterfall.Internal.FromOpenCascade: instance Waterfall.Internal.FromOpenCascade.HasShapeKind OpenCascade.TopoDS.Types.Vertex
+ Waterfall.Internal.FromOpenCascade: instance Waterfall.Internal.FromOpenCascade.HasShapeKind OpenCascade.TopoDS.Types.Wire
+ Waterfall.Internal.FromOpenCascade: shapeKind :: HasShapeKind a => Proxy a -> ShapeEnum
+ Waterfall.Internal.FromOpenCascade: subShapes :: (HasShapeKind a, DiscriminatedSubTypeOf Shape a) => Ptr Shape -> Acquire [Ptr a]
+ Waterfall.Internal.FromOpenCascade: subShapesOf :: HasShapeKind a => Proxy a -> Ptr Shape -> Acquire [Ptr Shape]
+ Waterfall.Internal.Path: instance GHC.Internal.Base.Monoid Waterfall.Internal.Path.Path
+ Waterfall.Internal.Path: instance GHC.Internal.Base.Semigroup Waterfall.Internal.Path.Path
+ Waterfall.Internal.Path.Common: instance GHC.Internal.Base.Monoid Waterfall.Internal.Path.Common.RawPath
+ Waterfall.Internal.Path.Common: instance GHC.Internal.Base.Semigroup Waterfall.Internal.Path.Common.RawPath
+ Waterfall.Internal.ShapeMap: instance GHC.Internal.Base.Functor Waterfall.Internal.ShapeMap.ShapeMap
+ Waterfall.Internal.ShapeMap: instance GHC.Internal.Data.Foldable.Foldable Waterfall.Internal.ShapeMap.ShapeMap
+ Waterfall.Internal.ShapeMap: instance GHC.Internal.Data.Traversable.Traversable Waterfall.Internal.ShapeMap.ShapeMap
+ Waterfall.Internal.Solid: instance GHC.Internal.Base.Monoid Waterfall.Internal.Solid.Solid
+ Waterfall.Internal.Solid: instance GHC.Internal.Base.Semigroup Waterfall.Internal.Solid.Solid
+ Waterfall.Internal.Solid: mapPaintMap :: (PaintMap, History) -> Acquire (PaintMap, Ptr Shape)
+ Waterfall.Internal.Solid: shapeDivideHistory :: Ptr ShapeDivide -> History
+ Waterfall.Internal.Solid: solidFromAcquireTWithPaintMap :: Traversable t => Acquire (t (PaintMap, Ptr Shape)) -> t Solid
+ Waterfall.Internal.Solid: solidFromAcquireWithPaintMap :: Acquire (PaintMap, Ptr Shape) -> Solid
+ Waterfall.Internal.ToOpenCascade: shapeSingletonList :: Ptr Shape -> Acquire (Ptr (List Shape))
+ Waterfall.Paint: instance GHC.Internal.Base.Monoid Waterfall.Paint.Paint
+ Waterfall.Paint: instance GHC.Internal.Base.Semigroup Waterfall.Paint.Paint
+ Waterfall.Paint: instance GHC.Internal.Generics.Generic Waterfall.Paint.Paint
+ Waterfall.Paint: instance GHC.Internal.Show.Show Waterfall.Paint.DoubleSidedness
+ Waterfall.Paint: instance GHC.Internal.Show.Show Waterfall.Paint.Paint
+ Waterfall.Paint: mixPaints :: NonEmpty Paint -> Paint
+ Waterfall.Paint: mixPaintsWithColours :: (NonEmpty Colour -> Colour) -> NonEmpty Paint -> Paint
+ Waterfall.Revolution: revolutionByAngle :: Double -> Shape -> Solid
+ Waterfall.Revolution: tryRevolutionByAngle :: Double -> Shape -> Either WaterfallError Solid
+ Waterfall.Solid: box :: V3 Double -> Solid
+ Waterfall.Solid: centerOfMass :: Solid -> V3 Double
+ Waterfall.Solid: centeredCube :: Solid
+ Waterfall.Solid: centeredCylinder :: Solid
+ Waterfall.Solid: colourSolid :: Colour -> Solid -> Solid
+ Waterfall.Solid: data Solid
+ Waterfall.Solid: dodecahedron :: Solid
+ Waterfall.Solid: emptySolid :: Solid
+ Waterfall.Solid: icosahedron :: Solid
+ Waterfall.Solid: looseParts :: Solid -> [Solid]
+ Waterfall.Solid: momentOfInertia :: V3 Double -> V3 Double -> Solid -> Double
+ Waterfall.Solid: octahedron :: Solid
+ Waterfall.Solid: paintSolid :: Paint -> Solid -> Solid
+ Waterfall.Solid: prism :: Double -> Shape -> Solid
+ Waterfall.Solid: tetrahedron :: Solid
+ Waterfall.Solid: torus :: Double -> Double -> Solid
+ Waterfall.Solid: unitCone :: Solid
+ Waterfall.Solid: unitCube :: Solid
+ Waterfall.Solid: unitCylinder :: Solid
+ Waterfall.Solid: unitSphere :: Solid
+ Waterfall.Solid: volume :: Solid -> Double
+ Waterfall.TwoD.BoundingBox.AxisAligned: aabbToShape :: (V2 Double, V2 Double) -> Shape
+ Waterfall.TwoD.BoundingBox.AxisAligned: axisAlignedBoundingBox2D :: HasAxisAlignedBoundingBox2D a => a -> Maybe (V2 Double, V2 Double)
+ Waterfall.TwoD.BoundingBox.AxisAligned: class HasAxisAlignedBoundingBox2D a
+ Waterfall.TwoD.BoundingBox.AxisAligned: instance Waterfall.TwoD.BoundingBox.AxisAligned.HasAxisAlignedBoundingBox2D Waterfall.Diagram.Diagram
+ Waterfall.TwoD.BoundingBox.AxisAligned: instance Waterfall.TwoD.BoundingBox.AxisAligned.HasAxisAlignedBoundingBox2D Waterfall.TwoD.Internal.Path2D.Path2D
+ Waterfall.TwoD.BoundingBox.AxisAligned: instance Waterfall.TwoD.BoundingBox.AxisAligned.HasAxisAlignedBoundingBox2D Waterfall.TwoD.Internal.Shape.Shape
+ Waterfall.TwoD.BoundingBox.Oriented: class HasOrientedBoundingBox2D a
+ Waterfall.TwoD.BoundingBox.Oriented: data OrientedBoundingBox2D
+ Waterfall.TwoD.BoundingBox.Oriented: instance Control.DeepSeq.NFData Waterfall.TwoD.BoundingBox.Oriented.OrientedBoundingBox2D
+ Waterfall.TwoD.BoundingBox.Oriented: instance Waterfall.TwoD.BoundingBox.Oriented.HasOrientedBoundingBox2D Waterfall.Diagram.Diagram
+ Waterfall.TwoD.BoundingBox.Oriented: instance Waterfall.TwoD.BoundingBox.Oriented.HasOrientedBoundingBox2D Waterfall.TwoD.Internal.Path2D.Path2D
+ Waterfall.TwoD.BoundingBox.Oriented: instance Waterfall.TwoD.BoundingBox.Oriented.HasOrientedBoundingBox2D Waterfall.TwoD.Internal.Shape.Shape
+ Waterfall.TwoD.BoundingBox.Oriented: obb2DCenter :: OrientedBoundingBox2D -> V2 Double
+ Waterfall.TwoD.BoundingBox.Oriented: obb2DSideX :: OrientedBoundingBox2D -> V2 Double
+ Waterfall.TwoD.BoundingBox.Oriented: obb2DSideY :: OrientedBoundingBox2D -> V2 Double
+ Waterfall.TwoD.BoundingBox.Oriented: obbToShape :: OrientedBoundingBox2D -> Shape
+ Waterfall.TwoD.BoundingBox.Oriented: orientedBoundingBox2D :: HasOrientedBoundingBox2D a => a -> Maybe OrientedBoundingBox2D
+ Waterfall.TwoD.Internal.Path2D: instance GHC.Internal.Base.Monoid Waterfall.TwoD.Internal.Path2D.Path2D
+ Waterfall.TwoD.Internal.Path2D: instance GHC.Internal.Base.Semigroup Waterfall.TwoD.Internal.Path2D.Path2D
+ Waterfall.TwoD.Internal.Shape: instance GHC.Internal.Base.Monoid Waterfall.TwoD.Internal.Shape.Shape
+ Waterfall.TwoD.Internal.Shape: instance GHC.Internal.Base.Semigroup Waterfall.TwoD.Internal.Shape.Shape
+ Waterfall.TwoD.Offset: offsetShape :: Double -> Shape -> Shape
+ Waterfall.TwoD.Offset: tryOffsetShape :: Double -> Shape -> Either WaterfallError Shape
+ Waterfall.TwoD.Path2D: instance GHC.Internal.Show.Show Waterfall.TwoD.Path2D.Sense
+ Waterfall.TwoD.Shape: area :: Shape -> Double
+ Waterfall.TwoD.Shape: centroid :: Shape -> V2 Double
+ Waterfall.TwoD.Shape: looseShapes :: Shape -> [Shape]
+ Waterfall.TwoD.Shape: section :: Solid -> Shape
+ Waterfall.TwoD.Shape: silhouette :: Solid -> Shape
- Waterfall.BoundingBox.AxisAligned: axisAlignedBoundingBox :: Solid -> Maybe (V3 Double, V3 Double)
+ Waterfall.BoundingBox.AxisAligned: axisAlignedBoundingBox :: HasAxisAlignedBoundingBox a => a -> Maybe (V3 Double, V3 Double)
- Waterfall.BoundingBox.Oriented: orientedBoundingBox :: Solid -> Maybe OrientedBoundingBox
+ Waterfall.BoundingBox.Oriented: orientedBoundingBox :: HasOrientedBoundingBox a => a -> Maybe OrientedBoundingBox
- Waterfall.Internal.Solid: History :: (Ptr Shape -> Acquire (Ptr (List Shape))) -> (Ptr Shape -> Acquire (Ptr (List Shape))) -> (Ptr Shape -> IO Bool) -> Acquire (Ptr Shape) -> History
+ Waterfall.Internal.Solid: History :: (Ptr Shape -> Acquire [Ptr Shape]) -> (Ptr Shape -> Acquire [Ptr Shape]) -> (Ptr Shape -> IO Bool) -> Acquire (Ptr Shape) -> History
- Waterfall.Internal.Solid: [historyGenerated] :: History -> Ptr Shape -> Acquire (Ptr (List Shape))
+ Waterfall.Internal.Solid: [historyGenerated] :: History -> Ptr Shape -> Acquire [Ptr Shape]
- Waterfall.Internal.Solid: [historyModified] :: History -> Ptr Shape -> Acquire (Ptr (List Shape))
+ Waterfall.Internal.Solid: [historyModified] :: History -> Ptr Shape -> Acquire [Ptr Shape]
- Waterfall.Revolution: revolution :: Path2D -> Solid
+ Waterfall.Revolution: revolution :: Shape -> Solid
- Waterfall.Revolution: tryRevolution :: Path2D -> Either WaterfallError Solid
+ Waterfall.Revolution: tryRevolution :: Shape -> Either WaterfallError Solid
Files
- CHANGELOG.md +61/−0
- src/Waterfall.hs +16/−7
- src/Waterfall/Booleans.hs +13/−8
- src/Waterfall/BoundingBox/AxisAligned.hs +40/−12
- src/Waterfall/BoundingBox/Oriented.hs +37/−12
- src/Waterfall/Colour.hs +62/−5
- src/Waterfall/Diagram.hs +49/−85
- src/Waterfall/Fillet.hs +62/−20
- src/Waterfall/IO.hs +29/−12
- src/Waterfall/Internal/Diagram.hs +89/−51
- src/Waterfall/Internal/Edges.hs +151/−96
- src/Waterfall/Internal/Finalizers.hs +5/−5
- src/Waterfall/Internal/FromOpenCascade.hs +81/−1
- src/Waterfall/Internal/PaintHistory.hs +2/−4
- src/Waterfall/Internal/Path.hs +1/−1
- src/Waterfall/Internal/Path/Common.hs +2/−1
- src/Waterfall/Internal/Remesh.hs +2/−2
- src/Waterfall/Internal/Solid.hs +105/−33
- src/Waterfall/Internal/ToOpenCascade.hs +9/−0
- src/Waterfall/Loft.hs +20/−9
- src/Waterfall/Offset.hs +40/−38
- src/Waterfall/Paint.hs +80/−10
- src/Waterfall/Path.hs +1/−1
- src/Waterfall/Path/Common.hs +22/−14
- src/Waterfall/Revolution.hs +67/−22
- src/Waterfall/Solid.hs +325/−0
- src/Waterfall/Solids.hs +3/−293
- src/Waterfall/Sweep.hs +42/−6
- src/Waterfall/Transforms.hs +129/−78
- src/Waterfall/TwoD/Booleans.hs +1/−1
- src/Waterfall/TwoD/BoundingBox/AxisAligned.hs +81/−0
- src/Waterfall/TwoD/BoundingBox/Oriented.hs +134/−0
- src/Waterfall/TwoD/Internal/Shape.hs +72/−13
- src/Waterfall/TwoD/Offset.hs +81/−0
- src/Waterfall/TwoD/Path2D.hs +17/−6
- src/Waterfall/TwoD/Shape.hs +92/−12
- src/Waterfall/TwoD/Text.hs +3/−0
- src/Waterfall/TwoD/Transforms.hs +196/−73
- waterfall-cad.cabal +7/−2
CHANGELOG.md view
@@ -8,6 +8,67 @@ ## Unreleased +## 0.9.0.0++### Added ++- Added conversions between `Waterfall.Colour.Colour` and the `Colour` type from [the colour package](https://hackage.haskell.org/package/colour) (`toDataColour` and `fromDataColour`)+- Added `mixPaints` and `mixPaintsWithColours` to `Waterfall.Paint` and `mixColours` to `Waterfall.Colour`+- Added `sRGBComponents` to `Waterfall.Colour`+- Added `Waterfall.Solid.looseParts` and `Waterfall.TwoD.Shape.looseShapes`+- Added `Waterfall.TwoD.Shape.section` and `Waterfall.TwoD.Shape.silhouette`+- Added `Waterfall.TwoD.Shape.area` and `Waterfall.TwoD.Shape.centroid`+- `.stp` is now a supported extension for STEP files in `Waterfall.IO.readSolid` and `Waterfall.IO.writeSolid`+- Added `offsetShape` and `tryOffsetShape` in `Waterfall.TwoD.Offset`+- Added `revolutionByAngle` and `tryRevolutionByAngle` to `Waterfall.Revolution`+- Added `Waterfall.TwoD.BoundingBox.AxisAligned` and `Waterfall.TwoD.BoundingBox.Oriented`++### Fixed++- Boolean operations on `Shape` now correctly merge neighbouring faces (Github issue #52)+- Nearly uniform arguments to `scale` and `scale2D` no longer produce invalid geometry (Github issue #55)+- Arguments to `matTransform` and `matTransform2D` which consist of an orthogonal matrix plus a uniform scale no longer produce invalid geometry (Github issue #33)+- `Waterfall.Sweep` now uses `MakePipeShell` rather than `MakePipe` which is more modern, and has fewer bugs, (Github issue #25)+- Colour components are clamped to the range [0..1] on write; out of range components would previously have raised an exception.+- `volume`, `centerOfMass` and `momentOfInertia` now use a different kernel function and should be more accurate+- Diagrams of objects with an outline consisting of a single edge were computed without a fill+- A "Noop Fillet" (with a function that matches no edges) no longer fails+- Fixed an issue where `intersections`/`intersections3D`/`intersections2D` would give the wrong result on lists with more than two items+- Fixed an issue where `unions`/`unions3D` and `mconcat @Solid` would give the wrong result on lists with more than two items which also contain `mempty`+- Fixed an issue where functions on the `Path2D`s returned by `shapePaths` could give incorrect results (for instance, on a mirrored shape)+- Methods in `Waterfall.Fillet` now ignore edges that are degenerate, or have greater than C0 continuity, this should make them less prone to fail+- Improved error handling in `readSTEP` so that this throws where it used to segfault +- `Sweep` now uses OpenCascade's "Right Corner" transition mode to handle sweeping paths with corners+- `fontFromSystem` now loads the correct FontAspect+- Lowered the threshold used when creating line segments when appending paths, as previously a gap between 1e-6 and 1e-7 could cause this to fail+- Allow a slight tolerance in `Waterfall.TwoD.Path2D.arc` as some exact semicircles were previously incorrectly rejected, arc now accepts negative radii (but ignores the sign)+- Prevent `takePathFraction` from crashing when the output path would have been very small+- Fixed a bug in `repeatLooping` when the path straddled the negative y axis+- `arcVia`, `arcViaTo` and `arcViaRelative` no longer crash when the points are collinear, and the midpoint lies between the two endpoints+- Fixed a bug where a `Diagram` fill could be incorrectly created for a hole if the centroid of the hole's outline overlapped with a solid face, or a small part of the hole's area overlapped with the object+- Fixed a number of issues where passing specific arguments to methods of `Transformable` and `Transformable2D` would result in exceptions or bad geometry+- Offset now supports objects with internal cavities+- Offset now supports objects with faces that are not C1 continuous, by splitting on their discontinuities before processing. Such faces include the faces of a (non-uniformly) scaled cylinder, so offsets can be computed on these when they couldn't previously.+- Fixed an issue where Boolean operations could modify their arguments+- Fixed an issue where glTF node transforms were ignored by `readGLTF`/`readGLB`+- Stopped using mesh data to compute bounding boxes, as this led to a different result for Solids that had/had not been written using a mesh format, breaking referential transparency+- Mesh data is now cleared after writing a mesh format. Prior to this, writing a solid at a high resolution, then at a low one would reuse the high resolution mesh++### Removed+- `Waterfall.Diagram.diagramBoundingBox` (in favour of `Waterfall.TwoD.BoundingBox.AxisAligned.axisAlignedBoundingBox2D`)++### Changed ++- `Waterfall.TwoD.Shape.makeShape` now closes the path if it was open (Github issue #57)+ - This fixes shape construction from SVG files with endpoints that were previously processed as "not quite closed" due to rounding errors.+- The `Show` instance on `Colour` now displays values in terms of `Waterfall.Colour.rgb24` when this is possible.+- Emissive Colour is now converted to linear RGB when written+- In `Waterfall.Revolution`, `revolution` and `tryRevolution` now take a `Shape` rather than a `Path2D`+- `writeGLTF`, `writeGLB` and `writeOBJ` now throw on error+- Changes to `Shape` and `makeShape` may impact the order and direction in which paths are returned by `shapePaths`+- The `Waterfall.Solids` module has moved to `Waterfall.Solid` to match the `Solid` type, `Waterfall.Solids` exists but is marked as deprecated+- Functions in `Waterfall.BoundingBox.*` now accept either a `Solid` or a `Path` via a typeclass, rather than just a `Solid`+ ## 0.8.0.0 ### Added
src/Waterfall.hs view
@@ -7,9 +7,9 @@ module Waterfall ( -- | `Solid` is the main data type in the Waterfall-CAD API,--- The "Waterfall.Solids" module is the easiest way to construct +-- The "Waterfall.Solid" module is the easiest way to construct -- instances of `Solid`.- module Waterfall.Solids+ module Waterfall.Solid -- | The functions in this module can be used to transform `Solid`s. , module Waterfall.Transforms -- | `Solid`s can be combined together with @@ -27,11 +27,11 @@ , module Waterfall.Colour -- | `Paint` can be applied to a `Solid` to affect how it appears -- --- (only supported by some file formats, see the documentation of `Waterfall.IO` for specifics)+-- (only supported by some file formats, see the module documentation for specifics) , module Waterfall.Paint--- | Calculating Axis Aligned Bounding Boxes from a `Solid`.+-- | Calculating Axis Aligned Bounding Boxes from a `Solid` or `Path`. , module Waterfall.BoundingBox.AxisAligned--- | Calculating Oriented Bounding Boxes from a `Solid`.+-- | Calculating Oriented Bounding Boxes from a `Solid` or `Path`. , module Waterfall.BoundingBox.Oriented -- | This module deals with adding rounds\/fillets\/bevels to a `Solid`. , module Waterfall.Fillet@@ -45,7 +45,7 @@ , module Waterfall.Sweep -- | Generate a [Loft](https://en.wikipedia.org/wiki/Loft_\(3D\)) between a sequence of `Path`s , module Waterfall.Loft--- | Construct a `Solid` of revolution from a `Path2D`.+-- | Construct a `Solid` of revolution from a `Shape`. , module Waterfall.Revolution -- | Transforms for data types that exist in Two Dimensional space, like `Shape` and `Path2D`. , module Waterfall.TwoD.Transforms@@ -53,6 +53,8 @@ , module Waterfall.TwoD.Path2D -- | Create a `Shape` from text, rendered using a specific `Font`. , module Waterfall.TwoD.Text+-- | This module deals with offsetting a `Shape`: either shrinking/expanding it.+, module Waterfall.TwoD.Offset -- | Paths in 2D / 3D space. -- -- This module defines functions that can be used with "Waterfall.Path" or "Waterfall.TwoD.Path2D".@@ -60,6 +62,10 @@ , module Waterfall.Path.Common -- | Generate 2D `Diagram`s from 3D `Solid`s , module Waterfall.Diagram+-- | Calculating Axis Aligned Bounding Boxes from a `Shape`, `Path2D` or `Diagram`.+, module Waterfall.TwoD.BoundingBox.AxisAligned+-- | Calculating Oriented Bounding Boxes from a `Shape`, `Path2D` or `Diagram`.+, module Waterfall.TwoD.BoundingBox.Oriented -- | This module defines the Error type used by some functions , module Waterfall.Error )where@@ -78,7 +84,7 @@ import Waterfall.Path.Common import Waterfall.Path import Waterfall.Revolution-import Waterfall.Solids+import Waterfall.Solid import Waterfall.Sweep import Waterfall.Loft import Waterfall.Transforms@@ -86,4 +92,7 @@ import Waterfall.TwoD.Path2D import Waterfall.TwoD.Shape import Waterfall.TwoD.Text+import Waterfall.TwoD.Offset+import Waterfall.TwoD.BoundingBox.AxisAligned+import Waterfall.TwoD.BoundingBox.Oriented import Waterfall.Error
src/Waterfall/Booleans.hs view
@@ -1,18 +1,18 @@ {-|-[Constructive Solid Geometry \(CSG\)](https://en.wikipedia.org/wiki/Constructive_solid_geometry) operations on `Solid`, and `Shape`.+[Constructive Solid Geometry \(CSG\)](https://en.wikipedia.org/wiki/Constructive_solid_geometry) operations on `Waterfall.Solid.Solid`, and `Waterfall.TwoD.Shape.Shape`. -} module Waterfall.Booleans-( union3D+( Boolean(..)+, union3D , difference3D , intersection3D , complement , unions3D , intersections3D-, Boolean(..) ) where import Waterfall.Internal.Solid(union3D, unions3D, difference3D, intersection3D, intersections3D, complement)-import qualified Waterfall.Solids as Solids+import qualified Waterfall.Solid as Solid import qualified Waterfall.TwoD.Internal.Shape as Shape import Waterfall.TwoD.Internal.Shape (union2D, difference2D, intersection2D, unions2D, intersections2D) @@ -37,8 +37,13 @@ -- -- Represents a region of space containing no volume or area. --- -- For union: @empty `union` x = x `union` empty = x@- -- For intersection: @empty `intersection` x = x `intersection` empty = empty@+ -- For union: + --+ -- > empty `union` x = x `union` empty = x+ -- + -- For intersection: + -- + -- > empty `intersection` x = x `intersection` empty = empty empty :: a -- | Take the union of a list of objects@@ -54,11 +59,11 @@ intersections [] = empty intersections xs = foldr1 intersection xs -instance Boolean Solids.Solid where+instance Boolean Solid.Solid where union = union3D difference = difference3D intersection = intersection3D- empty = Solids.emptySolid+ empty = Solid.emptySolid unions = unions3D intersections = intersections3D
src/Waterfall/BoundingBox/AxisAligned.hs view
@@ -1,30 +1,58 @@ module Waterfall.BoundingBox.AxisAligned-( axisAlignedBoundingBox+( HasAxisAlignedBoundingBox ()+, axisAlignedBoundingBox , aabbToSolid ) where import Waterfall.Internal.Solid(Solid, acquireSolid)-import Waterfall.Internal.Finalizers (unsafeFromAcquire)+import Waterfall.Internal.Finalizers (unsafeFromAcquire, acquireForeignPtr) import Waterfall.Internal.FromOpenCascade (gpPntToV3)-import Waterfall.Solids (box, volume)+import Waterfall.Solid (box, volume) import Waterfall.Transforms (translate) import Linear (V3 (..), (^-^)) import qualified OpenCascade.Bnd.Box as Bnd.Box import qualified OpenCascade.BRepBndLib as BRepBndLib import Control.Monad.IO.Class (liftIO)+import Data.Acquire (Acquire)+import Foreign (Ptr)+import qualified OpenCascade.TopoDS as TopoDS+import Waterfall.Internal.Path (Path (..))+import Waterfall.Internal.Path.Common (RawPath(..))+import OpenCascade.Inheritance (upcast)+import Waterfall.Internal.ToOpenCascade (v3ToVertex)+import Control.Monad (forM_) --- | Return the smallest Axis Aligned Bounding Box (AABB) that contains the Solid.+-- | Class for things that have a Bounding Box -- --- If computable, the AABB is returned in the form '(lo, hi)',--- where 'lo' is the vertex of the box with the lowest individual values,--- and 'hi' is the vertex with the highest values.-axisAlignedBoundingBox :: Solid -> Maybe (V3 Double, V3 Double)+-- Has instances for `Solid` and `Path`+class HasAxisAlignedBoundingBox a where+ _isEmpty :: a -> Bool+ _getShapes :: a -> Acquire [Ptr TopoDS.Shape]++instance HasAxisAlignedBoundingBox Solid where+ _isEmpty s = volume s == 0+ _getShapes = fmap pure . acquireSolid++instance HasAxisAlignedBoundingBox Path where+ _isEmpty (Path EmptyRawPath) = True+ _isEmpty _ = False++ _getShapes (Path (ComplexRawPath p)) = fmap (pure . upcast) . acquireForeignPtr $ p+ _getShapes (Path (SinglePointRawPath p)) = fmap (pure . upcast) . v3ToVertex $ p+ _getShapes (Path EmptyRawPath) = pure []++-- | Return the smallest Axis Aligned Bounding Box (AABB) that contains the `Solid` or `Path`.+-- +-- If computable, the AABB is returned in the form @(lo, hi)@,+-- where @lo@ is the vertex of the box with the lowest individual values,+-- and @hi@ is the vertex with the highest values.+axisAlignedBoundingBox :: HasAxisAlignedBoundingBox a => a -> Maybe (V3 Double, V3 Double) axisAlignedBoundingBox s = - if volume s <= 0+ if _isEmpty s then Nothing else Just . unsafeFromAcquire $ do- solid <- acquireSolid s+ shapes <- _getShapes s theBox <- Bnd.Box.new- liftIO $ BRepBndLib.addOptimal solid theBox True False+ liftIO $ forM_ shapes $ \shape -> BRepBndLib.addOptimal shape theBox False False p1 <- liftIO . gpPntToV3 =<< Bnd.Box.cornerMin theBox p2 <- liftIO . gpPntToV3 =<< Bnd.Box.cornerMax theBox return (p1, p2)@@ -32,6 +60,6 @@ -- | A cuboid, specified by two diagonal vertices. -- -- This can be used to make a solid from the output of `axisAlignedBoundingBox` -aabbToSolid :: (V3 Double, V3 Double) -- ^ if this argument input is `(lo, hi)`, one vertex of the cuboid is placed at `lo`, the opposite vertex is at `hi`+aabbToSolid :: (V3 Double, V3 Double) -- ^ if this argument input is @(lo, hi)@, one vertex of the cuboid is placed at @lo@, the opposite vertex is at @hi@ -> Solid aabbToSolid (lo, hi) = translate lo $ box (hi ^-^ lo)
src/Waterfall/BoundingBox/Oriented.hs view
@@ -1,5 +1,7 @@+{-# LANGUAGE InstanceSigs #-} module Waterfall.BoundingBox.Oriented-( OrientedBoundingBox+( HasOrientedBoundingBox ()+, OrientedBoundingBox , obbCenter , obbSideX , obbSideY@@ -13,7 +15,7 @@ import Waterfall.Internal.Finalizers (acquireForeignPtr, unsafeFromAcquirePtr, unsafeFromAcquire) import Waterfall.Internal.FromOpenCascade (gpXYZToV3) import Foreign.Ptr (Ptr)-import Waterfall.Solids (volume, box)+import Waterfall.Solid (volume, box) import Waterfall.Transforms (translate) import qualified OpenCascade.Bnd.OBB as OBB import OpenCascade.Bnd.OBB (OBB)@@ -27,26 +29,49 @@ import OpenCascade.Inheritance (upcast) import Data.Acquire (Acquire) import Control.Monad.IO.Class (liftIO)-import Control.Monad ((<=<))+import Control.Monad ((<=<), forM_) import Foreign.ForeignPtr (ForeignPtr) import Control.DeepSeq (NFData (rnf), rwhnf)+import qualified OpenCascade.TopoDS as TopoDS+import Waterfall.Internal.Path (Path (..))+import Waterfall.Internal.Path.Common (RawPath(..))+import Waterfall.Internal.ToOpenCascade (v3ToVertex) --- | An OrientedBoundingBox may be a tighter fit for a Shape than an axis aligned bounding box would be+-- | Class for things that have a Oriented Bounding Box -- +-- Has instances for `Solid` and `Path`+class HasOrientedBoundingBox a where+ _isEmpty :: a -> Bool+ _getShapes :: a -> Acquire [Ptr TopoDS.Shape]++instance HasOrientedBoundingBox Solid where+ _isEmpty s = volume s == 0+ _getShapes :: Solid -> Acquire [Ptr TopoDS.Shape]+ _getShapes = fmap pure . acquireSolid++instance HasOrientedBoundingBox Path where+ _isEmpty (Path EmptyRawPath) = True+ _isEmpty _ = False++ _getShapes (Path (ComplexRawPath p)) = fmap (pure . upcast) . acquireForeignPtr $ p+ _getShapes (Path (SinglePointRawPath p)) = fmap (pure . upcast) . v3ToVertex $ p+ _getShapes (Path EmptyRawPath) = pure []++-- | An OrientedBoundingBox may be a tighter fit than an axis aligned bounding box would be newtype OrientedBoundingBox = OrientedBoundingBox { rawOBB :: ForeignPtr OBB } instance NFData OrientedBoundingBox where rnf (OrientedBoundingBox obb) = rwhnf obb --- | Compute an OrientedBoundingBox for a solid-orientedBoundingBox :: Solid -> Maybe OrientedBoundingBox+-- | Compute an `OrientedBoundingBox` for a `Solid` or `Path`+orientedBoundingBox :: HasOrientedBoundingBox a => a -> Maybe OrientedBoundingBox orientedBoundingBox s = - if volume s == 0+ if _isEmpty s then Nothing else Just . OrientedBoundingBox . unsafeFromAcquirePtr $ do obb <- OBB.new- solid <- acquireSolid s- liftIO $ BRepBndLib.addOBB solid obb True True True+ shapes <- _getShapes s+ liftIO $ forM_ shapes $ \shape -> BRepBndLib.addOBB shape obb False True True return obb queryOBB :: (Ptr OBB -> Acquire (V3 Double)) -> OrientedBoundingBox -> V3 Double@@ -65,21 +90,21 @@ -- | The "X" side of the oriented bounding box. -- -- This is measured from the center to one Face.--- So the length of this vector is _half_ of the side length of the bounding box.+-- So the length of this vector is /half/ of the side length of the bounding box. obbSideX :: OrientedBoundingBox -> V3 Double obbSideX = getSide OBB.xDirection OBB.xHSize -- | The "Y" side of the oriented bounding box. -- -- This is measured from the center to one face.--- So the length of this vector is _half_ of the side length of the bounding box.+-- So the length of this vector is /half/ of the side length of the bounding box. obbSideY :: OrientedBoundingBox -> V3 Double obbSideY = getSide OBB.yDirection OBB.yHSize -- | The "Z" side of the oriented bounding box -- -- This is measured from the center to one face.--- So the length of this vector is _half_ of the side length of the bounding box.+-- So the length of this vector is /half/ of the side length of the bounding box. obbSideZ :: OrientedBoundingBox -> V3 Double obbSideZ = getSide OBB.zDirection OBB.zHSize
src/Waterfall/Colour.hs view
@@ -1,7 +1,11 @@ {-#LANGUAGE DeriveGeneric #-} module Waterfall.Colour ( Colour (..)+, toDataColour+, fromDataColour+, sRGBComponents , rgb24+, mixColours , black , white , silver@@ -21,16 +25,51 @@ ) where import Data.Word (Word32)-import Data.Bits (shiftR, (.&.))-import GHC.Generics (Generic)+import Data.Bits (shiftL, shiftR, (.&.), (.|.))+import Numeric (showHex) import Control.DeepSeq (NFData)+import GHC.Generics (Generic)+import qualified Data.Colour+import qualified Data.Colour.SRGB as SRGB+import qualified Data.Colour.Ok as Ok+import Linear (V3 (..), (^*))+import Data.List.NonEmpty (NonEmpty ((:|))) -- | Three sRGB values, in the range [0, 1] data Colour = Colour Double Double Double- deriving (Eq, Ord, Show, Generic)+ deriving (Eq, Ord, Generic) instance NFData Colour +-- | Create a `Colour` from a `Data.Colour.Colour` (from the @colour@ package)+fromDataColour :: Data.Colour.Colour Double -> Colour+fromDataColour dc = case SRGB.toSRGB dc of + SRGB.RGB r g b -> Colour r g b++-- | Convert a `Colour` into a `Data.Colour.Colour` (from the @colour@ package)+toDataColour :: Colour -> Data.Colour.Colour Double+toDataColour (Colour r g b) = SRGB.sRGB r g b++-- | The RGB components from a colour as a vector +sRGBComponents :: Colour -> V3 Double+sRGBComponents (Colour r g b) = V3 r g b+ +instance Show Colour where+ showsPrec d c@(Colour r g b) = showParen (d > 10) $+ let SRGB.RGB r8 g8 b8 = SRGB.toSRGB24 (toDataColour c)+ word = (fromIntegral r8 `shiftL` 16) .|. (fromIntegral g8 `shiftL` 8) .|. fromIntegral b8 :: Word32+ hex = showHex word ""+ in if rgb24 word == c+ then showString "rgb24 0x"+ . showString (replicate (6 - length hex) '0')+ . showString hex+ else showString "Colour " + . showsPrec 11 r+ . showChar ' ' + . showsPrec 11 g+ . showChar ' '+ . showsPrec 11 b+ -- | Convert an integer into a Colour -- -- This is useful because it lets you write hex codes, e.g.@@ -39,9 +78,27 @@ -- rgb24 0xFFFFFF == white -- @ rgb24 :: Word32 -> Colour-rgb24 rgb =- let channel shift = fromIntegral ((rgb `shiftR` shift) .&. 0xFF) / 255+rgb24 word =+ let channel shift = fromIntegral ((word `shiftR` shift) .&. 0xFF) / 255 in Colour (channel 16) (channel 8) (channel 0)++-- | Compute an average from a List of `Colour`s+-- +-- The average is computed in [the "OkLAB" colour space](https://en.wikipedia.org/wiki/Oklab_color_space).+mixColours :: NonEmpty Colour -> Colour+-- Special casing the singleton list avoids floating point errors when roundtripping through OkLAB+mixColours (c :| []) = c+mixColours cs =+ let toLAB c = + let (l, a, b) = Ok.okLabView . toDataColour $ c+ in V3 l a b+ fromLAB (V3 l a b) = fromDataColour $ Ok.okLab l a b+ weight = 1 / realToFrac (length cs)+ in fromLAB+ . (^* weight)+ . sum+ . fmap toLAB+ $ cs black, white, silver, grey, maroon, red, purple, fuchsia, green, lime, olive, yellow, navy, blue, teal, aqua :: Colour -- | <<doc-images/black.svg black>>
src/Waterfall/Diagram.hs view
@@ -11,13 +11,9 @@ , pathDiagram , shapeDiagram , diagramLines-, diagramBoundingBox ) where import Linear.V3 (V3)-import Linear.V2 (V2)-import Linear (_xy)-import Control.Lens ((^.)) import Waterfall.Internal.Solid (Solid (solidPaintMap), acquireSolid) import qualified OpenCascade.HLRBRep.TypeOfResultingEdge as HLRBRep import qualified OpenCascade.HLRBRep.Algo as HLRBRep.Algo@@ -25,26 +21,21 @@ import qualified OpenCascade.HLRBRep.HLRToShape as HLRBRep.HLRToShape import qualified OpenCascade.GP as GP import qualified OpenCascade.GP.Ax2 as GP.Ax2-import qualified OpenCascade.Bnd.Box as Bnd.Box-import qualified OpenCascade.BRepBndLib as BRepBndLib-import Waterfall.Internal.ToOpenCascade (v3ToDir, v3ToVertex)+import Waterfall.Internal.ToOpenCascade (v3ToDir) import Waterfall.TwoD.Internal.Path2D (Path2D (..)) import Control.Monad.IO.Class (liftIO)-import Waterfall.Internal.Finalizers (unsafeFromAcquire, acquireForeignPtr, fromAcquirePtrT)+import Waterfall.Internal.Finalizers (unsafeFromAcquire, fromAcquirePtrT) import Waterfall.Internal.Edges (allEdges, buildEdgeCurve3D, edgeToWire) import Waterfall.Internal.Path.Common (RawPath (..)) import Waterfall.TwoD.Transforms (Transformable2D (..))-import Waterfall.Internal.FromOpenCascade (gpPntToV3)-import OpenCascade.Inheritance (upcast)-import Control.Monad (forM_, (<=<))+import Control.Monad ((<=<)) import Data.Map (Map) import Waterfall.TwoD.Internal.Shape (Shape (..)) import Waterfall.Paint (Paint) import qualified Data.Map as M-import Data.Maybe (fromMaybe, mapMaybe)-import Data.Either (partitionEithers)+import Data.Maybe (fromMaybe) import Waterfall.Internal.Diagram (buildSolidDiagramFills)-import Waterfall.TwoD.Shape (shapePaths)+import Waterfall.Internal.NearZero (nearZero) import GHC.Generics (Generic) import Control.DeepSeq (NFData (rnf), rwhnf) @@ -87,7 +78,7 @@ translate2D v = mapDiagram (translate2D v) mirror2D v = mapDiagram (mirror2D v) --- | Categorize the lines in a diagram+-- | Categorise the lines in a diagram data LineType = -- | Represents lines at the edge of objects, the "silhouette" -- @@ -121,52 +112,54 @@ -- -- Uses an orthographic projection, viewed from the provided direction solidDiagram :: V3 Double -> Solid -> Diagram-solidDiagram projectionDirection solid = unsafeFromAcquire $ do- s' <- acquireSolid solid- algo <- HLRBRep.Algo.new- liftIO $ HLRBRep.Algo.add algo s'- o <- GP.origin- d <- v3ToDir projectionDirection- projector <- HLRAlgo.Projector.fromAx2 =<< GP.Ax2.newAutoX o d- liftIO $ do - HLRBRep.Algo.projector algo projector- HLRBRep.Algo.update algo- HLRBRep.Algo.hide algo+solidDiagram projectionDirection solid+ | all nearZero projectionDirection = mempty+ | otherwise = unsafeFromAcquire $ do+ s' <- acquireSolid solid+ algo <- HLRBRep.Algo.new+ liftIO $ HLRBRep.Algo.add algo s'+ o <- GP.origin+ d <- v3ToDir projectionDirection+ projector <- HLRAlgo.Projector.fromAx2 =<< GP.Ax2.newAutoX o d+ liftIO $ do + HLRBRep.Algo.projector algo projector+ HLRBRep.Algo.update algo+ HLRBRep.Algo.hide algo - extractor <- HLRBRep.HLRToShape.fromAlgo algo+ extractor <- HLRBRep.HLRToShape.fromAlgo algo - theLines <- fmap M.fromList . sequence $- [ do- compoundOfEdges <- HLRBRep.HLRToShape.compoundOfEdges - extractor - (lineTypeToOpenCascade lt) - (visibility == Visible) - False- rawEdges <- allEdges compoundOfEdges- wires <- liftIO . fromAcquirePtrT $ traverse ( edgeToWire <=< buildEdgeCurve3D) rawEdges- return ((lt, visibility), Path2D . ComplexRawPath <$> wires)+ theLines <- fmap M.fromList . sequence $+ [ do+ compoundOfEdges <- HLRBRep.HLRToShape.compoundOfEdges + extractor + (lineTypeToOpenCascade lt) + (visibility == Visible) + False+ rawEdges <- allEdges compoundOfEdges+ wires <- liftIO . fromAcquirePtrT $ traverse ( edgeToWire <=< buildEdgeCurve3D) rawEdges+ return ((lt, visibility), Path2D . ComplexRawPath <$> wires) - | lt <- - [ OutLine- , SharpLine- , RawLine HLRBRep.IsoLine- , RawLine HLRBRep.Rg1Line- , RawLine HLRBRep.RgNLine- ]- , visibility <- [Visible, Hidden]- ]+ | lt <- + [ OutLine+ , SharpLine+ , RawLine HLRBRep.IsoLine+ , RawLine HLRBRep.Rg1Line+ , RawLine HLRBRep.RgNLine+ ]+ , visibility <- [Visible, Hidden]+ ] - theFills <- buildSolidDiagramFills - (solidPaintMap solid) - s' - projectionDirection - projector- extractor + theFills <- buildSolidDiagramFills + (solidPaintMap solid) + s' + projectionDirection + projector+ extractor - return $ Diagram - { getDiagramLines = theLines- , getDiagramFills = theFills- }+ return $ Diagram + { getDiagramLines = theLines+ , getDiagramFills = theFills+ } -- | Produce a `Diagram` from a `Path2D`@@ -190,32 +183,3 @@ -- | Access the lines in a `Diagram` as `Path2D` diagramLines :: LineType -> Visibility -> Diagram -> [Path2D] diagramLines lt v = fromMaybe [] . M.lookup (normaliseLineType lt, v) . getDiagramLines---- | Compute the Axis Aligned Bounding Box of a `Diagram`--- --- Returns Nothing if the `Diagram` does not contain lines that are `OutLine` or `Sharp`-diagramBoundingBox :: Diagram -> Maybe (V2 Double, V2 Double)-diagramBoundingBox d = unsafeFromAcquire $ do- let outline = diagramLines OutLine Visible d- let sharpLine = diagramLines SharpLine Visible d- fillLines = concatMap (shapePaths . snd) $ getDiagramFills d- let allLines = outline <> sharpLine <> fillLines- let partitionLine (Path2D (ComplexRawPath wire)) = Just (Left wire)- partitionLine (Path2D (SinglePointRawPath point)) = Just (Right point)- partitionLine _ = Nothing- (allWires, allPoints) = partitionEithers . mapMaybe partitionLine $ allLines- if null allWires && null allPoints- then pure Nothing- else do- theBox <- Bnd.Box.new- forM_ allWires $ \wire -> do- w <- acquireForeignPtr wire- liftIO $ BRepBndLib.addOptimal (upcast w) theBox True False- forM_ allPoints $ \point -> do- v <- v3ToVertex point- liftIO $ BRepBndLib.addOptimal (upcast v) theBox True False-- p1 <- liftIO . gpPntToV3 =<< Bnd.Box.cornerMin theBox- p2 <- liftIO . gpPntToV3 =<< Bnd.Box.cornerMax theBox- return $ Just (p1 ^. _xy, p2 ^. _xy)-
src/Waterfall/Fillet.hs view
@@ -48,7 +48,7 @@ import qualified OpenCascade.BRepBuilderAPI.MakeShape as MakeShape import qualified OpenCascade.TopoDS.Types as TopoDS import Foreign.Ptr (Ptr)-import Control.Monad (forM, forM_)+import Control.Monad (forM, forM_, join) import Control.Monad.IO.Class (liftIO) import OpenCascade.Inheritance (upcast, SubTypeOf, unsafeDowncast) import Linear.V3 (V3 (..))@@ -64,11 +64,36 @@ import qualified OpenCascade.BRepBuilderAPI as BRepBuilderAPI import qualified OpenCascade.BRepBuilderAPI.MakeWire as MakeWire import qualified OpenCascade.TopoDS.Shape as TopoDS.Shape+import qualified OpenCascade.BRep.Tool as BRep.Tool+import qualified OpenCascade.BRepLib as BRepLib import Waterfall.Internal.PaintHistory (remapWithBlendFunction) import Waterfall.Internal.Path.Common (RawPath(ComplexRawPath)) import Waterfall.Internal.Finalizers (fromAcquirePtr)+import qualified OpenCascade.NCollection.IndexedDataMap as NCollection.IndexedDataMap+import qualified OpenCascade.TopExp as TopExp+import qualified OpenCascade.TopAbs.ShapeEnum as ShapeEnum+import qualified OpenCascade.NCollection as NCollection+import Waterfall.Internal.FromOpenCascade (shapesFromListOfShape)+import qualified OpenCascade.GeomAbs.Shape as GeomAbs.Shape -edgeToPath :: Ptr TopoDS.Edge -> IO Path+canFillet + :: Ptr (NCollection.IndexedDataMap.IndexedDataMap TopoDS.Shape (NCollection.List TopoDS.Shape))+ -> Ptr TopoDS.Edge + -> Acquire Bool+canFillet m edge = do+ isDegenerated <- liftIO $ BRep.Tool.degenerated edge+ if isDegenerated + then return False+ else do+ neighbours <- shapesFromListOfShape =<< NCollection.IndexedDataMap.findFromKeyShapeListOfShapeMap m (upcast edge)+ case neighbours of + [a, b] -> do+ continuity <- liftIO . join $ BRep.Tool.continuity edge <$> (unsafeDowncast a) <*> (unsafeDowncast b)+ return (continuity == GeomAbs.Shape.C0)+ _ -> return False+edgeToPath + :: Ptr TopoDS.Edge + -> IO (Path) edgeToPath edge = fmap (Path . ComplexRawPath) . fromAcquirePtr $ do builder <- MakeWire.new liftIO . MakeWire.addEdge builder @@ -76,12 +101,20 @@ =<< TopoDS.Shape.copy (upcast edge) MakeWire.wire builder -getEdgesWithRadius :: (Integer -> Path -> Maybe Double) -> Ptr TopoDS.Shape -> Acquire [(Double, Ptr TopoDS.Edge)]-getEdgesWithRadius f s = do+getEdgesWithRadius + :: (Integer -> Path -> Maybe Double) + -> Ptr (NCollection.IndexedDataMap.IndexedDataMap TopoDS.Shape (NCollection.List TopoDS.Shape))+ -> Ptr TopoDS.Shape + -> Acquire [(Double, Ptr TopoDS.Edge)]+getEdgesWithRadius f m s = do edges <- allEdges s fmap catMaybes . forM (zip [0..] edges) $ \(i, e) -> do- path <- liftIO . edgeToPath $ e- return $ (, e) <$> find (> 0) (f i path)+ shouldFillet <- canFillet m e+ if not shouldFillet + then return Nothing+ else do+ path <- liftIO . edgeToPath $ e+ return $ (, e) <$> (find (> 0) (f i path)) trySomeIndexedConditionalFilletWithPaint :: (SubTypeOf BRepBuilderAPI.MakeShape a)@@ -94,24 +127,33 @@ trySomeIndexedConditionalFilletWithPaint makeBuilder addEdge paintFunction radiusFunction solid = solidFromAcquireWithPaintMapWithCatch $ do s <- acquireSolid solid- builder <- makeBuilder s - edgesWithRadius <- getEdgesWithRadius radiusFunction s+ liftIO $ BRepLib.encodeRegularity s 1e-4 - liftIO $ forM_ edgesWithRadius (uncurry (addEdge builder))+ m <- NCollection.IndexedDataMap.newShapeListOfShapeMap+ liftIO $ TopExp.mapShapesAndAncestors s ShapeEnum.Edge ShapeEnum.Face m - resultShape <- MakeShape.shape (upcast builder)+ edgesWithRadius <- getEdgesWithRadius radiusFunction m s - newPaintMap <-- remapWithBlendFunction- paintFunction- s- (snd <$> edgesWithRadius)- (makeShapeHistory . upcast $ builder)- (solidPaintMap solid)+ if null edgesWithRadius + then pure (solidPaintMap solid, s)+ else do+ builder <- makeBuilder s - pure (newPaintMap, resultShape)+ liftIO $ forM_ edgesWithRadius (uncurry (addEdge builder)) + resultShape <- MakeShape.shape (upcast builder)++ newPaintMap <-+ remapWithBlendFunction+ paintFunction+ s+ (snd <$> edgesWithRadius)+ (makeShapeHistory . upcast $ builder)+ (solidPaintMap solid)++ pure (newPaintMap, resultShape)+ -- | Version of `tryRoundIndexedConditionalFillet` -- -- Exposes how to assign `Paint` to the fillet surface@@ -137,7 +179,7 @@ -- -- In general, relying on the edge index is inelegant, ----- In an earlier version of Waterfall-CAD, fillets were controlled by the edge *endpoints*, rather than the edge path+-- In an earlier version of Waterfall-CAD, fillets were controlled by the edge /endpoints/, rather than the edge path -- -- If you consider a Solid with a semicircular face, -- there's no way to select either the curved or the flat edge of the semicircle based on just the endpoints@@ -350,7 +392,7 @@ chamferWithPaint paintFunction d = conditionalChamferWithPaint paintFunction (const . pure $ d ) --- | Returns a value when the target of a lens, when applied to the edge's `Path`'s endpoints are close to one another.+-- | Returns a value when the target of a lens is nearly equal at both endpoints of the edge's `Path`. -- -- This can be used in combination with `roundConditionalFillet`/`conditionalChamfer`. --
src/Waterfall/IO.hs view
@@ -58,13 +58,14 @@ import Control.Monad.IO.Class (liftIO) import Control.Monad (unless, when, forM, forM_, (<=<)) import Waterfall.Internal.Finalizers (acquireForeignPtr, fromAcquirePtr)-import Data.Acquire ( Acquire, withAcquire )+import Data.Acquire ( Acquire, withAcquire, mkAcquire) import Foreign.Ptr (Ptr) import Data.Char (toLower) import System.FilePath (takeExtension) import Control.Exception (Exception, throwIO) import OpenCascade.TDF.Label (Label)-import Waterfall.Paint (Colour(..), paintColour, defaultPaint, Paint, DoubleSidedness(..), paintName, paintOpacity, paintEmissiveColour, paintMetallic, paintDoubleSidedness, paintRoughness)+import Waterfall.Paint (paintColour, defaultPaint, Paint, DoubleSidedness(..), paintName, paintOpacity, paintEmissiveColour, paintMetallic, paintDoubleSidedness, paintRoughness)+import Waterfall.Colour (Colour, toDataColour) import qualified OpenCascade.XCAFDoc.ColorTool as XCafDoc.ColourTool import Control.Lens ((^.), Getting) import System.IO (hPutStrLn, stderr)@@ -78,6 +79,9 @@ import Control.Applicative ((<|>), Alternative) import qualified OpenCascade.Graphic3D.AlphaMode as AlphaMode import qualified OpenCascade.Graphic3D.TypeOfBackfacingModel as TypeOfBackfacingModel+import qualified Data.Colour.SRGB as SRGB+import qualified Data.Colour.SRGB.Linear as SRGB.Linear+import qualified OpenCascade.BRepTools as BRepTools import Data.Map (Map) import qualified Data.Map as M@@ -112,6 +116,7 @@ in case ext of ".stl" -> Just (writeSTL, readSTL) ".step" -> Just (const writeSTEP, readSTEP)+ ".stp" -> Just (const writeSTEP, readSTEP) ".gltf" -> Just (writeGLTF, readGLTF) ".glb" -> Just (writeGLB, readGLB) ".obj" -> Just (writeOBJ, readOBJ)@@ -177,13 +182,19 @@ resWrite <- liftIO $ StepCAFControl.Writer.write writer filepath unless (resWrite == IFSelect.ReturnStatus.Done) (liftIO . throwIO $ WaterfallIOException FileError filepath) +clamp :: Double -> Double+clamp = min 1 . max 0+ colourToOCColor :: Colour -> Acquire (Ptr Quantity.Color)-colourToOCColor (Colour r g b) =- Quantity.Color.new r g b Quantity.TypeOfColor.SRGB- +colourToOCColor c = + let SRGB.RGB r g b = SRGB.toSRGB . toDataColour $ c+ in Quantity.Color.new (clamp r) (clamp g) (clamp b) Quantity.TypeOfColor.SRGB++-- Used for Emissive Colour, which is in a linear RGB space colourToOCVec3 :: Colour -> Acquire (Ptr (NCollection.Vec3 Float))-colourToOCVec3 (Colour r g b) =- NCollection.Vec3.newVec3Float (realToFrac r) (realToFrac g) (realToFrac b)+colourToOCVec3 c =+ let SRGB.Linear.RGB r g b = SRGB.Linear.toRGB . toDataColour $ c+ in NCollection.Vec3.newVec3Float (realToFrac . clamp $ r) (realToFrac . clamp $ g) (realToFrac . clamp $ b) paintLookup :: Alternative f => Paint -> Getting (f a) Paint (f a) -> f a paintLookup paint lens = paint ^. lens <|> defaultPaint ^. lens@@ -263,7 +274,9 @@ mesh :: Double -> Ptr TopoDS.Shape -> Acquire () mesh linDeflection s = do mesher <- BRepMesh.IncrementalMesh.fromShapeAndLinDeflection s linDeflection- liftIO $ BRepMesh.IncrementalMesh.perform mesher+ mkAcquire+ (BRepTools.clean s False >> BRepMesh.IncrementalMesh.perform mesher)+ (const $ BRepTools.clean s False) cafDocument :: Ptr TopoDS.Shape @@ -285,7 +298,8 @@ s <- acquireSolid solid mesh linDeflection s doc <- cafDocument s (solidPaintMap solid)- liftIO $ RWGltf.CafWriter.perform writer doc meta progress+ writtenOkay <- liftIO $ RWGltf.CafWriter.perform writer doc meta progress+ liftIO . unless writtenOkay . throwIO $ WaterfallIOException FileError filepath -- | Write a `Solid` to a glTF file at a given path --@@ -329,8 +343,10 @@ s <- acquireSolid solid mesh linDeflection s doc <- cafDocument s (solidPaintMap solid)- liftIO $ RWObj.CafWriter.perform writer doc meta progress+ writtenOkay <- liftIO $ RWObj.CafWriter.perform writer doc meta progress+ liftIO . unless writtenOkay . throwIO $ WaterfallIOException FileError filepath + -- | Read a `Solid` from a file at a given path -- -- Throws an error if loading fails, or if it's unable to work out@@ -362,9 +378,10 @@ readSTEP filepath = fmap (`Solid` emptyPaintMap) . fromAcquirePtr $ do reader <- STEPReader.new status <- liftIO $ XSControl.Reader.readFile (upcast reader) filepath- _ <- liftIO $ XSControl.Reader.transferRoots (upcast reader)- shape <- XSControl.Reader.oneShape (upcast reader) unless (status == IFSelect.ReturnStatus.Done) (liftIO . throwIO $ WaterfallIOException FileError filepath)+ rootCount <- liftIO $ XSControl.Reader.transferRoots (upcast reader)+ unless (rootCount > 0) (liftIO . throwIO $ WaterfallIOException BadGeometryError filepath)+ shape <- XSControl.Reader.oneShape (upcast reader) shapeIsNull <- liftIO $ TopoDS.Shape.isNull shape when shapeIsNull (liftIO . throwIO $ WaterfallIOException BadGeometryError filepath) return shape
src/Waterfall/Internal/Diagram.hs view
@@ -1,6 +1,8 @@ {-# LANGUAGE TupleSections #-}+{-# LANGUAGE TypeApplications #-} module Waterfall.Internal.Diagram ( buildSolidDiagramFills+, silhouetteShape ) where import Waterfall.Internal.Solid (PaintMap(..), materialiseFacePaints, paintMapIsEmpty) import Waterfall.Paint (Paint)@@ -10,21 +12,20 @@ import qualified OpenCascade.HLRBRep.Types as HLRBRep import qualified OpenCascade.HLRBRep.TypeOfResultingEdge as HLRBRep import qualified OpenCascade.TopoDS as TopoDS-import Waterfall.Internal.Edges (allEdges, buildEdgeCurve3D, allSubShapesWithCopy)+import Waterfall.Internal.Edges (allEdges, buildEdgeCurve3D) import Data.Traversable (forM) import qualified OpenCascade.HLRBRep.HLRToShape as HLRBRep.HLRToShape import qualified OpenCascade.Bnd.Box as Bnd.Box-import Data.Foldable (forM_)+import Data.Foldable (forM_, maximumBy) import Control.Monad.IO.Class (liftIO) import qualified OpenCascade.BRepBndLib as BRepBndLib import qualified OpenCascade.BOPAlgo.Builder as BOPAlgo.Builder-import qualified OpenCascade.TopAbs.ShapeEnum as ShapeEnum import qualified OpenCascade.TopoDS.Builder as TopoDS.Builder import qualified OpenCascade.TopoDS.Compound as TopoDS.Compound-import OpenCascade.Inheritance (upcast, unsafeDowncast)-import Waterfall.Internal.FromOpenCascade (gpPntToV3)+import OpenCascade.Inheritance (upcast)+import Waterfall.Internal.FromOpenCascade (gpPntToV3, subShapes, subShapesOf) import Control.Lens ((^.), (&), (.~), (<&>))-import Linear (_x, _y, _z, V3, norm)+import Linear (V3 (..), _x, _y, _z, norm, unit, cross) import qualified Data.IntMap as IntMap import Data.Maybe (fromMaybe, catMaybes) import qualified Waterfall.Internal.ShapeMap as ShapeMap@@ -40,7 +41,7 @@ import qualified OpenCascade.GProp.GProps as GProps import qualified OpenCascade.Poly.Triangulation as Poly.Triangulation import qualified OpenCascade.Poly.Triangle as Poly.Triangle-import Control.Monad ((<=<), filterM)+import Control.Monad ((<=<), filterM, join) import Waterfall.Internal.ToOpenCascade (v3ToPnt, v3ToDir) import qualified OpenCascade.GP.Pnt as GP.Pnt import qualified OpenCascade.GP.Lin as GP.Lin@@ -48,6 +49,13 @@ import qualified OpenCascade.TopoDS.Shape as TopoDS.Shape import qualified Data.Map as M import qualified OpenCascade.ShapeUpgrade.UnifySameDomain as UnifySameDomain+import qualified OpenCascade.HLRBRep.Algo as HLRBRep.Algo+import qualified OpenCascade.GP as GP+import qualified OpenCascade.HLRAlgo.Projector as HLRAlgo.Projector+import qualified OpenCascade.GP.Ax2 as GP.Ax2+import Data.Function (on)+import qualified Data.List.NonEmpty as NE+import Data.Proxy (Proxy(..)) boundaryEdges :: Ptr HLRBRep.HLRToShape -> Acquire [Ptr TopoDS.Edge] boundaryEdges extractor = @@ -81,7 +89,7 @@ pruneDangling :: [Ptr TopoDS.Edge] -> Acquire [Ptr TopoDS.Edge] pruneDangling edges = do withVertices <- forM edges $ \e -> do- (e, ) <$> allSubShapesWithCopy ShapeEnum.Vertex (upcast e)+ (e, ) <$> subShapesOf (Proxy @TopoDS.Vertex) (upcast e) let loop current = do vertexIndex <- liftIO $ ShapeMap.fromList (zip (concatMap snd current) [0 :: Int ..]) labelled <- forM current $ \(e, vs) ->@@ -103,7 +111,7 @@ unifier <- UnifySameDomain.fromShape (upcast compound) False True False liftIO $ UnifySameDomain.build unifier sameDomain <- UnifySameDomain.shape unifier- liftIO . fmap (fmap Shape) . fromAcquirePtrT $ allSubShapesWithCopy ShapeEnum.Face sameDomain+ liftIO . fmap (fmap Shape) . fromAcquirePtrT $ subShapesOf (Proxy @TopoDS.Face) sameDomain faceArea :: Ptr TopoDS.Face -> Acquire Double faceArea face = do@@ -111,14 +119,13 @@ liftIO $ BRepGProp.surfaceProperties (upcast face) props False False liftIO $ GProps.mass props -buildSolidDiagramFills' - :: Ptr TopoDS.Shape+projectedRegions+ :: Ptr TopoDS.Shape -> V3 Double - -> Ptr HLRAlgo.Projector+ -> Ptr HLRAlgo.Projector -> Ptr HLRBRep.HLRToShape- -> [(Ptr TopoDS.Face, Paint)]- -> Acquire [(Paint, Shape)]-buildSolidDiagramFills' s projectionDir projector extractor paints = do+ -> Acquire [(Ptr TopoDS.Face, Maybe (Ptr TopoDS.Face))]+projectedRegions s projectionDir projector extractor = do boundary <- boundaryEdges extractor if null boundary then return []@@ -126,14 +133,17 @@ tolerance <- calcFuzzyTolerance boundary rayBound <- calcRayBound s let angularTolerance = 1e-8- fuser <- BOPAlgo.Builder.new - liftIO $ BOPAlgo.Builder.setFuzzyValue fuser tolerance- forM_ boundary (liftIO . BOPAlgo.Builder.addArgument fuser . upcast)- liftIO $ BOPAlgo.Builder.perform fuser- keptEdges <- pruneDangling - =<< traverse (liftIO . unsafeDowncast)- =<< allSubShapesWithCopy ShapeEnum.Edge - =<< BOPAlgo.Builder.shape fuser+ keptEdges <- case boundary of + [oneEdge] -> pure [oneEdge]+ _ -> do+ fuser <- BOPAlgo.Builder.new + liftIO $ BOPAlgo.Builder.setNonDestructive fuser True+ liftIO $ BOPAlgo.Builder.setFuzzyValue fuser tolerance+ forM_ boundary (liftIO . BOPAlgo.Builder.addArgument fuser . upcast)+ liftIO $ BOPAlgo.Builder.perform fuser+ pruneDangling + =<< subShapes+ =<< BOPAlgo.Builder.shape fuser builder <- TopoDS.Builder.new compound <- TopoDS.Compound.new@@ -150,58 +160,86 @@ if not ok then return [] else do- regions <- traverse (liftIO . unsafeDowncast)- =<< allSubShapesWithCopy ShapeEnum.Face faces+ regions <- subShapes faces inv <- Projector.invertedTransformation projector intersector <- ShapeIntersector.new liftIO $ ShapeIntersector.load intersector s (tolerance/1000) - paintMap <- liftIO $ ShapeMap.fromList (first upcast <$> paints)- d <- v3ToDir projectionDir forwardFacingRegions <- filterM (fmap (> 0) . faceArea) regions- paintRegionMap <- fmap (M.fromListWith (<>) . catMaybes) $ forM forwardFacingRegions $ \region -> do+ forM forwardFacingRegions $ \region -> do mesh <- IncrementalMesh.fromShapeAndLinDeflection (upcast region) tolerance liftIO $ IncrementalMesh.perform mesh loc <- TopLoc.Location.new- props <- GProps.new- liftIO $ BRepGProp.surfaceProperties (upcast region) props False False tri <- BRep.Tool.triangulation region loc nullTriangulation <- liftIO $ Poly.Triangulation.isNull tri nTri <- if nullTriangulation then pure 0 else liftIO $ Poly.Triangulation.nbTriangles tri - triangleCenters <- forM [1..nTri] $ \i -> do + triangles <- forM [1..nTri] $ \i -> do t <- Poly.Triangulation.triangle tri i- indices <- traverse (liftIO . Poly.Triangle.value t) [1, 2, 3]- corners <- traverse (liftIO . gpPntToV3 <=< Poly.Triangulation.node tri) indices- pure (sum corners / 3)- centerOfMass <- liftIO . gpPntToV3 =<< GProps.centreOfMass props- let candidatePoints = (triangleCenters <> [centerOfMass])- & (traverse . _z .~ 0)+ indices <- traverse (liftIO . Poly.Triangle.value t) (V3 1 2 3)+ traverse (liftIO . gpPntToV3 <=< Poly.Triangulation.node tri) indices+ let triangleArea (V3 a b c) = norm ((b - a) `cross` (c - a)) / 2+ triangleCenter corners = sum corners / 3+ candidatePoint = triangles+ & NE.nonEmpty+ & fmap (triangleCenter + . (maximumBy (compare `on` triangleArea)))+ & traverse . _z .~ 0 - let lookupCandidatePaint [] = pure Nothing- lookupCandidatePaint (h:t) = do- pin <- v3ToPnt h+ let lookupCandidateFace point = do+ pin <- v3ToPnt point p <- GP.Pnt.transformed pin inv line <- GP.Lin.new p d liftIO $ ShapeIntersector.perform intersector line (-rayBound) rayBound n <- liftIO $ ShapeIntersector.nbPnt intersector hits <- forM [1 .. n] $ \i -> (, i) <$> liftIO (ShapeIntersector.wParameter intersector i)- case hits of- [] -> lookupCandidatePaint t- _ -> do- let (_, nearest) = maximum hits- hit <- ShapeIntersector.face intersector nearest- found <- liftIO $ ShapeMap.lookup paintMap (upcast hit)- return $ Just (fromMaybe mempty found)- paint <- lookupCandidatePaint candidatePoints- return $ (, [region]) <$> paint+ forM (NE.nonEmpty hits) $ \h -> do+ let (_, nearest) = maximum h+ ShapeIntersector.face intersector nearest - traverse mergeRegions paintRegionMap- <&> foldMap sequence . M.toList+ faceMaybe <- fmap join . traverse lookupCandidateFace $ candidatePoint+ return $ (region, faceMaybe)++silhouetteShape + :: Ptr TopoDS.Shape + -> Acquire [Shape]+silhouetteShape s = do+ algo <- HLRBRep.Algo.new+ liftIO $ HLRBRep.Algo.add algo s+ o <- GP.origin+ let projectionDir = unit _z+ projector <- HLRAlgo.Projector.fromAx2 =<< GP.Ax2.newAutoX o =<< v3ToDir projectionDir+ liftIO $ do + HLRBRep.Algo.projector algo projector+ HLRBRep.Algo.update algo+ HLRBRep.Algo.hide algo+ extractor <- HLRBRep.HLRToShape.fromAlgo algo+ regions <- projectedRegions s projectionDir projector extractor+ let hitRegions = fmap fst . catMaybes . fmap sequence $ regions+ mergeRegions hitRegions++buildSolidDiagramFills' + :: Ptr TopoDS.Shape+ -> V3 Double + -> Ptr HLRAlgo.Projector+ -> Ptr HLRBRep.HLRToShape+ -> [(Ptr TopoDS.Face, Paint)]+ -> Acquire [(Paint, Shape)]+buildSolidDiagramFills' s projectionDir projector extractor paints = do+ paintMap <- liftIO $ ShapeMap.fromList (first upcast <$> paints)+ regions <- projectedRegions s projectionDir projector extractor+ let hitRegions = catMaybes . fmap sequence $ regions+ paintRegionMap <- fmap (M.fromListWith (<>) . catMaybes)+ $ forM hitRegions $ \(region, hit) -> do+ paint <- liftIO $ ShapeMap.lookup paintMap (upcast hit)+ return $ (, [region]) <$> paint++ traverse mergeRegions paintRegionMap+ <&> foldMap sequence . M.toList buildSolidDiagramFills :: PaintMap
src/Waterfall/Internal/Edges.hs view
@@ -2,7 +2,6 @@ ( edgeEndpoints , edgeValue , wireEndpoints-, allSubShapesWithCopy , allWireEndpoints , allWires , allEdges@@ -11,6 +10,8 @@ , buildEdgeCurve3D , reverseEdge , reverseWire+, forwardWire+, forwardWireAndStripZeroLengthEdges , intersperseLines , joinWires , splitWires@@ -24,13 +25,11 @@ import qualified OpenCascade.BRep.Tool as BRep.Tool import qualified OpenCascade.Geom.Curve as Geom.Curve import qualified OpenCascade.BRepTools.WireExplorer as WireExplorer-import qualified OpenCascade.TopExp.Explorer as Explorer -import qualified OpenCascade.TopAbs.ShapeEnum as ShapeEnum import qualified OpenCascade.BRepBuilderAPI.MakeEdge as MakeEdge import qualified OpenCascade.BRepLib as BRepLib import Waterfall.Internal.NearZero (nearZero) import OpenCascade.GeomAbs.Shape as GeomAbs.Shape-import Waterfall.Internal.FromOpenCascade (gpPntToV3, gpVecToV3)+import Waterfall.Internal.FromOpenCascade (gpPntToV3, gpVecToV3, subShapes) import qualified OpenCascade.BRepAdaptor.Curve as BRepAdaptor.Curve import qualified OpenCascade.GCPnts.AbscissaPoint as AbscissaPoint import qualified OpenCascade.GProp.GProps as GProps@@ -40,12 +39,12 @@ import Linear (V3 (..), distance, normalize) import Foreign.Ptr import qualified OpenCascade.BRepBuilderAPI.MakeWire as MakeWire-import Control.Monad (when)+import Control.Monad (when, (<=<), unless, filterM) import Waterfall.Internal.ToOpenCascade (v3ToPnt)-import Data.Foldable (traverse_) import OpenCascade.Inheritance (upcast, unsafeDowncast) import qualified Waterfall.Internal.ShapeMap as ShapeMap import qualified OpenCascade.TopAbs.Orientation as TopAbs.Orientation+import qualified OpenCascade.TopExp as TopExp edgeEndpoints :: Ptr TopoDS.Edge -> IO (V3 Double, V3 Double) edgeEndpoints edge = (`with` pure) $ do@@ -54,18 +53,23 @@ p2 <- liftIO . BRep.Tool.curveParamLast $ edge s <- (liftIO . gpPntToV3) =<< Geom.Curve.value curve p1 e <- (liftIO . gpPntToV3) =<< Geom.Curve.value curve p2- return (s, e)+ isForward <- liftIO $ edgeIsForward edge+ if isForward+ then return (s, e)+ else return (e, s) edgeValue :: Ptr TopoDS.Edge -> Double -> IO (V3 Double) edgeValue edge v = (`with` pure) $ do curve <- BRep.Tool.curve edge p1 <- liftIO . BRep.Tool.curveParamFirst $ edge p2 <- liftIO . BRep.Tool.curveParamLast $ edge- let p' = (1-v) * p1 + v * p2+ isForward <- liftIO $ edgeIsForward edge+ let v' = if isForward then v else (1-v)+ let p' = (1-v') * p1 + v' * p2 (liftIO . gpPntToV3) =<< Geom.Curve.value curve p' allWireEndpoints :: Ptr TopoDS.Wire -> IO [(V3 Double, V3 Double)]-allWireEndpoints wire = with (WireExplorer.fromWire wire) $ \explorer -> do+allWireEndpoints wire = with (WireExplorer.fromWire =<< forwardWire wire) $ \explorer -> do let runToEnd = do more <- WireExplorer.more explorer if more then do@@ -76,35 +80,55 @@ else pure [] runToEnd -allSubShapesWithCopy :: ShapeEnum.ShapeEnum -> Ptr TopoDS.Shape -> Acquire [Ptr TopoDS.Shape]-allSubShapesWithCopy t s = do - explorer <- Explorer.new s t- let go acc = do- isMore <- liftIO $ Explorer.more explorer- if isMore - then do- v <- liftIO $ Explorer.value explorer- isPresent <- liftIO $ ShapeMap.lookup acc v- (newAcc, add) <- case isPresent of - Nothing -> do - v' <- TopoDS.Shape.copy v- newMap <- liftIO $ ShapeMap.addIfAbsent (v', ()) acc- return (newMap, (v':))- Just _ -> pure (acc, id) - liftIO $ Explorer.next explorer- add <$> go newAcc- else return []- go ShapeMap.empty - allEdges :: Ptr TopoDS.Shape -> Acquire [Ptr TopoDS.Edge]-allEdges s = traverse (liftIO . unsafeDowncast) =<< allSubShapesWithCopy ShapeEnum.Edge s +allEdges = subShapes allWires :: Ptr TopoDS.Shape -> Acquire [Ptr TopoDS.Wire]-allWires s = traverse (liftIO . unsafeDowncast) =<< allSubShapesWithCopy ShapeEnum.Wire s- +allWires = traverse forwardWire <=< subShapes++wireFromEdges :: [Ptr TopoDS.Edge] -> Acquire (Ptr TopoDS.Wire)+wireFromEdges edges = do+ builder <- MakeWire.new+ let addAll [] = pure ()+ addAll (e:es) = do+ hasNoLength <- nearZero <$> edgeLength e+ unless hasNoLength $ MakeWire.addEdge builder e+ done <- MakeWire.isDone builder+ when done (addAll es)+ liftIO $ addAll edges+ MakeWire.wire builder++forwardWire :: Ptr TopoDS.Wire -> Acquire (Ptr TopoDS.Wire)+forwardWire wire = do+ edges <- wireEdgesWithoutReversing wire+ alreadyGood <- and <$> liftIO (traverse edgeIsForward edges)+ if alreadyGood + then return wire+ else do+ wireFromEdges =<< wireEdges wire++forwardWireAndStripZeroLengthEdges :: Ptr TopoDS.Wire -> Acquire (Maybe (Ptr TopoDS.Wire))+forwardWireAndStripZeroLengthEdges wire = do+ edges <- wireEdgesWithoutReversing wire+ let isAlreadyFine e = (&&) <$> edgeIsForward e <*> edgeHasLength e+ alreadyGood <- and <$> liftIO (traverse isAlreadyFine edges)+ if alreadyGood + then return (Just wire)+ else do+ lengthyEdges <- liftIO . filterM edgeHasLength =<< wireEdges wire+ if null lengthyEdges + then return Nothing+ else Just <$> wireFromEdges lengthyEdges+edgeIsForward :: Ptr TopoDS.Edge -> IO Bool+edgeIsForward = + fmap (== TopAbs.Orientation.Forward) . TopoDS.Shape.orientation . upcast++edgeHasLength :: Ptr TopoDS.Edge -> IO Bool+edgeHasLength = fmap (not . nearZero) . edgeLength+ wireEndpoints :: Ptr TopoDS.Wire -> IO (V3 Double, V3 Double)-wireEndpoints wire = with (WireExplorer.fromWire wire) $ \explorer -> do+wireEndpoints wire = with (WireExplorer.fromWire =<< forwardWire wire) $ \explorer -> do v1 <- WireExplorer.current explorer (s, _) <- edgeEndpoints v1 let runToEnd = do@@ -121,63 +145,106 @@ edgeTangentStart :: Ptr TopoDS.Edge -> IO (V3 Double) edgeTangentStart e = (`with` pure) $ do curve <- BRep.Tool.curve e- p1 <- liftIO . BRep.Tool.curveParamFirst $ e- liftIO . gpVecToV3 =<< Geom.Curve.dn curve p1 1+ isForward <- liftIO $ edgeIsForward e+ p1 <- if isForward+ then liftIO . BRep.Tool.curveParamFirst $ e+ else liftIO . BRep.Tool.curveParamLast $ e+ let reverseTangent =+ if isForward+ then id+ else negate + reverseTangent <$> (liftIO . gpVecToV3 =<< Geom.Curve.dn curve p1 1) + edgeTangentEnd :: Ptr TopoDS.Edge -> IO (V3 Double) edgeTangentEnd e = (`with` pure) $ do curve <- BRep.Tool.curve e- p1 <- liftIO . BRep.Tool.curveParamLast $ e- liftIO . gpVecToV3 =<< Geom.Curve.dn curve p1 1+ isForward <- liftIO $ edgeIsForward e+ p1 <- if isForward+ then liftIO . BRep.Tool.curveParamLast $ e+ else liftIO . BRep.Tool.curveParamFirst $ e+ let reverseTangent =+ if isForward+ then id+ else negate + reverseTangent <$> (liftIO . gpVecToV3 =<< Geom.Curve.dn curve p1 1) wireTangentStart :: Ptr TopoDS.Wire -> IO (V3 Double) wireTangentStart wire = with (WireExplorer.fromWire wire) $ \explorer -> do v1 <- WireExplorer.current explorer edgeTangentStart v1 +forwardEdge :: Ptr TopoDS.Edge -> Acquire (Ptr TopoDS.Edge)+forwardEdge e = do+ isForward <- liftIO $ edgeIsForward e+ if isForward + then return e+ else do+ curve <- BRep.Tool.curve e + firstP <- liftIO $ BRep.Tool.curveParamFirst e+ lastP <- liftIO $ BRep.Tool.curveParamLast e+ firstP' <- liftIO $ Geom.Curve.reversedParameter curve firstP+ lastP' <- liftIO $ Geom.Curve.reversedParameter curve lastP+ firstVertex <- TopExp.firstVertex e False+ lastVertex <- TopExp.lastVertex e False+ curve' <- Geom.Curve.reversed curve+ MakeEdge.fromCurveVerticesAndParameters curve' lastVertex firstVertex lastP' firstP' + reverseEdge :: Ptr TopoDS.Edge -> Acquire (Ptr TopoDS.Edge) reverseEdge e = do curve <- BRep.Tool.curve e firstP <- liftIO $ BRep.Tool.curveParamFirst e lastP <- liftIO $ BRep.Tool.curveParamLast e- firstP' <- liftIO $ Geom.Curve.reversedParameter curve firstP- lastP' <- liftIO $ Geom.Curve.reversedParameter curve lastP- curve' <- Geom.Curve.reversed curve- MakeEdge.fromCurveAndParameters curve' lastP' firstP' + firstVertex <- TopExp.firstVertex e True+ lastVertex <- TopExp.lastVertex e True+ isForward <- liftIO $ edgeIsForward e+ if not isForward + then do+ MakeEdge.fromCurveVerticesAndParameters curve lastVertex firstVertex firstP lastP+ else do+ firstP' <- liftIO $ Geom.Curve.reversedParameter curve firstP+ lastP' <- liftIO $ Geom.Curve.reversedParameter curve lastP+ curve' <- Geom.Curve.reversed curve+ MakeEdge.fromCurveVerticesAndParameters curve' lastVertex firstVertex lastP' firstP' -wireEdges :: Ptr TopoDS.Wire -> Acquire [Ptr TopoDS.Edge]-wireEdges wire = do+wireEdgesWithoutReversing :: Ptr TopoDS.Wire -> Acquire [Ptr TopoDS.Edge]+wireEdgesWithoutReversing wire = do explorer <- WireExplorer.fromWire wire let runToEnd = do more <- liftIO $ WireExplorer.more explorer if not more then pure [] else do- edge <- liftIO $ WireExplorer.current explorer- edge' <- (liftIO . unsafeDowncast) =<< TopoDS.Shape.copy (upcast edge)- orientation <- liftIO $ TopoDS.Shape.orientation (upcast edge')- edge'' <- if orientation == TopAbs.Orientation.Reversed- then reverseEdge edge'- else return edge'+ edge <- (liftIO . unsafeDowncast)+ =<< TopoDS.Shape.copy . upcast+ =<< (liftIO $ WireExplorer.current explorer)+ liftIO $ WireExplorer.next explorer- (edge'' :) <$> runToEnd+ (edge :) <$> runToEnd runToEnd -reverseWire :: Ptr TopoDS.Wire -> Acquire (Ptr TopoDS.Wire) -reverseWire wire = do+wireEdges :: Ptr TopoDS.Wire -> Acquire [Ptr TopoDS.Edge]+wireEdges wire = do explorer <- WireExplorer.fromWire wire- makeWire <- MakeWire.new let runToEnd = do more <- liftIO $ WireExplorer.more explorer- when more $ do- edge <- liftIO $ WireExplorer.current explorer- edge' <- reverseEdge edge- liftIO $ WireExplorer.next explorer- runToEnd- liftIO $ MakeWire.addEdge makeWire edge'+ if not more+ then pure []+ else do+ edge <- forwardEdge+ =<< (liftIO . unsafeDowncast) + =<< TopoDS.Shape.copy . upcast + =<< (liftIO $ WireExplorer.current explorer)+ liftIO $ WireExplorer.next explorer+ (edge :) <$> runToEnd runToEnd- MakeWire.wire makeWire +reverseWire :: Ptr TopoDS.Wire -> Acquire (Ptr TopoDS.Wire) +reverseWire wire = do+ wireFromEdges+ =<< fmap reverse . traverse reverseEdge+ =<< wireEdges wire + line' :: V3 Double -> V3 Double -> Acquire (Ptr TopoDS.Wire) line' s e = do builder <- MakeWire.new@@ -198,21 +265,10 @@ else (a :) <$> ((:) <$> line' ea sb <*> intersperseLines (b:xs)) joinWires :: [Ptr TopoDS.Wire] -> Acquire (Ptr TopoDS.Wire)-joinWires wires = do- builder <- MakeWire.new- let addWire wire = do - explorer <- WireExplorer.fromWire wire- let runToEnd = do- edge <- liftIO $ WireExplorer.current explorer- liftIO $ MakeWire.addEdge builder edge- liftIO $ WireExplorer.next explorer- more <- liftIO $ WireExplorer.more explorer- when more runToEnd- runToEnd- traverse_ addWire $ wires- MakeWire.wire builder+joinWires wires =+ wireFromEdges+ =<< (concat <$> traverse wireEdges wires) - edgeToWire :: Ptr TopoDS.Edge -> Acquire (Ptr TopoDS.Wire) edgeToWire edge = do builder <- MakeWire.new@@ -221,28 +277,27 @@ splitWires :: Ptr TopoDS.Wire -> Acquire [Ptr TopoDS.Wire] splitWires wire = do- explorer <- WireExplorer.fromWire wire- let makeSegment = do- builder <- MakeWire.new- let addOneWire lastDelta = do- edge <- liftIO $ WireExplorer.current explorer- s' <- normalize <$> edgeTangentStart edge- e' <- normalize <$> edgeTangentEnd edge- let startIsTangent = maybe True (all nearZero . (s' -)) lastDelta- when startIsTangent $ do- liftIO $ MakeWire.addEdge builder edge- liftIO $ WireExplorer.next explorer- more <- liftIO $ WireExplorer.more explorer- when more (addOneWire (Just e'))- liftIO $ addOneWire Nothing- thisWire <- MakeWire.wire builder- more <- liftIO $ WireExplorer.more explorer- rest <- if more- then makeSegment - else return []- return $ thisWire : rest - makeSegment+ edges <- wireEdges $ wire+ let pairWithTangents edge = do+ s' <- normalize <$> edgeTangentStart edge+ e' <- normalize <$> edgeTangentEnd edge+ return (edge, s', e')+ edgesWithTangents <- liftIO $ traverse pairWithTangents edges + let shouldPair (_, _, e') (_, s', _) = all nearZero (s' - e')+ let getEdgeFromPair (e, _, _) = e+ let groupEdgesBy _f [] = []+ groupEdgesBy _f (e:[]) = [[e]]+ groupEdgesBy f (a:b:rest) = + if f a b + then case groupEdgesBy f (b:rest) of + (h:t) -> (a:h):t+ [] -> [[a]]+ else [a] : groupEdgesBy f (b:rest)++ traverse wireFromEdges (fmap getEdgeFromPair <$> groupEdgesBy shouldPair edgesWithTangents)++ buildEdgeCurve3D :: Ptr TopoDS.Edge -> Acquire (Ptr TopoDS.Edge) buildEdgeCurve3D edge = do edge' <- (liftIO . unsafeDowncast) =<< TopoDS.Shape.copy (upcast edge)@@ -263,7 +318,7 @@ truncateWire :: Double -> Ptr TopoDS.Wire -> Acquire (Ptr TopoDS.Wire) truncateWire targetLength wire = do- explorer <- WireExplorer.fromWire wire+ explorer <- WireExplorer.fromWire =<< forwardWire wire builder <- MakeWire.new let go remaining = do more <- liftIO $ WireExplorer.more explorer
src/Waterfall/Internal/Finalizers.hs view
@@ -8,7 +8,7 @@ However @waterfall-cad@ does not (at the highest level) keep values in the @Acquire@ monad. -(This is required to support functions like `Waterfall.Solids.volume`, which return pure Haskell primitives.)+(This is required to support functions like `Waterfall.Solid.volume`, which return pure Haskell primitives.) -} module Waterfall.Internal.Finalizers @@ -73,11 +73,11 @@ liftIO $ Concurrent.newForeignPtr ptr finalize -- | Converting to a value in the `Data.Acquire.Acquire` monad, to a raw value.--- Analagous to calling `unsafePerformIO` to extract a value in the `IO` monad.+-- Analogous to calling `unsafePerformIO` to extract a value in the `IO` monad. -- The same constraints as apply to `unsafePerformIO` apply to this method. -- That is, it should only be used on "philosophically pure" actions. ----- The `free` action of the resource is called when the underlying value goes out of scope of the Haskell garbage collection,+-- The "free" action of the resource is called when the underlying value goes out of scope of the Haskell garbage collection, -- so may run at an unpredictable time. {-# NOINLINE unsafeFromAcquirePtr #-} unsafeFromAcquirePtr :: Acquire (Ptr a) -> ForeignPtr a@@ -110,7 +110,7 @@ -- | calling the pure valued functions with a pointer type would almost certainly be a bug -- --- @Ptr@ has an @NFData@ instance, so if we _only_ used that constraint, the functions could be applied to pointers+-- @Ptr@ has an @NFData@ instance, so if we /only/ used that constraint, the functions could be applied to pointers -- -- Defining a type family for "things that aren't pointers" lets us check that we aren't acquiring pointers type NoPtr :: k -> Constraint@@ -131,7 +131,7 @@ -- | Run a resource in the `Data.Acquire.Acquire` monad, returning its (fully evaluated) result as a pure value. ----- Analagous to calling `unsafePerformIO` to extract a value in the `IO` monad.+-- Analogous to calling `unsafePerformIO` to extract a value in the `IO` monad. -- The same constraints as apply to `unsafePerformIO` apply to this method. -- That is, it should only be used on "philosophically pure" actions. --
src/Waterfall/Internal/FromOpenCascade.hs view
@@ -1,8 +1,17 @@+{-# LANGUAGE TupleSections #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeApplications #-}+{-# LANGUAGE FlexibleContexts #-} module Waterfall.Internal.FromOpenCascade ( gpPntToV3 , gpVecToV3 , gpXYZToV3 , shapesFromListOfShape+, deduplicateTopoDSShapes+, containsShapeKind+, HasShapeKind (shapeKind)+, subShapes+, subShapesOf ) where import qualified OpenCascade.GP.Pnt as GP.Pnt@@ -10,13 +19,24 @@ import qualified OpenCascade.GP.XYZ as GP.XYZ import qualified OpenCascade.GP as GP import qualified OpenCascade.NCollection as NCollection-import qualified OpenCascade.NCollection.List as NCollection.List import qualified OpenCascade.NCollection.List.Iterator as NCollection.List.Iterator import qualified OpenCascade.TopoDS as TopoDS +import qualified OpenCascade.TopoDS.Shape as TopoDS.Shape import Linear (V3 (..)) import Foreign.Ptr import Data.Acquire (Acquire) import Control.Monad.IO.Class (liftIO)+import Waterfall.Internal.Finalizers (unsafeFromAcquire, NoPtr)+import qualified Waterfall.Internal.ShapeMap as ShapeMap+import Data.Maybe (isJust)+import Data.Foldable (foldrM)+import Control.DeepSeq (NFData)+import OpenCascade.TopAbs (ShapeEnum)+import qualified OpenCascade.TopAbs.ShapeEnum as ShapeEnum+import qualified OpenCascade.TopExp.Explorer as Explorer+import Control.Monad ((<=<))+import OpenCascade.Inheritance (unsafeDowncast, DiscriminatedSubTypeOf)+import Data.Proxy (Proxy (Proxy)) gpPntToV3 :: Ptr GP.Pnt -> IO (V3 Double) gpPntToV3 pnt = V3 <$> GP.Pnt.getX pnt <*> GP.Pnt.getY pnt <*> GP.Pnt.getZ pnt@@ -40,3 +60,63 @@ (value :) <$> go else pure [] go++deduplicateTopoDSShapes :: (NFData a, NoPtr a) => (a -> Acquire (Ptr TopoDS.Shape)) -> [a] -> [a]+deduplicateTopoDSShapes toShape ss = + let f s (shapeMap, acc) = do+ shape <- toShape s+ inMap <- liftIO $ isJust <$> ShapeMap.lookup shapeMap shape+ if inMap+ then pure (shapeMap, acc)+ else+ liftIO $ (, s:acc) <$> ShapeMap.addIfAbsent (shape, ()) shapeMap+ in unsafeFromAcquire (snd <$> foldrM f (ShapeMap.empty, []) ss)+++containsShapeKind :: ShapeEnum -> Ptr TopoDS.Shape -> Acquire Bool+containsShapeKind kind = + liftIO . Explorer.more <=< (`Explorer.new` kind)++class HasShapeKind a where+ shapeKind :: Proxy a -> ShapeEnum++instance HasShapeKind TopoDS.Face where+ shapeKind _ = ShapeEnum.Face++instance HasShapeKind TopoDS.Wire where+ shapeKind _ = ShapeEnum.Wire++instance HasShapeKind TopoDS.Edge where+ shapeKind _ = ShapeEnum.Edge++instance HasShapeKind TopoDS.Shell where+ shapeKind _ = ShapeEnum.Shell++instance HasShapeKind TopoDS.Solid where+ shapeKind _ = ShapeEnum.Solid++instance HasShapeKind TopoDS.Vertex where+ shapeKind _ = ShapeEnum.Vertex++subShapesOf :: forall a. (HasShapeKind a) => Proxy a -> Ptr TopoDS.Shape -> Acquire [Ptr TopoDS.Shape]+subShapesOf proxy s = do + explorer <- Explorer.new s (shapeKind proxy)+ let go acc = do+ isMore <- liftIO $ Explorer.more explorer+ if isMore + then do+ v <- liftIO $ Explorer.value explorer+ isPresent <- liftIO $ ShapeMap.lookup acc v+ (newAcc, add) <- case isPresent of + Nothing -> do + v' <- TopoDS.Shape.copy v+ newMap <- liftIO $ ShapeMap.addIfAbsent (v', ()) acc+ return (newMap, (v':))+ Just _ -> pure (acc, id) + liftIO $ Explorer.next explorer+ add <$> go newAcc+ else return []+ go ShapeMap.empty++subShapes :: forall a. (HasShapeKind a, DiscriminatedSubTypeOf TopoDS.Shape a) => Ptr TopoDS.Shape -> Acquire [Ptr a]+subShapes = traverse (liftIO . unsafeDowncast) <=< subShapesOf (Proxy @a)
src/Waterfall/Internal/PaintHistory.hs view
@@ -14,7 +14,6 @@ import OpenCascade.Inheritance (SubTypeOf(upcast), unsafeDowncast) import qualified OpenCascade.NCollection as NCollection import qualified Waterfall.Internal.ShapeMap as ShapeMap-import Waterfall.Internal.Edges (allSubShapesWithCopy) import Data.Foldable (toList) import qualified OpenCascade.NCollection.IndexedDataMap as NCollection.IndexedDataMap import qualified OpenCascade.TopExp as TopExp@@ -24,11 +23,11 @@ import qualified OpenCascade.TopAbs.ShapeEnum as ShapeEnum import qualified OpenCascade.TopoDS.Shape as TopoDS.Shape import Control.Monad (filterM)-import Waterfall.Internal.FromOpenCascade (shapesFromListOfShape)+import Waterfall.Internal.FromOpenCascade (shapesFromListOfShape, subShapes) getUniqueVertexes :: [Ptr TopoDS.Edge] -> Acquire [Ptr TopoDS.Vertex] getUniqueVertexes edges = - let vertsForEdge e = traverse (liftIO . unsafeDowncast) =<< allSubShapesWithCopy ShapeEnum.Vertex (upcast e)+ let vertsForEdge = subShapes . upcast dup a = (upcast a, a) in fmap toList . liftIO . ShapeMap.fromList . fmap dup . concat =<< traverse vertsForEdge edges @@ -49,7 +48,6 @@ let filletSurfacesFor :: Ptr TopoDS.Shape -> Acquire [(Ptr TopoDS.Face, Paint)] filletSurfacesFor edge = do faces <- liftIO . filterM (fmap (== ShapeEnum.Face) . TopoDS.Shape.shapeType)- =<< shapesFromListOfShape =<< historyGenerated history edge if null faces then pure [] else do neighbours <- shapesFromListOfShape =<<
src/Waterfall/Internal/Path.hs view
@@ -15,7 +15,7 @@ -- -- Under the hood, this is represented by an OpenCascade `TopoDS.Wire`. ----- The monoid instance Joins `Path`s, @ a <> b @ connects the end point of @ a @ to the start of @ b @, if these points are not coincident, a line is created between them.+-- The monoid instance joins `Path`s, @ a <> b @ connects the end point of @ a @ to the start of @ b @, if these points are not coincident, a line is created between them. -- newtype Path = Path { rawPath :: RawPath } deriving (Semigroup, Monoid, NFData) via RawPath
src/Waterfall/Internal/Path/Common.hs view
@@ -21,6 +21,7 @@ import Data.List.NonEmpty (NonEmpty ()) import Data.Foldable (toList) import Control.DeepSeq (NFData (rnf), rwhnf)+import qualified Waterfall.Internal.NearZero as NearZero data RawPath = EmptyRawPath | SinglePointRawPath (V3 Double) | ComplexRawPath (ForeignPtr TopoDS.Wire) @@ -60,7 +61,7 @@ Left pnt -> pure pnt Right wire -> liftIO $ fst <$> wireEndpoints wire let prependA = either (const id) (:) a- if distance ea sb < 1e-6+ if distance ea sb < NearZero.confusion then prependA <$> intersperseLines (b:xs) else prependA <$> ((:) <$> line' ea sb <*> intersperseLines (b:xs))
src/Waterfall/Internal/Remesh.hs view
@@ -15,7 +15,7 @@ However, we can safely access the Triangulation of the Shape, construct Polygons from this and then use BReps derived from these Polygons. -In this way, the `remesh` function produces a new Boundary Represenation from the Mesh of an `OpenCascade.TopoDS.Shape`+In this way, the `remesh` function produces a new Boundary Representation from the Mesh of an `OpenCascade.TopoDS.Shape` -} module Waterfall.Internal.Remesh @@ -104,8 +104,8 @@ faceAsFace <- liftIO . unsafeDowncast $ faceAsShape loc <- TopLoc.Location.new orientation <- liftIO $ TopoDS.Shape.orientation faceAsShape- trsf <- TopLoc.Location.toGPTrsf loc triangulation <- BRep.Tool.triangulation faceAsFace loc+ trsf <- TopLoc.Location.toGPTrsf loc triCount <- liftIO $ Poly.Triangulation.nbTriangles triangulation forM_ [1..triCount] $ \i -> do triangle <- Poly.Triangulation.triangle triangulation i
src/Waterfall/Internal/Solid.hs view
@@ -3,6 +3,7 @@ {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE DerivingVia #-}+{-# LANGUAGE TypeApplications #-} module Waterfall.Internal.Solid ( Solid (..) , PaintMap (..)@@ -16,13 +17,17 @@ , solidFromAcquireWithCatch , solidFromAcquireTWithCatch , solidFromAcquireMappingPaintMap+, solidFromAcquireWithPaintMap+, solidFromAcquireTWithPaintMap , solidFromAcquireWithPaintMapWithCatch , solidFromAcquireTWithPaintMapWithCatch , solidFromAcquireMappingPaintMapWithCatch , remapPaints+, mapPaintMap , materialiseFacePaints , makeShapeHistory , bopBuilderHistory+, shapeDivideHistory , union3D , difference3D , intersection3D@@ -42,27 +47,34 @@ import qualified OpenCascade.BRepAlgoAPI.Fuse as Fuse import qualified OpenCascade.BRepAlgoAPI.Cut as Cut import qualified OpenCascade.BRepAlgoAPI.Common as Common+import OpenCascade.BRepAlgoAPI (BuilderAlgo, BooleanOperation)+import qualified OpenCascade.BRepAlgoAPI.BuilderAlgo as BuilderAlgo+import qualified OpenCascade.BRepAlgoAPI.BooleanOperation as BooleanOperation import qualified OpenCascade.BRepBuilderAPI.MakeSolid as MakeSolid import OpenCascade.BRepBuilderAPI (MakeShape) import qualified OpenCascade.BRepBuilderAPI.MakeShape as MakeShape import qualified OpenCascade.BOPAlgo.Operation as BOPAlgo.Operation import qualified OpenCascade.BOPAlgo.BOP as BOPAlgo.BOP+import qualified OpenCascade.BOPAlgo.CellsBuilder as CellsBuilder import qualified OpenCascade.BOPAlgo.Builder as BOPAlgo.Builder import qualified OpenCascade.TopAbs.ShapeEnum as ShapeEnum import OpenCascade.Inheritance (SubTypeOf(..), upcast, unsafeDowncast) import Waterfall.Internal.Finalizers (acquireForeignPtr, fromAcquirePtrT, unsafeFromAcquire, unsafeFromAcquirePtr, unsafeFromAcquirePtrTWithCatch, unsafeFromAcquirePtrWithCatch, unsafeFromAcquirePtrT)-import Waterfall.Internal.Edges (allSubShapesWithCopy)-import qualified OpenCascade.BOPAlgo.Builder as BOPAlgo+import Waterfall.Internal.ToOpenCascade (shapeSingletonList) import Data.Foldable (traverse_) import Data.Bifunctor.Flip (Flip (..)) import Waterfall.Error (WaterfallError) import Waterfall.Paint (Paint, paintIsDefined) import Data.Functor.Compose (Compose(..))-import qualified OpenCascade.NCollection as NCollection-import Control.Monad (filterM)-import Waterfall.Internal.FromOpenCascade (shapesFromListOfShape)+import Control.Monad (filterM, forM_, (<=<))+import Waterfall.Internal.FromOpenCascade (shapesFromListOfShape, deduplicateTopoDSShapes, containsShapeKind, subShapes, subShapesOf) import Foreign.ForeignPtr (ForeignPtr) import Control.DeepSeq (NFData (rnf), liftRnf, liftRnf2, rwhnf)+import qualified OpenCascade.NCollection.List as NCollection.List+import qualified OpenCascade.ShapeUpgrade.Types as ShapeUpgrade+import qualified OpenCascade.ShapeBuild.ReShape as ShapeBuild.ReShape+import qualified OpenCascade.ShapeUpgrade.ShapeDivide as ShapeBuild.ShapeDivide+import Data.Proxy (Proxy(..)) data PaintMap = UniformPaint Paint@@ -84,7 +96,7 @@ -- Alternatively, a region of 3d Space. -- -- Under the hood, this is represented by an OpenCascade `TopoDS.Shape`.--- The underlying shape should either be a Solid, or a CompSolid.+-- The underlying shape should either be a Solid, or a Compound of Solids -- -- While you shouldn't need to know what this means to use the library, -- please feel free to report a bug if you're able to construct a `Solid`@@ -108,11 +120,14 @@ let (paintMap, ptr) = unsafeFromAcquirePtrT f in Solid ptr paintMap +solidFromAcquireTWithPaintMap :: Traversable t => Acquire (t (PaintMap, Ptr TopoDS.Shape.Shape)) -> t Solid+solidFromAcquireTWithPaintMap = + fmap (uncurry (flip Solid)) . getCompose . unsafeFromAcquirePtrT . fmap Compose+ solidFromAcquireWithPaintMapWithCatch :: Acquire (PaintMap, Ptr TopoDS.Shape.Shape) -> Either WaterfallError Solid solidFromAcquireWithPaintMapWithCatch f = do (paintMap, ptr) <- unsafeFromAcquirePtrTWithCatch f return $ Solid ptr paintMap- solidFromAcquireTWithPaintMapWithCatch :: Traversable t => Acquire (t (PaintMap, Ptr TopoDS.Shape.Shape)) -> Either WaterfallError (t Solid) solidFromAcquireTWithPaintMapWithCatch = @@ -124,8 +139,8 @@ solidFromAcquireTWithCatch :: Traversable t => PaintMap -> Acquire (t (Ptr TopoDS.Shape.Shape)) -> Either WaterfallError (t Solid) solidFromAcquireTWithCatch paintMap = fmap (fmap (`Solid` paintMap)) . unsafeFromAcquirePtrTWithCatch --- | print debug information about a Solid when it's evaluated --- exposes the properties of the underlying OpenCacade.TopoDS.Shape+-- | print debug information about a `Solid` when it's evaluated +-- exposes the properties of the underlying `OpenCascade.TopoDS.Shape` debug :: Solid -> String debug (Solid ptr _) = let @@ -177,8 +192,8 @@ -- | this is used to abstract between `MakeShape` and `BOPAlgo.Builder` data History = History - { historyModified :: Ptr TopoDS.Shape -> Acquire (Ptr (NCollection.List TopoDS.Shape))- , historyGenerated :: Ptr TopoDS.Shape -> Acquire (Ptr (NCollection.List TopoDS.Shape))+ { historyModified :: Ptr TopoDS.Shape -> Acquire [Ptr TopoDS.Shape]+ , historyGenerated :: Ptr TopoDS.Shape -> Acquire [Ptr TopoDS.Shape] , historyIsDeleted :: Ptr TopoDS.Shape -> IO Bool , historyResult :: Acquire (Ptr TopoDS.Shape) }@@ -186,19 +201,34 @@ makeShapeHistory :: Ptr MakeShape -> History makeShapeHistory builder = History - (MakeShape.modified builder)- (MakeShape.generated builder)+ (shapesFromListOfShape <=< MakeShape.modified builder)+ (shapesFromListOfShape <=< MakeShape.generated builder) (MakeShape.isDeleted builder) (MakeShape.shape builder) -bopBuilderHistory :: Ptr BOPAlgo.Builder -> History+bopBuilderHistory :: Ptr BOPAlgo.Builder.Builder -> History bopBuilderHistory builder = History - (BOPAlgo.Builder.modified builder)- (BOPAlgo.Builder.generated builder)+ (shapesFromListOfShape <=< BOPAlgo.Builder.modified builder)+ (shapesFromListOfShape <=< BOPAlgo.Builder.generated builder) (BOPAlgo.Builder.isDeleted builder) (BOPAlgo.Builder.shape builder) +shapeDivideHistory :: Ptr ShapeUpgrade.ShapeDivide -> History+shapeDivideHistory shapeDivide = History + (\shape -> do + reshape <- ShapeBuild.ShapeDivide.getContext shapeDivide+ recorded <- liftIO $ ShapeBuild.ReShape.isRecorded reshape shape+ if not recorded + then return []+ else subShapesOf (Proxy @TopoDS.Face)+ =<< ShapeBuild.ReShape.apply reshape shape ShapeEnum.Face+ )+ (const . pure $ mempty)+ (const . pure $ False)+ (ShapeBuild.ShapeDivide.result shapeDivide)++ -- | for a builder, and a shape, return: -- -- * if the shape was modified by the builder, or there were generated shapes of the same kind, return the modified/generated shapes@@ -206,10 +236,8 @@ -- * otherwise, return the shape remap :: History -> Ptr TopoDS.Shape -> Acquire [Ptr TopoDS.Shape] remap history s = do- modified <- shapesFromListOfShape- =<< historyModified history s- generated <- shapesFromListOfShape- =<< historyGenerated history s+ modified <- historyModified history s+ generated <- historyGenerated history s inputShapeType <- liftIO $ TopoDS.Shape.shapeType s sameTypeGenerated <- liftIO $ filterM (fmap (== inputShapeType) . TopoDS.Shape.shapeType) generated@@ -241,8 +269,7 @@ materialiseFacePaints :: Ptr TopoDS.Shape -> PaintMap -> Acquire [(Ptr TopoDS.Face, Paint)] materialiseFacePaints _ (FacePaints facePaints) = acquireFacePaints facePaints materialiseFacePaints solid (UniformPaint paint) = do- faces <- traverse (liftIO . unsafeDowncast)- =<< allSubShapesWithCopy ShapeEnum.Face solid+ faces <- subShapes solid return $ fmap (, paint) faces materialiseSolidFacePaints :: Solid -> Acquire [(Ptr TopoDS.Face, Paint)]@@ -270,12 +297,20 @@ solidFromAcquireMappingPaintMapWithCatch f = solidFromAcquireWithPaintMapWithCatch (mapPaintMap =<< f) -toBoolean :: (SubTypeOf MakeShape a) => (Ptr TopoDS.Shape -> Ptr TopoDS.Shape -> Acquire (Ptr a)) -> Solid -> Solid -> Solid+toBoolean + :: (SubTypeOf MakeShape a+ , SubTypeOf BooleanOperation a+ , SubTypeOf BuilderAlgo a)+ => (Acquire (Ptr a)) -> Solid -> Solid -> Solid toBoolean f (Solid ptrA paintMapA) (Solid ptrB paintMapB) = solidFromAcquireMappingPaintMap $ do a <- acquireForeignPtr ptrA b <- acquireForeignPtr ptrB- builder <- f a b- + builder <- f+ liftIO $ BuilderAlgo.setNonDestructive (upcast builder) True+ liftIO . BuilderAlgo.setArguments (upcast builder) =<< shapeSingletonList a+ liftIO . BooleanOperation.setTools (upcast builder) =<< shapeSingletonList b+ liftIO $ MakeShape.build (upcast builder)+ materialisedPaintMap <- case (paintMapA, paintMapB) of (UniformPaint paintA, UniformPaint paintB) | paintA == paintB -> pure paintMapA _ -> liftIO $ FacePaints <$> fromAcquirePaints (@@ -288,8 +323,12 @@ -- -- The region occupied by either one of them. union3D :: Solid -> Solid -> Solid-union3D = toBoolean Fuse.fromShapes+union3D = toBoolean Fuse.new +matchesUniformPaint :: Paint -> PaintMap -> Bool+matchesUniformPaint pa (UniformPaint pb) = pa == pb+matchesUniformPaint _ _ = False+ toBooleans :: BOPAlgo.Operation.Operation -> [Solid] -> Solid toBooleans _ [] = emptySolid toBooleans _ [x] = x@@ -299,14 +338,13 @@ bop <- BOPAlgo.BOP.new let builder = upcast bop liftIO $ do+ BOPAlgo.Builder.setNonDestructive builder True BOPAlgo.BOP.setOperation bop op BOPAlgo.Builder.addArgument builder firstPtr traverse_ (BOPAlgo.BOP.addTool bop) ptrs- BOPAlgo.setRunParallel builder True+ BOPAlgo.Builder.setRunParallel builder True BOPAlgo.Builder.perform builder - let matchesUniformPaint pa (UniformPaint pb) = pa == pb- matchesUniformPaint _ _ = False combinedPaintMap <- case solidPaintMap h of@@ -320,26 +358,60 @@ -- -- May be more performant than chaining multiple applications of `union3D` unions3D :: [Solid] -> Solid-unions3D = toBooleans BOPAlgo.Operation.Fuse+unions3D = toBooleans BOPAlgo.Operation.Fuse + . filter (not . isEmptySolid)+ . deduplicateSolids -- | Take the difference of two solids -- -- The region occupied by the first, but not the second. difference3D :: Solid -> Solid -> Solid-difference3D = toBoolean Cut.fromShapes+difference3D = toBoolean Cut.new -- | Take the intersection of two solids -- -- The region occupied by both of them. intersection3D :: Solid -> Solid -> Solid-intersection3D = toBoolean Common.fromShapes+intersection3D = toBoolean Common.new +deduplicateSolids :: [Solid] -> [Solid]+deduplicateSolids = deduplicateTopoDSShapes acquireSolid +isEmptySolid :: Solid -> Bool+isEmptySolid = + not . unsafeFromAcquire . (containsShapeKind ShapeEnum.Face <=< acquireSolid)++intersections3D' :: [Solid] -> Solid+intersections3D' [] = emptySolid+intersections3D' [x] = x+intersections3D' solids@(h:t) + | any isEmptySolid solids = emptySolid+ | otherwise = solidFromAcquireMappingPaintMap $ do+ builder <- CellsBuilder.new + liftIO $ BOPAlgo.Builder.setRunParallel (upcast builder) True+ liftIO $ BOPAlgo.Builder.setNonDestructive (upcast builder) True+ listToTake <- NCollection.List.newListOfShape+ shapes <- traverse acquireSolid solids+ forM_ shapes (liftIO . NCollection.List.appendListOfShape listToTake)+ listToAvoid <- NCollection.List.newListOfShape+ liftIO $ forM_ shapes (BOPAlgo.Builder.addArgument (upcast builder))+ liftIO (BOPAlgo.Builder.perform (upcast builder))+ liftIO $ CellsBuilder.addToResult builder listToTake listToAvoid 1 False+ liftIO $ CellsBuilder.removeInternalBoundaries builder++ combinedPaintMap <- + case solidPaintMap h of+ UniformPaint p | all (matchesUniformPaint p . solidPaintMap) t -> + pure $ UniformPaint p+ _ -> liftIO $ FacePaints <$> fromAcquirePaints (concat <$> traverse materialiseSolidFacePaints solids)+ + return (combinedPaintMap, bopBuilderHistory . upcast $ builder)+ -- | Take the intersection of a list of solids -- -- May be more performant than chaining multiple applications of `intersection3D` intersections3D :: [Solid] -> Solid-intersections3D = toBooleans BOPAlgo.Operation.Common+intersections3D = intersections3D' . deduplicateSolids -- | While `Solid` could form a Semigroup via either `union3D` or `intersection3D`. -- the default Semigroup is from `union3D`.
src/Waterfall/Internal/ToOpenCascade.hs view
@@ -2,6 +2,7 @@ ( v3ToVertex , v3ToPnt , v3ToDir+, shapeSingletonList ) where import Linear (V3 (..))@@ -12,6 +13,9 @@ import qualified OpenCascade.GP.Pnt as GP.Pnt import qualified OpenCascade.GP.Dir as GP.Dir import qualified OpenCascade.BRepBuilderAPI.MakeVertex as MakeVertex+import qualified OpenCascade.NCollection as NCollection+import qualified OpenCascade.NCollection.List as NCollection.List+import Control.Monad.IO.Class (liftIO) v3ToPnt :: V3 Double -> Acquire (Ptr GP.Pnt)@@ -26,4 +30,9 @@ builder <- MakeVertex.fromPnt pnt MakeVertex.vertex builder +shapeSingletonList :: Ptr TopoDS.Shape -> Acquire (Ptr (NCollection.List TopoDS.Shape))+shapeSingletonList s = do+ list <- NCollection.List.newListOfShape+ liftIO $ NCollection.List.appendListOfShape list s+ return list
src/Waterfall/Loft.hs view
@@ -18,10 +18,10 @@ ) where import Linear (V3 (..))-import Waterfall.Internal.Path (Path, rawPath)+import Waterfall.Internal.Path (Path (Path), rawPath) import Waterfall.Internal.Solid (Solid (..), solidFromAcquireWithCatch, emptyPaintMap) import Waterfall.Internal.ToOpenCascade (v3ToVertex)-import Waterfall.Internal.Path.Common (rawPathWire)+import Waterfall.Internal.Path.Common (rawPathWire, RawPath (ComplexRawPath)) import qualified OpenCascade.BRepOffsetAPI.ThruSections as ThruSections import qualified OpenCascade.BRepBuilderAPI.MakeShape as MakeShape import Data.Either (fromRight)@@ -29,19 +29,30 @@ import Control.Monad.IO.Class (liftIO) import Control.Monad (forM_, (<=<)) import Waterfall.Error (WaterfallError)+import Data.Maybe (mapMaybe) +processablePath :: Path -> Maybe Path+processablePath p@(Path (ComplexRawPath _)) = Just p+processablePath _ = Nothing++ -- | like `pointedLoftWithPrecision`, but returns an Either on error tryPointedLoftWithPrecision :: Double -- ^ The loft precision, this should be a small value, e.g. @ 1e-6 @ -> Maybe (V3 Double) -- ^ Optional start point for the loft -> [Path] -- ^ Series of cross-sections that the loft will pass through -> Maybe (V3 Double) -- ^ Optional end point for the loft -> Either WaterfallError Solid-tryPointedLoftWithPrecision precision start paths end = solidFromAcquireWithCatch emptyPaintMap $ do- thruSections <- ThruSections.new True False precision- forM_ start ((liftIO . ThruSections.addVertex thruSections) <=< v3ToVertex)- forM_ paths (traverse (liftIO . ThruSections.addWire thruSections) <=< rawPathWire . rawPath)- forM_ end ((liftIO . ThruSections.addVertex thruSections) <=< v3ToVertex)- MakeShape.shape (upcast thruSections)+tryPointedLoftWithPrecision precision start paths end = + let processablePaths = mapMaybe processablePath paths+ totalLength = length start + length processablePaths + length end+ in if totalLength <= 1 || length processablePaths == 0+ then Right mempty + else solidFromAcquireWithCatch emptyPaintMap $ do+ thruSections <- ThruSections.new True False precision+ forM_ start ((liftIO . ThruSections.addVertex thruSections) <=< v3ToVertex)+ forM_ processablePaths (traverse (liftIO . ThruSections.addWire thruSections) <=< rawPathWire . rawPath)+ forM_ end ((liftIO . ThruSections.addVertex thruSections) <=< v3ToVertex)+ MakeShape.shape (upcast thruSections) -- | like `pointedLoft`, but returns an Either on error tryPointedLoft :: @@ -51,7 +62,7 @@ -> Either WaterfallError Solid tryPointedLoft = tryPointedLoftWithPrecision defaultPrecision --- | like `pointedLoft`, but returns an Either on error+-- | like `loft`, but returns an Either on error tryLoft :: [Path] -- ^ Series of cross-sections that the loft will pass through -> Either WaterfallError Solid
src/Waterfall/Offset.hs view
@@ -1,4 +1,5 @@ {-# LANGUAGE TupleSections #-}+{-# LANGUAGE TypeApplications #-} {-| Module: Waterfall.Offset @@ -16,6 +17,8 @@ * The algorithm may fail if the shape S contains vertices where more than 3 edges converge. * Since 3d-offset algorithm involves intersection of surfaces, it is under limitations of surface intersection algorithm. * A result cannot be generated if the underlying geometry of S is BSpline with continuity C0.++We work around the first and last of these constraints by splitting any face that is not C1 continuous along its discontinuities. -} module Waterfall.Offset ( offset@@ -29,65 +32,60 @@ , tryOffsetWithToleranceWithPaint ) where -import Waterfall.Internal.Solid (Solid (..), acquireSolid, acquireFacePaints, fromAcquirePaints, PaintMap (..), makeShapeHistory, solidFromAcquireTWithPaintMapWithCatch)+import Waterfall.Internal.Solid (Solid (..), acquireSolid, acquireFacePaints, fromAcquirePaints, PaintMap (..), makeShapeHistory, solidFromAcquireTWithPaintMapWithCatch, intersections3D, shapeDivideHistory, mapPaintMap, solidFromAcquireWithPaintMapWithCatch) import qualified OpenCascade.BRepOffsetAPI.MakeOffsetShape as MakeOffsetShape import Control.Monad.IO.Class (liftIO)-import OpenCascade.Inheritance (SubTypeOf(upcast), unsafeDowncast)+import OpenCascade.Inheritance (SubTypeOf(upcast)) 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 qualified OpenCascade.TopoDS.Types as TopoDS-import qualified OpenCascade.TopoDS.Shape as TopoDS.Shape-import qualified OpenCascade.TopExp.Explorer as TopExp.Explorer-import qualified OpenCascade.TopAbs.ShapeEnum as TopAbs.ShapeEnum-import Control.Monad (when, filterM)+import Control.Monad (filterM, forM_) import Foreign.Ptr (Ptr) import Data.Acquire (Acquire) import Waterfall.Internal.NearZero (nearZero) import Waterfall.Error (WaterfallError) import Data.Either (fromRight)-import Waterfall.Internal.Edges (allSubShapesWithCopy)+import Waterfall.Internal.FromOpenCascade (subShapes, subShapesOf) import qualified Waterfall.Internal.ShapeMap as ShapeMap-import qualified OpenCascade.TopAbs.ShapeEnum as ShapeEnum import Data.Maybe (isJust) import Waterfall.Internal.PaintHistory (remapWithBlendFunction) import Data.List.NonEmpty (NonEmpty) import Waterfall.Paint (Paint) import qualified Data.List.NonEmpty as NE+import Data.Functor.Compose (Compose (..))+import qualified OpenCascade.ShapeUpgrade.ShapeDivideContinuity as ShapeUpgrade.ShapeDivideContinuity+import qualified OpenCascade.GeomAbs.Shape as GeomAbs.Shape+import qualified OpenCascade.ShapeUpgrade.ShapeDivide as ShapeUpgrade.ShapeDivide+import Data.Proxy (Proxy(..)) combineShellsToSolid :: Ptr TopoDS.Shape -> Acquire (Ptr TopoDS.Shape) combineShellsToSolid s = do- explorer <- TopExp.Explorer.new s TopAbs.ShapeEnum.Shell+ shells <- subShapes s makeSolid <- MakeSolid.new- let go = do- isMore <- liftIO $ TopExp.Explorer.more explorer- when isMore $ do- shell <- liftIO $ unsafeDowncast =<< TopExp.Explorer.value explorer- liftIO $ MakeSolid.add makeSolid shell- liftIO $ TopExp.Explorer.next explorer- go- go+ liftIO $ forM_ shells (MakeSolid.add makeSolid) upcast <$> MakeSolid.solid makeSolid -getCompoundAsSolids :: Ptr TopoDS.Shape -> Acquire [Ptr TopoDS.Shape]-getCompoundAsSolids s = do- explorer <- TopExp.Explorer.new s TopAbs.ShapeEnum.Solid- let go = do- isMore <- liftIO $ TopExp.Explorer.more explorer- if not isMore- then pure []- else do- solid <- TopoDS.Shape.copy =<< liftIO (TopExp.Explorer.value explorer)- liftIO $ TopExp.Explorer.next explorer- (solid :) <$> go- go+splitC0BSplines' :: PaintMap -> Ptr TopoDS.Shape -> Acquire (PaintMap, Ptr TopoDS.Shape)+splitC0BSplines' paintMap s = do+ shapeDivide <- ShapeUpgrade.ShapeDivideContinuity.fromShape s+ liftIO $ ShapeUpgrade.ShapeDivideContinuity.setBoundaryCriterion shapeDivide GeomAbs.Shape.C1+ liftIO $ ShapeUpgrade.ShapeDivideContinuity.setSurfaceCriterion shapeDivide GeomAbs.Shape.C1+ liftIO $ ShapeUpgrade.ShapeDivideContinuity.setPCurveCriterion shapeDivide GeomAbs.Shape.C1+ performed <- liftIO $ ShapeUpgrade.ShapeDivide.perform (upcast shapeDivide) True+ if performed + then mapPaintMap (paintMap, shapeDivideHistory (upcast shapeDivide))+ else return (paintMap, s) +splitC0BSplines :: Solid -> Either WaterfallError Solid+splitC0BSplines solid = solidFromAcquireWithPaintMapWithCatch+ (splitC0BSplines' (solidPaintMap solid) =<< acquireSolid solid) filterPaintMap :: Ptr TopoDS.Shape -> PaintMap -> Acquire PaintMap filterPaintMap _ (UniformPaint paint) = pure (UniformPaint paint) filterPaintMap s (FacePaints paints) = do- faceSet <- liftIO . ShapeMap.fromList . fmap (,()) =<< allSubShapesWithCopy ShapeEnum.Face s+ faceSet <- liftIO . ShapeMap.fromList . fmap (,()) =<< (fmap upcast <$> (subShapes s :: Acquire [Ptr TopoDS.Face])) fmap FacePaints . liftIO . fromAcquirePaints $ ( filterM (liftIO . fmap isJust . ShapeMap.lookup faceSet . upcast . fst) =<< acquireFacePaints paints@@ -102,14 +100,13 @@ -> Acquire (PaintMap, Ptr TopoDS.Shape) offsetOneWithTolerance tolerance value paintFn paintMap s = do builder <- MakeOffsetShape.new- allEdges <- traverse (liftIO . unsafeDowncast) =<< allSubShapesWithCopy ShapeEnum.Edge s+ allEdges <- subShapes s liftIO $ MakeOffsetShape.performByJoin builder s value tolerance Mode.Skin False False GeomAbs.JoinType.Arc False shell <- MakeShape.shape (upcast builder) newPaintMap <- remapWithBlendFunction paintFn s allEdges (makeShapeHistory $ upcast builder) =<< filterPaintMap s paintMap (newPaintMap,) <$> combineShellsToSolid shell - -- | Version of `tryOffsetWithTolerance` that exposes how to assign `Paint` to the generated parts of the surface tryOffsetWithToleranceWithPaint :: Double -- ^ Tolerance, this can be relatively small@@ -119,12 +116,15 @@ -> Either WaterfallError Solid tryOffsetWithToleranceWithPaint tolerance paintFn value solid | nearZero value = Right solid- | otherwise =- fmap mconcat- . solidFromAcquireTWithPaintMapWithCatch- $ traverse (offsetOneWithTolerance tolerance value paintFn (solidPaintMap solid))- =<< getCompoundAsSolids- =<< acquireSolid solid+ | otherwise = do + continuousSolid <- splitC0BSplines solid+ fmap (mconcat . fmap intersections3D . getCompose)+ . solidFromAcquireTWithPaintMapWithCatch+ $ traverse (offsetOneWithTolerance tolerance value paintFn (solidPaintMap continuousSolid))+ =<< fmap Compose+ . traverse (subShapesOf (Proxy @TopoDS.Shell))+ =<< subShapesOf (Proxy @TopoDS.Solid)+ =<< acquireSolid continuousSolid -- | Version of `offsetWithTolerance` that returns an error on failure tryOffsetWithTolerance@@ -158,6 +158,8 @@ defaultTolerance = 1e-6 -- | Expand or contract a `Solid` by a certain amount.+-- +-- Returns an empty `Solid` on failure, see `tryOffset`. offset :: Double -- ^ Amount to offset by, positive values expand, negative values contract -> Solid -- ^ The `Solid` to offset
src/Waterfall/Paint.hs view
@@ -1,9 +1,10 @@ {-# LANGUAGE DerivingVia, DeriveGeneric #-} {-# LANGUAGE InstanceSigs #-}+{-# LANGUAGE RankNTypes #-} {-| Module: Waterfall.Paint -`Paint` can be applied to change the appearance of the surface of a `Waterfall.Solids.Solid` (with `Waterfall.Solids.paintSolid`).+`Paint` can be applied to change the appearance of the surface of a `Waterfall.Solid.Solid` (with `Waterfall.Solid.paintSolid`). `Paint` values can be constructed from the @paintWith*@ functions and can be combined monoidally (with `<>`), e.g. @@ -17,9 +18,11 @@ Not all `Paint` properties are supported by every file format: -* glTF and OBJ use the full set+* glTF uses the full set+* OBJ uses the colour, opacity, and roughness (as part of the specular component) * STEP only uses the colour * SVG uses colour and opacity+* STL ignores the `Paint` properties completely -} module Waterfall.Paint ( Colour (..)@@ -27,6 +30,8 @@ , DoubleSidedness (..) , defaultPaint , paintIsDefined+, mixPaints+, mixPaintsWithColours -- * Constructors , paintWithColour , paintWithOpacity@@ -46,10 +51,13 @@ ) where import Data.Monoid (Last (..), Endo (..)) import GHC.Generics (Generically (..), Generic)-import Data.Maybe (catMaybes)-import Data.List (intersperse)-import Control.Lens (Lens', lens)-import Waterfall.Colour (Colour (..))+import Data.Maybe (catMaybes, mapMaybe, isNothing, fromMaybe)+import Data.List (intersperse, intercalate)+import Control.Lens (Lens', lens, (^.), (.~), (&))+import Waterfall.Colour (Colour (..), mixColours)+import qualified Waterfall.Colour as Colour+import Data.List.NonEmpty (NonEmpty, toList)+import qualified Data.List.NonEmpty as NE import Control.DeepSeq (NFData (rnf), rwhnf) -- | Whether to display a surface as Double or Single Sided@@ -60,7 +68,7 @@ instance NFData DoubleSidedness where rnf = rwhnf --- | Can be applied to change the appearance of the surface of a `Solid`+-- | Can be applied to change the appearance of the surface of a `Waterfall.Solid.Solid` -- -- `Paint` values can be constructed from the @paintWith*@ functions -- and can be combined monoidally (with `<>`).@@ -111,7 +119,7 @@ -- defaultPaint /= mempty -- @ defaultPaint :: Paint-defaultPaint = paintWithColour (Colour 1 1 1)+defaultPaint = paintWithColour (Colour.white) <> paintWithOpacity 1 <> paintWithDoubleSidedness DoubleSided <> paintWithMetallic 0@@ -121,6 +129,69 @@ paintIsDefined :: Paint -> Bool paintIsDefined = (/= mempty) ++average :: [Double] -> Maybe Double+average [] = Nothing+average s = Just (sum s / realToFrac (length s))++mixValue :: Lens' Paint (Maybe Double) -> NonEmpty Paint -> Paint+mixValue l paints = + let value = paints+ & toList+ & mapMaybe (^. l)+ & average+ in mempty & l .~ value++ +mixColoursWith+ :: (NonEmpty Colour -> Colour) + -> Lens' Paint (Maybe Colour) + -> NonEmpty Paint+ -> Paint+mixColoursWith f l paints = + let definedColours = + NE.nonEmpty . mapMaybe (^. l) . toList $ paints + in mempty & l .~ (f <$> definedColours)++mixNames :: NonEmpty Paint -> Paint+mixNames paints = + if all (isNothing . (^. paintName)) paints+ then mempty+ else + let name = + intercalate " plus " + $ toList + (fromMaybe "unnamed-paint" . (^. paintName)+ <$> paints+ )+ in paintWithName name++mixDoubleSidedness :: NonEmpty Paint -> Paint+mixDoubleSidedness paints = + mempty + & paintDoubleSidedness .~ + (maximum . fmap (^. paintDoubleSidedness) $ paints)++-- | A version of `mixPaints` that exposes how to average `Colour`s+mixPaintsWithColours + :: (NonEmpty Colour -> Colour)+ -> NonEmpty Paint + -> Paint+mixPaintsWithColours colourFn paints = + mixColoursWith colourFn paintColour paints+ <> mixColoursWith colourFn paintEmissiveColour paints+ <> mixValue paintOpacity paints+ <> mixValue paintMetallic paints+ <> mixValue paintRoughness paints+ <> mixNames paints+ <> mixDoubleSidedness paints++-- | Compute an average from a list of `Paint`s +-- +-- Undefined values in the `Paint`s do not contribute to the average (although they do affect the name, if any of the `Paint`s have a name set).+mixPaints :: NonEmpty Paint -> Paint+mixPaints = mixPaintsWithColours mixColours+ -- | The paint colour paintColour :: Lens' Paint (Maybe Colour) paintColour = @@ -158,7 +229,6 @@ paintWithMetallic :: Double -> Paint paintWithMetallic m = mempty { _paintMetallic = Last (Just m) } - -- | The paint "Roughness" value, in a [PBR](https://en.wikipedia.org/wiki/Physically_based_rendering) model. paintRoughness :: Lens' Paint (Maybe Double) paintRoughness = @@ -174,7 +244,7 @@ -- | The paint "Emissive" factor, in a [PBR](https://en.wikipedia.org/wiki/Physically_based_rendering) model. ----- EmissiveColour is written as linear RGB, rather than converted to sRGB.+-- EmissiveColour is converted from sRGB to linear RGB when written. paintEmissiveColour :: Lens' Paint (Maybe Colour) paintEmissiveColour = lens
src/Waterfall/Path.hs view
@@ -5,7 +5,7 @@ ( Path , module Waterfall.Path.Common , fromPath2D--- $ reexports+-- $reexports , line3D , lineTo3D , lineRelative3D
src/Waterfall/Path/Common.hs view
@@ -6,7 +6,7 @@ Paths in 2D / 3D space. This module defines functions that can be used with "Waterfall.Path" or "Waterfall.TwoD.Path2D".-Those modules both export monomorphized variants of the functions defined in this module+Those modules both export monomorphised variants of the functions defined in this module -} module Waterfall.Path.Common ( AnyPath ()@@ -39,7 +39,7 @@ import Waterfall.Internal.Finalizers (unsafeFromAcquire, unsafeFromAcquirePtr, acquireForeignPtr, unsafeFromAcquirePtrT) import Waterfall.Internal.FromOpenCascade (gpPntToV3) import Waterfall.Internal.Edges (wireEndpoints, reverseWire, splitWires, wireLength, truncateWire)-import Waterfall.Internal.NearZero (nearZero)+import Waterfall.Internal.NearZero (nearZero, confusion) import Control.Arrow (second) import Prelude hiding (Foldable(..)) import Data.Foldable (Foldable(..))@@ -55,7 +55,7 @@ import qualified OpenCascade.BRepBuilderAPI.Transform as BRepBuilderAPI.Transform import qualified OpenCascade.BRepBuilderAPI.MakeShape as BRepBuilderAPI.MakeShape import Data.Proxy (Proxy (..))-import Linear (V3 (..), V2 (..), _xy, Epsilon)+import Linear (V3 (..), V2 (..), _xy, norm, normalize, quadrance, Epsilon) import qualified OpenCascade.GP.Pnt as GP.Pnt import Control.Lens ((^.)) @@ -112,17 +112,25 @@ -- | Section of a circle based on three arguments, the start point, a point on the arc, and the endpoint arcVia :: forall point path. (AnyPath point path) => point -> point -> point -> path-arcVia start mid end =- let vc = veryClose (Proxy :: Proxy path)- in if vc start end && vc start mid- then reconstructPath . SinglePointRawPath . pointToV3 (Proxy :: Proxy path) $ start- else edgeToPath $ do- s <- pointToGPPnt (Proxy :: Proxy path) start- m <- pointToGPPnt (Proxy :: Proxy path) mid- e <- pointToGPPnt (Proxy :: Proxy path) end+arcVia start mid end+ | vc start end && vc start mid = + reconstructPath . SinglePointRawPath . pointToV3 prx $ start+ | colinear && midBetween = line start end+ | otherwise = edgeToPath $ do+ s <- pointToGPPnt prx start+ m <- pointToGPPnt prx mid+ e <- pointToGPPnt prx end theArc <- MakeArcOfCircle.from3Pnts s m e MakeEdge.fromCurve (upcast theArc)+ where + prx = (Proxy :: Proxy path)+ vc = veryClose prx + d1 = (pointToV3 prx mid - pointToV3 prx start)+ d2 = (pointToV3 prx end - pointToV3 prx start)+ colinear = nearZero . norm $ (normalize d1 - normalize d2)+ midBetween = quadrance d1 < quadrance d2 + -- | Version of `arcVia` designed to work with `pathFrom` -- -- The first argument is a point on the arc@@ -280,7 +288,7 @@ takePathFraction :: forall point path. AnyPath point path => Double -> path -> path takePathFraction fraction p | fraction >= 1 = p- | fraction <= 0 =+ | targetLength <= confusion = case pathEndpoints p of Just (s, _) -> reconstructPath . SinglePointRawPath $ pointToV3 (Proxy :: Proxy path) s Nothing -> p@@ -288,10 +296,10 @@ case deconstructPath p of ComplexRawPath r -> fromWire $ do wire <- acquireForeignPtr r- totalLength <- liftIO $ wireLength wire- let targetLength = fraction * totalLength truncateWire targetLength wire _ -> p+ where + targetLength = fraction * pathLength p instance AnyPath (V3 Double) Path where reconstructPath :: RawPath -> Path
src/Waterfall/Revolution.hs view
@@ -1,42 +1,87 @@ module Waterfall.Revolution ( revolution+, revolutionByAngle , tryRevolution+, tryRevolutionByAngle ) where -import Waterfall.Internal.Solid (Solid (..), solidFromAcquireWithCatch, emptyPaintMap)-import Waterfall.TwoD.Internal.Path2D (Path2D (..))-import Waterfall.Internal.Finalizers (acquireForeignPtr)+import Waterfall.Internal.Solid (Solid (..), solidFromAcquireWithCatch, emptyPaintMap, emptySolid)+import Waterfall.TwoD.Internal.Shape (Shape(Shape), acquireShape)+import qualified Waterfall.TwoD.Shape as Shape+import Waterfall.Internal.Finalizers (acquireForeignPtr, unsafeFromAcquire) import qualified OpenCascade.BRepPrimAPI.MakeRevol as MakeRevol-import qualified OpenCascade.BRepBuilderAPI.MakeSolid as MakeSolid import qualified OpenCascade.BRepBuilderAPI.MakeShape as MakeShape import qualified OpenCascade.GP as GP-import OpenCascade.Inheritance (upcast, unsafeDowncast)+import OpenCascade.Inheritance (upcast) import Waterfall.Transforms (rotate) import Waterfall.Error (WaterfallError) import Control.Monad.IO.Class (liftIO)-import Linear (unit, _x)-import Waterfall.Internal.Path.Common (RawPath(..))+import Linear (unit, _x, _y, _xy, V2 (V2), Epsilon (nearZero)) import Data.Either (fromRight)+import qualified OpenCascade.Bnd.Box as Bnd.Box+import qualified OpenCascade.BRepBndLib as BRepBndLib+import Waterfall.Internal.FromOpenCascade (gpPntToV3)+import Control.Lens ((^.), (&))+import qualified Waterfall.TwoD.Transforms as TwoD.Transforms+import Waterfall.Booleans (intersection, difference) --- | Version of `revolution` that returns an `Error` on failure.------ Revolution can fail, for example, if the `Path2D` crosses the axis of revolution.-tryRevolution :: Path2D -> Either WaterfallError Solid-tryRevolution (Path2D (ComplexRawPath theRawPath)) =+splitShapeAboutAxis :: Shape -> [Shape]+splitShapeAboutAxis shape = unsafeFromAcquire $ do+ s <- acquireShape shape + bnd <- Bnd.Box.new+ liftIO $ BRepBndLib.addOptimal s bnd True False+ isVoid <- liftIO $ Bnd.Box.isVoid bnd+ if isVoid + then return []+ else do+ p1 <- liftIO . gpPntToV3 =<< Bnd.Box.cornerMin bnd+ p2 <- liftIO . gpPntToV3 =<< Bnd.Box.cornerMax bnd+ let permittedOverlap = 1e-6+ return $ if p2 ^. _x <= permittedOverlap || p1 ^. _x >= (negate permittedOverlap)+ then [shape]+ else let lo = V2 0 (p1 ^. _y)+ hi = (p2 ^. _xy) + mask = Shape.unitSquare+ & TwoD.Transforms.scale2D (hi - lo)+ & TwoD.Transforms.translate2D (lo)+ in [shape `intersection` mask, shape `difference` mask]++tryOneRevolutionByAngle :: Double -> Shape -> Either WaterfallError Solid+tryOneRevolutionByAngle angle (Shape shape)+ | nearZero angle = Right emptySolid+ | otherwise = fmap (rotate (unit _x) (pi/2)) . solidFromAcquireWithCatch emptyPaintMap $ do- p <- acquireForeignPtr theRawPath+ s <- acquireForeignPtr shape axis <- GP.oy -- revolve around the y axis- revol <- MakeRevol.fromShapeAndAx1 (upcast p) axis True- shell <- MakeShape.shape (upcast revol)- solidBuilder <- MakeSolid.new- liftIO $ MakeSolid.add solidBuilder =<< unsafeDowncast shell- MakeShape.shape (upcast solidBuilder)-tryRevolution _ = Right mempty+ -- clamp the angle to [-2*pi, 2*pi]+ let angle' = signum angle * (min (2*pi) (abs angle))+ revol <- MakeRevol.fromShapeAx1AndAngle s axis angle' True+ MakeShape.shape (upcast revol) --- | Construct a `Solid` of revolution from a `Path2D`.+-- | Version of `revolutionByAngle` that returns a `WaterfallError` on failure.+tryRevolutionByAngle :: Double -> Shape -> Either WaterfallError Solid+tryRevolutionByAngle angle =+ fmap mconcat . traverse (tryOneRevolutionByAngle angle) . splitShapeAboutAxis++-- | Version of `revolution` that returns a `WaterfallError` on failure.+tryRevolution :: Shape -> Either WaterfallError Solid+tryRevolution = tryRevolutionByAngle (2*pi)++-- | Construct a `Solid` of revolution from a `Shape`. ----- The `Path2D` is rotated about the y axis, should have endpoints that lie on it ( \(x = 0\) ).+-- The `Shape` is rotated about the y axis -- -- The resulting `Solid` is rotated such that the axis of revolution is the z axis.-revolution :: Path2D -> Solid+revolution :: Shape -> Solid revolution = fromRight mempty . tryRevolution++-- | Construct a Partial Revolution of a `Shape`+--+-- The `Shape` is rotated about the y axis, +-- and then rotated such that the axis of revolution is in the z-axis,+-- the start of the wedge lies in the xz plane, +-- and the wedge direction is counter-clockwise about the z-axis.+-- +-- The angle is clamped to ±2π.+revolutionByAngle :: Double -> Shape -> Solid+revolutionByAngle = (fromRight mempty .) . tryRevolutionByAngle
+ src/Waterfall/Solid.hs view
@@ -0,0 +1,325 @@+{-# LANGUAGE TupleSections #-}+{-# LANGUAGE TypeApplications #-}+module Waterfall.Solid+( Solid+, emptySolid+, unitCube+, centeredCube+, box+, unitSphere+, unitCylinder+, centeredCylinder+, unitCone+, torus+, tetrahedron+, octahedron+, dodecahedron+, icosahedron+, colourSolid+, paintSolid+, looseParts+, prism+, volume+, centerOfMass+, momentOfInertia+) where+++import Waterfall.Internal.Solid (Solid (..), PaintMap (..), solidFromAcquire, acquireSolid, emptySolid, emptyPaintMap, solidFromAcquireTWithPaintMap)+import Waterfall.Paint (Paint, paintWithColour)+import Waterfall.Internal.Finalizers (NoPtr, acquireForeignPtr, unsafeFromAcquire)+import Control.DeepSeq (NFData)+import Waterfall.TwoD.Internal.Shape (rawShape)+import Waterfall.Internal.ToOpenCascade (v3ToVertex)+import Waterfall.Internal.FromOpenCascade (gpPntToV3, subShapesOf)+import Waterfall.Internal.Remesh (makeSolidFromShell)+import Waterfall.Transforms (translate, rotate)+import Waterfall.Internal.NearZero (nearZero)+import qualified Waterfall.TwoD.Shape as TwoD.Shape+import Waterfall.Colour (Colour)+import qualified OpenCascade.BRepBuilderAPI.MakeShape as MakeShape+import qualified OpenCascade.BRepBuilderAPI.MakeEdge as MakeEdge+import qualified OpenCascade.BRepBuilderAPI.MakeWire as MakeWire+import qualified OpenCascade.BRepBuilderAPI.MakeFace as MakeFace+import qualified OpenCascade.BRepBuilderAPI.Sewing as BRepBuilderAPI.Sewing+import qualified OpenCascade.TopoDS as TopoDS+import qualified OpenCascade.TopoDS.Shape as TopoDS.Shape+import qualified OpenCascade.TopoDS.Compound as TopoDS.Compound+import qualified OpenCascade.TopoDS.Builder as TopoDS.Builder+import qualified OpenCascade.BRepPrimAPI.MakeBox as MakeBox+import qualified OpenCascade.BRepPrimAPI.MakeSphere as MakeSphere+import qualified OpenCascade.BRepPrimAPI.MakeCylinder as MakeCylinder+import qualified OpenCascade.BRepPrimAPI.MakeCone as MakeCone+import qualified OpenCascade.BRepPrimAPI.MakeTorus as MakeTorus+import qualified OpenCascade.GProp.GProps as GProps+import qualified OpenCascade.BRepGProp as BRepGProp+import qualified OpenCascade.GP as GP+import Control.Lens ((^.), (&), (.~))+import Linear (V3 (..), V2 (..), unit, _x, _y, _z, _xy, _yz, _zx, (^*), (*^), unangle, zero)+import qualified OpenCascade.GP.Pnt as GP.Pnt+import qualified OpenCascade.GP.Vec as GP.Vec+import qualified OpenCascade.GP.Dir as GP.Dir+import qualified OpenCascade.GP.Ax1 as GP.Ax1+import qualified OpenCascade.BRepPrimAPI.MakePrism as MakePrism+import qualified OpenCascade.Inheritance as Inheritance++import Control.Monad.IO.Class (liftIO)+import Control.Monad ((<=<), forM, filterM)+import Foreign.Ptr (Ptr)+import Data.Acquire (Acquire)+import qualified Waterfall.Internal.ShapeMap as ShapeMap+import Data.Maybe (isJust)+import Data.Proxy (Proxy(..))++-- | A cube with side lengths of 1, one vertex on the origin, another on \( (1, 1, 1) \)+unitCube :: Solid+unitCube = solidFromAcquire emptyPaintMap $ do+ a <- GP.origin+ b <- GP.Pnt.new 1 1 1+ builder <- MakeBox.fromPnts a b+ Inheritance.upcast <$> MakeBox.solid builder++-- | A cube with side lengths of 1, centered on the origin+centeredCube :: Solid+centeredCube = solidFromAcquire emptyPaintMap $ do+ a <- GP.Pnt.new (-1/2) (-1/2) (-1/2)+ b <- GP.Pnt.new (1/2) (1/2) (1/2)+ builder <- MakeBox.fromPnts a b+ Inheritance.upcast <$> MakeBox.solid builder++-- | A cuboid, one vertex on the origin, another on a given point+box :: V3 Double -> Solid+box v@(V3 x y z) + | any nearZero v = mempty+ | otherwise = solidFromAcquire emptyPaintMap $ do+ a <- GP.origin+ b <- GP.Pnt.new x y z+ builder <- MakeBox.fromPnts a b+ Inheritance.upcast <$> MakeBox.solid builder++ +-- | A sphere with radius of 1, centered on the origin+unitSphere :: Solid+unitSphere = solidFromAcquire emptyPaintMap $ Inheritance.upcast <$> MakeSphere.fromRadius 1++-- | A cylinder with radius 1, length 1,+-- one of its circular faces centered on the origin,+-- the other centered on \( (0, 0, 1) \)+unitCylinder :: Solid+unitCylinder = solidFromAcquire emptyPaintMap $ Inheritance.upcast <$> MakeCylinder.fromRadiusAndHeight 1 1++-- | A cylinder with radius 1, length 1,+-- centered on the origin+centeredCylinder :: Solid+centeredCylinder = translate (unit _z ^* (-0.5)) $ unitCylinder+++-- | A Torus, with the axis of revolution about the Z axis+-- +-- Warning, this will fail to generate geometry if asked to generate a Spindle Torus+-- (when the Major Radius is smaller than the Minor Radius)+torus ::+ Double -- ^ The Major Radius (Distance from center of torus to center of tube)+ -> Double -- ^ The Minor Radius (Distance from center of tube to the surface of the torus)+ -> Solid+torus major' minor' + | major < minor = mempty + | nearZero minor = mempty+ | otherwise = solidFromAcquire emptyPaintMap+ $ MakeShape.shape + . Inheritance.upcast + =<< MakeTorus.fromRadii major minor+ where + major = abs major'+ minor = abs minor'++-- | A cone +-- With a point at the origin +-- and a circular face with Radius 1, centered on \( (0, 0, 1) \)+unitCone :: Solid+unitCone = solidFromAcquire emptyPaintMap $ Inheritance.upcast <$> MakeCone.fromTwoRadiiAndHeight 0 1 1++-- | Extrude a 2D face into a prism with a given length \(len\).+--+-- One of the prism's faces lies on the plane \(z = 0\),+-- the other on the plane \(z = len\).+prism :: Double -> TwoD.Shape.Shape -> Solid+prism len face + | nearZero len = mempty+ | otherwise = solidFromAcquire emptyPaintMap $ do+ p <- acquireForeignPtr . rawShape $ face+ v <- GP.Vec.new 0 0 len+ MakePrism.fromVec p v True True++faceFromVerts :: [V3 Double] -> Acquire (Ptr TopoDS.Face)+faceFromVerts pnts = do+ verts <- traverse v3ToVertex pnts+ edges <- traverse (uncurry MakeEdge.fromVertices) $ zip verts (drop 1 (cycle verts))+ wireBuilder <- MakeWire.new+ _ <- liftIO $ traverse (MakeWire.addEdge wireBuilder) edges+ wire <- MakeWire.wire wireBuilder+ -- passing True here forces the face to be a plane+ faceBuilder <- MakeFace.fromWire wire True+ MakeFace.face faceBuilder++solidFromFaces :: [Ptr TopoDS.Face] -> Acquire (Ptr TopoDS.Solid)+solidFromFaces faces = do+ sewing <- BRepBuilderAPI.Sewing.new 1e-6 True True True False+ compound <- TopoDS.Compound.new+ builder <- TopoDS.Builder.new+ liftIO $ TopoDS.Builder.makeCompound builder compound+ _ <- liftIO $ traverse (TopoDS.Builder.add builder (Inheritance.upcast compound) . Inheritance.upcast) faces+ liftIO $ BRepBuilderAPI.Sewing.load sewing (Inheritance.upcast compound)+ liftIO . BRepBuilderAPI.Sewing.perform $ sewing+ shape <- BRepBuilderAPI.Sewing.sewedShape sewing+ maybeShapeAsSolid <- makeSolidFromShell shape+ case maybeShapeAsSolid of + Just s -> return s+ Nothing -> error "Failed to construct solid from faces"++solidFromVerts :: [[V3 Double]] -> Solid+solidFromVerts = solidFromAcquire emptyPaintMap . fmap Inheritance.upcast . (solidFromFaces <=< traverse faceFromVerts)++-- | Regular Tetrahedron with unit side lengths+-- +-- One vertex is in the Z direction+tetrahedron :: Solid+tetrahedron = + let r = ((1/sqrt 8) *^)+ . rotate (unit _z) (pi/4)+ . rotate (V3 1 1 0) (pi - unangle (V2 1 (sqrt 2)))+ v1 = V3 1 1 1+ v2 = V3 1 (-1) (-1)+ v3 = V3 (-1) 1 (-1)+ v4 = V3 (-1) (-1) 1+ in solidFromVerts . fmap (fmap r) $+ [ [v1, v2, v3] + , [v1 ,v2, v4]+ , [v2, v3, v4]+ , [v3, v1, v4]+ ]++-- | Regular Octahedron with unit side lengths+--+-- The vertices of the Octahedra lie on the X, Y and Z axes+octahedron :: Solid+octahedron = + let h = 1 / sqrt 2+ t = unit _z ^* h+ b = negate t+ c1 = h *^ unit _x+ c2 = h *^ unit _y+ c3 = negate c1+ c4 = negate c2+ in solidFromVerts+ [ [t, c1, c2]+ , [t, c2, c3]+ , [t, c3, c4]+ , [t, c4, c1]+ , [b, c2, c1]+ , [b, c3, c2]+ , [b, c4, c3]+ , [b, c1, c4]+ ]++-- | Regular Icosahedron with unit side lengths+icosahedron :: Solid+icosahedron = + let phi = (1 + sqrt 5) / 2+ signs = [-1, 1]+ in solidFromVerts $+ [ + let a = zero & l1 .~ (V2 (s1 * phi/2) 0.5)+ b = zero & l1 .~ (V2 (s1 * phi/2) (-0.5))+ c = zero & l2 .~ (V2 (s2 * phi/2) (0.5 * s1))+ in if s1 < 0 then [b, a, c]+ else [a, b, c]+ | s1 <- signs+ , s2 <- signs+ , (l1, l2) <- [(_xy, _zx), (_zx, _yz), (_yz, _xy)]+ ] <> + [+ [ zero & _xy .~ (V2 (a * phi/2) (c * 0.5))+ , zero & _yz .~ (V2 (c * phi/2) (b * 0.5))+ , zero & _zx .~ (V2 (b * phi/2) (a * 0.5))+ ]+ | a <- signs+ , b <- signs+ , c <- signs+ ]++-- | Regular Dodecahedron with unit side lengths+dodecahedron :: Solid+dodecahedron = + let phi = (1 + sqrt 5)/2 + plusMinusOne = [1, -1]+ scale = phi / 2 + -- colours taken from https://commons.wikimedia.org/wiki/File:Dodecahedron_vertices.svg+ orange x y z = scale *^ V3 x y z+ green y z = scale *^ V3 0 (phi * y) (z / phi)+ blue x z = scale *^ V3 (x/phi) 0 (phi * z)+ pink x y = scale *^ V3 (phi * x) (y/phi) 0+ in solidFromVerts $+ [ \y z -> [ blue (-1) z, blue (1) z, orange (1) y z, green y z, orange (-1) y z]+ , \x y -> [ green y (-1), green y 1, orange x y 1, pink x y, orange x y (-1)] + , \x z -> [ pink x (-1), pink x 1, orange x 1 z, blue x z, orange x (-1) z] + ] <*> plusMinusOne <*> plusMinusOne+++-- | Apply a `Colour` to a `Solid`+--+-- Replaces any previously applied paint+colourSolid :: Colour -> Solid -> Solid+colourSolid colour = paintSolid (paintWithColour colour)++-- | Apply a `Paint` to a `Solid`+--+-- Replaces any previously applied paint+paintSolid :: Paint -> Solid -> Solid+paintSolid paint (Solid s _) = + Solid s (UniformPaint paint )++-- | Split a `Solid` into a list of disjoint parts+looseParts :: Solid -> [Solid] +looseParts s = solidFromAcquireTWithPaintMap $ do+ solid <- acquireSolid s+ childSolids <- + filterM (fmap (>0) . liftIO . TopoDS.Shape.nbChildren)+ =<< subShapesOf (Proxy @TopoDS.Solid) solid+ forM childSolids $ \child -> do+ newPaintMap <- case solidPaintMap s of + UniformPaint p -> pure . UniformPaint $ p+ FacePaints paints -> do+ faces <- liftIO . ShapeMap.fromList . fmap (,()) =<< subShapesOf (Proxy @TopoDS.Face) child+ let exists = fmap isJust . liftIO . ShapeMap.lookup faces . Inheritance.upcast <=< acquireForeignPtr . fst+ newPaints <- filterM exists paints+ return (FacePaints newPaints)+ return (newPaintMap, child)++gPropQuery :: (NoPtr a, NFData a) => (Ptr GProps.GProps -> Acquire a) -> Solid -> a+gPropQuery f s = unsafeFromAcquire $ do+ solid <- acquireSolid s+ gProp <- GProps.new+ liftIO $ BRepGProp.volumePropertiesWithEps solid gProp 1e-9 False False+ f gProp++-- | Volume of the Solid+volume :: Solid -> Double+volume = gPropQuery (liftIO . GProps.mass)++-- | Center Of Mass of the Solid+centerOfMass :: Solid -> V3 Double +centerOfMass = gPropQuery ((liftIO . gpPntToV3) <=< GProps.centreOfMass)++-- | Moment of Inertia of the Solid around a particular point and axis+momentOfInertia :: V3 Double -- ^ Point on the Axis of the Moment+ -> V3 Double -- ^ Direction of the Axis of the Moment + -> Solid+ -> Double +momentOfInertia center axis+ | all nearZero axis = const 0+ | otherwise = gPropQuery $ \gprop -> do+ pnt <- GP.Pnt.new (center ^. _x) (center ^. _y) (center ^. _z)+ dir <- GP.Dir.new (axis ^. _x) (axis ^. _y) (axis ^. _z)+ ax1 <- GP.Ax1.new pnt dir+ liftIO $ GProps.momentOfInertia gprop ax1
src/Waterfall/Solids.hs view
@@ -1,295 +1,5 @@-module Waterfall.Solids -( Solid-, emptySolid-, unitCube-, centeredCube-, box-, unitSphere-, unitCylinder-, centeredCylinder-, unitCone-, torus-, tetrahedron-, octahedron-, dodecahedron-, icosahedron-, colourSolid-, paintSolid-, prism-, volume-, centerOfMass-, momentOfInertia+module Waterfall.Solids {-# DEPRECATED "This module has been renamed to @Waterfall.Solid@." #-}+( module Waterfall.Solid ) where --import Waterfall.Internal.Solid (Solid (..), PaintMap (..), solidFromAcquire, acquireSolid, emptySolid, emptyPaintMap)-import Waterfall.Paint (Paint, paintWithColour)-import Waterfall.Internal.Finalizers (NoPtr, acquireForeignPtr, unsafeFromAcquire)-import Control.DeepSeq (NFData)-import Waterfall.TwoD.Internal.Shape (rawShape)-import Waterfall.Internal.ToOpenCascade (v3ToVertex)-import Waterfall.Internal.FromOpenCascade (gpPntToV3)-import Waterfall.Internal.Remesh (makeSolidFromShell)-import Waterfall.Transforms (translate, rotate)-import Waterfall.Internal.NearZero (nearZero)-import qualified Waterfall.TwoD.Shape as TwoD.Shape-import Waterfall.Colour (Colour)-import qualified OpenCascade.BRepBuilderAPI.MakeShape as MakeShape-import qualified OpenCascade.BRepBuilderAPI.MakeEdge as MakeEdge-import qualified OpenCascade.BRepBuilderAPI.MakeWire as MakeWire-import qualified OpenCascade.BRepBuilderAPI.MakeFace as MakeFace-import qualified OpenCascade.BRepBuilderAPI.Sewing as BRepBuilderAPI.Sewing-import qualified OpenCascade.TopoDS as TopoDS-import qualified OpenCascade.TopoDS.Compound as TopoDS.Compound-import qualified OpenCascade.TopoDS.Builder as TopoDS.Builder-import qualified OpenCascade.BRepPrimAPI.MakeBox as MakeBox-import qualified OpenCascade.BRepPrimAPI.MakeSphere as MakeSphere-import qualified OpenCascade.BRepPrimAPI.MakeCylinder as MakeCylinder-import qualified OpenCascade.BRepPrimAPI.MakeCone as MakeCone-import qualified OpenCascade.BRepPrimAPI.MakeTorus as MakeTorus-import qualified OpenCascade.GProp.GProps as GProps-import qualified OpenCascade.BRepGProp as BRepGProp-import qualified OpenCascade.GP as GP-import Control.Lens ((^.), (&), (.~))-import Linear (V3 (..), V2 (..), unit, _x, _y, _z, _xy, _yz, _zx, (^*), (*^), unangle, zero)-import qualified OpenCascade.GP.Pnt as GP.Pnt-import qualified OpenCascade.GP.Vec as GP.Vec-import qualified OpenCascade.GP.Dir as GP.Dir-import qualified OpenCascade.GP.Ax1 as GP.Ax1-import qualified OpenCascade.BRepPrimAPI.MakePrism as MakePrism-import qualified OpenCascade.Inheritance as Inheritance--import Control.Monad.IO.Class (liftIO)-import Control.Monad ((<=<))-import Foreign.Ptr (Ptr)-import Data.Acquire (Acquire)---- | A cube with side lengths of 1, one vertex on the origin, another on \( (1, 1, 1) \)-unitCube :: Solid-unitCube = solidFromAcquire emptyPaintMap $ do- a <- GP.origin- b <- GP.Pnt.new 1 1 1- builder <- MakeBox.fromPnts a b- Inheritance.upcast <$> MakeBox.solid builder---- | A cube with side lengths of 1, centered on the origin-centeredCube :: Solid-centeredCube = solidFromAcquire emptyPaintMap $ do- a <- GP.Pnt.new (-1/2) (-1/2) (-1/2)- b <- GP.Pnt.new (1/2) (1/2) (1/2)- builder <- MakeBox.fromPnts a b- Inheritance.upcast <$> MakeBox.solid builder---- | A cuboid, one vertex on the origin, another on a given point-box :: V3 Double -> Solid-box v@(V3 x y z) - | any nearZero v = mempty- | otherwise = solidFromAcquire emptyPaintMap $ do- a <- GP.origin- b <- GP.Pnt.new x y z- builder <- MakeBox.fromPnts a b- Inheritance.upcast <$> MakeBox.solid builder-- --- | A sphere with radius of 1, centered on the origin-unitSphere :: Solid-unitSphere = solidFromAcquire emptyPaintMap $ Inheritance.upcast <$> MakeSphere.fromRadius 1---- | A cylinder with radius 1, length 1,--- one of its circular faces centered on the origin,--- the other centered on \( (0, 0, 1) \)-unitCylinder :: Solid-unitCylinder = solidFromAcquire emptyPaintMap $ Inheritance.upcast <$> MakeCylinder.fromRadiusAndHeight 1 1---- | A cylinder with radius 1, length 1,--- centered on the origin-centeredCylinder :: Solid-centeredCylinder = translate (unit _z ^* (-0.5)) $ unitCylinder----- | A Torus, with the axis of revolution about the Z axis--- --- Warning, this will fail to generate geometry if asked to generate a Spindle Torus--- (when the Major Radius is smaller than the Minor Radius)-torus ::- Double -- ^ The Major Radius (Distance from center of torus to center of tube)- -> Double -- ^ The Minor Radius (Distance from center of tube to the surface of the torus)- -> Solid-torus major minor - | major < minor = mempty - | otherwise = solidFromAcquire emptyPaintMap- $ MakeShape.shape - . Inheritance.upcast - =<< MakeTorus.fromRadii major minor---- | A cone --- With a point at the origin --- and a circular face with Radius 1, centered on \( (0, 0, 1) \)-unitCone :: Solid-unitCone = solidFromAcquire emptyPaintMap $ Inheritance.upcast <$> MakeCone.fromTwoRadiiAndHeight 0 1 1---- | Extrude a 2D face into a prism with a given length \(len\).------ One of the prism's faces lies on the plane \(z = 0\),--- the other on the plane \(z = len\).-prism :: Double -> TwoD.Shape.Shape -> Solid-prism len face - | nearZero len = mempty- | otherwise = solidFromAcquire emptyPaintMap $ do- p <- acquireForeignPtr . rawShape $ face- v <- GP.Vec.new 0 0 len- MakePrism.fromVec p v True True--faceFromVerts :: [V3 Double] -> Acquire (Ptr TopoDS.Face)-faceFromVerts pnts = do- verts <- traverse v3ToVertex pnts- edges <- traverse (uncurry MakeEdge.fromVertices) $ zip verts (drop 1 (cycle verts))- wireBuilder <- MakeWire.new- _ <- liftIO $ traverse (MakeWire.addEdge wireBuilder) edges- wire <- MakeWire.wire wireBuilder- -- passing True here forces the face to be a plane- faceBuilder <- MakeFace.fromWire wire True- MakeFace.face faceBuilder--solidFromFaces :: [Ptr TopoDS.Face] -> Acquire (Ptr TopoDS.Solid)-solidFromFaces faces = do- sewing <- BRepBuilderAPI.Sewing.new 1e-6 True True True False- compound <- TopoDS.Compound.new- builder <- TopoDS.Builder.new- liftIO $ TopoDS.Builder.makeCompound builder compound- _ <- liftIO $ traverse (TopoDS.Builder.add builder (Inheritance.upcast compound) . Inheritance.upcast) faces- liftIO $ BRepBuilderAPI.Sewing.load sewing (Inheritance.upcast compound)- liftIO . BRepBuilderAPI.Sewing.perform $ sewing- shape <- BRepBuilderAPI.Sewing.sewedShape sewing- maybeShapeAsSolid <- makeSolidFromShell shape- case maybeShapeAsSolid of - Just s -> return s- Nothing -> error "Failed to construct solid from faces"--solidFromVerts :: [[V3 Double]] -> Solid-solidFromVerts = solidFromAcquire emptyPaintMap . fmap Inheritance.upcast . (solidFromFaces <=< traverse faceFromVerts)---- | Regular Tetrahedron with unit side lengths--- --- One vertex is in the Z direction-tetrahedron :: Solid-tetrahedron = - let r = ((1/sqrt 8) *^)- . rotate (unit _z) (pi/4)- . rotate (V3 1 1 0) (pi - unangle (V2 1 (sqrt 2)))- v1 = V3 1 1 1- v2 = V3 1 (-1) (-1)- v3 = V3 (-1) 1 (-1)- v4 = V3 (-1) (-1) 1- in solidFromVerts . fmap (fmap r) $- [ [v1, v2, v3] - , [v1 ,v2, v4]- , [v2, v3, v4]- , [v3, v1, v4]- ]---- | Regular Octahedron with unit side lengths------ The vertices of the Octahedra lie on the X, Y and Z axes-octahedron :: Solid-octahedron = - let h = 1 / sqrt 2- t = unit _z ^* h- b = negate t- c1 = h *^ unit _x- c2 = h *^ unit _y- c3 = negate c1- c4 = negate c2- in solidFromVerts- [ [t, c1, c2]- , [t, c2, c3]- , [t, c3, c4]- , [t, c4, c1]- , [b, c2, c1]- , [b, c3, c2]- , [b, c4, c3]- , [b, c1, c4]- ]---- | Regular Icosahedron with unit side lengths-icosahedron :: Solid-icosahedron = - let phi = (1 + sqrt 5) / 2- signs = [-1, 1]- in solidFromVerts $- [ - let a = zero & l1 .~ (V2 (s1 * phi/2) 0.5)- b = zero & l1 .~ (V2 (s1 * phi/2) (-0.5))- c = zero & l2 .~ (V2 (s2 * phi/2) (0.5 * s1))- in if s1 < 0 then [b, a, c]- else [a, b, c]- | s1 <- signs- , s2 <- signs- , (l1, l2) <- [(_xy, _zx), (_zx, _yz), (_yz, _xy)]- ] <> - [- [ zero & _xy .~ (V2 (a * phi/2) (c * 0.5))- , zero & _yz .~ (V2 (c * phi/2) (b * 0.5))- , zero & _zx .~ (V2 (b * phi/2) (a * 0.5))- ]- | a <- signs- , b <- signs- , c <- signs- ]---- | Regular Dodecahedron with unit side lengths-dodecahedron :: Solid-dodecahedron = - let phi = (1 + sqrt 5)/2 - plusMinusOne = [1, -1]- scale = phi / 2 - -- colours taken from https://commons.wikimedia.org/wiki/File:Dodecahedron_vertices.svg- orange x y z = scale *^ V3 x y z- green y z = scale *^ V3 0 (phi * y) (z / phi)- blue x z = scale *^ V3 (x/phi) 0 (phi * z)- pink x y = scale *^ V3 (phi * x) (y/phi) 0- in solidFromVerts $- [ \y z -> [ blue (-1) z, blue (1) z, orange (1) y z, green y z, orange (-1) y z]- , \x y -> [ green y (-1), green y 1, orange x y 1, pink x y, orange x y (-1)] - , \x z -> [ pink x (-1), pink x 1, orange x 1 z, blue x z, orange x (-1) z] - ] <*> plusMinusOne <*> plusMinusOne----- | Apply a `Colour` to a `Solid`------ Replaces any previously applied paint-colourSolid :: Colour -> Solid -> Solid-colourSolid colour = paintSolid (paintWithColour colour)---- | Apply a `Paint` to a `Solid`------ Replaces any previously applied paint-paintSolid :: Paint -> Solid -> Solid-paintSolid paint (Solid s _) = - Solid s (UniformPaint paint )--gPropQuery :: (NoPtr a, NFData a) => (Ptr GProps.GProps -> Acquire a) -> Solid -> a-gPropQuery f s = unsafeFromAcquire $ do- solid <- acquireSolid s- gProp <- GProps.new- liftIO $ BRepGProp.volumeProperties solid gProp False False False- f gProp---- | Volume of the Solid-volume :: Solid -> Double-volume = gPropQuery (liftIO . GProps.mass)---- | Center Of Mass of the Solid-centerOfMass :: Solid -> V3 Double -centerOfMass = gPropQuery ((liftIO . gpPntToV3) <=< GProps.centreOfMass)---- | Moment of Inertia of the Solid around a particular point and axis-momentOfInertia :: V3 Double -- ^ Point on the Axis of the Moment- -> V3 Double -- ^ Direction of the Axis of the Moment - -> Solid- -> Double -momentOfInertia center axis = gPropQuery $ \gprop -> do- pnt <- GP.Pnt.new (center ^. _x) (center ^. _y) (center ^. _z)- dir <- GP.Dir.new (axis ^. _x) (axis ^. _y) (axis ^. _z)- ax1 <- GP.Ax1.new pnt dir- liftIO $ GProps.momentOfInertia gprop ax1+import Waterfall.Solid
src/Waterfall/Sweep.hs view
@@ -3,24 +3,34 @@ , trySweep ) where -import Waterfall.Internal.Solid (Solid (..), acquireSolid, solidFromAcquire, solidFromAcquireWithCatch, emptyPaintMap)+import Waterfall.Internal.Solid (Solid (..), acquireSolid, solidFromAcquire, emptyPaintMap, solidFromAcquireTWithCatch) import Waterfall.Internal.Path (Path (..)) import Waterfall.Internal.Path.Common (RawPath (..)) import Waterfall.Internal.Edges (wireTangentStart, wireEndpoints) import Waterfall.Internal.Finalizers (acquireForeignPtr) import Waterfall.Internal.NearZero (nearZero)+import Waterfall.Internal.FromOpenCascade (subShapes) import Waterfall.Transforms (rotate, translate)+import Waterfall.Booleans (difference) import Waterfall.TwoD.Internal.Shape (Shape (..))-import qualified OpenCascade.BRepOffsetAPI.MakePipe as MakePipe+import qualified OpenCascade.BRepOffsetAPI.MakePipeShell as MakePipeShell import qualified OpenCascade.BRepBuilderAPI.MakeShape as MakeShape-import OpenCascade.Inheritance (upcast)+import qualified OpenCascade.BRepTools as BRepTools+import qualified OpenCascade.TopoDS.Shape as TopoDS.Shape+import qualified OpenCascade.BRepBuilderAPI.TransitionMode as TransitionMode import qualified OpenCascade.TopoDS as TopoDS+import OpenCascade.Inheritance (upcast) import Control.Monad.IO.Class (liftIO) import Foreign.Ptr import Linear (V3, normalize, unit, _x, _z, cross, dot) import Data.Acquire (Acquire) import Waterfall.Error (WaterfallError) import Data.Either (fromRight)+import Control.Monad (void, forM, filterM)+import Data.Functor.Compose (Compose (..))+import Data.Foldable (foldl')+import Data.List.NonEmpty (NonEmpty((:|)))+import Data.Maybe (catMaybes) rotateFace :: V3 Double -> Ptr TopoDS.Shape -> Acquire (Ptr TopoDS.Shape) rotateFace v face = @@ -39,17 +49,43 @@ positionFace :: V3 Double -> Ptr TopoDS.Shape -> Acquire (Ptr TopoDS.Shape) positionFace p = acquireSolid . translate p . solidFromAcquire emptyPaintMap . pure +reassembleSweep :: Compose [] NonEmpty Solid -> Solid+reassembleSweep = + let subtractTail (h :| t) = foldl' difference h t+ in mconcat . fmap subtractTail . getCompose -- | Version of `sweep` that returns an Error on Failure trySweep :: Path -> Shape -> Either WaterfallError Solid-trySweep (Path (ComplexRawPath theRawPath)) (Shape theRawShape) = solidFromAcquireWithCatch emptyPaintMap $ do+trySweep (Path (ComplexRawPath theRawPath)) (Shape theRawShape) = fmap reassembleSweep . solidFromAcquireTWithCatch emptyPaintMap $ do path <- acquireForeignPtr theRawPath shape <- acquireForeignPtr theRawShape tangent <- liftIO $ wireTangentStart path (start,_) <- liftIO $ wireEndpoints path adjustedFace <- positionFace start =<< rotateFace tangent shape- builder <- MakePipe.fromWireAndShape path adjustedFace- MakeShape.shape (upcast builder)+ faces <- subShapes adjustedFace+ let shapeForWire wire = do+ builder <- MakePipeShell.new path+ liftIO $ do+ MakePipeShell.setTransitionMode builder TransitionMode.RightCorner+ MakePipeShell.setDiscreteMode builder+ MakePipeShell.add builder wire False False+ MakeShape.build (upcast builder)+ void $ MakePipeShell.makeSolid builder+ MakeShape.shape (upcast builder)+ fmap (Compose . catMaybes) . forM faces $ \face -> do+ outerWire <- BRepTools.outerWire face+ isNull <- liftIO $ TopoDS.Shape.isNull (upcast outerWire)+ if isNull+ then pure Nothing + else do+ innerWires <- filterM + (liftIO + . fmap not + . TopoDS.Shape.isSame (upcast outerWire)+ . upcast+ ) =<< subShapes (upcast face)+ (Just .) . (:|) <$> shapeForWire outerWire+ <*> forM innerWires shapeForWire trySweep _ _ = Right mempty
src/Waterfall/Transforms.hs view
@@ -18,12 +18,13 @@ , _mirrored ) where import Waterfall.Internal.Solid (Solid (..), acquireSolid, solidFromAcquireMappingPaintMap, makeShapeHistory)-import Waterfall.Internal.Finalizers (acquireForeignPtr, unsafeFromAcquirePtr) +import Waterfall.Internal.Finalizers (acquireForeignPtr, unsafeFromAcquirePtrT) import Waterfall.Internal.Path.Common (RawPath(..))-import Waterfall.Internal.NearZero (nearZero)+import Waterfall.Internal.NearZero (nearZero, confusion)+import Waterfall.Internal.Edges (forwardWireAndStripZeroLengthEdges) import Linear.V3 (V3 (..)) import Linear.V4 (V4 (..))-import Linear (M34, (*^), normalize, dot, (!*), unit, _w, _xyz, _x, _y, _z)+import Linear (M34, M33, (*^), normalize, dot, (!*), unit, _w, _xyz, _x, _y, _z, (!*!), transpose, (!-!), (*!!), identity, zero, norm, det33) import qualified Linear.Quaternion as Quaternion import qualified OpenCascade.GP.Trsf as GP.Trsf import qualified OpenCascade.GP as GP@@ -35,14 +36,15 @@ import qualified OpenCascade.BRepBuilderAPI.Transform as BRepBuilderAPI.Transform import qualified OpenCascade.BRepBuilderAPI.GTransform as BRepBuilderAPI.GTransform import qualified OpenCascade.BRepBuilderAPI.MakeShape as BRepBuilderAPI.MakeShape-import Control.Monad (when)+import Control.Monad (when, void) import Control.Monad.IO.Class (liftIO) import Data.Acquire import Foreign.Ptr import Waterfall.Internal.Path (Path(..)) import OpenCascade.Inheritance (upcast, unsafeDowncast) import Data.Function ((&))-import Control.Lens ((.~), Iso', iso)+import Control.Lens ((.~), Iso', iso, (^.))+import Waterfall.Path (pathEndpoints) -- | Typeclass for objects that can be manipulated in 3D space class Transformable a where@@ -79,24 +81,36 @@ transformPathSinglePointPaths _ p = p fromTrsfPath :: (V3 Double -> V3 Double) -> Acquire (Ptr GP.Trsf) -> Path -> Path-fromTrsfPath _ mkTrsf (Path (ComplexRawPath p)) = Path . ComplexRawPath . unsafeFromAcquirePtr $ do - path <- acquireForeignPtr p- trsf <- mkTrsf - (liftIO . unsafeDowncast)- =<< BRepBuilderAPI.MakeShape.shape- =<< fmap upcast - (BRepBuilderAPI.Transform.fromShapeTrsfAndCopy (upcast path) trsf True)+fromTrsfPath f mkTrsf p@(Path (ComplexRawPath rawPath)) = + let pathFromEndpoints = + Path . maybe EmptyRawPath (SinglePointRawPath . f . fst) . pathEndpoints+ in maybe + (pathFromEndpoints p)+ (Path . ComplexRawPath) . unsafeFromAcquirePtrT $ do + path <- acquireForeignPtr rawPath+ trsf <- mkTrsf + forwardWireAndStripZeroLengthEdges + =<< (liftIO . unsafeDowncast)+ =<< BRepBuilderAPI.MakeShape.shape+ =<< fmap upcast + (BRepBuilderAPI.Transform.fromShapeTrsfAndCopy (upcast path) trsf True) fromTrsfPath f _ (Path (SinglePointRawPath v)) = Path . SinglePointRawPath . f $ v fromTrsfPath _ _ (Path EmptyRawPath) = Path EmptyRawPath fromGTrsfPath :: (V3 Double -> V3 Double) -> Acquire (Ptr GP.GTrsf) -> Path -> Path-fromGTrsfPath _ mkTrsf (Path (ComplexRawPath p)) = Path . ComplexRawPath . unsafeFromAcquirePtr $ do - path <- acquireForeignPtr p- trsf <- mkTrsf - (liftIO . unsafeDowncast) - =<< BRepBuilderAPI.MakeShape.shape- =<< fmap upcast- (BRepBuilderAPI.GTransform.fromShapeGTrsfAndCopy (upcast path) trsf True)+fromGTrsfPath f mkTrsf p@(Path (ComplexRawPath rawPath)) = + let pathFromEndpoints = + Path . maybe EmptyRawPath (SinglePointRawPath . f . fst) . pathEndpoints+ in maybe + (pathFromEndpoints p)+ (Path . ComplexRawPath) . unsafeFromAcquirePtrT $ do + path <- acquireForeignPtr rawPath+ trsf <- mkTrsf + forwardWireAndStripZeroLengthEdges+ =<< (liftIO . unsafeDowncast) + =<< BRepBuilderAPI.MakeShape.shape+ =<< fmap upcast+ (BRepBuilderAPI.GTransform.fromShapeGTrsfAndCopy (upcast path) trsf True) fromGTrsfPath f _ (Path (SinglePointRawPath v)) = Path . SinglePointRawPath . f $ v fromGTrsfPath _ _ (Path EmptyRawPath) = Path EmptyRawPath @@ -111,7 +125,7 @@ scaleTrsf :: V3 Double -> (Maybe (Acquire (Ptr GP.Trsf)), Maybe (Acquire (Ptr GP.GTrsf))) scaleTrsf (V3 1 1 1) = (Nothing, Nothing) scaleTrsf (V3 x y z ) =- let isUniform = abs x == abs y && abs y == abs z + let isUniform = nearZero (abs x - abs y) && nearZero (abs y - abs z) isAllPositive = x >= 0 && y >= 0 && z >= 0 in if isUniform && isAllPositive then (Just $ uScaleTrsf x, Nothing)@@ -122,14 +136,14 @@ then uScaleTrsf (abs x) else GP.Trsf.new when (x < 0) $ do- mirrorX <- mirrorTrsf (unit _x)- liftIO $ GP.Trsf.multiply trsf mirrorX+ mirrorX <- sequence (mirrorTrsf (unit _x))+ void . liftIO $ traverse (GP.Trsf.multiply trsf) mirrorX when (y < 0) $ do- mirrorY <- mirrorTrsf (unit _y)- liftIO $ GP.Trsf.multiply trsf mirrorY+ mirrorY <- sequence $ (mirrorTrsf (unit _y))+ void . liftIO $ traverse (GP.Trsf.multiply trsf) mirrorY when (z < 0) $ do- mirrorZ <- mirrorTrsf (unit _z)- liftIO $ GP.Trsf.multiply trsf mirrorZ+ mirrorZ <- sequence $ mirrorTrsf (unit _z)+ void . liftIO $ traverse (GP.Trsf.multiply trsf) mirrorZ return trsf , if isUniform then Nothing@@ -139,7 +153,6 @@ GP.GTrsf.setValue gtrsf 1 1 (abs x) GP.GTrsf.setValue gtrsf 2 2 (abs y) GP.GTrsf.setValue gtrsf 3 3 (abs z)- GP.GTrsf.setForm gtrsf return gtrsf ) @@ -150,14 +163,16 @@ liftIO $ GP.Trsf.setScale trsf o factor return trsf -rotateTrsf :: V3 Double -> Double -> Acquire (Ptr GP.Trsf)-rotateTrsf (V3 ax ay az) angle = do- trsf <- GP.Trsf.new- o <- GP.origin- dir <- GP.Dir.new ax ay az- axis <- GP.Ax1.new o dir- liftIO $ GP.Trsf.setRotationAboutAxisAngle trsf axis angle- return trsf+rotateTrsf :: V3 Double -> Double -> Maybe (Acquire (Ptr GP.Trsf))+rotateTrsf v@(V3 ax ay az) angle+ | all nearZero v = Nothing+ | otherwise = Just $ do+ trsf <- GP.Trsf.new+ o <- GP.origin+ dir <- GP.Dir.new ax ay az+ axis <- GP.Ax1.new o dir+ liftIO $ GP.Trsf.setRotationAboutAxisAngle trsf axis angle+ return trsf translateTrsf :: V3 Double -> Acquire (Ptr GP.Trsf) translateTrsf (V3 x y z) = do@@ -166,57 +181,85 @@ liftIO $ GP.Trsf.setTranslation trsf vec return trsf -mirrorTrsf :: V3 Double -> Acquire (Ptr GP.Trsf)-mirrorTrsf (V3 x y z) = do- trsf <- GP.Trsf.new- dir <- GP.Dir.new x y z- axis <- GP.xoy- liftIO $ do - GP.Ax2.setDirection axis dir- GP.Trsf.setMirrorAboutAx2 trsf axis- return trsf+mirrorTrsf :: V3 Double -> Maybe (Acquire (Ptr GP.Trsf))+mirrorTrsf v@(V3 x y z) + | all nearZero v = Nothing+ | otherwise = Just $ do+ trsf <- GP.Trsf.new+ dir <- GP.Dir.new x y z+ axis <- GP.xoy+ liftIO $ do + GP.Ax2.setDirection axis dir+ GP.Trsf.setMirrorAboutAx2 trsf axis+ return trsf +-- is a matrix a combination of an Orthogonal Matrix + a uniform Scale+isOrthogonalAndScale :: M33 Double -> Bool+isOrthogonalAndScale m = + let p = m !*! transpose m+ s = p ^. _x . _x+ in not (nearZero s) && all (all (nearZero . (/s))) (p !-! (s *!! identity))+ matrixGTrsf :: M34 Double -> Maybe (Either (Acquire (Ptr GP.Trsf)) (Acquire (Ptr GP.GTrsf))) matrixGTrsf (V3 (V4 1 0 0 0) (V4 0 1 0 0) (V4 0 0 1 0)) = Nothing-matrixGTrsf (V3 (V4 x 0 0 0) (V4 0 y 0 0) (V4 0 0 z 0)) | x == y && y == z = Just . Left . uScaleTrsf $ x-matrixGTrsf (V3 (V4 v11 v12 v13 v14) (V4 v21 v22 v23 v24) (V4 v31 v32 v33 v34)) = Just . Right $ do- trsf <- GP.GTrsf.new- liftIO $ do - GP.GTrsf.setValue trsf 1 1 v11- GP.GTrsf.setValue trsf 1 2 v12- GP.GTrsf.setValue trsf 1 3 v13- GP.GTrsf.setValue trsf 1 4 v14- GP.GTrsf.setValue trsf 2 1 v21- GP.GTrsf.setValue trsf 2 2 v22- GP.GTrsf.setValue trsf 2 3 v23- GP.GTrsf.setValue trsf 2 4 v24- GP.GTrsf.setValue trsf 3 1 v31- GP.GTrsf.setValue trsf 3 2 v32- GP.GTrsf.setValue trsf 3 3 v33- GP.GTrsf.setValue trsf 3 4 v34- GP.GTrsf.setForm trsf+matrixGTrsf (V3 (V4 x 0 0 0) (V4 0 y 0 0) (V4 0 0 z 0)) + | x == y && y == z && not (nearZero x)= Just . Left . uScaleTrsf $ x+matrixGTrsf m@(V3 (V4 v11 v12 v13 v14) (V4 v21 v22 v23 v24) (V4 v31 v32 v33 v34)) + | isOrthogonalAndScale (fmap (^. _xyz) m) = Just . Left $ do+ trsf <- GP.Trsf.new+ liftIO $ GP.Trsf.setValues trsf v11 v12 v13 v14 v21 v22 v23 v24 v31 v32 v33 v34 return trsf+ | otherwise = Just . Right $ do+ trsf <- GP.GTrsf.new+ liftIO $ do + GP.GTrsf.setValue trsf 1 1 v11+ GP.GTrsf.setValue trsf 1 2 v12+ GP.GTrsf.setValue trsf 1 3 v13+ GP.GTrsf.setValue trsf 1 4 v14+ GP.GTrsf.setValue trsf 2 1 v21+ GP.GTrsf.setValue trsf 2 2 v22+ GP.GTrsf.setValue trsf 2 3 v23+ GP.GTrsf.setValue trsf 2 4 v24+ GP.GTrsf.setValue trsf 3 1 v31+ GP.GTrsf.setValue trsf 3 2 v32+ GP.GTrsf.setValue trsf 3 3 v33+ GP.GTrsf.setValue trsf 3 4 v34+ return trsf instance Transformable Solid where matTransform :: M34 Double -> Solid -> Solid- matTransform = maybe id (either fromTrsfSolid fromGTrsfSolid) . matrixGTrsf - + matTransform m + | isSingular = mempty + | otherwise = maybe id (either fromTrsfSolid fromGTrsfSolid) (matrixGTrsf m)+ where + isSingular =+ let m33 = (^. _xyz) <$> m+ rowNorms = norm <$> m33+ in any nearZero rowNorms || abs (det33 m33) < confusion * product rowNorms+ scale :: V3 Double -> Solid -> Solid- scale factor = - applyScaleTrsf fromTrsfSolid fromGTrsfSolid (scaleTrsf factor)+ scale factor+ | any nearZero factor = mempty + | otherwise = applyScaleTrsf fromTrsfSolid fromGTrsfSolid (scaleTrsf factor) uScale :: Double -> Solid -> Solid- uScale = fromTrsfSolid . uScaleTrsf+ uScale factor+ | nearZero factor = mempty+ | otherwise = fromTrsfSolid . uScaleTrsf $ factor rotate :: V3 Double -> Double -> Solid -> Solid- rotate axis angle = fromTrsfSolid (rotateTrsf axis angle)+ rotate axis angle = maybe id fromTrsfSolid (rotateTrsf axis angle) translate :: V3 Double -> Solid -> Solid translate = fromTrsfSolid . translateTrsf mirror :: V3 Double -> Solid -> Solid- mirror = fromTrsfSolid . mirrorTrsf+ mirror = maybe id fromTrsfSolid . mirrorTrsf +collapseToOrigin :: Path -> Path+collapseToOrigin (Path EmptyRawPath) = Path EmptyRawPath+collapseToOrigin _ = Path . SinglePointRawPath $ zero+ instance Transformable Path where matTransform :: M34 Double -> Path -> Path matTransform m = @@ -224,21 +267,25 @@ in maybe id (either (fromTrsfPath transformPnt) (fromGTrsfPath transformPnt)) $ matrixGTrsf m scale :: V3 Double -> Path -> Path- scale s =- let transformPnt = scale s - in transformPathSinglePointPaths transformPnt . applyScaleTrsf (fromTrsfPath id) (fromGTrsfPath id) (scaleTrsf s)+ scale s+ | all nearZero s = collapseToOrigin+ | otherwise = + let transformPnt = scale s + in transformPathSinglePointPaths transformPnt . applyScaleTrsf (fromTrsfPath id) (fromGTrsfPath id) (scaleTrsf s) uScale :: Double -> Path -> Path- uScale s = fromTrsfPath (uScale s) (uScaleTrsf s)+ uScale s+ | nearZero s = collapseToOrigin+ | otherwise = fromTrsfPath (uScale s) (uScaleTrsf s) rotate :: V3 Double -> Double -> Path -> Path- rotate axis angle = fromTrsfPath (rotate axis angle) (rotateTrsf axis angle)+ rotate axis angle = maybe id (fromTrsfPath (rotate axis angle)) (rotateTrsf axis angle) translate :: V3 Double -> Path -> Path translate v = fromTrsfPath (translate v) (translateTrsf v) mirror :: V3 Double -> Path -> Path- mirror v = fromTrsfPath (mirror v) (mirrorTrsf v)+ mirror v = maybe id (fromTrsfPath (mirror v)) (mirrorTrsf v) instance Transformable (V3 Double) where matTransform :: M34 Double -> V3 Double -> V3 Double@@ -252,15 +299,19 @@ uScale = (*^) rotate :: V3 Double -> Double -> V3 Double -> V3 Double - rotate axis angle = Quaternion.rotate (Quaternion.axisAngle axis angle)+ rotate axis angle + | all nearZero axis = id+ | otherwise = Quaternion.rotate (Quaternion.axisAngle axis angle) translate :: V3 Double -> V3 Double -> V3 Double translate = (+) mirror :: V3 Double -> V3 Double -> V3 Double - mirror mirrorVec toMirror = - let nm = normalize mirrorVec- in toMirror - (2 * (nm `dot` toMirror) *^ nm)+ mirror mirrorVec toMirror+ | all nearZero mirrorVec = toMirror+ | otherwise = + let nm = normalize mirrorVec+ in toMirror - (2 * (nm `dot` toMirror) *^ nm) -- | Every translation is an isomorphism _translated :: Transformable t => V3 Double -> Iso' t t
src/Waterfall/TwoD/Booleans.hs view
@@ -1,5 +1,5 @@ {-|-[Boolean Operations](https://en.wikipedia.org/wiki/Boolean_operations_on_polygons) on `Shape`.+[Boolean Operations](https://en.wikipedia.org/wiki/Boolean_operations_on_polygons) on `Waterfall.TwoD.Shape.Shape`. -} module Waterfall.TwoD.Booleans ( union2D
+ src/Waterfall/TwoD/BoundingBox/AxisAligned.hs view
@@ -0,0 +1,81 @@+module Waterfall.TwoD.BoundingBox.AxisAligned+( HasAxisAlignedBoundingBox2D ()+, axisAlignedBoundingBox2D+, aabbToShape+) where+import Waterfall.TwoD.Shape (Shape, unitSquare, area)+import Waterfall.TwoD.Internal.Shape (acquireShape)+import Waterfall.Internal.Finalizers (unsafeFromAcquire, acquireForeignPtr)+import Waterfall.Internal.FromOpenCascade (gpPntToV3)+import Linear (V2 (..), (^-^), _xy)+import qualified OpenCascade.Bnd.Box as Bnd.Box+import qualified OpenCascade.BRepBndLib as BRepBndLib+import Control.Monad.IO.Class (liftIO)+import Data.Acquire (Acquire)+import Foreign (Ptr)+import qualified OpenCascade.TopoDS as TopoDS+import Waterfall.TwoD.Internal.Path2D (Path2D (..))+import Waterfall.Internal.Path.Common (RawPath(..))+import OpenCascade.Inheritance (upcast)+import Waterfall.Internal.ToOpenCascade (v3ToVertex)+import Control.Monad (forM_)+import Waterfall.TwoD.Transforms (scale2D, translate2D)+import Control.Lens ((^.))+import Waterfall.Diagram (Diagram (getDiagramLines, getDiagramFills))+import Data.Functor.Compose (Compose(..))+import Data.Monoid (Ap(..))++-- | Class for things that have a Bounding Box+-- +-- Has instances for `Shape`, `Path2D` and `Diagram`+class HasAxisAlignedBoundingBox2D a where+ _isEmpty :: a -> Bool+ _getShapes :: a -> Acquire [Ptr TopoDS.Shape]++instance HasAxisAlignedBoundingBox2D Shape where+ _isEmpty s = area s == 0+ _getShapes = fmap pure . acquireShape++instance HasAxisAlignedBoundingBox2D Path2D where+ _isEmpty (Path2D EmptyRawPath) = True+ _isEmpty _ = False++ _getShapes (Path2D (ComplexRawPath p)) = fmap (pure . upcast) . acquireForeignPtr $ p+ _getShapes (Path2D (SinglePointRawPath p)) = fmap (pure . upcast) . v3ToVertex $ p+ _getShapes (Path2D EmptyRawPath) = pure []++instance HasAxisAlignedBoundingBox2D Diagram where+ _isEmpty diagram = + all (all _isEmpty) (getDiagramLines diagram)+ && all (_isEmpty . snd) (getDiagramFills diagram)++ _getShapes diagram = + getAp + ((foldMap (Ap . _getShapes) . Compose) (getDiagramLines diagram)+ <> (foldMap (Ap . _getShapes) . Compose) (getDiagramFills diagram)+ )+++-- | Return the smallest Axis Aligned Bounding Box (AABB) that contains the `Shape`, `Path2D` or `Diagram`.+-- +-- If computable, the AABB is returned in the form @(lo, hi)@,+-- where @lo@ is the vertex of the box with the lowest individual values,+-- and @hi@ is the vertex with the highest values.+axisAlignedBoundingBox2D :: HasAxisAlignedBoundingBox2D a => a -> Maybe (V2 Double, V2 Double)+axisAlignedBoundingBox2D s = + if _isEmpty s+ then Nothing + else Just . unsafeFromAcquire $ do+ shapes <- _getShapes s+ theBox <- Bnd.Box.new+ liftIO $ forM_ shapes $ \shape -> BRepBndLib.addOptimal shape theBox False False+ p1 <- liftIO . gpPntToV3 =<< Bnd.Box.cornerMin theBox+ p2 <- liftIO . gpPntToV3 =<< Bnd.Box.cornerMax theBox+ return (p1 ^. _xy, p2 ^. _xy)++-- | A rectangle, specified by two diagonal vertices.+-- +-- This can be used to make a shape from the output of `axisAlignedBoundingBox2D` +aabbToShape :: (V2 Double, V2 Double) -- ^ if this argument input is @(lo, hi)@, one vertex of the rectangle is placed at @lo@, the opposite vertex is at @hi@+ -> Shape+aabbToShape (lo, hi) = translate2D lo . scale2D (hi ^-^ lo) $ unitSquare
+ src/Waterfall/TwoD/BoundingBox/Oriented.hs view
@@ -0,0 +1,134 @@+{-# LANGUAGE InstanceSigs #-}+module Waterfall.TwoD.BoundingBox.Oriented+( HasOrientedBoundingBox2D ()+, OrientedBoundingBox2D+, obb2DCenter+, obb2DSideX+, obb2DSideY+, orientedBoundingBox2D+, obbToShape+) where++import Linear (V2 (..), normalize, (^*), _xy, norm, unangle, quadrance, zero)+import Waterfall.TwoD.Shape (Shape, centeredSquare, area)+import Waterfall.Internal.Finalizers (acquireForeignPtr, unsafeFromAcquirePtr, unsafeFromAcquire)+import Waterfall.Internal.FromOpenCascade (gpXYZToV3)+import Foreign.Ptr (Ptr)+import qualified OpenCascade.Bnd.OBB as OBB+import OpenCascade.Bnd.OBB (OBB)+import OpenCascade.GP.Types (XYZ)+import qualified OpenCascade.BRepBndLib as BRepBndLib+import OpenCascade.Inheritance (upcast)+import Data.Acquire (Acquire)+import Control.Monad.IO.Class (liftIO)+import Control.Monad ((<=<), forM_)+import Foreign.ForeignPtr (ForeignPtr)+import Control.DeepSeq (NFData (rnf), rwhnf)+import qualified OpenCascade.TopoDS as TopoDS+import Waterfall.Internal.Path.Common (RawPath(..))+import Waterfall.Internal.ToOpenCascade (v3ToVertex)+import Waterfall.TwoD.Internal.Path2D (Path2D (..))+import Waterfall.Diagram (Diagram (getDiagramFills), getDiagramLines)+import Waterfall.TwoD.Internal.Shape (acquireShape)+import Data.Monoid (Ap(..))+import Data.Functor.Compose (Compose(..))+import Control.Lens ((^.))+import Data.Function ((&))+import Waterfall.TwoD.Transforms (scale2D, rotate2D, Transformable2D (translate2D))+import Data.List (sortOn)+import Data.Ord (Down(..))++-- | Class for things that have a Bounding Box+-- +-- Has instances for `Shape`, `Path2D` and `Diagram`+class HasOrientedBoundingBox2D a where+ _isEmpty :: a -> Bool+ _getShapes :: a -> Acquire [Ptr TopoDS.Shape]++instance HasOrientedBoundingBox2D Shape where+ _isEmpty s = area s == 0+ _getShapes = fmap pure . acquireShape++instance HasOrientedBoundingBox2D Path2D where+ _isEmpty (Path2D EmptyRawPath) = True+ _isEmpty _ = False++ _getShapes (Path2D (ComplexRawPath p)) = fmap (pure . upcast) . acquireForeignPtr $ p+ _getShapes (Path2D (SinglePointRawPath p)) = fmap (pure . upcast) . v3ToVertex $ p+ _getShapes (Path2D EmptyRawPath) = pure []++instance HasOrientedBoundingBox2D Diagram where+ _isEmpty diagram = + all (all _isEmpty) (getDiagramLines diagram)+ && all (_isEmpty . snd) (getDiagramFills diagram)++ _getShapes diagram = + getAp + ((foldMap (Ap . _getShapes) . Compose) (getDiagramLines diagram)+ <> (foldMap (Ap . _getShapes) . Compose) (getDiagramFills diagram)+ )+++-- | An OrientedBoundingBox may be a tighter fit than an axis aligned bounding box would be+-- +newtype OrientedBoundingBox2D = OrientedBoundingBox2D { rawOBB :: ForeignPtr OBB }++instance NFData OrientedBoundingBox2D where + rnf (OrientedBoundingBox2D obb) = rwhnf obb++-- | Compute an `OrientedBoundingBox2D` for a `Shape`, `Path2D` or Diagram+orientedBoundingBox2D :: HasOrientedBoundingBox2D a => a -> Maybe OrientedBoundingBox2D+orientedBoundingBox2D s = + if _isEmpty s+ then Nothing + else Just . OrientedBoundingBox2D . unsafeFromAcquirePtr $ do+ obb <- OBB.new+ shapes <- _getShapes s+ liftIO $ forM_ shapes $ \shape -> BRepBndLib.addOBB shape obb False True True+ return obb++queryOBB :: (Ptr OBB -> Acquire (V2 Double)) -> OrientedBoundingBox2D -> V2 Double+queryOBB f = unsafeFromAcquire . ( f <=< acquireForeignPtr . rawOBB)++-- | The center point of an `OrientedBoundingBox2D`+obb2DCenter :: OrientedBoundingBox2D -> V2 Double+obb2DCenter = queryOBB (fmap (^. _xy) . liftIO . gpXYZToV3 <=< OBB.center)++getSide :: (Ptr OBB -> Acquire (Ptr XYZ)) -> (Ptr OBB -> IO Double) -> OrientedBoundingBox2D -> V2 Double+getSide fxyz fLength = queryOBB $ \obb -> do+ side <- fmap (^. _xy) . liftIO . gpXYZToV3 =<< fxyz obb+ len <- liftIO $ fLength obb+ return $ normalize side ^* len++obb2DSides :: OrientedBoundingBox2D -> (V2 Double, V2 Double)+obb2DSides obb = + let x = getSide OBB.xDirection OBB.xHSize obb+ y = getSide OBB.yDirection OBB.yHSize obb+ z = getSide OBB.zDirection OBB.zHSize obb+ in case sortOn (Down . quadrance) [x, y, z] of + (a : b : _) -> (a, b)+ _ -> (zero, zero)++-- | The longer side of the oriented bounding box.+--+-- This is measured from the center to one edge.+-- So the length of this vector is /half/ of the side length of the bounding box.+obb2DSideX :: OrientedBoundingBox2D -> V2 Double +obb2DSideX = fst . obb2DSides ++-- | The shorter side of the oriented bounding box.+--+-- This is measured from the center to one edge.+-- So the length of this vector is /half/ of the side length of the bounding box.+obb2DSideY :: OrientedBoundingBox2D -> V2 Double +obb2DSideY = snd . obb2DSides+ +-- | Reify an `OrientedBoundingBox2D` as a `Shape`+obbToShape :: OrientedBoundingBox2D -> Shape+obbToShape obb =+ let box = V2 (norm $ obb2DSideX obb) (norm $ obb2DSideY obb) ^* 2+ theta = unangle (obb2DSideX obb)+ in centeredSquare+ & scale2D box+ & rotate2D theta + & translate2D (obb2DCenter obb)
src/Waterfall/TwoD/Internal/Shape.hs view
@@ -16,22 +16,32 @@ import Foreign.Ptr import Data.Acquire (Acquire) import Algebra.Lattice-import Waterfall.Internal.Finalizers (acquireForeignPtr, unsafeFromAcquirePtr)+import Waterfall.Internal.Finalizers (acquireForeignPtr, unsafeFromAcquirePtr, unsafeFromAcquire) import qualified OpenCascade.BRepAlgoAPI.Fuse as Fuse import qualified OpenCascade.BRepAlgoAPI.Cut as Cut import qualified OpenCascade.BRepAlgoAPI.Common as Common-import qualified OpenCascade.TopoDS.Shape as TopoDS.Shape import OpenCascade.BRepBuilderAPI (MakeShape)-import qualified OpenCascade.BRepBuilderAPI.MakeFace as MakeFace import qualified OpenCascade.BRepBuilderAPI.MakeShape as MakeShape import qualified OpenCascade.BOPAlgo.Operation as BOPAlgo.Operation import qualified OpenCascade.BOPAlgo.BOP as BOPAlgo.BOP import qualified OpenCascade.BOPAlgo.Builder as BOPAlgo.Builder+import qualified OpenCascade.ShapeUpgrade.UnifySameDomain as UnifySameDomain import OpenCascade.Inheritance (SubTypeOf, upcast) import Control.Monad.IO.Class (liftIO) import Data.Foldable (traverse_) import Foreign.ForeignPtr (ForeignPtr) import Control.DeepSeq (NFData (rnf), rwhnf)+import qualified OpenCascade.TopoDS.Builder as TopoDS.Builder+import qualified OpenCascade.TopoDS.Compound as TopoDS.Compound+import Control.Monad ((<=<), forM_)+import qualified OpenCascade.TopAbs.ShapeEnum as ShapeEnum+import Waterfall.Internal.FromOpenCascade (containsShapeKind, deduplicateTopoDSShapes)+import qualified OpenCascade.BOPAlgo.CellsBuilder as CellsBuilder+import qualified OpenCascade.NCollection.List as NCollection.List+import OpenCascade.BRepAlgoAPI (BooleanOperation, BuilderAlgo)+import Waterfall.Internal.ToOpenCascade (shapeSingletonList)+import qualified OpenCascade.BRepAlgoAPI.BuilderAlgo as BuilderAlgo+import qualified OpenCascade.BRepAlgoAPI.BooleanOperation as BooleanOperation -- | A Region in 2D Space -- @@ -55,26 +65,39 @@ shapeFromAcquire :: Acquire (Ptr TopoDS.Shape) -> Shape shapeFromAcquire = Shape . unsafeFromAcquirePtr -toBoolean2D :: (SubTypeOf MakeShape a) => (Ptr TopoDS.Shape.Shape -> Ptr TopoDS.Shape.Shape -> Acquire (Ptr a)) -> Shape -> Shape -> Shape+toBoolean2D+ :: (SubTypeOf MakeShape a+ , SubTypeOf BooleanOperation a+ , SubTypeOf BuilderAlgo a)+ => (Acquire (Ptr a)) -> Shape -> Shape -> Shape toBoolean2D f (Shape ptrA) (Shape ptrB) = Shape . unsafeFromAcquirePtr $ do a <- acquireForeignPtr ptrA b <- acquireForeignPtr ptrB- MakeShape.shape =<< fmap upcast (f a b)+ builder <- f + liftIO $ BuilderAlgo.setNonDestructive (upcast builder) True+ liftIO . BuilderAlgo.setArguments (upcast builder) =<< shapeSingletonList a+ liftIO . BooleanOperation.setTools (upcast builder) =<< shapeSingletonList b+ liftIO $ MakeShape.build (upcast builder) + r <- MakeShape.shape (upcast builder)+ unifier <- UnifySameDomain.fromShape r False True False+ liftIO $ UnifySameDomain.build unifier+ UnifySameDomain.shape unifier+ -- | Take the union of two 2D shapes. -- The region occupied by either one of them union2D :: Shape -> Shape -> Shape-union2D = toBoolean2D Fuse.fromShapes+union2D = toBoolean2D Fuse.new -- | Take the difference of two 2D shapes. -- The region occupied by the first, but not the second difference2D :: Shape -> Shape -> Shape-difference2D = toBoolean2D Cut.fromShapes+difference2D = toBoolean2D Cut.new -- | Take the intersection of two 2D shapes. -- The region occupied by both of them intersection2D :: Shape -> Shape -> Shape-intersection2D = toBoolean2D Common.fromShapes+intersection2D = toBoolean2D Common.new toBooleans2D :: BOPAlgo.Operation.Operation -> [Shape] -> Shape toBooleans2D _ [] = emptyShape@@ -86,26 +109,62 @@ let builder = upcast bop liftIO $ do BOPAlgo.BOP.setOperation bop op+ BOPAlgo.Builder.setNonDestructive builder True BOPAlgo.Builder.addArgument builder firstPtr traverse_ (BOPAlgo.BOP.addTool bop) ptrs BOPAlgo.Builder.setRunParallel builder True BOPAlgo.Builder.perform builder- BOPAlgo.Builder.shape builder+ r <- BOPAlgo.Builder.shape builder+ unifier <- UnifySameDomain.fromShape r False True False+ liftIO $ UnifySameDomain.build unifier+ UnifySameDomain.shape unifier -- | Take the union of a list of 2D shapes -- May be more performant than chaining multiple applications of `union2D` unions2D :: [Shape] -> Shape-unions2D = toBooleans2D BOPAlgo.Operation.Fuse+unions2D = toBooleans2D BOPAlgo.Operation.Fuse + . filter (not . isEmptyShape)+ . deduplicateShapes +deduplicateShapes :: [Shape] -> [Shape]+deduplicateShapes = deduplicateTopoDSShapes acquireShape++isEmptyShape :: Shape -> Bool+isEmptyShape = + not . unsafeFromAcquire . (containsShapeKind ShapeEnum.Face <=< acquireShape)++intersections2D' :: [Shape] -> Shape+intersections2D' [] = emptyShape+intersections2D' [x] = x+intersections2D' ss+ | any isEmptyShape ss = emptyShape+ | otherwise = shapeFromAcquire $ do+ builder <- CellsBuilder.new + liftIO $ BOPAlgo.Builder.setRunParallel (upcast builder) True+ liftIO $ BOPAlgo.Builder.setNonDestructive (upcast builder) True+ listToTake <- NCollection.List.newListOfShape+ shapes <- traverse acquireShape ss+ forM_ shapes (liftIO . NCollection.List.appendListOfShape listToTake)+ listToAvoid <- NCollection.List.newListOfShape+ liftIO $ forM_ shapes (BOPAlgo.Builder.addArgument (upcast builder))+ liftIO (BOPAlgo.Builder.perform (upcast builder))+ liftIO $ CellsBuilder.addToResult builder listToTake listToAvoid 1 False+ liftIO $ CellsBuilder.removeInternalBoundaries builder++ BOPAlgo.Builder.shape (upcast builder)+ -- | Take the intersection of a list of 2D shapes -- May be more performant than chaining multiple applications of `intersection2D` intersections2D :: [Shape] -> Shape-intersections2D = toBooleans2D BOPAlgo.Operation.Common+intersections2D = intersections2D' . deduplicateShapes -- | An empty 2D shape emptyShape :: Shape-emptyShape = Shape . unsafeFromAcquirePtr $ - upcast <$> (MakeFace.face =<< MakeFace.new)+emptyShape = Shape . unsafeFromAcquirePtr $ do+ builder <- TopoDS.Builder.new+ compound <- TopoDS.Compound.new+ liftIO $ TopoDS.Builder.makeCompound builder compound+ pure (upcast compound) -- defining these boolean operators here, rather than in Waterfall.TwoD.Booleans -- means that we can use them in typeclass instances without resorting to orphans
+ src/Waterfall/TwoD/Offset.hs view
@@ -0,0 +1,81 @@+module Waterfall.TwoD.Offset+( offsetShape+, tryOffsetShape+) where+import Waterfall.TwoD.Internal.Shape (Shape (..))+import Waterfall.Error (WaterfallError)+import Waterfall.Internal.Finalizers (acquireForeignPtr, unsafeFromAcquirePtrTWithCatch)+import Data.Either (fromRight)+import Waterfall.Internal.NearZero (nearZero)+import Waterfall.Internal.FromOpenCascade (subShapes)+import Foreign (Ptr)+import qualified OpenCascade.TopoDS as TopoDS+import qualified OpenCascade.TopoDS.Shape as TopoDS.Shape+import Data.Acquire (Acquire)+import OpenCascade.Inheritance (upcast)+import Control.Monad.IO.Class (liftIO)+import qualified OpenCascade.BRepOffsetAPI.MakeOffset as MakeOffset+import qualified OpenCascade.BRepBuilderAPI.MakeShape as MakeShape+import qualified OpenCascade.BRepTools as BRepTools+import Control.Monad (forM, filterM)+import qualified Waterfall.Booleans as Booleans+import Data.Functor.Compose (Compose(..))+import qualified OpenCascade.BRepBuilderAPI.MakeFace as MakeFace+import qualified Data.List.NonEmpty as NE+import Data.List.NonEmpty (NonEmpty((:|)))+import qualified OpenCascade.GP.Pln as GP.Pln++-- | Expand or contract a `Shape` by a certain amount.+--+-- Returns an empty `Shape` on failure, see `tryOffsetShape`.+offsetShape + :: Double -- ^ Amount to offset by, positive values expand, negative values contract+ -> Shape -- ^ The `Shape` to offset+ -> Shape+offsetShape amount s = fromRight mempty $ tryOffsetShape amount s++offsetOne :: Double -> Ptr TopoDS.Face -> Acquire (NonEmpty [Ptr TopoDS.Shape])+offsetOne amount f = do+ outer <- BRepTools.outerWire f+ wires <- subShapes (upcast f)+ inner <- filterM (liftIO . fmap not . TopoDS.Shape.isSame (upcast outer) . upcast) wires+ pln <- GP.Pln.new+ let wiresAndAmounts = (outer :| inner) `NE.zip` (amount :| repeat (negate amount))+ forM wiresAndAmounts $ \(wire, amount') -> do+ builder <- MakeOffset.new+ liftIO $ MakeOffset.addWire builder wire+ liftIO $ MakeOffset.perform builder amount' 0.0+ done <- liftIO . MakeShape.isDone . upcast $ builder++ if not done+ then return []+ else do + outShape <- MakeShape.shape (upcast builder)+ outWires <- subShapes outShape+ forM outWires $ \wire -> + (MakeShape.shape . upcast)+ =<< MakeFace.fromPlnAndWire pln wire True++-- | Version of `offsetShape` that returns an error on failure+tryOffsetShape + :: Double -- ^ Amount to offset by, positive values expand, negative values contract+ -> Shape -- ^ The `Shape` to offset+ -> Either WaterfallError Shape+tryOffsetShape amount (Shape s)+ | nearZero amount = Right (Shape s)+ | otherwise =+ fmap + (mconcat + . fmap + (foldl1 Booleans.difference+ . fmap mconcat + . getCompose+ )+ . getCompose + . fmap Shape+ )+ . unsafeFromAcquirePtrTWithCatch+ . fmap (Compose . fmap Compose)+ $ traverse (offsetOne amount)+ =<< subShapes+ =<< acquireForeignPtr s
src/Waterfall/TwoD/Path2D.hs view
@@ -10,7 +10,7 @@ , arcTo , arcRelative , repeatLooping--- $ reexports+-- $reexports , line2D , lineTo2D , lineRelative2D@@ -33,7 +33,7 @@ import Waterfall.TwoD.Internal.Path2D (Path2D(..)) import Waterfall.TwoD.Transforms (rotate2D)-import Waterfall.Internal.NearZero (nearZero)+import Waterfall.Internal.NearZero (nearZero, confusion) import Linear.V2 (V2(..)) import Control.Lens ((^.)) import Linear ((^*), _xy, distance, normalize, unangle)@@ -54,16 +54,17 @@ -- -- `arc` is not polymorphic, as it would not be possible to define an arc in 3D space in this way. arc :: Sense -> Double -> V2 Double -> V2 Double -> Path2D -arc sense radius start end = +arc sense radius' start end = let mid = (start + end) ^* 0.5+ radius = abs radius' (V2 dx dy) = normalize $ end - start rotD = case sense of Clockwise -> V2 dy (-dx) Counterclockwise -> V2 (-dy) dx dse = distance start end - tangent = radius - sqrt (radius * radius - dse * dse / 4) + tangent = radius - sqrt (max 0 (radius * radius - dse * dse / 4)) arcMid = mid + rotD ^* tangent- in if dse > 2 * radius+ in if dse > 2 * radius + confusion then error "points too far apart in arc" else arcVia start arcMid end @@ -80,6 +81,16 @@ end <- (+ dEnd) arcTo sense radius end +-- Linear.unangle returns in the range (−π/2, 3π/2)+-- which means that the difference between two angles returned from unangle +-- lies in (−2π, 2π)+-- this clamps such an angle to the range (−π, π)+clampAngle :: Double -> Double +clampAngle a + | a < -pi = a + pi*2+ | a > pi = a - pi*2+ | otherwise = a+ -- | Given a Path where both endpoints are equidistant from the origin, -- and which subtends an angle \( φ \) from the origin that evenly divides a complete revolution, such that \(n φ = 2 π \). -- @@ -91,7 +102,7 @@ case pathEndpoints2D p of Nothing -> p Just (s, e) ->- let a = unangle (e ^. _xy) - unangle (s ^. _xy)+ let a = clampAngle (unangle (e ^. _xy) - unangle (s ^. _xy)) in if nearZero a then mempty else let times :: Integer = round (pi * 2 / abs a)
src/Waterfall/TwoD/Shape.hs view
@@ -1,3 +1,4 @@+{-# LANGUAGE TypeApplications #-} module Waterfall.TwoD.Shape ( Shape , makeShape@@ -6,6 +7,11 @@ , unitSquare , centeredSquare , unitPolygon+, looseShapes+, section+, silhouette+, area+, centroid -- * Boolean operations , union2D , difference2D@@ -18,21 +24,44 @@ import Waterfall.TwoD.Internal.Shape (Shape (..), union2D, difference2D, intersection2D, unions2D, intersections2D, emptyShape) import Waterfall.TwoD.Internal.Path2D (Path2D (..)) import Waterfall.TwoD.Transforms (translate2D, rotate2D)-import Waterfall.Internal.Finalizers (acquireForeignPtr, unsafeFromAcquirePtr, unsafeFromAcquirePtrT)+import Waterfall.Internal.Finalizers (acquireForeignPtr, unsafeFromAcquirePtr, unsafeFromAcquirePtrT, unsafeFromAcquire, NoPtr) import Waterfall.Internal.Edges (allWires) import qualified OpenCascade.BRepBuilderAPI.MakeFace as MakeFace+import qualified OpenCascade.TopoDS.Shape as TopoDS.Shape+import qualified OpenCascade.GP.Pln as GP.Pln import OpenCascade.Inheritance (upcast)-import Linear (unit, _x, _y, zero, V2 (..))-import Waterfall.Path.Common (pathFrom, arcViaTo, lineTo, line)+import Linear (unit, _x, _y, _xy, zero, V2 (..))+import Waterfall.Path.Common (pathFrom, arcViaTo, lineTo, line, closeLoop) import Waterfall.Internal.Path.Common (RawPath(ComplexRawPath))+import Control.Monad.IO.Class (liftIO)+import Control.Monad (filterM, (<=<))+import Waterfall.Internal.Solid (Solid, acquireSolid)+import Waterfall.Internal.Diagram (silhouetteShape)+import qualified OpenCascade.BRepAlgoAPI.Common as Common+import qualified OpenCascade.BRepBuilderAPI.MakeShape as MakeShape+import Control.DeepSeq (NFData)+import Foreign (Ptr)+import Data.Acquire (Acquire)+import Control.Lens ((^.))+import qualified OpenCascade.GProp.GProps as GProps+import qualified OpenCascade.BRepGProp as BRepGProp+import Waterfall.Internal.FromOpenCascade (gpPntToV3, subShapesOf)+import qualified OpenCascade.BRepAlgoAPI.BuilderAlgo as BuilderAlgo+import qualified OpenCascade.BRepAlgoAPI.BooleanOperation as BooleanOperation+import Waterfall.Internal.ToOpenCascade (shapeSingletonList)+import qualified OpenCascade.TopoDS as TopoDS+import Data.Proxy (Proxy(..)) --- | Construct a 2D Shape from a closed path +-- | Construct a 2D Shape from a path +--+-- Closes it (with a straight line) if it's open makeShape :: Path2D -> Shape-makeShape (Path2D (ComplexRawPath r)) = Shape . unsafeFromAcquirePtr $ do- p <- acquireForeignPtr r- upcast <$> (MakeFace.face =<< MakeFace.fromWire p False)-makeShape _ = Shape . unsafeFromAcquirePtr $- upcast <$> (MakeFace.face =<< MakeFace.new)+makeShape path = case closeLoop path of + (Path2D (ComplexRawPath r)) -> Shape . unsafeFromAcquirePtr $ do+ p <- acquireForeignPtr r+ pln <- GP.Pln.new+ MakeShape.shape . upcast =<< MakeFace.fromPlnAndWire pln p True+ _ -> mempty -- | Get the paths back from a 2D shape -- @@ -41,9 +70,13 @@ -- @ -- shapePaths . makeShape ≡ pure -- @--- --- Although this can only hold when the shape has one boundary path, --- and is not guaranteed+--+-- Although this only holds when the shape has one boundary path,+-- the path is closed (because `makeShape` will close it otherwise),+-- and the boundary path is counter-clockwise.+-- A clockwise boundary path is reversed,+-- and the start point may change.+-- The specifics of this are not guaranteed. shapePaths :: Shape -> [Path2D] shapePaths (Shape r) = fmap (Path2D . ComplexRawPath) . unsafeFromAcquirePtrT $ do s <- acquireForeignPtr r @@ -71,6 +104,8 @@ centeredSquare = translate2D (V2 (-0.5) (-0.5)) unitSquare -- | \(n\) sided Polygon, centered on the origin+--+-- The polygon has a circumradius of 1, with one vertex on the positive x-axis -- -- Empty when n <= 2 unitPolygon :: Integer -> Shape@@ -87,3 +122,48 @@ | (a, b) <- zip points (drop 1 points) ] in makeShape paths++-- | Split a `Shape` into a list of disjoint parts+looseShapes :: Shape -> [Shape] +looseShapes (Shape r) = fmap Shape . unsafeFromAcquirePtrT $ do+ shape <- acquireForeignPtr r+ filterM (fmap (>0) . liftIO . TopoDS.Shape.nbChildren)+ =<< subShapesOf (Proxy @TopoDS.Face) shape++-- | Compute the cross-section of a `Solid` on the @xy@ plane+--+-- The cross section is computed at @z=0@+section :: Solid -> Shape+section solid = Shape . unsafeFromAcquirePtr $ do+ s <- acquireSolid solid+ face <- MakeFace.face =<< MakeFace.fromPln =<< GP.Pln.new+ builder <- Common.new+ liftIO $ BuilderAlgo.setNonDestructive (upcast builder) True+ liftIO . BuilderAlgo.setArguments (upcast builder) =<< shapeSingletonList s+ liftIO . BooleanOperation.setTools (upcast builder) =<< shapeSingletonList (upcast face)+ liftIO $ MakeShape.build (upcast builder)+ MakeShape.shape (upcast builder)++-- | Compute the Shadow of a `Solid` projected onto the @xy@ plane+silhouette :: Solid -> Shape+silhouette solid = unsafeFromAcquire $ do+ s <- acquireSolid solid+ mconcat <$> silhouetteShape s +++gPropQuery :: (NoPtr a, NFData a) => (Ptr GProps.GProps -> Acquire a) -> Shape -> a+gPropQuery f (Shape s) = unsafeFromAcquire $ do+ shape <- acquireForeignPtr s+ gProp <- GProps.new+ liftIO $ BRepGProp.surfacePropertiesWithEps shape gProp 1e-9 False+ f gProp++-- | Area of the `Shape`+area :: Shape -> Double+area = gPropQuery (liftIO . GProps.mass)++-- | Center Of Mass of the `Shape` +-- +-- The 2D counterpart of `Waterfall.Solid.centerOfMass`+centroid :: Shape -> V2 Double +centroid = (^. _xy) . (gPropQuery ((liftIO . gpPntToV3) <=< GProps.centreOfMass))
src/Waterfall/TwoD/Text.hs view
@@ -21,6 +21,9 @@ import Control.Exception (throwIO) import Control.DeepSeq (NFData (rnf), rwhnf) +-- | A typeface at a specific size+--+-- Constructed with `fontFromPath` or `fontFromSystem` newtype Font = Font { rawFont :: ForeignPtr BRepFont.BRepFont } instance NFData Font where
src/Waterfall/TwoD/Transforms.hs view
@@ -19,9 +19,9 @@ ) where import Waterfall.TwoD.Internal.Path2D (Path2D (..))-import Waterfall.Internal.Finalizers (acquireForeignPtr, unsafeFromAcquirePtr)-import Waterfall.Internal.NearZero (nearZero)-import Linear ((*^), normalize, dot, V3 (..), V2 (..), (!*), _xy, _z, unit, M23)+import Waterfall.Internal.Finalizers (acquireForeignPtr, unsafeFromAcquirePtr, unsafeFromAcquirePtrT)+import Waterfall.Internal.NearZero (nearZero, confusion)+import Linear (M23, M22, (*^), normalize, dot, V3 (..), V2 (..), (!*), _xy, _z, _y, _x, unit, transpose, (!*!), (!-!), (*!!), identity, zero, norm, det22) import qualified OpenCascade.GP.Trsf as GP.Trsf import qualified OpenCascade.GP as GP import qualified OpenCascade.GP.GTrsf as GP.GTrsf@@ -32,14 +32,26 @@ import qualified OpenCascade.BRepBuilderAPI.MakeShape as BRepBuilderAPI.MakeShape import qualified OpenCascade.BRepBuilderAPI.Transform as BRepBuilderAPI.Transform import qualified OpenCascade.BRepBuilderAPI.GTransform as BRepBuilderAPI.GTransform+import qualified OpenCascade.BRepBuilderAPI.MakeFace as BRepBuilderAPI.MakeFace+import qualified OpenCascade.TopoDS as TopoDS+import qualified OpenCascade.TopoDS.Shape as TopoDS.Shape+import qualified OpenCascade.TopoDS.Compound as TopoDS.Compound+import qualified OpenCascade.TopoDS.Builder as TopoDS.Builder+import qualified OpenCascade.BRepTools as BRepTools import OpenCascade.Inheritance (upcast, unsafeDowncast) import Control.Monad.IO.Class (liftIO) import Data.Acquire import Foreign.Ptr import Waterfall.TwoD.Internal.Shape (Shape(..)) import Data.Function ((&))-import Control.Lens ((.~), (%~), Iso', iso)+import Control.Lens ((.~), (%~), Iso', iso, (^.), over) import Waterfall.Internal.Path.Common (RawPath(..))+import Waterfall.Internal.FromOpenCascade (subShapes)+import Waterfall.Path (pathEndpoints)+import Waterfall.Internal.Edges (forwardWireAndStripZeroLengthEdges)+import Data.Foldable (traverse_)+import Control.Monad (filterM, forM_, when, (<=<))+import qualified OpenCascade.GP.Pln as GP.Pln -- | Typeclass for objects that can be manipulated in 2D space class Transformable2D a where@@ -58,15 +70,26 @@ -- Note that in order to maintain consistency with 'Waterfall.Transforms.Transformable', -- the mirror is in the line / perpendicular / to the vector, not in the line / parallel / to the vector mirror2D :: V2 Double -> a -> a+ +v2ToV3 :: V2 Double -> V3 Double+v2ToV3 xy = zero & _xy .~ xy +pathFromEndpoints :: (V2 Double -> V2 Double) -> Path2D -> Path2D+pathFromEndpoints f =+ Path2D . maybe EmptyRawPath (SinglePointRawPath . v2ToV3 . f . fst) . pathEndpoints+ fromTrsfPath :: (V2 Double -> V2 Double) -> Acquire (Ptr GP.Trsf) -> Path2D -> Path2D-fromTrsfPath _ mkTrsf (Path2D (ComplexRawPath p)) = Path2D . ComplexRawPath . unsafeFromAcquirePtr $ do - path <- acquireForeignPtr p- trsf <- mkTrsf - (liftIO . unsafeDowncast) - =<< BRepBuilderAPI.MakeShape.shape- =<< fmap upcast- (BRepBuilderAPI.Transform.fromShapeTrsfAndCopy (upcast path) trsf True)+fromTrsfPath f mkTrsf p@(Path2D (ComplexRawPath rawPath)) = + maybe + (pathFromEndpoints f p)+ (Path2D . ComplexRawPath) . unsafeFromAcquirePtrT $ do + path <- acquireForeignPtr rawPath+ trsf <- mkTrsf + forwardWireAndStripZeroLengthEdges + =<< (liftIO . unsafeDowncast) + =<< BRepBuilderAPI.MakeShape.shape+ =<< fmap upcast+ (BRepBuilderAPI.Transform.fromShapeTrsfAndCopy (upcast path) trsf True) fromTrsfPath f _ (Path2D (SinglePointRawPath v)) = Path2D . SinglePointRawPath $ (v & _xy %~ f) fromTrsfPath _ _ (Path2D EmptyRawPath) = Path2D EmptyRawPath @@ -75,47 +98,85 @@ shape <- acquireForeignPtr theRawShape trsf <- mkTrsf builder <- BRepBuilderAPI.Transform.fromShapeTrsfAndCopy shape trsf True - BRepBuilderAPI.MakeShape.shape (upcast builder)+ isNegative <- liftIO $ GP.Trsf.isNegative trsf+ res <- BRepBuilderAPI.MakeShape.shape (upcast builder)+ if isNegative + then planariseFaces True =<< TopoDS.Shape.reversed res + else pure res -fromGTrsfPath :: (V2 Double -> V2 Double) -> Acquire (Maybe (Ptr GP.GTrsf)) -> Path2D -> Path2D-fromGTrsfPath _ mkTrsf (Path2D (ComplexRawPath p)) = Path2D . ComplexRawPath . unsafeFromAcquirePtr $ do - path <- acquireForeignPtr p- trsfMay <- mkTrsf - case trsfMay of- Just trsf -> - (liftIO . unsafeDowncast) +fromGTrsfPath :: (V2 Double -> V2 Double) -> Acquire (Ptr GP.GTrsf) -> Path2D -> Path2D+fromGTrsfPath f mkTrsf p@(Path2D (ComplexRawPath rawPath)) =+ maybe + (pathFromEndpoints f p)+ (Path2D . ComplexRawPath) . unsafeFromAcquirePtrT $ do + path <- acquireForeignPtr rawPath+ trsf <- mkTrsf + forwardWireAndStripZeroLengthEdges + =<< (liftIO . unsafeDowncast) =<< BRepBuilderAPI.MakeShape.shape =<< fmap upcast (BRepBuilderAPI.GTransform.fromShapeGTrsfAndCopy (upcast path) trsf True)- Nothing -> pure path+ fromGTrsfPath f _ (Path2D (SinglePointRawPath v)) = Path2D . SinglePointRawPath $ (v & _xy %~ f) fromGTrsfPath _ _ (Path2D EmptyRawPath) = Path2D EmptyRawPath -fromGTrsfShape :: Acquire (Maybe (Ptr GP.GTrsf)) -> Shape -> Shape+planariseFaces :: Bool -> Ptr TopoDS.Shape -> Acquire (Ptr TopoDS.Shape)+planariseFaces reversed s = do+ faces <- subShapes s+ compoundBuilder <- TopoDS.Builder.new+ compound <- TopoDS.Compound.new+ liftIO $ TopoDS.Builder.makeCompound compoundBuilder compound+ pln <- GP.Pln.new+ let reverseMaybe = + if reversed + then liftIO . unsafeDowncast <=< TopoDS.Shape.reversed . upcast + else pure+ forM_ faces $ \f -> do+ outer <- BRepTools.outerWire f+ wires <- subShapes (upcast f)+ inner <- filterM (liftIO . fmap not . TopoDS.Shape.isSame (upcast outer) . upcast) wires+ builder <- BRepBuilderAPI.MakeFace.fromPlnAndWire pln outer True+ forM_ inner (liftIO . BRepBuilderAPI.MakeFace.add builder <=< reverseMaybe)+ liftIO . TopoDS.Builder.add compoundBuilder (upcast compound) . upcast+ =<< BRepBuilderAPI.MakeFace.face builder+ return . upcast $ compound++fromGTrsfShape :: Acquire (Ptr GP.GTrsf) -> Shape -> Shape fromGTrsfShape mkTrsf (Shape theRawShape) = Shape . unsafeFromAcquirePtr $ do shape <- acquireForeignPtr theRawShape - trsfMay <- mkTrsf - case trsfMay of- Just trsf -> - BRepBuilderAPI.MakeShape.shape - =<< fmap upcast- (BRepBuilderAPI.GTransform.fromShapeGTrsfAndCopy shape trsf True)- Nothing -> pure shape+ trsf <- mkTrsf + isNegative <- liftIO $ GP.GTrsf.isNegative trsf+ res <- BRepBuilderAPI.MakeShape.shape + =<< fmap upcast+ (BRepBuilderAPI.GTransform.fromShapeGTrsfAndCopy shape trsf True)+ planariseFaces isNegative =<< if isNegative then TopoDS.Shape.reversed res else pure res -matrixGTrsf :: M23 Double -> Acquire (Maybe (Ptr GP.GTrsf))-matrixGTrsf (V2 (V3 1 0 0) (V3 0 1 0)) = pure Nothing-matrixGTrsf (V2 (V3 v11 v12 v13) (V3 v21 v22 v23)) = do- trsf <- GP.GTrsf.new- liftIO $ do - GP.GTrsf.setValue trsf 1 1 v11- GP.GTrsf.setValue trsf 1 2 v12- GP.GTrsf.setValue trsf 1 4 v13- GP.GTrsf.setValue trsf 2 1 v21- GP.GTrsf.setValue trsf 2 2 v22- GP.GTrsf.setValue trsf 2 4 v23- GP.GTrsf.setForm trsf- return . pure $ trsf+isOrthogonalAndScale :: M22 Double -> Bool+isOrthogonalAndScale m =+ let p = m !*! transpose m+ s = p ^. _x . _x+ in not (nearZero s) && all (all (nearZero . (/s))) (p !-! (s *!! identity)) +matrixGTrsf :: M23 Double -> Maybe (Either (Acquire (Ptr GP.Trsf)) (Acquire (Ptr GP.GTrsf)))+matrixGTrsf (V2 (V3 1 0 0) (V3 0 1 0)) = Nothing+matrixGTrsf (V2 (V3 x 0 0) (V3 0 y 0)) | nearZero (x-y) && not (nearZero x) = Just . Left . uScaleTrsf $ x+matrixGTrsf m@(V2 (V3 v11 v12 v13) (V3 v21 v22 v23)) + | isOrthogonalAndScale (fmap (^. _xy ) m) = Just . Left $ do+ trsf <- GP.Trsf.new+ let s = sqrt (abs (v11 * v22 - v12 * v21))+ liftIO $ GP.Trsf.setValues trsf v11 v12 0 v13 v21 v22 0 v23 0 0 s 0+ return trsf+ | otherwise = Just . Right $ do+ trsf <- GP.GTrsf.new+ liftIO $ do + GP.GTrsf.setValue trsf 1 1 v11+ GP.GTrsf.setValue trsf 1 2 v12+ GP.GTrsf.setValue trsf 1 4 v13+ GP.GTrsf.setValue trsf 2 1 v21+ GP.GTrsf.setValue trsf 2 2 v22+ GP.GTrsf.setValue trsf 2 4 v23+ return trsf+ rotateTrsf :: Double -> Acquire (Ptr GP.Trsf) rotateTrsf angle = do trsf <- GP.Trsf.new@@ -125,19 +186,49 @@ liftIO $ GP.Trsf.setRotationAboutAxisAngle trsf axis angle return trsf -scaleGTrsf :: V2 Double -> Acquire (Maybe (Ptr GP.GTrsf))-scaleGTrsf v@(V2 x y) = - if v == V2 1 1 - then pure Nothing- else do- trsf <- GP.GTrsf.new - liftIO $ do- GP.GTrsf.setValue trsf 1 1 x- GP.GTrsf.setValue trsf 2 2 y- GP.GTrsf.setValue trsf 3 3 1- GP.GTrsf.setForm trsf- return . Just $ trsf+applyScaleTrsfs :: + (Acquire (Ptr GP.Trsf) -> a -> a) + -> (Acquire (Ptr GP.GTrsf) -> a -> a)+ -> (Maybe (Acquire (Ptr GP.Trsf)), Maybe (Acquire (Ptr GP.GTrsf)))+ -> a -> a+applyScaleTrsfs applyTrsf applyGTrsf (maybeTrsf, maybeGTrsf) = + maybe id applyTrsf maybeTrsf . maybe id applyGTrsf maybeGTrsf +scaleTrsfs :: V2 Double -> (Maybe (Acquire (Ptr GP.Trsf)), Maybe (Acquire (Ptr GP.GTrsf)))+scaleTrsfs (V2 1 1) = (Nothing, Nothing)+scaleTrsfs (V2 x y) = + let isUniform = nearZero (abs x - abs y)+ bothArePositive = x >= 0 && y >= 0+ in if isUniform && bothArePositive + then (Just $ uScaleTrsf x, Nothing)+ else ( if bothArePositive+ then Nothing + else Just $ do+ trsf <- if isUniform + then uScaleTrsf (abs x)+ else GP.Trsf.new+ when (x < 0) $ do+ mirrorX <- sequence $ mirrorTrsf (unit _x)+ liftIO $ traverse_ (GP.Trsf.multiply trsf) mirrorX+ when (y < 0) $ do+ mirrorY <- sequence $ mirrorTrsf (unit _y)+ liftIO $ traverse_ (GP.Trsf.multiply trsf) mirrorY+ return trsf++ , if isUniform + then Nothing+ else Just $ do+ trsf <- GP.GTrsf.new + liftIO $ do+ GP.GTrsf.setValue trsf 1 1 (abs x) + GP.GTrsf.setValue trsf 2 2 (abs y) + GP.GTrsf.setValue trsf 3 3 1+ return trsf+++ ) + + uScaleTrsf :: Double -> Acquire (Ptr GP.Trsf) uScaleTrsf factor = do trsf <- GP.Trsf.new@@ -152,53 +243,83 @@ liftIO $ GP.Trsf.setTranslation trsf vec return trsf -mirrorTrsf :: V2 Double -> Acquire (Ptr GP.Trsf)-mirrorTrsf (V2 x y) = do - trsf <- GP.Trsf.new- dir <- GP.Dir.new x y 0- axis <- GP.xoy- liftIO $ do- GP.Ax2.setDirection axis dir- GP.Trsf.setMirrorAboutAx2 trsf axis- return trsf+mirrorTrsf :: V2 Double -> Maybe (Acquire (Ptr GP.Trsf))+mirrorTrsf v@(V2 x y) + | all nearZero v = Nothing+ | otherwise = Just $ do + trsf <- GP.Trsf.new+ dir <- GP.Dir.new x y 0+ axis <- GP.xoy+ liftIO $ do+ GP.Ax2.setDirection axis dir+ GP.Trsf.setMirrorAboutAx2 trsf axis+ return trsf +transformPathSinglePointPaths :: (V3 Double -> V3 Double) -> Path2D -> Path2D+transformPathSinglePointPaths f (Path2D (SinglePointRawPath v)) = Path2D . SinglePointRawPath . f $ v +transformPathSinglePointPaths _ p = p ++collapseToOrigin :: Path2D -> Path2D+collapseToOrigin (Path2D EmptyRawPath) = Path2D EmptyRawPath+collapseToOrigin _ = Path2D . SinglePointRawPath $ zero+ instance Transformable2D Path2D where matTransform2D :: M23 Double -> Path2D -> Path2D- matTransform2D m = fromGTrsfPath (matTransform2D m) (matrixGTrsf m)+ matTransform2D m = + let transformPnt = matTransform2D m+ in maybe id (either (fromTrsfPath transformPnt) (fromGTrsfPath transformPnt)) $ matrixGTrsf m rotate2D :: Double -> Path2D -> Path2D rotate2D a = fromTrsfPath (rotate2D a) (rotateTrsf a) scale2D :: V2 Double -> Path2D -> Path2D- scale2D s = fromGTrsfPath (scale2D s) (scaleGTrsf s)+ scale2D s + | all nearZero s = collapseToOrigin + | otherwise = + let transformPnt = over _xy (scale2D s)+ in transformPathSinglePointPaths transformPnt + . applyScaleTrsfs (fromTrsfPath id) (fromGTrsfPath id) (scaleTrsfs s) uScale2D :: Double -> Path2D -> Path2D- uScale2D s = fromTrsfPath (uScale2D s) (uScaleTrsf s)+ uScale2D s + | nearZero s = collapseToOrigin+ | otherwise = fromTrsfPath (uScale2D s) (uScaleTrsf s) translate2D :: V2 Double -> Path2D -> Path2D translate2D v = fromTrsfPath (translate2D v) (translateTrsf v) mirror2D :: V2 Double -> Path2D -> Path2D- mirror2D v = fromTrsfPath (mirror2D v) (mirrorTrsf v)+ mirror2D v = maybe id (fromTrsfPath (mirror2D v)) (mirrorTrsf v) instance Transformable2D Shape where matTransform2D :: M23 Double -> Shape -> Shape- matTransform2D = fromGTrsfShape . matrixGTrsf+ matTransform2D m + | isSingular = mempty + | otherwise = maybe id (either fromTrsfShape fromGTrsfShape) (matrixGTrsf m)+ where+ isSingular = + let m22 = (^. _xy) <$> m+ rowNorms = norm <$> m22+ in any nearZero rowNorms || abs (det22 m22) < confusion * product rowNorms rotate2D :: Double -> Shape -> Shape rotate2D = fromTrsfShape . rotateTrsf scale2D :: V2 Double -> Shape -> Shape- scale2D = fromGTrsfShape . scaleGTrsf+ scale2D factor + | any nearZero factor = mempty+ | otherwise = applyScaleTrsfs fromTrsfShape fromGTrsfShape (scaleTrsfs factor) uScale2D :: Double -> Shape -> Shape- uScale2D = fromTrsfShape . uScaleTrsf+ uScale2D factor + | nearZero factor = mempty+ | otherwise = fromTrsfShape (uScaleTrsf factor) translate2D :: V2 Double -> Shape -> Shape translate2D = fromTrsfShape .translateTrsf mirror2D :: V2 Double -> Shape -> Shape- mirror2D = fromTrsfShape . mirrorTrsf+ mirror2D = maybe id fromTrsfShape . mirrorTrsf instance Transformable2D (V2 Double) where matTransform2D :: M23 Double -> V2 Double -> V2 Double@@ -221,9 +342,11 @@ translate2D = (+) mirror2D :: V2 Double -> V2 Double -> V2 Double - mirror2D mirrorVec toMirror = - let nm = normalize mirrorVec- in toMirror - (2 * (nm `dot` toMirror) *^ nm)+ mirror2D mirrorVec toMirror + | all nearZero mirrorVec = toMirror+ | otherwise = + let nm = normalize mirrorVec+ in toMirror - (2 * (nm `dot` toMirror) *^ nm) -- | Every translation is an isomorphism _translated2D :: Transformable2D t => V2 Double -> Iso' t t
waterfall-cad.cabal view
@@ -5,7 +5,7 @@ -- see: https://github.com/sol/hpack name: waterfall-cad-version: 0.8.0.0+version: 0.9.0.0 synopsis: Declarative CAD/Solid Modeling Library description: Please see the README on GitHub at <https://github.com/joe-warren/opencascade-hs#readme> category: Graphics@@ -73,12 +73,16 @@ Waterfall.Path Waterfall.Path.Common Waterfall.Revolution+ Waterfall.Solid Waterfall.Solids Waterfall.Sweep Waterfall.Transforms Waterfall.TwoD.Booleans+ Waterfall.TwoD.BoundingBox.AxisAligned+ Waterfall.TwoD.BoundingBox.Oriented Waterfall.TwoD.Internal.Path2D Waterfall.TwoD.Internal.Shape+ Waterfall.TwoD.Offset Waterfall.TwoD.Path2D Waterfall.TwoD.Shape Waterfall.TwoD.Text@@ -91,12 +95,13 @@ build-depends: base >=4.17 && <5 , bifunctors ==5.*+ , colour >=2.3.7 && <3 , containers >=0.6 && <1 , deepseq >=1.4 && <2 , filepath >=1.4 && <1.6 , lattices >=2.0 && <3 , lens ==5.* , linear >=1.21 && <2- , opencascade-hs >=0.8.0.0 && <0.9+ , opencascade-hs >=0.9.0.0 && <0.10 , resourcet >=1.2 && <1.4 default-language: Haskell2010