1use std::cell::Cell;
6
7use canvas_traits::webgl::{
8 ActiveAttribInfo, WebGLCommand, WebGLError, WebGLResult, WebGLVersion, WebGLVertexArrayId,
9};
10
11use crate::dom::bindings::cell::{DomRefCell, Ref};
12use crate::dom::bindings::codegen::Bindings::WebGL2RenderingContextBinding::WebGL2RenderingContextConstants as constants2;
13use crate::dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants as constants;
14use crate::dom::bindings::root::{Dom, MutNullableDom};
15use crate::dom::webgl::webglbuffer::WebGLBuffer;
16use crate::dom::webgl::webglrenderingcontext::{Operation, WebGLRenderingContext};
17
18#[derive(JSTraceable, MallocSizeOf)]
19#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
20pub(crate) struct VertexArrayObject {
21 context: Dom<WebGLRenderingContext>,
22 #[no_trace]
23 id: Option<WebGLVertexArrayId>,
24 ever_bound: Cell<bool>,
25 is_deleted: Cell<bool>,
26 vertex_attribs: DomRefCell<Box<[VertexAttribData]>>,
27 element_array_buffer: MutNullableDom<WebGLBuffer>,
28}
29
30impl VertexArrayObject {
31 pub(crate) fn new(context: &WebGLRenderingContext, id: Option<WebGLVertexArrayId>) -> Self {
32 let max_vertex_attribs = context.limits().max_vertex_attribs as usize;
33 Self {
34 context: Dom::from_ref(context),
35 id,
36 ever_bound: Default::default(),
37 is_deleted: Default::default(),
38 vertex_attribs: DomRefCell::new(vec![Default::default(); max_vertex_attribs].into()),
39 element_array_buffer: Default::default(),
40 }
41 }
42
43 pub(crate) fn id(&self) -> Option<WebGLVertexArrayId> {
44 self.id
45 }
46
47 pub(crate) fn is_deleted(&self) -> bool {
48 self.is_deleted.get()
49 }
50
51 pub(crate) fn delete(&self, operation_fallibility: Operation) {
52 assert!(self.id.is_some());
53 if self.is_deleted.get() {
54 return;
55 }
56 self.is_deleted.set(true);
57 let cmd = WebGLCommand::DeleteVertexArray(self.id.unwrap());
58 match operation_fallibility {
59 Operation::Fallible => self.context.send_command_ignored(cmd),
60 Operation::Infallible => self.context.send_command(cmd),
61 }
62
63 for attrib_data in &**self.vertex_attribs.borrow() {
64 if let Some(buffer) = attrib_data.buffer() {
65 buffer.decrement_attached_counter(operation_fallibility);
66 }
67 }
68 if let Some(buffer) = self.element_array_buffer.get() {
69 buffer.decrement_attached_counter(operation_fallibility);
70 }
71 }
72
73 pub(crate) fn ever_bound(&self) -> bool {
74 self.ever_bound.get()
75 }
76
77 pub(crate) fn set_ever_bound(&self) {
78 self.ever_bound.set(true);
79 }
80
81 pub(crate) fn element_array_buffer(&self) -> &MutNullableDom<WebGLBuffer> {
82 &self.element_array_buffer
83 }
84
85 pub(crate) fn get_vertex_attrib(&self, index: u32) -> Option<Ref<'_, VertexAttribData>> {
86 Ref::filter_map(self.vertex_attribs.borrow(), |attribs| {
87 attribs.get(index as usize)
88 })
89 .ok()
90 }
91
92 pub(crate) fn set_vertex_attrib_type(&self, index: u32, type_: u32) {
93 self.vertex_attribs.borrow_mut()[index as usize].type_ = type_;
94 }
95
96 pub(crate) fn vertex_attrib_pointer(
97 &self,
98 index: u32,
99 size: i32,
100 type_: u32,
101 normalized: bool,
102 stride: i32,
103 offset: i64,
104 ) -> WebGLResult<()> {
105 let mut attribs = self.vertex_attribs.borrow_mut();
106 let data = attribs
107 .get_mut(index as usize)
108 .ok_or(WebGLError::InvalidValue)?;
109
110 if !(1..=4).contains(&size) {
111 return Err(WebGLError::InvalidValue);
112 }
113
114 if !(0..=255).contains(&stride) || offset < 0 {
117 return Err(WebGLError::InvalidValue);
118 }
119
120 let is_webgl2 = matches!(self.context.webgl_version(), WebGLVersion::WebGL2);
121
122 let bytes_per_component: i32 = match type_ {
123 constants::BYTE | constants::UNSIGNED_BYTE => 1,
124 constants::SHORT | constants::UNSIGNED_SHORT => 2,
125 constants::FLOAT => 4,
126 constants::INT | constants::UNSIGNED_INT if is_webgl2 => 4,
127 constants2::HALF_FLOAT if is_webgl2 => 2,
128 glow::FIXED if is_webgl2 => 4,
129 constants2::INT_2_10_10_10_REV | constants2::UNSIGNED_INT_2_10_10_10_REV
130 if is_webgl2 && size == 4 =>
131 {
132 4
133 },
134 _ => return Err(WebGLError::InvalidEnum),
135 };
136
137 if offset % bytes_per_component as i64 > 0 || stride % bytes_per_component > 0 {
138 return Err(WebGLError::InvalidOperation);
139 }
140
141 let buffer = self.context.array_buffer();
142 match buffer {
143 Some(ref buffer) => buffer.increment_attached_counter(),
144 None if offset != 0 => {
145 return Err(WebGLError::InvalidOperation);
147 },
148 _ => {},
149 }
150 self.context.send_command(WebGLCommand::VertexAttribPointer(
151 index,
152 size,
153 type_,
154 normalized,
155 stride,
156 offset as u32,
157 ));
158 if let Some(old) = data.buffer() {
159 old.decrement_attached_counter(Operation::Infallible);
160 }
161
162 *data = VertexAttribData {
163 enabled_as_array: data.enabled_as_array,
164 size: size as u8,
165 type_,
166 bytes_per_vertex: size as u8 * bytes_per_component as u8,
167 normalized,
168 stride: stride as u8,
169 offset: offset as u32,
170 buffer: buffer.map(|b| Dom::from_ref(&*b)),
171 divisor: data.divisor,
172 };
173
174 Ok(())
175 }
176
177 pub(crate) fn vertex_attrib_divisor(&self, index: u32, value: u32) {
178 self.vertex_attribs.borrow_mut()[index as usize].divisor = value;
179 }
180
181 pub(crate) fn enabled_vertex_attrib_array(&self, index: u32, value: bool) {
182 self.vertex_attribs.borrow_mut()[index as usize].enabled_as_array = value;
183 }
184
185 pub(crate) fn unbind_buffer(&self, buffer: &WebGLBuffer) {
186 for attrib in &mut **self.vertex_attribs.borrow_mut() {
187 if let Some(b) = attrib.buffer() {
188 if b.id() != buffer.id() {
189 continue;
190 }
191 b.decrement_attached_counter(Operation::Infallible);
192 }
193 attrib.buffer = None;
194 }
195 if self
196 .element_array_buffer
197 .get()
198 .is_some_and(|b| buffer == &*b)
199 {
200 buffer.decrement_attached_counter(Operation::Infallible);
201 self.element_array_buffer.set(None);
202 }
203 }
204
205 pub(crate) fn validate_for_draw(
206 &self,
207 required_len: u32,
208 instance_count: u32,
209 active_attribs: &[ActiveAttribInfo],
210 ) -> WebGLResult<()> {
211 let attribs = self.vertex_attribs.borrow();
213 if attribs
215 .iter()
216 .any(|data| data.enabled_as_array && data.buffer.is_none())
217 {
218 return Err(WebGLError::InvalidOperation);
219 }
220 let mut has_active_attrib = false;
221 let mut has_divisor_0 = false;
222 for active_info in active_attribs {
223 let Some(location) = active_info.location else {
224 continue;
225 };
226 has_active_attrib = true;
227 let attrib = &attribs[location as usize];
228 if attrib.divisor == 0 {
229 has_divisor_0 = true;
230 }
231 if !attrib.enabled_as_array {
232 continue;
233 }
234 if required_len > 0 && instance_count > 0 {
236 let max_vertices = attrib.max_vertices();
237 if attrib.divisor == 0 {
238 if max_vertices < required_len {
239 return Err(WebGLError::InvalidOperation);
240 }
241 } else if max_vertices
242 .checked_mul(attrib.divisor)
243 .is_some_and(|v| v < instance_count)
244 {
245 return Err(WebGLError::InvalidOperation);
246 }
247 }
248 }
249 if has_active_attrib && !has_divisor_0 {
250 return Err(WebGLError::InvalidOperation);
251 }
252 Ok(())
253 }
254}
255
256impl Drop for VertexArrayObject {
257 fn drop(&mut self) {
258 if self.id.is_some() {
259 self.delete(Operation::Fallible);
260 }
261 }
262}
263
264#[derive(Clone, JSTraceable, MallocSizeOf)]
265#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
266pub(crate) struct VertexAttribData {
267 pub(crate) enabled_as_array: bool,
268 pub(crate) size: u8,
269 pub(crate) type_: u32,
270 bytes_per_vertex: u8,
271 pub(crate) normalized: bool,
272 pub(crate) stride: u8,
273 pub(crate) offset: u32,
274 pub(crate) buffer: Option<Dom<WebGLBuffer>>,
275 pub(crate) divisor: u32,
276}
277
278impl Default for VertexAttribData {
279 #[cfg_attr(crown, allow(crown::unrooted_must_root))]
280 fn default() -> Self {
281 Self {
282 enabled_as_array: false,
283 size: 4,
284 type_: constants::FLOAT,
285 bytes_per_vertex: 16,
286 normalized: false,
287 stride: 0,
288 offset: 0,
289 buffer: None,
290 divisor: 0,
291 }
292 }
293}
294
295impl VertexAttribData {
296 pub(crate) fn buffer(&self) -> Option<&WebGLBuffer> {
297 self.buffer.as_deref()
298 }
299
300 pub(crate) fn max_vertices(&self) -> u32 {
301 let capacity = (self.buffer().unwrap().capacity() as u32).saturating_sub(self.offset);
302 if capacity < self.bytes_per_vertex as u32 {
303 0
304 } else if self.stride == 0 {
305 capacity / self.bytes_per_vertex as u32
306 } else if self.stride < self.bytes_per_vertex {
307 (capacity - (self.bytes_per_vertex - self.stride) as u32) / self.stride as u32
308 } else {
309 let mut max = capacity / self.stride as u32;
310 if capacity % self.stride as u32 >= self.bytes_per_vertex as u32 {
311 max += 1;
312 }
313 max
314 }
315 }
316}