Skip to main content

mln_gfx/
drawable_builder.rs

1// Ports include/mln/gfx/drawable_builder.hpp, src/mln/gfx/drawable_builder.cpp,
2// src/mln/gfx/drawable_builder_impl.hpp and the non-polyline parts of
3// src/mln/gfx/drawable_builder_impl.cpp
4//
5// Same split as `Drawable`: `DrawableBuilderBase` holds the C++ data members
6// (including the private `Impl`), the trait has the virtuals
7// (`create_drawable`, `create_segment`, `init`) and provided methods for the
8// rest.
9//
10// TODO(port): addWideVectorPolylineLocal/Global and the wide-vector setup in
11// flush (Impl::Mode::WideVector*): no user on the WebGPU path.
12
13use std::cell::RefCell;
14use std::rc::Rc;
15
16use geometry::Point;
17use mln_tile_id::geometry_tile_data::GeometryCoordinates;
18use mln_util::identity::SimpleIdentity;
19
20use crate::color_mode::ColorMode;
21use crate::context::Context;
22use crate::cull_face_mode::CullFaceMode;
23use crate::draw_mode::DrawMode;
24use crate::drawable::{DrawPriority, Textures, UniqueDrawSegment, UniqueDrawable};
25use crate::drawable_tweaker::DrawableTweakerPtr;
26use crate::gfx_types::{AttributeDataType, DrawModeType};
27use crate::index_vector::{IndexVectorBase, IndexVectorBasePtr};
28use crate::polyline_generator::{PolylineGenerator, PolylineGeneratorOptions};
29use crate::renderer::render_pass::RenderPass;
30use crate::shaders::segment::SegmentBase;
31use crate::shaders::shader_defines::{ID_LINE_DATA_VERTEX_ATTRIBUTE, ID_LINE_POS_NORMAL_VERTEX_ATTRIBUTE};
32use crate::shaders::shader_program_base::ShaderProgramBasePtr;
33use crate::texture2d::Texture2DPtr;
34use crate::types::DepthMaskType;
35use crate::vertex_attribute::VertexAttributeArrayPtr;
36use crate::vertex_vector::VertexVector;
37
38/// `DrawableBuilder::Impl::Mode`
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub enum Mode {
41    /// building primitive drawables. Not implemented
42    Primitives,
43    /// building drawables for thick polylines
44    Polylines,
45    /// building drawables for thick polylines using wide vectors in local coordinates
46    WideVectorLocal,
47    /// building drawables for thick polylines using wide vectors in global coordinates
48    WideVectorGlobal,
49    /// building custom drawables.
50    Custom,
51}
52
53/// `DrawableBuilder::Impl::VT = gfx::detail::VertexType<AttributeType<int16_t, 2>>`
54pub type VT = [i16; 2];
55
56/// `DrawableBuilder::Impl::LineLayoutVertex`.
57#[repr(C)]
58#[derive(Clone, Copy, Debug, Default, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
59pub struct LineLayoutVertex {
60    pub a1: [i16; 2],
61    pub a2: [u8; 4],
62}
63
64/// `DrawableBuilder::Impl`
65pub struct DrawableBuilderImpl {
66    pub vertices: VertexVector<VT>,
67    pub raw_vertices: Vec<u8>,
68    pub raw_vertices_count: usize,
69    pub build_indexes: Vec<u16>,
70    pub shared_indexes: Option<IndexVectorBasePtr>,
71    pub segments: Vec<UniqueDrawSegment>,
72    /// C++ initializes this to `static_cast<AttributeDataType>(-1)` = 255 =
73    /// `Invalid`.
74    pub raw_vertices_type: AttributeDataType,
75    pub color_mode: ColorMode,
76    pub cull_face_mode: CullFaceMode,
77    mode: Mode,
78    pub polyline_vertices: Vec<LineLayoutVertex>,
79    pub polyline_indexes: Vec<u16>,
80    // TODO(port): wideVectorVertices, wideVectorInstanceData,
81    // wideVectorIndexes.
82}
83
84impl Default for DrawableBuilderImpl {
85    fn default() -> Self {
86        DrawableBuilderImpl {
87            vertices: VertexVector::new(),
88            raw_vertices: Vec::new(),
89            raw_vertices_count: 0,
90            build_indexes: Vec::new(),
91            shared_indexes: None,
92            segments: Vec::new(),
93            raw_vertices_type: AttributeDataType::Invalid,
94            color_mode: ColorMode::disabled(),
95            cull_face_mode: CullFaceMode::disabled(),
96            mode: Mode::Custom,
97            polyline_vertices: Vec::new(),
98            polyline_indexes: Vec::new(),
99        }
100    }
101}
102
103impl DrawableBuilderImpl {
104    pub fn check_and_set_mode(&mut self, target: Mode) -> bool {
105        if target != self.mode && self.vertex_count() != 0 {
106            // C++ logs "DrawableBuilder mode mismatch. Target is <target>,
107            // current is <mode>" and asserts.
108            // TODO(port): mln::Log once a logging port exists.
109            debug_assert!(false, "DrawableBuilder mode mismatch. Target is {target:?}, current is {:?}", self.mode);
110            return false;
111        }
112        self.mode = target;
113        true
114    }
115
116    pub fn get_mode(&self) -> Mode {
117        self.mode
118    }
119
120    /// C++ `bool setMode(Mode value) { return mode == value; }` - a quirk: it
121    /// does not set anything. Ported as is.
122    pub fn set_mode(&self, value: Mode) -> bool {
123        self.mode == value
124    }
125
126    pub fn vertex_count(&self) -> usize {
127        self.raw_vertices_count.max(self.vertices.elements()).max(self.polyline_vertices.len())
128    }
129
130    pub fn clear(&mut self) {
131        self.vertices.clear();
132        self.raw_vertices.clear();
133        self.raw_vertices_count = 0;
134        self.polyline_vertices.clear();
135        self.polyline_indexes.clear();
136        self.build_indexes.clear();
137        self.segments.clear();
138    }
139
140    /// `layoutVertex(p, e, round, up, dir, linesofar)`.
141    pub fn layout_vertex(
142        p: Point<i16>,
143        e: Point<f64>,
144        round: bool,
145        up: bool,
146        dir: i8,
147        linesofar: i32,
148    ) -> LineLayoutVertex {
149        // Scale the extrusion vector so that the normal length is this value.
150        // Contains the "texture" normals (-1..1). This is distinct from the
151        // extrude normals for line joins, because the x-value remains 0 for
152        // the texture normal array, while the extrude normal actually moves
153        // the vertex to create the acute/bevelled line join.
154        const EXTRUDE_SCALE: f64 = 63.0;
155        let dir_value: i32 = if dir == 0 {
156            0
157        } else if dir < 0 {
158            -1
159        } else {
160            1
161        };
162        LineLayoutVertex {
163            a1: [((p.x as i32 * 2) | round as i32) as i16, ((p.y as i32 * 2) | up as i32) as i16],
164            a2: [
165                // add 128 to store a byte in an unsigned byte
166                ((EXTRUDE_SCALE * e.x).round() + 128.0) as u8,
167                ((EXTRUDE_SCALE * e.y).round() + 128.0) as u8,
168                // Encode the -1/0/1 direction value into the first two bits
169                // of .z of a_data. Combine it with the lower 6 bits of
170                // `linesofar` (shifted by 2 bites to make room for the
171                // direction value). The upper 8 bits of `linesofar` are
172                // placed in the `w` component.
173                ((dir_value + 1) | ((linesofar & 0x3F) << 2)) as u8,
174                (linesofar >> 6) as u8,
175            ],
176        }
177    }
178}
179
180/// The data members of `gfx::DrawableBuilder`.
181pub struct DrawableBuilderBase {
182    pub name: String,
183    pub drawable_name: String,
184    pub vertex_attr_id: usize,
185    pub render_pass: RenderPass,
186    pub enabled: bool,
187    pub enable_color: bool,
188    pub enable_stencil: bool,
189    pub enable_depth: bool,
190    pub is_3d: bool,
191    pub line_width: f32,
192    pub draw_priority: DrawPriority,
193    pub sub_layer_index: i32,
194    pub depth_type: DepthMaskType,
195    pub shader: Option<ShaderProgramBasePtr>,
196    pub current_drawable: Option<UniqueDrawable>,
197    pub drawables: Vec<UniqueDrawable>,
198    pub textures: Textures,
199    pub tweakers: Vec<DrawableTweakerPtr>,
200    pub vertex_attrs: Option<VertexAttributeArrayPtr>,
201    pub instance_attrs: Option<VertexAttributeArrayPtr>,
202    pub origin: Option<Point<f64>>,
203    pub impl_: DrawableBuilderImpl,
204}
205
206impl DrawableBuilderBase {
207    pub fn new(name: String) -> Self {
208        DrawableBuilderBase {
209            name,
210            drawable_name: String::new(),
211            vertex_attr_id: 0,
212            render_pass: RenderPass::Opaque,
213            enabled: true,
214            enable_color: true,
215            enable_stencil: false,
216            enable_depth: true,
217            is_3d: false,
218            line_width: 1.0,
219            draw_priority: 0,
220            sub_layer_index: 0,
221            depth_type: DepthMaskType::ReadOnly,
222            shader: None,
223            current_drawable: None,
224            drawables: Vec::new(),
225            textures: Default::default(),
226            tweakers: Vec::new(),
227            vertex_attrs: None,
228            instance_attrs: None,
229            origin: None,
230            impl_: DrawableBuilderImpl::default(),
231        }
232    }
233}
234
235pub trait DrawableBuilder {
236    fn base(&self) -> &DrawableBuilderBase;
237    fn base_mut(&mut self) -> &mut DrawableBuilderBase;
238
239    /// Create an instance of the appropriate drawable type
240    fn create_drawable(&self) -> UniqueDrawable;
241    /// Create a segment wrapper
242    fn create_segment(&self, mode: DrawMode, segment: SegmentBase) -> UniqueDrawSegment;
243    /// Setup the SDK-specific aspects after all the values are present
244    fn init(&mut self);
245
246    /// Get the drawable we're currently working on, if any
247    fn get_current_drawable(&mut self, create_if_none: bool) -> Option<&mut UniqueDrawable> {
248        if self.base().current_drawable.is_none() && create_if_none {
249            let drawable = self.create_drawable();
250            self.base_mut().current_drawable = Some(drawable);
251        }
252        self.base_mut().current_drawable.as_mut()
253    }
254
255    /// Close the current drawable, using a new one for any further work
256    fn flush(&mut self, context: &dyn Context) {
257        if self.cur_vertex_count() != 0 {
258            match self.base().impl_.get_mode() {
259                Mode::Polylines => {
260                    // setup for polylines
261                    self.setup_for_polylines(context);
262                }
263                Mode::WideVectorLocal | Mode::WideVectorGlobal => {
264                    // TODO(port): impl->setupForWideVectors
265                }
266                _ => {}
267            }
268
269            let new_vertex_attributes =
270                if self.base().vertex_attrs.is_none() { Some(context.create_vertex_attribute_array()) } else { None };
271            self.get_current_drawable(true);
272            let base = self.base_mut();
273            let draw = base.current_drawable.as_mut().expect("current drawable");
274            draw.set_enabled(base.enabled);
275            draw.set_line_width(base.line_width as i32);
276            draw.set_enable_color(base.enable_color);
277            draw.set_enable_stencil(base.enable_stencil);
278            draw.set_render_pass(base.render_pass);
279            draw.set_draw_priority(base.draw_priority);
280            draw.set_sub_layer_index(base.sub_layer_index);
281            draw.set_enable_depth(base.enable_depth);
282            draw.set_depth_type(base.depth_type);
283            draw.set_is_3d(base.is_3d);
284            draw.set_color_mode(&base.impl_.color_mode);
285            draw.set_cull_face_mode(&base.impl_.cull_face_mode);
286            draw.set_shader(base.shader.clone());
287            draw.set_textures(base.textures.clone());
288            draw.set_tweakers(base.tweakers.clone());
289            draw.set_origin(base.origin);
290            if let Some(attrs) = &base.vertex_attrs {
291                draw.set_vertex_attributes(Some(attrs.clone()));
292            } else {
293                draw.set_vertex_attributes(new_vertex_attributes);
294            }
295            if let Some(attrs) = &base.instance_attrs {
296                draw.set_instance_attributes(Some(attrs.clone()));
297            }
298
299            self.init();
300
301            let base = self.base_mut();
302            // reset mode (quirk: C++ `setMode` only compares, see DrawableBuilderImpl::set_mode)
303            base.impl_.set_mode(Mode::Custom);
304            // reset origin
305            base.origin = None;
306        }
307
308        let base = self.base_mut();
309        if let Some(drawable) = base.current_drawable.take() {
310            base.drawables.push(drawable);
311        }
312    }
313
314    /// Get all the completed drawables
315    fn get_drawables(&self) -> &Vec<UniqueDrawable> {
316        &self.base().drawables
317    }
318
319    /// Get all the completed drawables and release ownership
320    fn clear_drawables(&mut self) -> Vec<UniqueDrawable> {
321        std::mem::take(&mut self.base_mut().drawables)
322    }
323
324    /// Get the ID of the drawable we're currently working on, if any
325    fn get_drawable_id(&self) -> SimpleIdentity {
326        self.base().current_drawable.as_ref().map_or(SimpleIdentity::EMPTY, |d| d.get_id())
327    }
328
329    fn get_enabled(&self) -> bool {
330        self.base().enabled
331    }
332    fn set_enabled(&mut self, value: bool) {
333        self.base_mut().enabled = value;
334    }
335    fn get_render_pass(&self) -> RenderPass {
336        self.base().render_pass
337    }
338    fn set_render_pass(&mut self, value: RenderPass) {
339        self.base_mut().render_pass = value;
340    }
341    fn get_draw_priority(&self) -> DrawPriority {
342        self.base().draw_priority
343    }
344    fn set_draw_priority(&mut self, value: DrawPriority) {
345        let base = self.base_mut();
346        base.draw_priority = value;
347        if let Some(d) = base.current_drawable.as_mut() {
348            d.set_draw_priority(value);
349        }
350    }
351    fn get_sub_layer_index(&self) -> i32 {
352        self.base().sub_layer_index
353    }
354    fn set_sub_layer_index(&mut self, value: i32) {
355        self.base_mut().sub_layer_index = value;
356    }
357    fn get_enable_depth(&self) -> bool {
358        self.base().enable_depth
359    }
360    fn set_enable_depth(&mut self, value: bool) {
361        self.base_mut().enable_depth = value;
362    }
363    fn get_depth_type(&self) -> DepthMaskType {
364        self.base().depth_type
365    }
366    fn set_depth_type(&mut self, value: DepthMaskType) {
367        self.base_mut().depth_type = value;
368    }
369    fn get_is_3d(&self) -> bool {
370        self.base().is_3d
371    }
372    fn set_is_3d(&mut self, value: bool) {
373        self.base_mut().is_3d = value;
374    }
375    /// Set the draw priority on all drawables including those already generated
376    fn reset_draw_priority(&mut self, value: DrawPriority) {
377        self.set_draw_priority(value);
378        for drawable in &mut self.base_mut().drawables {
379            drawable.set_draw_priority(value);
380        }
381    }
382    fn get_line_width(&self) -> f32 {
383        self.base().line_width
384    }
385    fn set_line_width(&mut self, value: f32) {
386        self.base_mut().line_width = value;
387    }
388    fn get_enable_color(&self) -> bool {
389        self.base().enable_color
390    }
391    fn set_enable_color(&mut self, value: bool) {
392        self.base_mut().enable_color = value;
393    }
394    fn get_enable_stencil(&self) -> bool {
395        self.base().enable_stencil
396    }
397    fn set_enable_stencil(&mut self, value: bool) {
398        self.base_mut().enable_stencil = value;
399    }
400    fn get_color_mode(&self) -> &ColorMode {
401        &self.base().impl_.color_mode
402    }
403    fn set_color_mode(&mut self, value: &ColorMode) {
404        self.base_mut().impl_.color_mode = *value;
405    }
406    fn get_cull_face_mode(&self) -> &CullFaceMode {
407        &self.base().impl_.cull_face_mode
408    }
409    fn set_cull_face_mode(&mut self, value: &CullFaceMode) {
410        self.base_mut().impl_.cull_face_mode = *value;
411    }
412    fn get_shader(&self) -> &Option<ShaderProgramBasePtr> {
413        &self.base().shader
414    }
415    fn set_shader(&mut self, value: Option<ShaderProgramBasePtr>) {
416        self.base_mut().shader = value;
417    }
418    /// Set the name given to new drawables
419    fn set_drawable_name(&mut self, value: String) {
420        self.base_mut().drawable_name = value;
421    }
422    /// The attribute id for vertex/position attribute
423    fn set_vertex_attr_id(&mut self, id: usize) {
424        self.base_mut().vertex_attr_id = id;
425    }
426    fn get_texture(&self, id: usize) -> Option<&Texture2DPtr> {
427        self.base().textures.get(id).and_then(Option::as_ref)
428    }
429    fn set_texture(&mut self, texture: Option<Texture2DPtr>, id: usize) {
430        debug_assert!(id < self.base().textures.len());
431        if id >= self.base().textures.len() {
432            return;
433        }
434        self.base_mut().textures[id] = texture;
435    }
436    fn add_tweaker(&mut self, value: DrawableTweakerPtr) {
437        self.base_mut().tweakers.push(value);
438    }
439    fn clear_tweakers(&mut self) {
440        self.base_mut().tweakers.clear();
441    }
442    fn get_vertex_attributes(&self) -> Option<&VertexAttributeArrayPtr> {
443        self.base().vertex_attrs.as_ref()
444    }
445    fn set_vertex_attributes(&mut self, attrs: Option<VertexAttributeArrayPtr>) {
446        self.base_mut().vertex_attrs = attrs;
447    }
448    fn get_instance_attributes(&self) -> Option<&VertexAttributeArrayPtr> {
449        self.base().instance_attrs.as_ref()
450    }
451    fn set_instance_attributes(&mut self, attrs: Option<VertexAttributeArrayPtr>) {
452        self.base_mut().instance_attrs = attrs;
453    }
454
455    /// Add some vertex elements, returns the index of the first one added
456    fn add_vertices(&mut self, vertices: &[[i16; 2]], vertex_offset: usize, vertex_length: usize) -> usize {
457        let impl_ = &mut self.base_mut().impl_;
458        let base_index = impl_.vertices.elements();
459        for x in &vertices[vertex_offset..vertex_offset + vertex_length] {
460            impl_.vertices.emplace_back(*x);
461        }
462        base_index
463    }
464
465    /// Provide raw data for vertices. Incompatible with adding primitives
466    fn set_raw_vertices(&mut self, data: Vec<u8>, count: usize, type_: AttributeDataType) {
467        let impl_ = &mut self.base_mut().impl_;
468        impl_.raw_vertices = data;
469        impl_.raw_vertices_count = count;
470        impl_.raw_vertices_type = type_;
471    }
472
473    /// Set indexes and segments
474    fn set_segments(&mut self, mode: DrawMode, indexes: Vec<u16>, segments: &[SegmentBase]) {
475        self.set_segments_shared(mode, Some(Rc::new(RefCell::new(IndexVectorBase::new(indexes)))), segments);
476    }
477
478    /// Set shared indices and segments
479    fn set_segments_shared(&mut self, mode: DrawMode, indexes: Option<IndexVectorBasePtr>, segments: &[SegmentBase]) {
480        let Some(indexes) = indexes.filter(|i| i.borrow().elements() != 0) else {
481            debug_assert!(false, "Missing segment indexes");
482            return;
483        };
484        #[cfg(debug_assertions)]
485        let vertex_count = self.cur_vertex_count();
486        self.base_mut().impl_.shared_indexes = Some(indexes);
487        for seg in segments {
488            #[cfg(debug_assertions)]
489            {
490                if mode.type_ == DrawModeType::Triangles {
491                    debug_assert!(seg.index_length % 3 == 0);
492                } else if mode.type_ == DrawModeType::Lines {
493                    debug_assert!(seg.index_length % 2 == 0);
494                }
495                let shared = self.base().impl_.shared_indexes.as_ref().unwrap().borrow();
496                debug_assert!(vertex_count == 0 || seg.vertex_offset + seg.vertex_length <= vertex_count);
497                debug_assert!(seg.index_offset + seg.index_length <= shared.elements());
498                if vertex_count != 0 {
499                    for j in 0..seg.index_length {
500                        debug_assert!((shared.vector()[seg.index_offset + j] as usize) < vertex_count);
501                    }
502                }
503            }
504            let draw_segment = self.create_segment(mode, seg.copy());
505            self.base_mut().impl_.segments.push(draw_segment);
506        }
507    }
508
509    /// Add a triangle
510    fn add_triangle(&mut self, x0: i16, y0: i16, x1: i16, y1: i16, x2: i16, y2: i16) {
511        // check and set the current mode
512        if !self.base_mut().impl_.check_and_set_mode(Mode::Primitives) {
513            return;
514        }
515        let needs_segment = self.base().impl_.segments.is_empty();
516        let new_segment =
517            if needs_segment { Some(self.create_segment(DrawMode::Triangles(), SegmentBase::new(0, 0))) } else { None };
518        let impl_ = &mut self.base_mut().impl_;
519        let n = impl_.vertices.elements() as u16;
520        impl_.vertices.emplace_back([x0, y0]);
521        impl_.vertices.emplace_back([x1, y1]);
522        impl_.vertices.emplace_back([x2, y2]);
523        impl_.build_indexes.extend_from_slice(&[n, n.wrapping_add(1), n.wrapping_add(2)]);
524        if let Some(segment) = new_segment {
525            impl_.segments.push(segment);
526        }
527        let segment = impl_.segments.last_mut().unwrap().get_segment_mut();
528        segment.vertex_length += 3;
529        segment.index_length += 3;
530    }
531
532    /// Add another triangle based on the previous two points
533    fn append_triangle(&mut self, x0: i16, y0: i16) {
534        // check and set the current mode
535        if !self.base_mut().impl_.check_and_set_mode(Mode::Primitives) {
536            return;
537        }
538        let impl_ = &mut self.base_mut().impl_;
539        let n = impl_.vertices.elements() as u16;
540        impl_.vertices.emplace_back([x0, y0]);
541        impl_.build_indexes.extend_from_slice(&[n.wrapping_sub(2), n.wrapping_sub(1), n]);
542        debug_assert!(!impl_.segments.is_empty());
543        let segment = impl_.segments.last_mut().unwrap().get_segment_mut();
544        segment.vertex_length += 1;
545        segment.index_length += 3;
546    }
547
548    /// Add a rectangle consisting of two triangles
549    fn add_quad(&mut self, x0: i16, y0: i16, x1: i16, y1: i16) {
550        // check and set the current mode
551        if !self.base_mut().impl_.check_and_set_mode(Mode::Primitives) {
552            return;
553        }
554        self.add_triangle(x0, y0, x1, y0, x0, y1);
555        self.append_triangle(x1, y1);
556    }
557
558    /// Add lines based on existing vertices
559    fn add_lines(&mut self, indexes: &[u16], index_offset: usize, index_length: usize, base_index: usize) {
560        if index_length == 0 {
561            return;
562        }
563        let line_width = self.base().line_width;
564        let segment = self
565            .create_segment(DrawMode::Lines(line_width), SegmentBase::with_lengths(0, indexes.len(), 0, index_length));
566        let impl_ = &mut self.base_mut().impl_;
567        impl_.segments.push(segment);
568        if impl_.build_indexes.is_empty() {
569            impl_.build_indexes.reserve(index_length);
570        }
571        for i in &indexes[index_offset..index_offset + index_length] {
572            impl_.build_indexes.push((*i as usize + base_index) as u16);
573        }
574    }
575
576    /// Add triangles based on existing vertices
577    fn add_triangles(&mut self, indexes: &[u16], index_offset: usize, index_length: usize, base_index: usize) {
578        if index_length == 0 {
579            return;
580        }
581        let (build_len, vertex_len) = {
582            let impl_ = &self.base().impl_;
583            (impl_.build_indexes.len(), impl_.vertices.elements())
584        };
585        let segment = self
586            .create_segment(DrawMode::Triangles(), SegmentBase::with_lengths(0, build_len, vertex_len, index_length));
587        let impl_ = &mut self.base_mut().impl_;
588        impl_.segments.push(segment);
589        if impl_.build_indexes.is_empty() {
590            impl_.build_indexes.reserve(index_length);
591        }
592        for i in &indexes[index_offset..index_offset + index_length] {
593            impl_.build_indexes.push((*i as usize + base_index) as u16);
594        }
595    }
596
597    /// Add a polyline. If the last point equals the first it will be
598    /// closed, otherwise open
599    fn add_polyline(&mut self, coordinates: &GeometryCoordinates, options: &PolylineGeneratorOptions) {
600        // mark the current mode
601        if !self.base_mut().impl_.check_and_set_mode(Mode::Polylines) {
602            return;
603        }
604
605        // append polyline (`Impl::addPolyline`); the vectors are moved out
606        // while the generator's segment factory borrows the builder.
607        let impl_ = &mut self.base_mut().impl_;
608        let mut vertices = std::mem::take(&mut impl_.polyline_vertices);
609        let mut segments = std::mem::take(&mut impl_.segments);
610        let mut indexes = std::mem::take(&mut impl_.polyline_indexes);
611        {
612            let create_segment = |vertex_offset: usize, index_offset: usize| {
613                self.create_segment(DrawMode::Triangles(), SegmentBase::new(vertex_offset, index_offset))
614            };
615            fn get_segment(segment: &mut UniqueDrawSegment) -> &mut SegmentBase {
616                segment.get_segment_mut()
617            }
618            let mut generator = PolylineGenerator::new(
619                &mut vertices,
620                DrawableBuilderImpl::layout_vertex,
621                &mut segments,
622                &create_segment,
623                get_segment,
624                &mut indexes,
625            );
626            generator.generate(coordinates, options);
627        }
628        let impl_ = &mut self.base_mut().impl_;
629        impl_.polyline_vertices = vertices;
630        impl_.segments = segments;
631        impl_.polyline_indexes = indexes;
632    }
633
634    /// `Impl::setupForPolylines(context, builder)`.
635    fn setup_for_polylines(&mut self, context: &dyn Context) {
636        // setup vertex attributes
637        self.set_vertex_attr_id(ID_LINE_POS_NORMAL_VERTEX_ATTRIBUTE);
638        let count = self.base().impl_.polyline_vertices.len();
639        self.set_raw_vertices(Vec::new(), count, AttributeDataType::Short2);
640
641        let attrs = context.create_vertex_attribute_array();
642        let vertices = std::mem::take(&mut self.base_mut().impl_.polyline_vertices);
643        let verts: crate::vertex_vector::VertexVectorBasePtr = Rc::new(VertexVector::from_vec(vertices));
644
645        {
646            let mut attrs = attrs.borrow_mut();
647            if let Some(attr) = attrs.set(ID_LINE_POS_NORMAL_VERTEX_ATTRIBUTE, -1, AttributeDataType::Invalid, 0) {
648                attr.set_shared_raw_data(
649                    Some(verts.clone()),
650                    0, // offsetof(LineLayoutVertex, a1)
651                    /*vertexOffset=*/ 0,
652                    std::mem::size_of::<LineLayoutVertex>() as u32,
653                    AttributeDataType::Short2,
654                );
655            }
656            if let Some(attr) = attrs.set(ID_LINE_DATA_VERTEX_ATTRIBUTE, -1, AttributeDataType::Invalid, 0) {
657                attr.set_shared_raw_data(
658                    Some(verts),
659                    4, // offsetof(LineLayoutVertex, a2)
660                    /*vertexOffset=*/ 0,
661                    std::mem::size_of::<LineLayoutVertex>() as u32,
662                    AttributeDataType::UByte4,
663                );
664            }
665        }
666
667        self.set_vertex_attributes(Some(attrs));
668
669        let indexes = std::mem::take(&mut self.base_mut().impl_.polyline_indexes);
670        self.base_mut().impl_.shared_indexes = Some(Rc::new(RefCell::new(IndexVectorBase::new(indexes))));
671    }
672
673    /// return the current vertex count
674    fn cur_vertex_count(&self) -> usize {
675        self.base().impl_.vertex_count()
676    }
677
678    fn empty(&self) -> bool {
679        self.base().drawables.is_empty() && self.cur_vertex_count() == 0
680    }
681}
682
683pub type UniqueDrawableBuilder = Box<dyn DrawableBuilder>;