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