Skip to main content

mln_webgpu/
drawable.rs

1// Ports include/mln/webgpu/drawable.hpp, src/mln/webgpu/drawable_impl.hpp and
2// src/mln/webgpu/drawable.cpp
3//
4// Logging: the C++ `Log::Warning`/`Log::Error` calls print to stderr here.
5// TODO(port): route them through mln::Log once a logging port exists.
6
7use std::any::Any;
8use std::cell::{Cell, RefCell};
9use std::rc::Rc;
10use std::time::Instant;
11
12use bytemuck::{Pod, Zeroable};
13use mln_gfx::attribute::AttributeBindingArray;
14use mln_gfx::color_mode::{BlendFunction, ColorMode};
15use mln_gfx::context::Context as _;
16use mln_gfx::cull_face_mode::CullFaceMode;
17use mln_gfx::depth_mode::DepthMode;
18use mln_gfx::draw_mode::DrawMode;
19use mln_gfx::drawable::{self, DrawSegment, DrawableBase, UniqueDrawSegment};
20use mln_gfx::gfx_types::{AttributeDataType, DrawModeType};
21use mln_gfx::index_vector::{IndexBufferBase, IndexVectorBasePtr};
22use mln_gfx::paint_parameters::PaintParameters;
23use mln_gfx::shaders::segment::SegmentBase;
24use mln_gfx::shaders::shader_defines::ID_GLOBAL_UBO_INDEX;
25use mln_gfx::shaders::shader_program_base::{ShaderProgramBasePtr, same_shader};
26use mln_gfx::stencil_mode::StencilMode;
27use mln_gfx::texture2d::Texture2D as _;
28use mln_gfx::types::{BufferUsageType, DepthMaskType};
29use mln_gfx::uniform_buffer::{UniformBufferArray, UniformBufferPtr};
30use mln_gfx::upload_pass::UploadPass as _;
31use mln_gfx::util_hash::hash;
32use mln_gfx::vertex_attribute::{VertexAttribute, VertexAttributeArray, VertexAttributeArrayPtr};
33use mln_gfx::vertex_buffer::{IndexBuffer as GfxIndexBuffer, UniqueVertexBufferResource};
34
35use crate::context::Context;
36use crate::render_pass::RenderPass;
37use crate::shaders::shader_program::{BindingType, ShaderProgram, VertexLayout, as_webgpu_shader};
38use crate::texture2d::Texture2D;
39use crate::uniform_buffer::UniformBuffer;
40use crate::upload_pass::UploadPass;
41use crate::vertex_buffer_resource::{IndexBufferResource, VertexBufferResource};
42
43#[derive(Clone, Copy, Pod, Zeroable)]
44#[repr(C, align(16))]
45struct GlobalUBOIndexData {
46    value: u32,
47    pad: [u32; 3],
48}
49
50fn hash_stencil_mode(mode: &StencilMode) -> u64 {
51    let mut h = hash(&[
52        mode.ref_ as i64 as u64,
53        u64::from(mode.mask),
54        mode.fail as u64,
55        mode.depth_fail as u64,
56        mode.pass as u64,
57    ]);
58    h = hash(&[h, mode.test.func() as u64]);
59    if let Some(mask) = mode.test.masked() {
60        h = hash(&[h, u64::from(mask)]);
61    }
62    h
63}
64
65fn hash_pipeline_state(
66    vertex_layouts: &[VertexLayout],
67    color_mode: &ColorMode,
68    depth_mode: &DepthMode,
69    stencil_mode: &StencilMode,
70    draw_mode_type: DrawModeType,
71) -> u64 {
72    let mut h = 0u64;
73    // Hash vertex layouts
74    for layout in vertex_layouts {
75        h = hash(&[h, layout.array_stride as u32 as u64]);
76        h = hash(&[h, layout.step_mode as u64]);
77        h = hash(&[h, layout.attributes.len() as u64]);
78        for attr in layout.attributes.iter().take(16) {
79            h = hash(&[h, attr.format as u64, u64::from(attr.shader_location), attr.offset as u32 as u64]);
80        }
81    }
82    // Hash color mode
83    h = hash(&[
84        h,
85        u64::from(color_mode.mask.r),
86        u64::from(color_mode.mask.g),
87        u64::from(color_mode.mask.b),
88        u64::from(color_mode.mask.a),
89    ]);
90    match &color_mode.blend_function {
91        BlendFunction::Replace => h = hash(&[h, 0]),
92        f => {
93            h = hash(&[h, f.equation() as u64, f.src_factor() as u64, f.dst_factor() as u64]);
94        }
95    }
96    // Hash depth mode
97    h = hash(&[h, depth_mode.func as u64, depth_mode.mask as u64]);
98    // Hash stencil mode
99    h = hash(&[h, hash_stencil_mode(stencil_mode)]);
100    // Hash draw mode
101    hash(&[h, draw_mode_type as u64])
102}
103
104fn wgpu_vertex_format_of(type_: AttributeDataType) -> wgpu::VertexFormat {
105    use AttributeDataType as A;
106    use wgpu::VertexFormat as F;
107    match type_ {
108        A::Byte => F::Sint8,
109        A::Byte2 => F::Sint8x2,
110        A::Byte4 => F::Sint8x4,
111        A::UByte => F::Uint8,
112        A::UByte2 => F::Uint8x2,
113        A::UByte4 => F::Uint8x4,
114        A::UByte4Normalized => F::Unorm8x4,
115        A::Short => F::Sint16,
116        A::Short2 => F::Sint16x2,
117        A::Short4 => F::Sint16x4,
118        A::UShort => F::Uint16,
119        A::UShort2 => F::Uint16x2,
120        A::UShort4 => F::Uint16x4,
121        A::Int => F::Sint32,
122        A::Int2 => F::Sint32x2,
123        A::Int3 => F::Sint32x3,
124        A::Int4 => F::Sint32x4,
125        A::UInt => F::Uint32,
126        A::UInt2 => F::Uint32x2,
127        A::UInt3 => F::Uint32x3,
128        A::UInt4 => F::Uint32x4,
129        A::Float => F::Float32,
130        A::Float2 => F::Float32x2,
131        A::Float3 => F::Float32x3,
132        A::Float4 => F::Float32x4,
133        _ => {
134            debug_assert!(false, "Unsupported vertex attribute format");
135            F::Float32x2 // Default fallback
136        }
137    }
138}
139
140/// `struct IndexBuffer : gfx::IndexBufferBase`: adapts `gfx::IndexBuffer`.
141struct IndexBuffer {
142    buffer: GfxIndexBuffer,
143}
144
145impl IndexBufferBase for IndexBuffer {
146    fn as_any(&self) -> &dyn Any {
147        self
148    }
149}
150
151struct BindGroupRecord {
152    slot: u32,
153    #[allow(dead_code)]
154    group: u32,
155    handle: wgpu::BindGroup,
156}
157
158/// `webgpu::Drawable::Impl`
159struct DrawableImpl {
160    segments: Vec<UniqueDrawSegment>,
161    vertex_desc_hash: u64,
162    indexes: Option<IndexVectorBasePtr>,
163    vertex_count: usize,
164    vertex_type: AttributeDataType,
165    attribute_bindings: AttributeBindingArray,
166    instance_bindings: AttributeBindingArray,
167    /// Store dummy vertex buffers to keep them alive
168    dummy_vertex_buffers: Vec<UniqueVertexBufferResource>,
169    uniform_buffers: UniformBufferArray,
170    ubo_index_uniform: Option<UniformBufferPtr>,
171    depth_mode: DepthMode,
172    stencil_mode: StencilMode,
173    #[allow(dead_code)]
174    cull_face_mode: CullFaceMode,
175    vertex_attr_id: usize,
176    stencil_mode_hash: u64,
177    stencil_mode_hash_valid: bool,
178    /// We don't own the pipeline - it's owned by the shader program's cache.
179    pipeline_state: Option<wgpu::RenderPipeline>,
180    previous_stencil_mode: StencilMode,
181    bind_groups: Vec<BindGroupRecord>,
182}
183
184pub struct Drawable {
185    base: DrawableBase,
186    impl_: DrawableImpl,
187}
188
189thread_local! {
190    static DRAW_CALL_COUNT: Cell<u64> = const { Cell::new(0) };
191}
192
193/// Owned resources of a bind group entry (the wgpu entries borrow them).
194enum EntryResource {
195    Buffer(wgpu::Buffer, u64),
196    Sampler(wgpu::Sampler),
197    TextureView(wgpu::TextureView),
198}
199
200impl Drawable {
201    pub fn new(name: String) -> Self {
202        Drawable {
203            base: DrawableBase::new(name),
204            impl_: DrawableImpl {
205                segments: Vec::new(),
206                vertex_desc_hash: 0,
207                indexes: None,
208                vertex_count: 0,
209                vertex_type: AttributeDataType::Invalid,
210                attribute_bindings: Vec::new(),
211                instance_bindings: Vec::new(),
212                dummy_vertex_buffers: Vec::new(),
213                uniform_buffers: UniformBufferArray::new(),
214                ubo_index_uniform: None,
215                depth_mode: DepthMode::disabled(),
216                stencil_mode: StencilMode::default(),
217                cull_face_mode: CullFaceMode::disabled(),
218                vertex_attr_id: 0,
219                stencil_mode_hash: 0,
220                stencil_mode_hash_valid: false,
221                pipeline_state: None,
222                previous_stencil_mode: StencilMode::default(),
223                bind_groups: Vec::new(),
224            },
225        }
226    }
227
228    pub fn set_depth_mode_for_3d(&mut self, value: &DepthMode) {
229        if self.impl_.depth_mode.func != value.func || self.impl_.depth_mode.mask != value.mask {
230            self.impl_.pipeline_state = None;
231        }
232        self.impl_.depth_mode = *value;
233    }
234
235    pub fn set_stencil_mode_for_3d(&mut self, value: &StencilMode) {
236        let new_hash = hash_stencil_mode(value);
237        let m = &self.impl_.stencil_mode;
238        if !self.impl_.stencil_mode_hash_valid
239            || self.impl_.stencil_mode_hash != new_hash
240            || m.ref_ != value.ref_
241            || m.mask != value.mask
242            || m.fail != value.fail
243            || m.depth_fail != value.depth_fail
244            || m.pass != value.pass
245        {
246            self.impl_.pipeline_state = None;
247            self.impl_.stencil_mode_hash_valid = false;
248        }
249        self.impl_.stencil_mode = *value;
250        self.impl_.stencil_mode_hash = new_hash;
251    }
252
253    pub fn set_vertex_attr_id(&mut self, id: usize) {
254        self.impl_.vertex_attr_id = id;
255    }
256
257    pub fn upload(&mut self, upload_pass: &UploadPass) {
258        if self.base.is_custom {
259            return;
260        }
261        let Some(shader) = self.base.shader.clone() else {
262            eprintln!("Missing shader for drawable {}/{}", self.base.unique_id, self.base.name);
263            debug_assert!(false);
264            return;
265        };
266
267        let usage = BufferUsageType::StaticDraw;
268
269        // We need either raw index data or a buffer already created from them.
270        // We can have a buffer and no indexes, but only if it's not marked dirty.
271        let Some(indexes) = self.impl_.indexes.clone() else {
272            debug_assert!(false, "Missing index data");
273            return;
274        };
275        {
276            let mut indexes = indexes.borrow_mut();
277            if indexes.empty() && (indexes.get_buffer().is_none() || indexes.get_dirty()) {
278                debug_assert!(false, "Missing index data");
279                return;
280            }
281            if indexes.get_buffer().is_none() || indexes.get_dirty() {
282                // Create or update a buffer for the index data. We don't
283                // update any existing buffer because it may still be in use
284                // by the previous frame.
285                let resource = upload_pass.create_index_buffer_resource(
286                    bytemuck::cast_slice(indexes.data()),
287                    usage,
288                    /*persistent=*/ false,
289                );
290                let gfx_index_buffer = GfxIndexBuffer::new(indexes.elements(), resource);
291                indexes.set_buffer(Some(Box::new(IndexBuffer { buffer: gfx_index_buffer })));
292                indexes.set_dirty(false);
293            }
294        }
295
296        // Upload vertex attributes (like Metal does)
297        let build_attribs = match (&self.base.vertex_attributes, self.base.attribute_update_time) {
298            (Some(attrs), Some(t)) => attrs.borrow().is_modified_after(t),
299            _ => true,
300        };
301        if build_attribs {
302            let attrs = self.base.vertex_attributes.get_or_insert_with(VertexAttributeArray::new_ptr).clone();
303            // Apply drawable values to shader defaults (matching Metal's approach)
304            let mut vertex_buffers = Vec::new();
305            let attribute_bindings = upload_pass.build_attribute_bindings(
306                self.impl_.vertex_count,
307                self.impl_.vertex_type,
308                /*vertexAttributeIndex=*/ usize::MAX,
309                /*vertexData=*/ &[],
310                shader.get_vertex_attributes(),
311                &mut attrs.borrow_mut(),
312                usage,
313                self.base.attribute_update_time,
314                &mut vertex_buffers,
315            );
316            if self.impl_.attribute_bindings != attribute_bindings {
317                self.impl_.attribute_bindings = attribute_bindings;
318                self.impl_.vertex_desc_hash = 0; // Reset hash when bindings change
319                self.impl_.pipeline_state = None; // Reset pipeline state when attribute bindings change
320                // Store the dummy vertex buffers to keep them alive
321                self.impl_.dummy_vertex_buffers = vertex_buffers;
322            }
323        }
324
325        // Build instance buffer (like Metal does)
326        let build_instance_buffer = match (&self.base.instance_attributes, self.base.attribute_update_time) {
327            (Some(attrs), Some(t)) => attrs.borrow().is_modified_after(t),
328            (Some(_), None) => true,
329            (None, _) => false,
330        };
331        if build_instance_buffer {
332            let attrs = self.base.instance_attributes.clone().unwrap();
333            let mut instance_buffers = Vec::new();
334            let instance_bindings = upload_pass.build_attribute_bindings(
335                self.impl_.vertex_count,
336                self.impl_.vertex_type,
337                usize::MAX,
338                &[],
339                shader.get_instance_attributes(),
340                &mut attrs.borrow_mut(),
341                usage,
342                self.base.attribute_update_time,
343                &mut instance_buffers,
344            );
345            if self.impl_.instance_bindings != instance_bindings {
346                self.impl_.instance_bindings = instance_bindings;
347                self.impl_.pipeline_state = None; // Reset pipeline state when instance bindings change
348                // Store the dummy instance buffers to keep them alive
349                self.impl_.dummy_vertex_buffers.extend(instance_buffers);
350            }
351        }
352
353        // Upload uniform buffers to ensure they're ready for the GPU: only a
354        // check that each has a GPU buffer.
355        for i in 0..self.impl_.uniform_buffers.allocated_size() {
356            if let Some(ub) = self.impl_.uniform_buffers.get(i)
357                && let Some(webgpu_ub) = ub.as_any().downcast_ref::<UniformBuffer>()
358                && webgpu_ub.get_buffer().is_none()
359            {
360                eprintln!("Uniform buffer {i} has no GPU buffer!");
361            }
362        }
363
364        // Upload textures if needed
365        let textures_need_upload = self.base.textures.iter().flatten().any(|t| t.borrow().needs_upload());
366        if textures_need_upload {
367            for texture in self.base.textures.iter().flatten() {
368                let mut t = texture.borrow_mut();
369                if t.needs_upload() {
370                    t.upload();
371                }
372            }
373        }
374
375        self.base.attribute_update_time = Some(Instant::now());
376    }
377
378    /// Build the bind groups for this draw from the shader's metadata.
379    /// Returns false when the draw must be skipped (C++ `return`).
380    fn build_bind_groups(&mut self, context: &Context, render_pass: &RenderPass, shader: &ShaderProgram) -> bool {
381        self.impl_.bind_groups.clear();
382        let Some(device) = context.get_backend().get_device() else {
383            return true;
384        };
385        let draw_call_count = DRAW_CALL_COUNT.with(Cell::get);
386        let global_buffers = render_pass.get_global_uniform_buffers();
387        let textures = &self.base.textures;
388        let find_texture_for_binding =
389            |binding: u32, sampler_binding: bool| -> Option<Rc<RefCell<dyn mln_gfx::texture2d::Texture2D>>> {
390                for (tex_index, texture) in textures.iter().enumerate() {
391                    let Some(texture) = texture else { continue };
392                    if let Some(location) = shader.get_sampler_location_of(tex_index) {
393                        let location = location as u32;
394                        if (sampler_binding && location == binding)
395                            || (!sampler_binding && (location == binding || location + 1 == binding))
396                        {
397                            return Some(texture.clone());
398                        }
399                    }
400                }
401                None
402            };
403
404        let group_order = shader.get_bind_group_order().to_vec();
405        for (slot, &group) in group_order.iter().enumerate() {
406            let Some(layout) = shader.get_bind_group_layout(group) else {
407                eprintln!(
408                    "WebGPU: missing bind group layout for group {group} in shader '{}'",
409                    shader.get_shader_name()
410                );
411                return false;
412            };
413            let binding_infos = shader.get_binding_infos_for_group(group);
414
415            let mut resources: Vec<(u32, EntryResource)> = Vec::with_capacity(binding_infos.len());
416            let mut valid_bindings = true;
417            for binding_info in binding_infos {
418                match binding_info.type_ {
419                    BindingType::UniformBuffer | BindingType::ReadOnlyStorageBuffer | BindingType::StorageBuffer => {
420                        let mut buffer = self.impl_.uniform_buffers.get(binding_info.binding as usize).cloned();
421                        if binding_info.binding as usize == ID_GLOBAL_UBO_INDEX {
422                            let index_data = GlobalUBOIndexData { value: self.base.ubo_index, pad: [0; 3] };
423                            context.emplace_or_update_uniform_buffer(
424                                &mut self.impl_.ubo_index_uniform,
425                                bytemuck::bytes_of(&index_data),
426                                false,
427                            );
428                            if let Some(ubo) = self.impl_.ubo_index_uniform.clone() {
429                                self.impl_.uniform_buffers.set(binding_info.binding as usize, Some(ubo.clone()));
430                                buffer = Some(ubo);
431                            }
432                        }
433                        if buffer.is_none()
434                            && let Some(globals) = &global_buffers
435                        {
436                            buffer = globals.get(binding_info.binding as usize).cloned();
437                        }
438                        let Some(buffer) = buffer else {
439                            if draw_call_count <= 200 {
440                                eprintln!(
441                                    "No buffer found for binding {} type={} group={group}",
442                                    binding_info.binding, binding_info.type_ as i32
443                                );
444                            }
445                            valid_bindings = false;
446                            break;
447                        };
448                        let gpu_buffer =
449                            buffer.as_any().downcast_ref::<UniformBuffer>().and_then(|b| b.get_buffer().cloned());
450                        let Some(gpu_buffer) = gpu_buffer else {
451                            if draw_call_count <= 200 {
452                                eprintln!(
453                                    "Uniform buffer missing GPU handle for binding {} group={group}",
454                                    binding_info.binding
455                                );
456                            }
457                            valid_bindings = false;
458                            break;
459                        };
460                        resources
461                            .push((binding_info.binding, EntryResource::Buffer(gpu_buffer, buffer.get_size() as u64)));
462                    }
463                    BindingType::Sampler => {
464                        let Some(texture) = find_texture_for_binding(binding_info.binding, true) else {
465                            valid_bindings = false;
466                            break;
467                        };
468                        let mut texture = texture.borrow_mut();
469                        let Some(texture) = texture.as_any_mut().downcast_mut::<Texture2D>() else {
470                            valid_bindings = false;
471                            break;
472                        };
473                        if texture.get_sampler().is_none() {
474                            let state = *texture.get_sampler_state();
475                            texture.set_sampler_configuration(state);
476                        }
477                        let Some(sampler) = texture.get_sampler().cloned() else {
478                            valid_bindings = false;
479                            break;
480                        };
481                        resources.push((binding_info.binding, EntryResource::Sampler(sampler)));
482                    }
483                    BindingType::Texture | BindingType::UnfilterableTexture => {
484                        let Some(texture) = find_texture_for_binding(binding_info.binding, false) else {
485                            valid_bindings = false;
486                            break;
487                        };
488                        let mut texture = texture.borrow_mut();
489                        let Some(texture) = texture.as_any_mut().downcast_mut::<Texture2D>() else {
490                            valid_bindings = false;
491                            break;
492                        };
493                        if texture.get_texture().is_none() || texture.get_texture_view().is_none() {
494                            texture.create();
495                        }
496                        let Some(view) = texture.get_texture_view().cloned() else {
497                            valid_bindings = false;
498                            break;
499                        };
500                        resources.push((binding_info.binding, EntryResource::TextureView(view)));
501                    }
502                }
503            }
504
505            if !valid_bindings || resources.is_empty() {
506                eprintln!("WebGPU: invalid bindings for drawable '{}' (group={group}, slot={slot})", self.base.name);
507                return false;
508            }
509
510            let entries: Vec<wgpu::BindGroupEntry<'_>> = resources
511                .iter()
512                .map(|(binding, resource)| wgpu::BindGroupEntry {
513                    binding: *binding,
514                    resource: match resource {
515                        EntryResource::Buffer(buffer, size) => wgpu::BindingResource::Buffer(wgpu::BufferBinding {
516                            buffer,
517                            offset: 0,
518                            size: wgpu::BufferSize::new(*size),
519                        }),
520                        EntryResource::Sampler(sampler) => wgpu::BindingResource::Sampler(sampler),
521                        EntryResource::TextureView(view) => wgpu::BindingResource::TextureView(view),
522                    },
523                })
524                .collect();
525            let label = format!("{} bind-group {group}", self.base.name);
526            let bind_group =
527                device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some(&label), layout, entries: &entries });
528            self.impl_.bind_groups.push(BindGroupRecord { slot: slot as u32, group, handle: bind_group });
529        }
530        true
531    }
532}
533
534impl ShaderProgram {
535    fn get_sampler_location_of(&self, id: usize) -> Option<usize> {
536        mln_gfx::shaders::shader_program_base::ShaderProgramBase::get_sampler_location(self, id)
537    }
538}
539
540/// `UniqueBinding` in `Drawable::draw`
541struct UniqueBinding {
542    vertex_resource: Rc<dyn mln_gfx::vertex_buffer::VertexBufferResource>,
543    buffer: Option<wgpu::Buffer>,
544    buffer_size: u64,
545    stride: u32,
546    base_offset: u64,
547    step_mode: wgpu::VertexStepMode,
548    attributes: Vec<wgpu::VertexAttribute>,
549    attribute_byte_offsets: Vec<u64>,
550}
551
552fn accumulate_bindings(source: &AttributeBindingArray, step_mode: wgpu::VertexStepMode, out: &mut Vec<UniqueBinding>) {
553    for (attribute_index, binding) in source.iter().enumerate() {
554        let Some(binding) = binding else { continue };
555        let Some(resource) = &binding.vertex_buffer_resource else { continue };
556        let Some(vertex_buffer_res) = resource.as_any().downcast_ref::<VertexBufferResource>() else {
557            continue;
558        };
559        let (buffer, buffer_size) = {
560            let b = vertex_buffer_res.get_buffer();
561            (b.get_buffer().cloned(), b.get_size_in_bytes() as u64)
562        };
563        if buffer.is_none() {
564            continue;
565        }
566        let binding_byte_offset = u64::from(binding.vertex_offset) * u64::from(binding.vertex_stride);
567        let pos = out.iter().position(|e| {
568            std::ptr::addr_eq(Rc::as_ptr(&e.vertex_resource), Rc::as_ptr(resource))
569                && e.stride == binding.vertex_stride
570                && e.step_mode == step_mode
571        });
572        let entry = match pos {
573            None => {
574                out.push(UniqueBinding {
575                    vertex_resource: resource.clone(),
576                    buffer,
577                    buffer_size,
578                    stride: binding.vertex_stride,
579                    base_offset: binding_byte_offset,
580                    step_mode,
581                    attributes: Vec::with_capacity(4),
582                    attribute_byte_offsets: Vec::with_capacity(4),
583                });
584                out.last_mut().unwrap()
585            }
586            Some(i) => {
587                let e = &mut out[i];
588                e.base_offset = e.base_offset.min(binding_byte_offset);
589                e
590            }
591        };
592        entry.attributes.push(wgpu::VertexAttribute {
593            format: wgpu_vertex_format_of(binding.attribute.data_type),
594            offset: u64::from(binding.attribute.offset),
595            shader_location: attribute_index as u32,
596        });
597        entry.attribute_byte_offsets.push(binding_byte_offset);
598    }
599}
600
601impl drawable::Drawable for Drawable {
602    fn base(&self) -> &DrawableBase {
603        &self.base
604    }
605    fn base_mut(&mut self) -> &mut DrawableBase {
606        &mut self.base
607    }
608    fn as_any(&self) -> &dyn Any {
609        self
610    }
611    fn as_any_mut(&mut self) -> &mut dyn Any {
612        self
613    }
614
615    fn draw(&mut self, parameters: &mut dyn PaintParameters) {
616        let draw_call_count = DRAW_CALL_COUNT.with(|c| {
617            c.set(c.get() + 1);
618            c.get()
619        });
620        if self.base.is_custom {
621            return;
622        }
623
624        // Get WebGPU context and render pass (following Metal's pattern)
625        let parameters: &dyn PaintParameters = parameters;
626        let Some(context) = parameters.context().as_any().downcast_ref::<Context>() else {
627            return;
628        };
629        let Some(render_pass) = parameters.render_pass().and_then(|p| p.as_any().downcast_ref::<RenderPass>()) else {
630            eprintln!("No render pass encoder available");
631            debug_assert!(false);
632            return;
633        };
634        if !render_pass.has_encoder() {
635            eprintln!("No render pass encoder available");
636            debug_assert!(false);
637            return;
638        }
639
640        let Some(shader_ptr) = self.base.shader.clone() else {
641            eprintln!("Missing shader for drawable {}/{}", self.base.unique_id, self.base.name);
642            debug_assert!(false);
643            return;
644        };
645        if !self.base.enabled {
646            return;
647        }
648
649        let backend = context.get_backend();
650        if backend.get_device().is_none() || backend.get_queue().is_none() {
651            return;
652        }
653
654        // Bind uniform buffers (a no-op in WebGPU, see UniformBufferArray).
655
656        // Check index buffer is valid (like Metal does)
657        if let Some(indexes) = &self.impl_.indexes {
658            let indexes = indexes.borrow();
659            if indexes.get_buffer().is_none() || indexes.get_dirty() {
660                debug_assert!(false, "Index buffer not uploaded");
661                return;
662            }
663        }
664
665        // Build bind groups based on shader metadata
666        let Some(shader) = as_webgpu_shader(&shader_ptr) else {
667            return;
668        };
669        if !self.build_bind_groups(context, render_pass, shader) {
670            return;
671        }
672
673        let drawable_tile_id = self.base.tile_id;
674        let mut depth_mode = DepthMode::disabled();
675        let mut stencil_mode = StencilMode::disabled();
676        if self.base.is_3d {
677            depth_mode = self.impl_.depth_mode;
678            stencil_mode = self.impl_.stencil_mode;
679        } else {
680            if self.base.enable_depth {
681                depth_mode = parameters.depth_mode_for_sublayer(self.base.sub_layer_index as u8, self.base.depth_type);
682            }
683            if self.base.enable_stencil
684                && let Some(tile_id) = drawable_tile_id
685            {
686                stencil_mode = parameters.stencil_mode_for_clipping(&tile_id.to_unwrapped());
687            }
688        }
689
690        let new_stencil_hash = hash_stencil_mode(&stencil_mode);
691        if !self.impl_.stencil_mode_hash_valid
692            || self.impl_.stencil_mode_hash != new_stencil_hash
693            || self.impl_.depth_mode.func != depth_mode.func
694            || self.impl_.depth_mode.mask != depth_mode.mask
695        {
696            self.impl_.pipeline_state = None;
697            self.impl_.stencil_mode_hash_valid = true;
698        }
699        self.impl_.depth_mode = depth_mode;
700        self.impl_.stencil_mode = stencil_mode;
701        self.impl_.stencil_mode_hash = new_stencil_hash;
702        self.impl_.previous_stencil_mode = stencil_mode;
703
704        let mut unique_bindings: Vec<UniqueBinding> =
705            Vec::with_capacity(self.impl_.attribute_bindings.len() + self.impl_.instance_bindings.len());
706        accumulate_bindings(&self.impl_.attribute_bindings, wgpu::VertexStepMode::Vertex, &mut unique_bindings);
707        accumulate_bindings(&self.impl_.instance_bindings, wgpu::VertexStepMode::Instance, &mut unique_bindings);
708
709        const MAX_VERTEX_BUFFER_SLOTS: usize = 8;
710        if unique_bindings.len() > MAX_VERTEX_BUFFER_SLOTS {
711            eprintln!(
712                "WebGPU: reducing vertex buffer bindings from {} to {MAX_VERTEX_BUFFER_SLOTS}",
713                unique_bindings.len()
714            );
715            unique_bindings.truncate(MAX_VERTEX_BUFFER_SLOTS);
716        }
717
718        for entry in &mut unique_bindings {
719            for j in 0..entry.attributes.len() {
720                if entry.attribute_byte_offsets[j] < entry.base_offset {
721                    continue;
722                }
723                let delta = entry.attribute_byte_offsets[j] - entry.base_offset;
724                entry.attributes[j].offset += u64::from(delta as u32);
725            }
726        }
727
728        if self.impl_.pipeline_state.is_none() {
729            // Create vertex layout from attribute bindings
730            let vertex_layouts: Vec<VertexLayout> = unique_bindings
731                .iter()
732                .map(|b| VertexLayout {
733                    array_stride: u64::from(b.stride),
734                    step_mode: b.step_mode,
735                    attributes: b.attributes.clone(),
736                })
737                .collect();
738            // Use the actual color mode from the drawable (like Metal does)
739            let color_mode = self.base.color_mode;
740            let draw_mode_type = self.impl_.segments.first().map_or(DrawModeType::Triangles, |s| s.get_mode().type_);
741            // Compute pipeline state hash for caching
742            let pipeline_hash =
743                hash_pipeline_state(&vertex_layouts, &color_mode, &depth_mode, &stencil_mode, draw_mode_type);
744            self.impl_.pipeline_state = shader.get_render_pipeline(
745                &vertex_layouts,
746                &color_mode,
747                &depth_mode,
748                &stencil_mode,
749                draw_mode_type,
750                Some(pipeline_hash),
751            );
752            if self.impl_.pipeline_state.is_none() {
753                eprintln!(
754                    "WebGPU: skipping pipeline creation for drawable '{}' (shader='{}')",
755                    self.base.name,
756                    mln_gfx::shader::Shader::type_name(shader)
757                );
758            }
759        }
760
761        let mut encoder_guard = render_pass.get_encoder();
762        let Some(encoder) = encoder_guard.as_mut() else {
763            eprintln!("renderPassEncoder is null!");
764            return;
765        };
766        let Some(pipeline) = &self.impl_.pipeline_state else {
767            eprintln!("WebGPU: no pipeline available for drawable '{}'; draw skipped", self.base.name);
768            return;
769        };
770        encoder.set_pipeline(pipeline);
771        if self.base.enable_stencil {
772            encoder.set_stencil_reference(stencil_mode.ref_ as u32);
773        }
774
775        // Clamp scissor to the current render pass size (not the default
776        // renderable, which may be different during offscreen passes).
777        {
778            let rt_size = render_pass.get_renderable_size();
779            let scissor = parameters.scissor_rect();
780            let sx = scissor.x as u32;
781            let sy = scissor.y as u32;
782            let sw = if sx < rt_size.width { scissor.width.min(rt_size.width - sx) } else { 0 };
783            let sh = if sy < rt_size.height { scissor.height.min(rt_size.height - sy) } else { 0 };
784            if sw > 0 && sh > 0 {
785                encoder.set_scissor_rect(sx, sy, sw, sh);
786            }
787        }
788
789        let mut buffer_slot = 0u32;
790        for binding in &unique_bindings {
791            let Some(buffer) = &binding.buffer else { continue };
792            let buffer_size = binding.buffer_size;
793            if binding.base_offset >= buffer_size {
794                eprintln!(
795                    "Skipping vertex buffer slot {buffer_slot} due to base offset {} >= size {buffer_size}",
796                    binding.base_offset
797                );
798                continue;
799            }
800            encoder.set_vertex_buffer(buffer_slot, buffer.slice(binding.base_offset..buffer_size));
801            buffer_slot += 1;
802        }
803
804        // Bind index buffer if present
805        if let Some(indexes) = &self.impl_.indexes {
806            let indexes = indexes.borrow();
807            if indexes.elements() > 0
808                && !indexes.get_dirty()
809                && let Some(index_buffer) = indexes.get_buffer().and_then(|b| b.as_any().downcast_ref::<IndexBuffer>())
810                && let Some(resource) = index_buffer.buffer.get_resource::<IndexBufferResource>()
811            {
812                let buffer_resource = resource.get_buffer();
813                if let Some(buffer) = buffer_resource.get_buffer() {
814                    // Always use Uint16 format for now
815                    encoder.set_index_buffer(
816                        buffer.slice(0..buffer_resource.get_size_in_bytes() as u64),
817                        wgpu::IndexFormat::Uint16,
818                    );
819                }
820            }
821        }
822
823        // Set bind groups
824        for record in &self.impl_.bind_groups {
825            encoder.set_bind_group(record.slot, &record.handle, &[]);
826        }
827
828        // Handle depth and stencil states (like Metal does). For 3D mode,
829        // stenciling is handled by the layer group.
830        if !self.base.is_3d {
831            if self.base.enable_stencil {
832                if let Some(tile_id) = self.base.tile_id {
833                    let expected_stencil = parameters.stencil_mode_for_clipping(&tile_id.to_unwrapped());
834                    if hash_stencil_mode(&expected_stencil) != hash_stencil_mode(&self.impl_.stencil_mode) {
835                        debug_assert!(false, "stencil mismatch");
836                        eprintln!("WebGPU drawable stencil mismatch for '{}' tile={tile_id}", self.base.name);
837                    }
838                    encoder.set_stencil_reference(expected_stencil.ref_ as u32);
839                }
840            } else {
841                // Reset the reference so subsequent drawables that re-enable
842                // stencilling start from a known value.
843                encoder.set_stencil_reference(0);
844            }
845            if self.base.enable_depth {
846                #[cfg(debug_assertions)]
847                {
848                    let expected_depth =
849                        parameters.depth_mode_for_sublayer(self.base.sub_layer_index as u8, self.base.depth_type);
850                    debug_assert!(expected_depth.func == self.impl_.depth_mode.func);
851                    debug_assert!(expected_depth.mask == self.impl_.depth_mode.mask);
852                }
853            }
854        }
855
856        // Draw indexed geometry - loop through segments (exactly like Metal does)
857        let instance_count = match &self.base.instance_attributes {
858            Some(attrs) => attrs.borrow().get_min_count() as u32,
859            None => 1,
860        };
861        let mut draw_calls = 0;
862        for segment in &self.impl_.segments {
863            let ml_segment = segment.get_segment();
864            if ml_segment.index_length > 0 {
865                let index_offset = ml_segment.index_offset as u32;
866                let base_vertex = ml_segment.vertex_offset as i32;
867                let base_instance = 0u32;
868                encoder.draw_indexed(
869                    index_offset..index_offset + ml_segment.index_length as u32,
870                    base_vertex,
871                    base_instance..base_instance + instance_count,
872                );
873                draw_calls += 1;
874            }
875        }
876        drop(encoder_guard);
877        if draw_calls > 0 {
878            let mut stats = context.rendering_stats_mut();
879            stats.num_draw_calls += draw_calls;
880            stats.total_draw_calls += draw_calls;
881        }
882        let _ = draw_call_count;
883    }
884
885    fn update_vertex_attributes(
886        &mut self,
887        vertices: Option<VertexAttributeArrayPtr>,
888        vertex_count: usize,
889        mode: DrawMode,
890        indexes: Option<IndexVectorBasePtr>,
891        segments: &[SegmentBase],
892    ) {
893        // Store the vertex attributes (base class method)
894        drawable::Drawable::set_vertex_attributes(self, vertices);
895        // Store vertex count
896        self.impl_.vertex_count = vertex_count;
897        // Handle segments
898        let draw_segs: Vec<UniqueDrawSegment> =
899            segments.iter().map(|seg| Box::new(DrawSegment::new(mode, seg.copy()))).collect();
900        // Set the index data with segments
901        self.set_index_data(indexes, draw_segs);
902    }
903
904    fn set_vertices(&mut self, data: Vec<u8>, count: usize, data_type: AttributeDataType) {
905        self.impl_.vertex_count = count;
906        self.impl_.vertex_type = data_type;
907        if count != 0 && data_type != AttributeDataType::Invalid && !data.is_empty() {
908            let attrs = self.base.vertex_attributes.get_or_insert_with(VertexAttributeArray::new_ptr).clone();
909            let mut attrs = attrs.borrow_mut();
910            if let Some(attrib) = attrs.set(self.impl_.vertex_attr_id, /*index=*/ -1, data_type, 0) {
911                attrib.set_raw_data(data);
912                attrib.set_stride(VertexAttribute::get_stride_of(data_type));
913            } else {
914                eprintln!("Vertex attribute type mismatch: {} / {}", self.base.name, self.impl_.vertex_attr_id);
915                debug_assert!(false);
916            }
917        }
918    }
919
920    fn set_index_data(&mut self, indexes: Option<IndexVectorBasePtr>, segments: Vec<UniqueDrawSegment>) {
921        self.impl_.indexes = indexes;
922        self.impl_.segments = segments;
923    }
924
925    fn get_uniform_buffers(&self) -> &UniformBufferArray {
926        &self.impl_.uniform_buffers
927    }
928
929    fn mutable_uniform_buffers(&mut self) -> &mut UniformBufferArray {
930        &mut self.impl_.uniform_buffers
931    }
932
933    fn set_color_mode(&mut self, value: &ColorMode) {
934        self.base.color_mode = *value;
935        self.impl_.pipeline_state = None; // Rebuild pipeline to honour new color mode
936    }
937
938    fn set_enable_stencil(&mut self, value: bool) {
939        if self.base.enable_stencil == value {
940            return;
941        }
942        self.base.enable_stencil = value;
943        self.impl_.pipeline_state = None; // Force recreation with new stencil state
944    }
945
946    fn set_enable_depth(&mut self, value: bool) {
947        if self.base.enable_depth == value {
948            return;
949        }
950        self.base.enable_depth = value;
951        self.impl_.pipeline_state = None; // Force recreation with new depth state
952    }
953
954    fn set_sub_layer_index(&mut self, value: i32) {
955        if self.base.sub_layer_index == value {
956            return;
957        }
958        self.base.sub_layer_index = value;
959    }
960
961    fn set_depth_type(&mut self, value: DepthMaskType) {
962        if self.base.depth_type == value {
963            return;
964        }
965        self.base.depth_type = value;
966        self.impl_.pipeline_state = None; // Force recreation with new depth mask
967    }
968
969    fn set_shader(&mut self, value: Option<ShaderProgramBasePtr>) {
970        if same_shader(&self.base.shader, &value) {
971            return;
972        }
973        self.base.shader = value;
974        self.impl_.pipeline_state = None; // Reset pipeline when shader changes
975    }
976}