Skip to main content

ink_rs/
stroke.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//! Strokes: building them incrementally, and reading their geometry back.
6
7use core::time::Duration;
8
9use crate::brush::Brush;
10use crate::error::{Result, check};
11use crate::ffi;
12use crate::geometry::{Mesh, Point, Rect};
13use crate::input::StrokeInputBatch;
14
15/// Pulls `count` vertex positions out of C++ via `copy`.
16fn read_positions(count: u32, copy: impl FnOnce(*mut ffi::Point, i32) -> i32) -> Vec<Point> {
17    let capacity = usize::try_from(count).unwrap_or(0);
18    if capacity == 0 {
19        return Vec::new();
20    }
21
22    let mut raw: Vec<ffi::Point> = Vec::with_capacity(capacity);
23    let written = copy(
24        raw.as_mut_ptr(),
25        i32::try_from(capacity).unwrap_or(i32::MAX),
26    );
27    let written = usize::try_from(written).unwrap_or(0).min(capacity);
28    // SAFETY: the facade wrote exactly `written` elements into the allocation,
29    // and `written <= capacity`.
30    unsafe { raw.set_len(written) };
31
32    raw.into_iter().map(Point::from_ffi).collect()
33}
34
35/// Pulls `triangle_count * 3` indices out of C++ via `copy`.
36fn read_indices(triangle_count: u32, copy: impl FnOnce(*mut u32, i32) -> i32) -> Vec<u32> {
37    let capacity = usize::try_from(triangle_count)
38        .unwrap_or(0)
39        .saturating_mul(3);
40    if capacity == 0 {
41        return Vec::new();
42    }
43
44    let mut raw: Vec<u32> = Vec::with_capacity(capacity);
45    let written = copy(
46        raw.as_mut_ptr(),
47        i32::try_from(capacity).unwrap_or(i32::MAX),
48    );
49    let written = usize::try_from(written).unwrap_or(0).min(capacity);
50    // SAFETY: as above.
51    unsafe { raw.set_len(written) };
52
53    raw
54}
55
56/// A stroke being drawn.
57///
58/// The usual loop is [`start`](Self::start), then
59/// [`enqueue_inputs`](Self::enqueue_inputs) and
60/// [`update_shape`](Self::update_shape) as events arrive and frames are drawn,
61/// then [`finish_inputs`](Self::finish_inputs) when the user lifts the pen and
62/// [`to_stroke`](Self::to_stroke) to keep the result.
63///
64/// Geometry is read back per brush coat with [`coat_mesh`](Self::coat_mesh).
65/// A brush with several coats produces one mesh per coat, drawn in order.
66pub struct InProgressStroke {
67    handle: ffi::InProgressStrokeHandle,
68}
69
70impl InProgressStroke {
71    pub fn new() -> Self {
72        let handle = unsafe { ffi::InProgressStrokeCreate() };
73        assert!(
74            !handle.handle.is_null(),
75            "ink: failed to allocate in-progress stroke"
76        );
77        Self { handle }
78    }
79
80    /// Throws away any stroke in progress.
81    pub fn clear(&mut self) {
82        unsafe { ffi::InProgressStrokeClear(self.handle) };
83    }
84
85    /// Begins a stroke with `brush`, discarding whatever was in progress.
86    pub fn start(&mut self, brush: &Brush) {
87        self.start_with_seed(brush, 0, 0.0);
88    }
89
90    /// Begins a stroke, choosing the noise seed and the starting phase for
91    /// animated brush paints.
92    pub fn start_with_seed(&mut self, brush: &Brush, noise_seed: u32, base_animation_phase: f32) {
93        unsafe {
94            ffi::InProgressStrokeStart(
95                self.handle,
96                brush.as_ffi(),
97                noise_seed,
98                base_animation_phase,
99            )
100        };
101    }
102
103    /// Queues newly arrived input.
104    ///
105    /// `predicted` is input the platform expects but has not confirmed, used to
106    /// hide latency; it is replaced wholesale on the next call rather than
107    /// accumulated. Pass `None` when there is no prediction.
108    pub fn enqueue_inputs(
109        &mut self,
110        real: &StrokeInputBatch,
111        predicted: Option<&StrokeInputBatch>,
112    ) -> Result<()> {
113        let predicted = predicted.map(StrokeInputBatch::as_ffi).unwrap_or({
114            ffi::StrokeInputBatchHandle {
115                handle: core::ptr::null_mut(),
116            }
117        });
118        check(unsafe { ffi::InProgressStrokeEnqueueInputs(self.handle, real.as_ffi(), predicted) })
119    }
120
121    /// Says no more input is coming.
122    pub fn finish_inputs(&mut self) {
123        unsafe { ffi::InProgressStrokeFinishInputs(self.handle) };
124    }
125
126    /// Regenerates geometry up to `elapsed`, measured from the start of the
127    /// stroke. Must not go backwards between calls.
128    pub fn update_shape(&mut self, elapsed: Duration) -> Result<()> {
129        check(unsafe { ffi::InProgressStrokeUpdateShape(self.handle, elapsed.as_secs_f32()) })
130    }
131
132    /// Whether queued input or time-varying behaviour means the geometry is
133    /// stale.
134    pub fn needs_update(&self) -> bool {
135        unsafe { ffi::InProgressStrokeNeedsUpdate(self.handle) }
136    }
137
138    pub fn inputs_are_finished(&self) -> bool {
139        unsafe { ffi::InProgressStrokeInputsAreFinished(self.handle) }
140    }
141
142    /// Whether the brush keeps changing the shape as time passes, which means
143    /// [`update_shape`](Self::update_shape) has to keep being called even after
144    /// input stops.
145    pub fn changes_with_time(&self) -> bool {
146        unsafe { ffi::InProgressStrokeChangesWithTime(self.handle) }
147    }
148
149    /// Number of coats the current brush paints, and so the number of meshes.
150    pub fn coat_count(&self) -> u32 {
151        unsafe { ffi::InProgressStrokeBrushCoatCount(self.handle) }
152    }
153
154    /// Inputs processed so far, real and predicted.
155    pub fn input_count(&self) -> usize {
156        usize::try_from(unsafe { ffi::InProgressStrokeInputCount(self.handle) }).unwrap_or(0)
157    }
158
159    /// Of those, how many were real rather than predicted.
160    pub fn real_input_count(&self) -> usize {
161        usize::try_from(unsafe { ffi::InProgressStrokeRealInputCount(self.handle) }).unwrap_or(0)
162    }
163
164    /// Current geometry for one coat. An out-of-range coat gives an empty mesh.
165    pub fn coat_mesh(&self, coat_index: u32) -> Mesh {
166        let vertices = unsafe { ffi::InProgressStrokeVertexCount(self.handle, coat_index) };
167        let triangles = unsafe { ffi::InProgressStrokeTriangleCount(self.handle, coat_index) };
168
169        Mesh {
170            positions: read_positions(vertices, |out, capacity| unsafe {
171                ffi::InProgressStrokeCopyVertexPositions(self.handle, coat_index, out, capacity)
172            }),
173            indices: read_indices(triangles, |out, capacity| unsafe {
174                ffi::InProgressStrokeCopyTriangleIndices(self.handle, coat_index, out, capacity)
175            }),
176        }
177    }
178
179    /// Bounding box of one coat, or `None` when it has no geometry yet.
180    pub fn coat_bounds(&self, coat_index: u32) -> Option<Rect> {
181        let mut out = ffi::Rect {
182            x_min: 0.0,
183            y_min: 0.0,
184            x_max: 0.0,
185            y_max: 0.0,
186        };
187        let found = unsafe { ffi::InProgressStrokeCoatBounds(self.handle, coat_index, &mut out) };
188        found.then(|| Rect::from_ffi(out))
189    }
190
191    /// Copies the current state into a finished [`Stroke`], leaving this
192    /// builder alone so drawing can carry on.
193    pub fn to_stroke(&self) -> Stroke {
194        Stroke::from_ffi(unsafe { ffi::InProgressStrokeCopyToStroke(self.handle) })
195    }
196}
197
198impl Default for InProgressStroke {
199    fn default() -> Self {
200        Self::new()
201    }
202}
203
204impl Drop for InProgressStroke {
205    fn drop(&mut self) {
206        unsafe { ffi::InProgressStrokeDestroy(self.handle) };
207    }
208}
209
210impl core::fmt::Debug for InProgressStroke {
211    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
212        f.debug_struct("InProgressStroke")
213            .field("coat_count", &self.coat_count())
214            .field("input_count", &self.input_count())
215            .field("inputs_are_finished", &self.inputs_are_finished())
216            .finish()
217    }
218}
219
220/// A finished stroke: the input, the brush, and the geometry generated from
221/// the two.
222///
223/// Geometry is organised as one render group per brush coat, each holding one
224/// or more meshes. Ink splits a coat into several meshes when it has more
225/// vertices than a single 16-bit index buffer can address, so a renderer should
226/// loop over [`mesh_count`](Self::mesh_count) rather than assume there is one.
227pub struct Stroke {
228    handle: ffi::StrokeHandle,
229}
230
231impl Stroke {
232    /// Generates a stroke from a brush and a complete run of input.
233    pub fn new(brush: &Brush, inputs: &StrokeInputBatch) -> Self {
234        Self::from_ffi(unsafe { ffi::StrokeCreate(brush.as_ffi(), inputs.as_ffi()) })
235    }
236
237    /// An empty stroke carrying just a brush.
238    pub fn from_brush(brush: &Brush) -> Self {
239        let empty = ffi::StrokeInputBatchHandle {
240            handle: core::ptr::null_mut(),
241        };
242        Self::from_ffi(unsafe { ffi::StrokeCreate(brush.as_ffi(), empty) })
243    }
244
245    pub(crate) fn from_ffi(handle: ffi::StrokeHandle) -> Self {
246        assert!(!handle.handle.is_null(), "ink: failed to allocate stroke");
247        Self { handle }
248    }
249
250    /// Total time covered by the stroke's input.
251    pub fn input_duration(&self) -> Duration {
252        let seconds = unsafe { ffi::StrokeInputDurationSeconds(self.handle) };
253        Duration::try_from_secs_f32(seconds).unwrap_or(Duration::ZERO)
254    }
255
256    /// A copy of the brush the stroke was drawn with.
257    pub fn brush(&self) -> Brush {
258        Brush::from_ffi(unsafe { ffi::StrokeGetBrush(self.handle) })
259    }
260
261    /// A copy of the input the stroke was generated from.
262    pub fn inputs(&self) -> StrokeInputBatch {
263        StrokeInputBatch::from_ffi(unsafe { ffi::StrokeGetInputs(self.handle) })
264    }
265
266    /// Number of render groups, one per brush coat.
267    pub fn render_group_count(&self) -> u32 {
268        unsafe { ffi::StrokeRenderGroupCount(self.handle) }
269    }
270
271    /// Number of meshes in one render group.
272    pub fn mesh_count(&self, group_index: u32) -> u32 {
273        unsafe { ffi::StrokeRenderGroupMeshCount(self.handle, group_index) }
274    }
275
276    /// One mesh. Out-of-range indices give an empty mesh.
277    pub fn mesh(&self, group_index: u32, mesh_index: u32) -> Mesh {
278        let vertices = unsafe { ffi::StrokeMeshVertexCount(self.handle, group_index, mesh_index) };
279        let triangles =
280            unsafe { ffi::StrokeMeshTriangleCount(self.handle, group_index, mesh_index) };
281
282        Mesh {
283            positions: read_positions(vertices, |out, capacity| unsafe {
284                ffi::StrokeCopyMeshVertexPositions(
285                    self.handle,
286                    group_index,
287                    mesh_index,
288                    out,
289                    capacity,
290                )
291            }),
292            indices: read_indices(triangles, |out, capacity| unsafe {
293                ffi::StrokeCopyMeshTriangleIndices(
294                    self.handle,
295                    group_index,
296                    mesh_index,
297                    out,
298                    capacity,
299                )
300            }),
301        }
302    }
303
304    /// Every mesh in the stroke, in the order they should be drawn.
305    pub fn meshes(&self) -> Vec<Mesh> {
306        let mut meshes = Vec::new();
307        for group in 0..self.render_group_count() {
308            for mesh in 0..self.mesh_count(group) {
309                meshes.push(self.mesh(group, mesh));
310            }
311        }
312        meshes
313    }
314
315    /// Bounding box of the whole stroke, or `None` when it has no geometry.
316    pub fn bounds(&self) -> Option<Rect> {
317        let mut out = ffi::Rect {
318            x_min: 0.0,
319            y_min: 0.0,
320            x_max: 0.0,
321            y_max: 0.0,
322        };
323        let found = unsafe { ffi::StrokeBounds(self.handle, &mut out) };
324        found.then(|| Rect::from_ffi(out))
325    }
326}
327
328impl Clone for Stroke {
329    fn clone(&self) -> Self {
330        Self::from_ffi(unsafe { ffi::StrokeClone(self.handle) })
331    }
332}
333
334impl Drop for Stroke {
335    fn drop(&mut self) {
336        unsafe { ffi::StrokeDestroy(self.handle) };
337    }
338}
339
340impl core::fmt::Debug for Stroke {
341    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
342        f.debug_struct("Stroke")
343            .field("render_group_count", &self.render_group_count())
344            .field("input_duration", &self.input_duration())
345            .finish()
346    }
347}