Skip to main content

ink_rs/
brush.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Brushes: what a stroke's path is drawn with.
6
7use crate::color::{Color, ColorFormat, ColorSpace};
8use crate::error::{Result, check};
9use crate::ffi;
10
11/// Panics if a C++ constructor handed back nothing.
12///
13/// The facade only returns a null handle when `new` failed, which in practice
14/// means the process is already out of memory.
15fn expect_handle<T>(handle: T, is_null: bool, what: &str) -> T {
16    assert!(!is_null, "ink: failed to allocate {what}");
17    handle
18}
19
20/// One of Ink's built-in brush families.
21///
22/// Stock brushes are versioned so that strokes stored as input points plus a
23/// brush spec still look the way they did when drawn, even after Ink is
24/// upgraded. [`StockBrush::family`] takes the latest version;
25/// [`StockBrush::family_version`] pins one.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
27#[non_exhaustive]
28pub enum StockBrush {
29    /// A simple circular fixed-width brush.
30    Marker,
31    /// Pressure- and speed-sensitive, tuned for handwriting with a stylus.
32    PressurePen,
33    /// A chisel tip, meant to be used with a translucent colour.
34    Highlighter,
35    /// Rounded rectangles with gaps between them, for decoration or for
36    /// showing a lasso selection.
37    DashedLine,
38}
39
40impl StockBrush {
41    /// The latest version of this stock brush.
42    pub fn family(self) -> BrushFamily {
43        self.family_version(0)
44    }
45
46    /// A specific version of this stock brush. Version `0` means the latest.
47    pub fn family_version(self, version: u32) -> BrushFamily {
48        let version = i32::try_from(version).unwrap_or(0);
49        let handle = unsafe {
50            match self {
51                Self::Marker => ffi::StockBrushMarker(version),
52                Self::PressurePen => ffi::StockBrushPressurePen(version),
53                Self::Highlighter => ffi::StockBrushHighlighter(version),
54                Self::DashedLine => ffi::StockBrushDashedLine(version),
55            }
56        };
57        BrushFamily {
58            handle: expect_handle(handle, handle.handle.is_null(), "brush family"),
59        }
60    }
61}
62
63/// The shape and behaviour half of a brush, without colour or size.
64pub struct BrushFamily {
65    handle: ffi::BrushFamilyHandle,
66}
67
68impl BrushFamily {
69    pub(crate) fn as_ffi(&self) -> ffi::BrushFamilyHandle {
70        self.handle
71    }
72
73    pub(crate) fn from_ffi(handle: ffi::BrushFamilyHandle) -> Self {
74        Self {
75            handle: expect_handle(handle, handle.handle.is_null(), "brush family"),
76        }
77    }
78}
79
80impl Clone for BrushFamily {
81    fn clone(&self) -> Self {
82        Self::from_ffi(unsafe { ffi::BrushFamilyClone(self.handle) })
83    }
84}
85
86impl Drop for BrushFamily {
87    fn drop(&mut self) {
88        unsafe { ffi::BrushFamilyDestroy(self.handle) };
89    }
90}
91
92impl core::fmt::Debug for BrushFamily {
93    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
94        f.debug_struct("BrushFamily").finish_non_exhaustive()
95    }
96}
97
98/// A brush family together with a colour, a size and an epsilon.
99///
100/// `size` is the stroke width in stroke units. `epsilon` is the smallest
101/// distance Ink bothers to distinguish, also in stroke units; it controls how
102/// aggressively the generated mesh is simplified, and must be positive and no
103/// larger than `size`.
104pub struct Brush {
105    handle: ffi::BrushHandle,
106}
107
108impl Brush {
109    /// Builds a brush.
110    ///
111    /// Fails with [`ErrorKind::InvalidArgument`](crate::ErrorKind::InvalidArgument)
112    /// unless `size` and `epsilon` are both finite and positive and
113    /// `epsilon <= size`.
114    pub fn new(family: &BrushFamily, color: Color, size: f32, epsilon: f32) -> Result<Self> {
115        let mut out = ffi::BrushHandle {
116            handle: core::ptr::null_mut(),
117        };
118        let status = unsafe {
119            ffi::BrushCreate(
120                family.as_ffi(),
121                color.to_ffi(),
122                color.space.to_ffi(),
123                color.format.to_ffi(),
124                size,
125                epsilon,
126                &mut out,
127            )
128        };
129        check(status)?;
130        Ok(Self {
131            handle: expect_handle(out, out.handle.is_null(), "brush"),
132        })
133    }
134
135    pub(crate) fn as_ffi(&self) -> ffi::BrushHandle {
136        self.handle
137    }
138
139    pub(crate) fn from_ffi(handle: ffi::BrushHandle) -> Self {
140        Self {
141            handle: expect_handle(handle, handle.handle.is_null(), "brush"),
142        }
143    }
144
145    /// Stroke width in stroke units.
146    pub fn size(&self) -> f32 {
147        unsafe { ffi::BrushSize(self.handle) }
148    }
149
150    /// Smallest distance Ink distinguishes, in stroke units.
151    pub fn epsilon(&self) -> f32 {
152        unsafe { ffi::BrushEpsilon(self.handle) }
153    }
154
155    /// The brush colour, gamma-encoded in the colour space Ink stored it in.
156    pub fn color(&self) -> Color {
157        self.color_in(ColorFormat::GammaEncoded)
158    }
159
160    /// The brush colour in a chosen encoding.
161    pub fn color_in(&self, format: ColorFormat) -> Color {
162        let rgba = unsafe { ffi::BrushColor(self.handle, format.to_ffi()) };
163        let space = ColorSpace::from_ffi(unsafe { ffi::BrushColorSpace(self.handle) });
164        Color::from_ffi(rgba, space, format)
165    }
166
167    /// How many coats this brush paints. Each coat becomes its own render
168    /// group in the resulting geometry.
169    pub fn coat_count(&self) -> u32 {
170        unsafe { ffi::BrushCoatCount(self.handle) }
171    }
172
173    /// A copy of the brush's family.
174    pub fn family(&self) -> BrushFamily {
175        BrushFamily::from_ffi(unsafe { ffi::BrushGetFamily(self.handle) })
176    }
177
178    /// Changes the stroke width. Same constraints as [`Brush::new`].
179    pub fn set_size(&mut self, size: f32) -> Result<()> {
180        check(unsafe { ffi::BrushSetSize(self.handle, size) })
181    }
182
183    /// Changes epsilon. Same constraints as [`Brush::new`].
184    pub fn set_epsilon(&mut self, epsilon: f32) -> Result<()> {
185        check(unsafe { ffi::BrushSetEpsilon(self.handle, epsilon) })
186    }
187
188    /// Changes the colour. Never invalidates geometry.
189    pub fn set_color(&mut self, color: Color) {
190        unsafe {
191            ffi::BrushSetColor(
192                self.handle,
193                color.to_ffi(),
194                color.space.to_ffi(),
195                color.format.to_ffi(),
196            );
197        }
198    }
199
200    /// Changes the brush family.
201    pub fn set_family(&mut self, family: &BrushFamily) {
202        unsafe { ffi::BrushSetFamily(self.handle, family.as_ffi()) };
203    }
204}
205
206impl Clone for Brush {
207    fn clone(&self) -> Self {
208        Self::from_ffi(unsafe { ffi::BrushClone(self.handle) })
209    }
210}
211
212impl Drop for Brush {
213    fn drop(&mut self) {
214        unsafe { ffi::BrushDestroy(self.handle) };
215    }
216}
217
218impl core::fmt::Debug for Brush {
219    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
220        f.debug_struct("Brush")
221            .field("size", &self.size())
222            .field("epsilon", &self.epsilon())
223            .field("color", &self.color())
224            .field("coat_count", &self.coat_count())
225            .finish()
226    }
227}