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