1use std::cell::Cell;
6use std::cmp;
7use std::ptr::{self, NonNull};
8#[cfg(feature = "webxr")]
9use std::rc::Rc;
10
11#[cfg(feature = "webgl_backtrace")]
12use backtrace::Backtrace;
13use base::generic_channel::GenericSharedMemory;
14use base::{Epoch, generic_channel};
15use bitflags::bitflags;
16use canvas_traits::webgl::WebGLError::*;
17use canvas_traits::webgl::{
18 AlphaTreatment, GLContextAttributes, GLLimits, GlType, Parameter, SizedDataType, TexDataType,
19 TexFormat, TexParameter, WebGLChan, WebGLCommand, WebGLCommandBacktrace, WebGLContextId,
20 WebGLError, WebGLFramebufferBindingRequest, WebGLMsg, WebGLMsgSender, WebGLProgramId,
21 WebGLResult, WebGLSLVersion, WebGLSendResult, WebGLVersion, YAxisTreatment, webgl_channel,
22};
23use dom_struct::dom_struct;
24use euclid::default::{Point2D, Rect, Size2D};
25use js::jsapi::{JSContext, JSObject, Type};
26use js::jsval::{BooleanValue, DoubleValue, Int32Value, NullValue, ObjectValue, UInt32Value};
27use js::rust::{CustomAutoRooterGuard, MutableHandleValue};
28use js::typedarray::{
29 ArrayBufferView, CreateWith, Float32, Float32Array, Int32, Int32Array, TypedArray,
30 TypedArrayElementCreator, Uint32Array,
31};
32use pixels::{self, Alpha, PixelFormat, Snapshot, SnapshotPixelFormat};
33use script_bindings::conversions::SafeToJSValConvertible;
34use serde::{Deserialize, Serialize};
35use servo_config::pref;
36use webrender_api::ImageKey;
37
38use crate::canvas_context::{CanvasContext, HTMLCanvasElementOrOffscreenCanvas};
39use crate::dom::bindings::cell::{DomRefCell, Ref, RefMut};
40use crate::dom::bindings::codegen::Bindings::ANGLEInstancedArraysBinding::ANGLEInstancedArraysConstants;
41use crate::dom::bindings::codegen::Bindings::EXTBlendMinmaxBinding::EXTBlendMinmaxConstants;
42use crate::dom::bindings::codegen::Bindings::OESVertexArrayObjectBinding::OESVertexArrayObjectConstants;
43use crate::dom::bindings::codegen::Bindings::WebGL2RenderingContextBinding::WebGL2RenderingContextConstants;
44use crate::dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::{
45 TexImageSource, WebGLContextAttributes, WebGLRenderingContextConstants as constants,
46 WebGLRenderingContextMethods,
47};
48use crate::dom::bindings::codegen::UnionTypes::{
49 ArrayBufferViewOrArrayBuffer, Float32ArrayOrUnrestrictedFloatSequence,
50 HTMLCanvasElementOrOffscreenCanvas as RootedHTMLCanvasElementOrOffscreenCanvas,
51 Int32ArrayOrLongSequence,
52};
53use crate::dom::bindings::conversions::DerivedFrom;
54use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
55use crate::dom::bindings::inheritance::Castable;
56use crate::dom::bindings::reflector::{DomGlobal, Reflector, reflect_dom_object};
57use crate::dom::bindings::root::{DomOnceCell, DomRoot, MutNullableDom};
58use crate::dom::bindings::str::DOMString;
59use crate::dom::event::{Event, EventBubbles, EventCancelable};
60#[cfg(feature = "webgl_backtrace")]
61use crate::dom::globalscope::GlobalScope;
62use crate::dom::node::NodeTraits;
63#[cfg(feature = "webxr")]
64use crate::dom::promise::Promise;
65use crate::dom::webgl::extensions::WebGLExtensions;
66use crate::dom::webgl::validations::WebGLValidator;
67use crate::dom::webgl::validations::tex_image_2d::{
68 CommonCompressedTexImage2DValidatorResult, CommonTexImage2DValidator,
69 CommonTexImage2DValidatorResult, CompressedTexImage2DValidator,
70 CompressedTexSubImage2DValidator, TexImage2DValidator, TexImage2DValidatorResult,
71};
72use crate::dom::webgl::validations::types::TexImageTarget;
73use crate::dom::webgl::vertexarrayobject::VertexAttribData;
74use crate::dom::webgl::webglactiveinfo::WebGLActiveInfo;
75use crate::dom::webgl::webglbuffer::WebGLBuffer;
76use crate::dom::webgl::webglcontextevent::WebGLContextEvent;
77use crate::dom::webgl::webglframebuffer::{
78 CompleteForRendering, WebGLFramebuffer, WebGLFramebufferAttachmentRoot,
79};
80use crate::dom::webgl::webglobject::WebGLObject;
81use crate::dom::webgl::webglprogram::WebGLProgram;
82use crate::dom::webgl::webglrenderbuffer::WebGLRenderbuffer;
83use crate::dom::webgl::webglshader::WebGLShader;
84use crate::dom::webgl::webglshaderprecisionformat::WebGLShaderPrecisionFormat;
85use crate::dom::webgl::webgltexture::{TexParameterValue, WebGLTexture};
86use crate::dom::webgl::webgluniformlocation::WebGLUniformLocation;
87use crate::dom::webgl::webglvertexarrayobject::WebGLVertexArrayObject;
88use crate::dom::webgl::webglvertexarrayobjectoes::WebGLVertexArrayObjectOES;
89use crate::dom::window::Window;
90use crate::script_runtime::{CanGc, JSContext as SafeJSContext};
91
92macro_rules! handle_object_deletion {
101 ($self_:expr, $binding:expr, $object:ident, $unbind_command:expr) => {
102 if let Some(bound_object) = $binding.get() {
103 if bound_object.id() == $object.id() {
104 $binding.set(None);
105 if let Some(command) = $unbind_command {
106 $self_.send_command(command);
107 }
108 }
109 }
110 };
111}
112
113fn has_invalid_blend_constants(arg1: u32, arg2: u32) -> bool {
114 match (arg1, arg2) {
115 (constants::CONSTANT_COLOR, constants::CONSTANT_ALPHA) => true,
116 (constants::ONE_MINUS_CONSTANT_COLOR, constants::ONE_MINUS_CONSTANT_ALPHA) => true,
117 (constants::ONE_MINUS_CONSTANT_COLOR, constants::CONSTANT_ALPHA) => true,
118 (constants::CONSTANT_COLOR, constants::ONE_MINUS_CONSTANT_ALPHA) => true,
119 (_, _) => false,
120 }
121}
122
123pub(crate) fn uniform_get<T, F>(triple: (&WebGLRenderingContext, WebGLProgramId, i32), f: F) -> T
124where
125 F: FnOnce(WebGLProgramId, i32, generic_channel::GenericSender<T>) -> WebGLCommand,
126 T: for<'de> Deserialize<'de> + Serialize,
127{
128 let (sender, receiver) = webgl_channel().unwrap();
129 triple.0.send_command(f(triple.1, triple.2, sender));
130 receiver.recv().unwrap()
131}
132
133#[expect(unsafe_code)]
134pub(crate) unsafe fn uniform_typed<T>(
135 cx: *mut JSContext,
136 value: &[T::Element],
137 mut retval: MutableHandleValue,
138) where
139 T: TypedArrayElementCreator,
140{
141 rooted!(in(cx) let mut rval = ptr::null_mut::<JSObject>());
142 unsafe {
143 <TypedArray<T, *mut JSObject>>::create(cx, CreateWith::Slice(value), rval.handle_mut())
144 }
145 .unwrap();
146 retval.set(ObjectValue(rval.get()));
147}
148
149#[derive(Clone, Copy, JSTraceable, MallocSizeOf)]
151pub(crate) struct TextureUnpacking(u8);
152
153bitflags! {
154 impl TextureUnpacking: u8 {
155 const FLIP_Y_AXIS = 0x01;
156 const PREMULTIPLY_ALPHA = 0x02;
157 const CONVERT_COLORSPACE = 0x04;
158 }
159}
160
161#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf)]
162pub(crate) enum VertexAttrib {
163 Float(f32, f32, f32, f32),
164 Int(i32, i32, i32, i32),
165 Uint(u32, u32, u32, u32),
166}
167
168#[derive(Clone, Copy, Debug)]
169pub(crate) enum Operation {
170 Fallible,
171 Infallible,
172}
173
174#[derive(JSTraceable, MallocSizeOf)]
175struct DroppableWebGLRenderingContext {
176 #[no_trace]
177 webgl_sender: WebGLMsgSender,
178}
179
180impl Drop for DroppableWebGLRenderingContext {
181 fn drop(&mut self) {
182 let _ = self.webgl_sender.send_remove();
183 }
184}
185
186#[dom_struct]
187pub(crate) struct WebGLRenderingContext {
188 reflector_: Reflector,
189 #[no_trace]
190 webgl_version: WebGLVersion,
191 #[no_trace]
192 glsl_version: WebGLSLVersion,
193 #[ignore_malloc_size_of = "Defined in surfman"]
194 #[no_trace]
195 limits: GLLimits,
196 canvas: HTMLCanvasElementOrOffscreenCanvas,
197 #[ignore_malloc_size_of = "Defined in canvas_traits"]
198 #[no_trace]
199 last_error: Cell<Option<WebGLError>>,
200 texture_packing_alignment: Cell<u8>,
201 texture_unpacking_settings: Cell<TextureUnpacking>,
202 texture_unpacking_alignment: Cell<u32>,
204 bound_draw_framebuffer: MutNullableDom<WebGLFramebuffer>,
205 bound_read_framebuffer: MutNullableDom<WebGLFramebuffer>,
208 bound_renderbuffer: MutNullableDom<WebGLRenderbuffer>,
209 bound_buffer_array: MutNullableDom<WebGLBuffer>,
210 current_program: MutNullableDom<WebGLProgram>,
211 current_vertex_attribs: DomRefCell<Box<[VertexAttrib]>>,
212 #[ignore_malloc_size_of = "Because it's small"]
213 current_scissor: Cell<(i32, i32, u32, u32)>,
214 #[ignore_malloc_size_of = "Because it's small"]
215 current_clear_color: Cell<(f32, f32, f32, f32)>,
216 #[no_trace]
217 size: Cell<Size2D<u32>>,
218 extension_manager: WebGLExtensions,
219 capabilities: Capabilities,
220 default_vao: DomOnceCell<WebGLVertexArrayObjectOES>,
221 current_vao: MutNullableDom<WebGLVertexArrayObjectOES>,
222 default_vao_webgl2: DomOnceCell<WebGLVertexArrayObject>,
223 current_vao_webgl2: MutNullableDom<WebGLVertexArrayObject>,
224 textures: Textures,
225 #[no_trace]
226 api_type: GlType,
227 droppable: DroppableWebGLRenderingContext,
228}
229
230impl WebGLRenderingContext {
231 #[cfg_attr(crown, expect(crown::unrooted_must_root))]
232 pub(crate) fn new_inherited(
233 window: &Window,
234 canvas: HTMLCanvasElementOrOffscreenCanvas,
235 webgl_version: WebGLVersion,
236 size: Size2D<u32>,
237 attrs: GLContextAttributes,
238 ) -> Result<WebGLRenderingContext, String> {
239 if pref!(webgl_testing_context_creation_error) {
240 return Err("WebGL context creation error forced by pref `webgl.testing.context_creation_error`".into());
241 }
242
243 let webgl_chan = match window.webgl_chan() {
244 Some(chan) => chan,
245 None => return Err("WebGL initialization failed early on".into()),
246 };
247
248 let (sender, receiver) = webgl_channel().unwrap();
249 webgl_chan
250 .send(WebGLMsg::CreateContext(
251 window.webview_id().into(),
252 webgl_version,
253 size,
254 attrs,
255 sender,
256 ))
257 .unwrap();
258 let result = receiver.recv().unwrap();
259
260 result.map(|ctx_data| {
261 let max_combined_texture_image_units = ctx_data.limits.max_combined_texture_image_units;
262 let max_vertex_attribs = ctx_data.limits.max_vertex_attribs as usize;
263 Self {
264 reflector_: Reflector::new(),
265 webgl_version,
266 glsl_version: ctx_data.glsl_version,
267 limits: ctx_data.limits,
268 canvas,
269 last_error: Cell::new(None),
270 texture_packing_alignment: Cell::new(4),
271 texture_unpacking_settings: Cell::new(TextureUnpacking::CONVERT_COLORSPACE),
272 texture_unpacking_alignment: Cell::new(4),
273 bound_draw_framebuffer: MutNullableDom::new(None),
274 bound_read_framebuffer: MutNullableDom::new(None),
275 bound_buffer_array: MutNullableDom::new(None),
276 bound_renderbuffer: MutNullableDom::new(None),
277 current_program: MutNullableDom::new(None),
278 current_vertex_attribs: DomRefCell::new(
279 vec![VertexAttrib::Float(0f32, 0f32, 0f32, 1f32); max_vertex_attribs].into(),
280 ),
281 current_scissor: Cell::new((0, 0, size.width, size.height)),
282 size: Cell::new(size),
285 current_clear_color: Cell::new((0.0, 0.0, 0.0, 0.0)),
286 extension_manager: WebGLExtensions::new(
287 webgl_version,
288 ctx_data.api_type,
289 ctx_data.glsl_version,
290 ),
291 capabilities: Default::default(),
292 default_vao: Default::default(),
293 current_vao: Default::default(),
294 default_vao_webgl2: Default::default(),
295 current_vao_webgl2: Default::default(),
296 textures: Textures::new(max_combined_texture_image_units),
297 api_type: ctx_data.api_type,
298 droppable: DroppableWebGLRenderingContext {
299 webgl_sender: ctx_data.sender,
300 },
301 }
302 })
303 }
304
305 #[cfg_attr(crown, expect(crown::unrooted_must_root))]
306 pub(crate) fn new(
307 window: &Window,
308 canvas: &RootedHTMLCanvasElementOrOffscreenCanvas,
309 webgl_version: WebGLVersion,
310 size: Size2D<u32>,
311 attrs: GLContextAttributes,
312 can_gc: CanGc,
313 ) -> Option<DomRoot<WebGLRenderingContext>> {
314 match WebGLRenderingContext::new_inherited(
315 window,
316 HTMLCanvasElementOrOffscreenCanvas::from(canvas),
317 webgl_version,
318 size,
319 attrs,
320 ) {
321 Ok(ctx) => Some(reflect_dom_object(Box::new(ctx), window, can_gc)),
322 Err(msg) => {
323 error!("Couldn't create WebGLRenderingContext: {}", msg);
324 let event = WebGLContextEvent::new(
325 window,
326 atom!("webglcontextcreationerror"),
327 EventBubbles::DoesNotBubble,
328 EventCancelable::Cancelable,
329 DOMString::from(msg),
330 can_gc,
331 );
332 match canvas {
333 RootedHTMLCanvasElementOrOffscreenCanvas::HTMLCanvasElement(canvas) => {
334 event.upcast::<Event>().fire(canvas.upcast(), can_gc);
335 },
336 RootedHTMLCanvasElementOrOffscreenCanvas::OffscreenCanvas(canvas) => {
337 event.upcast::<Event>().fire(canvas.upcast(), can_gc);
338 },
339 }
340 None
341 },
342 }
343 }
344
345 pub(crate) fn set_image_key(&self, image_key: ImageKey) {
346 self.droppable.webgl_sender.set_image_key(image_key);
347 }
348
349 pub(crate) fn update_rendering(&self, canvas_epoch: Epoch) -> bool {
350 if !self.onscreen() {
351 return false;
352 }
353
354 let global = self.global();
355 let Some(window) = global.downcast::<Window>() else {
356 return false;
357 };
358
359 window
360 .webgl_chan()
361 .expect("Where's the WebGL channel?")
362 .send(WebGLMsg::SwapBuffers(
363 vec![self.context_id()],
364 Some(canvas_epoch),
365 0, ))
367 .is_ok()
368 }
369
370 pub(crate) fn webgl_version(&self) -> WebGLVersion {
371 self.webgl_version
372 }
373
374 pub(crate) fn limits(&self) -> &GLLimits {
375 &self.limits
376 }
377
378 pub(crate) fn texture_unpacking_alignment(&self) -> u32 {
379 self.texture_unpacking_alignment.get()
380 }
381
382 pub(crate) fn bound_draw_framebuffer(&self) -> Option<DomRoot<WebGLFramebuffer>> {
383 self.bound_draw_framebuffer.get()
384 }
385
386 pub(crate) fn current_vao(&self) -> DomRoot<WebGLVertexArrayObjectOES> {
387 self.current_vao.or_init(|| {
388 DomRoot::from_ref(
389 self.default_vao
390 .init_once(|| WebGLVertexArrayObjectOES::new(self, None, CanGc::note())),
391 )
392 })
393 }
394
395 pub(crate) fn current_vao_webgl2(&self) -> DomRoot<WebGLVertexArrayObject> {
396 self.current_vao_webgl2.or_init(|| {
397 DomRoot::from_ref(
398 self.default_vao_webgl2
399 .init_once(|| WebGLVertexArrayObject::new(self, None, CanGc::note())),
400 )
401 })
402 }
403
404 pub(crate) fn current_vertex_attribs(&self) -> RefMut<'_, Box<[VertexAttrib]>> {
405 self.current_vertex_attribs.borrow_mut()
406 }
407
408 #[inline]
409 pub(crate) fn sender(&self) -> &WebGLMsgSender {
410 &self.droppable.webgl_sender
411 }
412
413 #[inline]
414 pub(crate) fn send_with_fallibility(&self, command: WebGLCommand, fallibility: Operation) {
415 let result = self
416 .droppable
417 .webgl_sender
418 .send(command, capture_webgl_backtrace());
419 if matches!(fallibility, Operation::Infallible) {
420 result.expect("Operation failed");
421 }
422 }
423
424 #[inline]
425 pub(crate) fn send_command(&self, command: WebGLCommand) {
426 self.send_with_fallibility(command, Operation::Infallible);
427 }
428
429 pub(crate) fn send_command_ignored(&self, command: WebGLCommand) {
430 self.send_with_fallibility(command, Operation::Fallible);
431 }
432
433 pub(crate) fn webgl_error(&self, err: WebGLError) {
434 warn!(
436 "WebGL error: {:?}, previous error was {:?}",
437 err,
438 self.last_error.get()
439 );
440
441 if self.last_error.get().is_none() {
444 self.last_error.set(Some(err));
445 }
446 }
447
448 pub(crate) fn validate_framebuffer(&self) -> WebGLResult<()> {
467 match self.bound_draw_framebuffer.get() {
468 Some(fb) => match fb.check_status_for_rendering() {
469 CompleteForRendering::Complete => Ok(()),
470 CompleteForRendering::Incomplete => Err(InvalidFramebufferOperation),
471 CompleteForRendering::MissingColorAttachment => Err(InvalidOperation),
472 },
473 None => Ok(()),
474 }
475 }
476
477 pub(crate) fn validate_ownership<T>(&self, object: &T) -> WebGLResult<()>
478 where
479 T: DerivedFrom<WebGLObject>,
480 {
481 let Some(context) = object.upcast().context() else {
482 return Err(WebGLError::InvalidOperation);
483 };
484 if !std::ptr::eq(self, &*context) {
485 return Err(WebGLError::InvalidOperation);
486 }
487 Ok(())
488 }
489
490 pub(crate) fn with_location<F>(&self, location: Option<&WebGLUniformLocation>, f: F)
491 where
492 F: FnOnce(&WebGLUniformLocation) -> WebGLResult<()>,
493 {
494 let location = match location {
495 Some(loc) => loc,
496 None => return,
497 };
498 match self.current_program.get() {
499 Some(ref program)
500 if program.id() == location.program_id() &&
501 program.link_generation() == location.link_generation() => {},
502 _ => return self.webgl_error(InvalidOperation),
503 }
504 handle_potential_webgl_error!(self, f(location));
505 }
506
507 pub(crate) fn textures(&self) -> &Textures {
508 &self.textures
509 }
510
511 fn tex_parameter(&self, target: u32, param: u32, value: TexParameterValue) {
512 let texture_slot = handle_potential_webgl_error!(
513 self,
514 self.textures
515 .active_texture_slot(target, self.webgl_version()),
516 return
517 );
518 let texture =
519 handle_potential_webgl_error!(self, texture_slot.get().ok_or(InvalidOperation), return);
520
521 if !self
522 .extension_manager
523 .is_get_tex_parameter_name_enabled(param)
524 {
525 return self.webgl_error(InvalidEnum);
526 }
527
528 handle_potential_webgl_error!(self, texture.tex_parameter(param, value), return);
529
530 if target != constants::TEXTURE_2D {
532 return;
533 }
534
535 let target = TexImageTarget::Texture2D;
536 if let Some(info) = texture.image_info_for_target(&target, 0) {
537 self.validate_filterable_texture(
538 &texture,
539 target,
540 0,
541 info.internal_format(),
542 Size2D::new(info.width(), info.height()),
543 info.data_type().unwrap_or(TexDataType::UnsignedByte),
544 );
545 }
546 }
547
548 fn vertex_attrib(&self, indx: u32, x: f32, y: f32, z: f32, w: f32) {
549 if indx >= self.limits.max_vertex_attribs {
550 return self.webgl_error(InvalidValue);
551 }
552
553 match self.webgl_version() {
554 WebGLVersion::WebGL1 => self
555 .current_vao()
556 .set_vertex_attrib_type(indx, constants::FLOAT),
557 WebGLVersion::WebGL2 => self
558 .current_vao_webgl2()
559 .set_vertex_attrib_type(indx, constants::FLOAT),
560 };
561 self.current_vertex_attribs.borrow_mut()[indx as usize] = VertexAttrib::Float(x, y, z, w);
562
563 self.send_command(WebGLCommand::VertexAttrib(indx, x, y, z, w));
564 }
565
566 pub(crate) fn get_current_framebuffer_size(&self) -> Option<(i32, i32)> {
567 match self.bound_draw_framebuffer.get() {
568 Some(fb) => fb.size(),
569
570 None => Some((self.DrawingBufferWidth(), self.DrawingBufferHeight())),
572 }
573 }
574
575 pub(crate) fn get_texture_packing_alignment(&self) -> u8 {
576 self.texture_packing_alignment.get()
577 }
578
579 pub(crate) fn get_current_unpack_state(
580 &self,
581 premultiplied: Alpha,
582 ) -> (Option<AlphaTreatment>, YAxisTreatment) {
583 let settings = self.texture_unpacking_settings.get();
584 let dest_premultiplied = settings.contains(TextureUnpacking::PREMULTIPLY_ALPHA);
585
586 let alpha_treatment = match (premultiplied, dest_premultiplied) {
587 (Alpha::Premultiplied, false) => Some(AlphaTreatment::Unmultiply),
588 (Alpha::NotPremultiplied, true) => Some(AlphaTreatment::Premultiply),
589 _ => None,
590 };
591
592 let y_axis_treatment = if settings.contains(TextureUnpacking::FLIP_Y_AXIS) {
593 YAxisTreatment::Flipped
594 } else {
595 YAxisTreatment::AsIs
596 };
597
598 (alpha_treatment, y_axis_treatment)
599 }
600
601 fn validate_filterable_texture(
604 &self,
605 texture: &WebGLTexture,
606 target: TexImageTarget,
607 level: u32,
608 internal_format: TexFormat,
609 size: Size2D<u32>,
610 data_type: TexDataType,
611 ) -> bool {
612 if self
613 .extension_manager
614 .is_filterable(data_type.as_gl_constant()) ||
615 !texture.is_using_linear_filtering()
616 {
617 return true;
618 }
619
620 let data_type = TexDataType::UnsignedByte;
623 let expected_byte_length = size.area() * 4;
624 let mut pixels = vec![0u8; expected_byte_length as usize];
625 for rgba8 in pixels.chunks_mut(4) {
626 rgba8[3] = 255u8;
627 }
628
629 self.tex_image_2d(
633 texture,
634 target,
635 data_type,
636 internal_format,
637 internal_format.to_unsized(),
638 level,
639 0,
640 1,
641 size,
642 TexSource::Pixels(TexPixels::new(
643 GenericSharedMemory::from_bytes(&pixels),
644 size,
645 PixelFormat::RGBA8,
646 None,
647 YAxisTreatment::AsIs,
648 )),
649 );
650
651 false
652 }
653
654 fn validate_stencil_actions(&self, action: u32) -> bool {
655 matches!(
656 action,
657 0 | constants::KEEP |
658 constants::REPLACE |
659 constants::INCR |
660 constants::DECR |
661 constants::INVERT |
662 constants::INCR_WRAP |
663 constants::DECR_WRAP
664 )
665 }
666
667 pub(crate) fn get_image_pixels(&self, source: TexImageSource) -> Fallible<Option<TexPixels>> {
668 Ok(Some(match source {
669 TexImageSource::ImageBitmap(bitmap) => {
670 if !bitmap.origin_is_clean() {
671 return Err(Error::Security(None));
672 }
673
674 let Some(snapshot) = bitmap.bitmap_data().clone() else {
675 return Ok(None);
676 };
677
678 let snapshot = snapshot.to_shared();
679 let size = snapshot.size().cast();
680 let format = match snapshot.format() {
681 SnapshotPixelFormat::RGBA => PixelFormat::RGBA8,
682 SnapshotPixelFormat::BGRA => PixelFormat::BGRA8,
683 };
684
685 TexPixels::new(
692 snapshot.shared_memory(),
693 size,
694 format,
695 None,
696 YAxisTreatment::AsIs,
697 )
698 },
699 TexImageSource::ImageData(image_data) => {
700 let (alpha_treatment, y_axis_treatment) =
701 self.get_current_unpack_state(Alpha::NotPremultiplied);
702
703 TexPixels::new(
704 image_data.to_shared_memory(),
705 image_data.get_size(),
706 PixelFormat::RGBA8,
707 alpha_treatment,
708 y_axis_treatment,
709 )
710 },
711 TexImageSource::HTMLImageElement(image) => {
712 let document = match self.canvas {
713 HTMLCanvasElementOrOffscreenCanvas::HTMLCanvasElement(ref canvas) => {
714 canvas.owner_document()
715 },
716 HTMLCanvasElementOrOffscreenCanvas::OffscreenCanvas(ref _canvas) => {
717 return Ok(None);
719 },
720 };
721 if !image.same_origin(document.origin()) {
722 return Err(Error::Security(None));
723 }
724
725 let Some(snapshot) = image.get_raster_image_data() else {
729 return Ok(None);
730 };
731
732 let snapshot = snapshot.to_shared();
733 let size = snapshot.size().cast();
734 let format: PixelFormat = match snapshot.format() {
735 SnapshotPixelFormat::RGBA => PixelFormat::RGBA8,
736 SnapshotPixelFormat::BGRA => PixelFormat::BGRA8,
737 };
738
739 let (alpha_treatment, y_axis_treatment) =
740 self.get_current_unpack_state(snapshot.alpha_mode().alpha());
741
742 TexPixels::new(
743 snapshot.shared_memory(),
744 size,
745 format,
746 alpha_treatment,
747 y_axis_treatment,
748 )
749 },
750 TexImageSource::HTMLCanvasElement(canvas) => {
754 if !canvas.origin_is_clean() {
755 return Err(Error::Security(None));
756 }
757
758 let Some(snapshot) = canvas.get_image_data() else {
759 return Ok(None);
760 };
761
762 let snapshot = snapshot.to_shared();
763 let size = snapshot.size().cast();
764 let format = match snapshot.format() {
765 SnapshotPixelFormat::RGBA => PixelFormat::RGBA8,
766 SnapshotPixelFormat::BGRA => PixelFormat::BGRA8,
767 };
768
769 let (alpha_treatment, y_axis_treatment) =
770 self.get_current_unpack_state(snapshot.alpha_mode().alpha());
771
772 TexPixels::new(
773 snapshot.shared_memory(),
774 size,
775 format,
776 alpha_treatment,
777 y_axis_treatment,
778 )
779 },
780 TexImageSource::HTMLVideoElement(video) => {
781 if !video.origin_is_clean() {
782 return Err(Error::Security(None));
783 }
784
785 let Some(snapshot) = video.get_current_frame_data() else {
786 return Ok(None);
787 };
788
789 let snapshot = snapshot.to_shared();
790 let size = snapshot.size().cast();
791 let format: PixelFormat = match snapshot.format() {
792 SnapshotPixelFormat::RGBA => PixelFormat::RGBA8,
793 SnapshotPixelFormat::BGRA => PixelFormat::BGRA8,
794 };
795
796 let (alpha_treatment, y_axis_treatment) =
797 self.get_current_unpack_state(snapshot.alpha_mode().alpha());
798
799 TexPixels::new(
800 snapshot.shared_memory(),
801 size,
802 format,
803 alpha_treatment,
804 y_axis_treatment,
805 )
806 },
807 }))
808 }
809
810 pub(crate) fn validate_tex_image_2d_data(
812 &self,
813 width: u32,
814 height: u32,
815 format: TexFormat,
816 data_type: TexDataType,
817 unpacking_alignment: u32,
818 data: Option<&ArrayBufferView>,
819 ) -> Result<u32, ()> {
820 let element_size = data_type.element_size();
821 let components_per_element = data_type.components_per_element();
822 let components = format.components();
823
824 let data_type_matches = data.as_ref().is_none_or(|buffer| {
832 Some(data_type.sized_data_type()) ==
833 array_buffer_type_to_sized_type(buffer.get_array_type()) &&
834 data_type.required_webgl_version() <= self.webgl_version()
835 });
836
837 if !data_type_matches {
838 self.webgl_error(InvalidOperation);
839 return Err(());
840 }
841
842 if height == 0 {
844 Ok(0)
845 } else {
846 let cpp = element_size * components / components_per_element;
851 let stride = (width * cpp + unpacking_alignment - 1) & !(unpacking_alignment - 1);
852 Ok(stride * (height - 1) + width * cpp)
853 }
854 }
855
856 #[allow(clippy::too_many_arguments)]
857 pub(crate) fn tex_image_2d(
858 &self,
859 texture: &WebGLTexture,
860 target: TexImageTarget,
861 data_type: TexDataType,
862 internal_format: TexFormat,
863 format: TexFormat,
864 level: u32,
865 _border: u32,
866 unpacking_alignment: u32,
867 size: Size2D<u32>,
868 source: TexSource,
869 ) {
870 handle_potential_webgl_error!(
872 self,
873 texture.initialize(
874 target,
875 size.width,
876 size.height,
877 1,
878 format,
879 level,
880 Some(data_type)
881 )
882 );
883
884 let internal_format = self
885 .extension_manager
886 .get_effective_tex_internal_format(internal_format, data_type.as_gl_constant());
887
888 let effective_data_type = self
889 .extension_manager
890 .effective_type(data_type.as_gl_constant());
891
892 match source {
893 TexSource::Pixels(pixels) => {
894 self.send_command(WebGLCommand::TexImage2D {
896 target: target.as_gl_constant(),
897 level,
898 internal_format,
899 size,
900 format,
901 data_type,
902 effective_data_type,
903 unpacking_alignment,
904 alpha_treatment: pixels.alpha_treatment,
905 y_axis_treatment: pixels.y_axis_treatment,
906 pixel_format: pixels.pixel_format,
907 data: pixels.data.into(),
908 });
909 },
910 TexSource::BufferOffset(offset) => {
911 self.send_command(WebGLCommand::TexImage2DPBO {
912 target: target.as_gl_constant(),
913 level,
914 internal_format,
915 size,
916 format,
917 effective_data_type,
918 unpacking_alignment,
919 offset,
920 });
921 },
922 }
923
924 if let Some(fb) = self.bound_draw_framebuffer.get() {
925 fb.invalidate_texture(texture);
926 }
927 }
928
929 #[allow(clippy::too_many_arguments)]
930 fn tex_sub_image_2d(
931 &self,
932 texture: DomRoot<WebGLTexture>,
933 target: TexImageTarget,
934 level: u32,
935 xoffset: i32,
936 yoffset: i32,
937 format: TexFormat,
938 data_type: TexDataType,
939 unpacking_alignment: u32,
940 pixels: TexPixels,
941 ) {
942 let image_info = match texture.image_info_for_target(&target, level) {
944 Some(info) => info,
945 None => return self.webgl_error(InvalidOperation),
946 };
947
948 if xoffset < 0 ||
953 (xoffset as u32 + pixels.size().width) > image_info.width() ||
954 yoffset < 0 ||
955 (yoffset as u32 + pixels.size().height) > image_info.height()
956 {
957 return self.webgl_error(InvalidValue);
958 }
959
960 debug_assert!(!format.is_sized());
962 if format != image_info.internal_format().to_unsized() {
963 return self.webgl_error(InvalidOperation);
964 }
965
966 if self.webgl_version() == WebGLVersion::WebGL1 &&
968 data_type != image_info.data_type().unwrap()
969 {
970 return self.webgl_error(InvalidOperation);
971 }
972
973 let effective_data_type = self
974 .extension_manager
975 .effective_type(data_type.as_gl_constant());
976
977 self.send_command(WebGLCommand::TexSubImage2D {
979 target: target.as_gl_constant(),
980 level,
981 xoffset,
982 yoffset,
983 size: pixels.size(),
984 format,
985 data_type,
986 effective_data_type,
987 unpacking_alignment,
988 alpha_treatment: pixels.alpha_treatment,
989 y_axis_treatment: pixels.y_axis_treatment,
990 pixel_format: pixels.pixel_format,
991 data: pixels.data.into(),
992 });
993 }
994
995 fn get_gl_extensions(&self) -> String {
996 let (sender, receiver) = webgl_channel().unwrap();
997 self.send_command(WebGLCommand::GetExtensions(sender));
998 receiver.recv().unwrap()
999 }
1000
1001 pub(crate) fn draw_arrays_instanced(
1003 &self,
1004 mode: u32,
1005 first: i32,
1006 count: i32,
1007 primcount: i32,
1008 ) -> WebGLResult<()> {
1009 match mode {
1010 constants::POINTS |
1011 constants::LINE_STRIP |
1012 constants::LINE_LOOP |
1013 constants::LINES |
1014 constants::TRIANGLE_STRIP |
1015 constants::TRIANGLE_FAN |
1016 constants::TRIANGLES => {},
1017 _ => {
1018 return Err(InvalidEnum);
1019 },
1020 }
1021 if first < 0 || count < 0 || primcount < 0 {
1022 return Err(InvalidValue);
1023 }
1024
1025 let current_program = self.current_program.get().ok_or(InvalidOperation)?;
1026
1027 let required_len = if count > 0 {
1028 first
1029 .checked_add(count)
1030 .map(|len| len as u32)
1031 .ok_or(InvalidOperation)?
1032 } else {
1033 0
1034 };
1035
1036 match self.webgl_version() {
1037 WebGLVersion::WebGL1 => self.current_vao().validate_for_draw(
1038 required_len,
1039 primcount as u32,
1040 ¤t_program.active_attribs(),
1041 )?,
1042 WebGLVersion::WebGL2 => self.current_vao_webgl2().validate_for_draw(
1043 required_len,
1044 primcount as u32,
1045 ¤t_program.active_attribs(),
1046 )?,
1047 };
1048
1049 self.validate_framebuffer()?;
1050
1051 if count == 0 || primcount == 0 {
1052 return Ok(());
1053 }
1054
1055 self.send_command(if primcount == 1 {
1056 WebGLCommand::DrawArrays { mode, first, count }
1057 } else {
1058 WebGLCommand::DrawArraysInstanced {
1059 mode,
1060 first,
1061 count,
1062 primcount,
1063 }
1064 });
1065 self.mark_as_dirty();
1066 Ok(())
1067 }
1068
1069 pub(crate) fn draw_elements_instanced(
1071 &self,
1072 mode: u32,
1073 count: i32,
1074 type_: u32,
1075 offset: i64,
1076 primcount: i32,
1077 ) -> WebGLResult<()> {
1078 match mode {
1079 constants::POINTS |
1080 constants::LINE_STRIP |
1081 constants::LINE_LOOP |
1082 constants::LINES |
1083 constants::TRIANGLE_STRIP |
1084 constants::TRIANGLE_FAN |
1085 constants::TRIANGLES => {},
1086 _ => {
1087 return Err(InvalidEnum);
1088 },
1089 }
1090 if count < 0 || offset < 0 || primcount < 0 {
1091 return Err(InvalidValue);
1092 }
1093 let type_size = match type_ {
1094 constants::UNSIGNED_BYTE => 1,
1095 constants::UNSIGNED_SHORT => 2,
1096 constants::UNSIGNED_INT => match self.webgl_version() {
1097 WebGLVersion::WebGL1 if self.extension_manager.is_element_index_uint_enabled() => 4,
1098 WebGLVersion::WebGL2 => 4,
1099 _ => return Err(InvalidEnum),
1100 },
1101 _ => return Err(InvalidEnum),
1102 };
1103 if offset % type_size != 0 {
1104 return Err(InvalidOperation);
1105 }
1106
1107 let current_program = self.current_program.get().ok_or(InvalidOperation)?;
1108 let array_buffer = match self.webgl_version() {
1109 WebGLVersion::WebGL1 => self.current_vao().element_array_buffer().get(),
1110 WebGLVersion::WebGL2 => self.current_vao_webgl2().element_array_buffer().get(),
1111 }
1112 .ok_or(InvalidOperation)?;
1113
1114 if count > 0 && primcount > 0 {
1115 let val = offset as u64 + (count as u64 * type_size as u64);
1117 if val > array_buffer.capacity() as u64 {
1118 return Err(InvalidOperation);
1119 }
1120 }
1121
1122 match self.webgl_version() {
1124 WebGLVersion::WebGL1 => self.current_vao().validate_for_draw(
1125 0,
1126 primcount as u32,
1127 ¤t_program.active_attribs(),
1128 )?,
1129 WebGLVersion::WebGL2 => self.current_vao_webgl2().validate_for_draw(
1130 0,
1131 primcount as u32,
1132 ¤t_program.active_attribs(),
1133 )?,
1134 };
1135
1136 self.validate_framebuffer()?;
1137
1138 if count == 0 || primcount == 0 {
1139 return Ok(());
1140 }
1141
1142 let offset = offset as u32;
1143 self.send_command(if primcount == 1 {
1144 WebGLCommand::DrawElements {
1145 mode,
1146 count,
1147 type_,
1148 offset,
1149 }
1150 } else {
1151 WebGLCommand::DrawElementsInstanced {
1152 mode,
1153 count,
1154 type_,
1155 offset,
1156 primcount,
1157 }
1158 });
1159 self.mark_as_dirty();
1160 Ok(())
1161 }
1162
1163 pub(crate) fn vertex_attrib_divisor(&self, index: u32, divisor: u32) {
1164 if index >= self.limits.max_vertex_attribs {
1165 return self.webgl_error(InvalidValue);
1166 }
1167
1168 match self.webgl_version() {
1169 WebGLVersion::WebGL1 => self.current_vao().vertex_attrib_divisor(index, divisor),
1170 WebGLVersion::WebGL2 => self
1171 .current_vao_webgl2()
1172 .vertex_attrib_divisor(index, divisor),
1173 };
1174 self.send_command(WebGLCommand::VertexAttribDivisor { index, divisor });
1175 }
1176
1177 pub(crate) fn array_buffer(&self) -> Option<DomRoot<WebGLBuffer>> {
1178 self.bound_buffer_array.get()
1179 }
1180
1181 pub(crate) fn array_buffer_slot(&self) -> &MutNullableDom<WebGLBuffer> {
1182 &self.bound_buffer_array
1183 }
1184
1185 pub(crate) fn bound_buffer(&self, target: u32) -> WebGLResult<Option<DomRoot<WebGLBuffer>>> {
1186 match target {
1187 constants::ARRAY_BUFFER => Ok(self.bound_buffer_array.get()),
1188 constants::ELEMENT_ARRAY_BUFFER => Ok(self.current_vao().element_array_buffer().get()),
1189 _ => Err(WebGLError::InvalidEnum),
1190 }
1191 }
1192
1193 pub(crate) fn buffer_usage(&self, usage: u32) -> WebGLResult<u32> {
1194 match usage {
1195 constants::STREAM_DRAW | constants::STATIC_DRAW | constants::DYNAMIC_DRAW => Ok(usage),
1196 _ => Err(WebGLError::InvalidEnum),
1197 }
1198 }
1199
1200 pub(crate) fn create_vertex_array(&self) -> Option<DomRoot<WebGLVertexArrayObjectOES>> {
1201 let (sender, receiver) = webgl_channel().unwrap();
1202 self.send_command(WebGLCommand::CreateVertexArray(sender));
1203 receiver
1204 .recv()
1205 .unwrap()
1206 .map(|id| WebGLVertexArrayObjectOES::new(self, Some(id), CanGc::note()))
1207 }
1208
1209 pub(crate) fn create_vertex_array_webgl2(&self) -> Option<DomRoot<WebGLVertexArrayObject>> {
1210 let (sender, receiver) = webgl_channel().unwrap();
1211 self.send_command(WebGLCommand::CreateVertexArray(sender));
1212 receiver
1213 .recv()
1214 .unwrap()
1215 .map(|id| WebGLVertexArrayObject::new(self, Some(id), CanGc::note()))
1216 }
1217
1218 pub(crate) fn delete_vertex_array(&self, vao: Option<&WebGLVertexArrayObjectOES>) {
1219 if let Some(vao) = vao {
1220 handle_potential_webgl_error!(self, self.validate_ownership(vao), return);
1221 assert!(vao.id().is_some());
1223 if vao.is_deleted() {
1224 return;
1225 }
1226 if vao == &*self.current_vao() {
1227 self.current_vao.set(None);
1230 self.send_command(WebGLCommand::BindVertexArray(None));
1231 }
1232 vao.delete(Operation::Infallible);
1233 }
1234 }
1235
1236 pub(crate) fn delete_vertex_array_webgl2(&self, vao: Option<&WebGLVertexArrayObject>) {
1237 if let Some(vao) = vao {
1238 handle_potential_webgl_error!(self, self.validate_ownership(vao), return);
1239 assert!(vao.id().is_some());
1241 if vao.is_deleted() {
1242 return;
1243 }
1244 if vao == &*self.current_vao_webgl2() {
1245 self.current_vao_webgl2.set(None);
1248 self.send_command(WebGLCommand::BindVertexArray(None));
1249 }
1250 vao.delete(Operation::Infallible);
1251 }
1252 }
1253
1254 pub(crate) fn is_vertex_array(&self, vao: Option<&WebGLVertexArrayObjectOES>) -> bool {
1255 vao.is_some_and(|vao| {
1256 assert!(vao.id().is_some());
1258 self.validate_ownership(vao).is_ok() && vao.ever_bound() && !vao.is_deleted()
1259 })
1260 }
1261
1262 pub(crate) fn is_vertex_array_webgl2(&self, vao: Option<&WebGLVertexArrayObject>) -> bool {
1263 vao.is_some_and(|vao| {
1264 assert!(vao.id().is_some());
1266 self.validate_ownership(vao).is_ok() && vao.ever_bound() && !vao.is_deleted()
1267 })
1268 }
1269
1270 pub(crate) fn bind_vertex_array(&self, vao: Option<&WebGLVertexArrayObjectOES>) {
1271 if let Some(vao) = vao {
1272 assert!(vao.id().is_some());
1274 handle_potential_webgl_error!(self, self.validate_ownership(vao), return);
1275 if vao.is_deleted() {
1276 return self.webgl_error(InvalidOperation);
1277 }
1278 vao.set_ever_bound();
1279 }
1280 self.send_command(WebGLCommand::BindVertexArray(vao.and_then(|vao| vao.id())));
1281 self.current_vao.set(vao);
1284 }
1285
1286 pub(crate) fn bind_vertex_array_webgl2(&self, vao: Option<&WebGLVertexArrayObject>) {
1287 if let Some(vao) = vao {
1288 assert!(vao.id().is_some());
1290 handle_potential_webgl_error!(self, self.validate_ownership(vao), return);
1291 if vao.is_deleted() {
1292 return self.webgl_error(InvalidOperation);
1293 }
1294 vao.set_ever_bound();
1295 }
1296 self.send_command(WebGLCommand::BindVertexArray(vao.and_then(|vao| vao.id())));
1297 self.current_vao_webgl2.set(vao);
1300 }
1301
1302 fn validate_blend_mode(&self, mode: u32) -> WebGLResult<()> {
1303 match mode {
1304 constants::FUNC_ADD | constants::FUNC_SUBTRACT | constants::FUNC_REVERSE_SUBTRACT => {
1305 Ok(())
1306 },
1307 EXTBlendMinmaxConstants::MIN_EXT | EXTBlendMinmaxConstants::MAX_EXT
1308 if self.extension_manager.is_blend_minmax_enabled() =>
1309 {
1310 Ok(())
1311 },
1312 _ => Err(InvalidEnum),
1313 }
1314 }
1315
1316 pub(crate) fn initialize_framebuffer(&self, clear_bits: u32) {
1317 if clear_bits == 0 {
1318 return;
1319 }
1320 self.send_command(WebGLCommand::InitializeFramebuffer {
1321 color: clear_bits & constants::COLOR_BUFFER_BIT != 0,
1322 depth: clear_bits & constants::DEPTH_BUFFER_BIT != 0,
1323 stencil: clear_bits & constants::STENCIL_BUFFER_BIT != 0,
1324 });
1325 }
1326
1327 pub(crate) fn extension_manager(&self) -> &WebGLExtensions {
1328 &self.extension_manager
1329 }
1330
1331 #[expect(unsafe_code)]
1332 pub(crate) fn buffer_data(
1333 &self,
1334 target: u32,
1335 data: Option<ArrayBufferViewOrArrayBuffer>,
1336 usage: u32,
1337 bound_buffer: Option<DomRoot<WebGLBuffer>>,
1338 ) {
1339 let data = handle_potential_webgl_error!(self, data.ok_or(InvalidValue), return);
1340 let bound_buffer =
1341 handle_potential_webgl_error!(self, bound_buffer.ok_or(InvalidOperation), return);
1342
1343 let data = unsafe {
1344 match data {
1346 ArrayBufferViewOrArrayBuffer::ArrayBuffer(ref data) => data.as_slice(),
1347 ArrayBufferViewOrArrayBuffer::ArrayBufferView(ref data) => data.as_slice(),
1348 }
1349 };
1350 handle_potential_webgl_error!(self, bound_buffer.buffer_data(target, data, usage));
1351 }
1352
1353 pub(crate) fn buffer_data_(
1354 &self,
1355 target: u32,
1356 size: i64,
1357 usage: u32,
1358 bound_buffer: Option<DomRoot<WebGLBuffer>>,
1359 ) {
1360 let bound_buffer =
1361 handle_potential_webgl_error!(self, bound_buffer.ok_or(InvalidOperation), return);
1362
1363 if size < 0 {
1364 return self.webgl_error(InvalidValue);
1365 }
1366
1367 let data = vec![0u8; size as usize];
1370 handle_potential_webgl_error!(self, bound_buffer.buffer_data(target, &data, usage));
1371 }
1372
1373 #[expect(unsafe_code)]
1374 pub(crate) fn buffer_sub_data(
1375 &self,
1376 target: u32,
1377 offset: i64,
1378 data: ArrayBufferViewOrArrayBuffer,
1379 bound_buffer: Option<DomRoot<WebGLBuffer>>,
1380 ) {
1381 let bound_buffer =
1382 handle_potential_webgl_error!(self, bound_buffer.ok_or(InvalidOperation), return);
1383
1384 if offset < 0 {
1385 return self.webgl_error(InvalidValue);
1386 }
1387
1388 let data = unsafe {
1389 match data {
1391 ArrayBufferViewOrArrayBuffer::ArrayBuffer(ref data) => data.as_slice(),
1392 ArrayBufferViewOrArrayBuffer::ArrayBufferView(ref data) => data.as_slice(),
1393 }
1394 };
1395 if (offset as u64) + data.len() as u64 > bound_buffer.capacity() as u64 {
1396 return self.webgl_error(InvalidValue);
1397 }
1398 let (sender, receiver) = generic_channel::channel().unwrap();
1399 self.send_command(WebGLCommand::BufferSubData(
1400 target,
1401 offset as isize,
1402 receiver,
1403 ));
1404 let buffer = GenericSharedMemory::from_bytes(data);
1405 sender.send(buffer).unwrap();
1406 }
1407
1408 pub(crate) fn bind_buffer_maybe(
1409 &self,
1410 slot: &MutNullableDom<WebGLBuffer>,
1411 target: u32,
1412 buffer: Option<&WebGLBuffer>,
1413 ) {
1414 if let Some(buffer) = buffer {
1415 handle_potential_webgl_error!(self, self.validate_ownership(buffer), return);
1416
1417 if buffer.is_marked_for_deletion() {
1418 return self.webgl_error(InvalidOperation);
1419 }
1420 handle_potential_webgl_error!(self, buffer.set_target_maybe(target), return);
1421 buffer.increment_attached_counter();
1422 }
1423
1424 self.send_command(WebGLCommand::BindBuffer(target, buffer.map(|b| b.id())));
1425 if let Some(old) = slot.get() {
1426 old.decrement_attached_counter(Operation::Infallible);
1427 }
1428
1429 slot.set(buffer);
1430 }
1431
1432 pub(crate) fn current_program(&self) -> Option<DomRoot<WebGLProgram>> {
1433 self.current_program.get()
1434 }
1435
1436 pub(crate) fn uniform_check_program(
1437 &self,
1438 program: &WebGLProgram,
1439 location: &WebGLUniformLocation,
1440 ) -> WebGLResult<()> {
1441 self.validate_ownership(program)?;
1442
1443 if program.is_deleted() ||
1444 !program.is_linked() ||
1445 self.context_id() != location.context_id() ||
1446 program.id() != location.program_id() ||
1447 program.link_generation() != location.link_generation()
1448 {
1449 return Err(InvalidOperation);
1450 }
1451
1452 Ok(())
1453 }
1454
1455 fn uniform_vec_section_int(
1456 &self,
1457 vec: Int32ArrayOrLongSequence,
1458 offset: u32,
1459 length: u32,
1460 uniform_size: usize,
1461 uniform_location: &WebGLUniformLocation,
1462 ) -> WebGLResult<Vec<i32>> {
1463 let vec = match vec {
1464 Int32ArrayOrLongSequence::Int32Array(v) => v.to_vec(),
1465 Int32ArrayOrLongSequence::LongSequence(v) => v,
1466 };
1467 self.uniform_vec_section::<i32>(vec, offset, length, uniform_size, uniform_location)
1468 }
1469
1470 fn uniform_vec_section_float(
1471 &self,
1472 vec: Float32ArrayOrUnrestrictedFloatSequence,
1473 offset: u32,
1474 length: u32,
1475 uniform_size: usize,
1476 uniform_location: &WebGLUniformLocation,
1477 ) -> WebGLResult<Vec<f32>> {
1478 let vec = match vec {
1479 Float32ArrayOrUnrestrictedFloatSequence::Float32Array(v) => v.to_vec(),
1480 Float32ArrayOrUnrestrictedFloatSequence::UnrestrictedFloatSequence(v) => v,
1481 };
1482 self.uniform_vec_section::<f32>(vec, offset, length, uniform_size, uniform_location)
1483 }
1484
1485 pub(crate) fn uniform_vec_section<T: Clone>(
1486 &self,
1487 vec: Vec<T>,
1488 offset: u32,
1489 length: u32,
1490 uniform_size: usize,
1491 uniform_location: &WebGLUniformLocation,
1492 ) -> WebGLResult<Vec<T>> {
1493 let offset = offset as usize;
1494 if offset > vec.len() {
1495 return Err(InvalidValue);
1496 }
1497
1498 let length = if length > 0 {
1499 length as usize
1500 } else {
1501 vec.len() - offset
1502 };
1503 if offset + length > vec.len() {
1504 return Err(InvalidValue);
1505 }
1506
1507 let vec = if offset == 0 && length == vec.len() {
1508 vec
1509 } else {
1510 vec[offset..offset + length].to_vec()
1511 };
1512
1513 if vec.len() < uniform_size || vec.len() % uniform_size != 0 {
1514 return Err(InvalidValue);
1515 }
1516 if uniform_location.size().is_none() && vec.len() != uniform_size {
1517 return Err(InvalidOperation);
1518 }
1519
1520 Ok(vec)
1521 }
1522
1523 pub(crate) fn uniform_matrix_section(
1524 &self,
1525 vec: Float32ArrayOrUnrestrictedFloatSequence,
1526 offset: u32,
1527 length: u32,
1528 transpose: bool,
1529 uniform_size: usize,
1530 uniform_location: &WebGLUniformLocation,
1531 ) -> WebGLResult<Vec<f32>> {
1532 let vec = match vec {
1533 Float32ArrayOrUnrestrictedFloatSequence::Float32Array(v) => v.to_vec(),
1534 Float32ArrayOrUnrestrictedFloatSequence::UnrestrictedFloatSequence(v) => v,
1535 };
1536 if transpose {
1537 return Err(InvalidValue);
1538 }
1539 self.uniform_vec_section::<f32>(vec, offset, length, uniform_size, uniform_location)
1540 }
1541
1542 pub(crate) fn get_draw_framebuffer_slot(&self) -> &MutNullableDom<WebGLFramebuffer> {
1543 &self.bound_draw_framebuffer
1544 }
1545
1546 pub(crate) fn get_read_framebuffer_slot(&self) -> &MutNullableDom<WebGLFramebuffer> {
1547 &self.bound_read_framebuffer
1548 }
1549
1550 pub(crate) fn validate_new_framebuffer_binding(
1551 &self,
1552 framebuffer: Option<&WebGLFramebuffer>,
1553 ) -> WebGLResult<()> {
1554 if let Some(fb) = framebuffer {
1555 self.validate_ownership(fb)?;
1556 if fb.is_deleted() {
1557 return Err(InvalidOperation);
1563 }
1564 }
1565 Ok(())
1566 }
1567
1568 pub(crate) fn bind_framebuffer_to(
1569 &self,
1570 target: u32,
1571 framebuffer: Option<&WebGLFramebuffer>,
1572 slot: &MutNullableDom<WebGLFramebuffer>,
1573 ) {
1574 match framebuffer {
1575 Some(framebuffer) => framebuffer.bind(target),
1576 None => {
1577 let cmd =
1579 WebGLCommand::BindFramebuffer(target, WebGLFramebufferBindingRequest::Default);
1580 self.send_command(cmd);
1581 },
1582 }
1583 slot.set(framebuffer);
1584 }
1585
1586 pub(crate) fn renderbuffer_storage(
1587 &self,
1588 target: u32,
1589 samples: i32,
1590 internal_format: u32,
1591 width: i32,
1592 height: i32,
1593 ) {
1594 if target != constants::RENDERBUFFER {
1595 return self.webgl_error(InvalidEnum);
1596 }
1597
1598 let max = self.limits.max_renderbuffer_size;
1599
1600 if samples < 0 || width < 0 || width as u32 > max || height < 0 || height as u32 > max {
1601 return self.webgl_error(InvalidValue);
1602 }
1603
1604 let rb = handle_potential_webgl_error!(
1605 self,
1606 self.bound_renderbuffer.get().ok_or(InvalidOperation),
1607 return
1608 );
1609 handle_potential_webgl_error!(
1610 self,
1611 rb.storage(self.api_type, samples, internal_format, width, height)
1612 );
1613 if let Some(fb) = self.bound_draw_framebuffer.get() {
1614 fb.invalidate_renderbuffer(&rb);
1615 }
1616
1617 }
1619
1620 pub(crate) fn valid_color_attachment_enum(&self, attachment: u32) -> bool {
1621 let last_slot = constants::COLOR_ATTACHMENT0 + self.limits().max_color_attachments - 1;
1622 constants::COLOR_ATTACHMENT0 <= attachment && attachment <= last_slot
1623 }
1624
1625 #[allow(clippy::too_many_arguments)]
1626 pub(crate) fn compressed_tex_image_2d(
1627 &self,
1628 target: u32,
1629 level: i32,
1630 internal_format: u32,
1631 width: i32,
1632 height: i32,
1633 border: i32,
1634 data: &[u8],
1635 ) {
1636 let validator = CompressedTexImage2DValidator::new(
1637 self,
1638 target,
1639 level,
1640 width,
1641 height,
1642 border,
1643 internal_format,
1644 data.len(),
1645 );
1646 let CommonCompressedTexImage2DValidatorResult {
1647 texture,
1648 target,
1649 level,
1650 width,
1651 height,
1652 compression,
1653 } = match validator.validate() {
1654 Ok(result) => result,
1655 Err(_) => return,
1656 };
1657
1658 if texture.is_immutable() {
1659 return self.webgl_error(InvalidOperation);
1660 }
1661
1662 let size = Size2D::new(width, height);
1663 let data = GenericSharedMemory::from_bytes(data);
1664
1665 handle_potential_webgl_error!(
1666 self,
1667 texture.initialize(
1668 target,
1669 size.width,
1670 size.height,
1671 1,
1672 compression.format,
1673 level,
1674 Some(TexDataType::UnsignedByte)
1675 )
1676 );
1677
1678 self.send_command(WebGLCommand::CompressedTexImage2D {
1679 target: target.as_gl_constant(),
1680 level,
1681 internal_format,
1682 size: Size2D::new(width, height),
1683 data: data.into(),
1684 });
1685
1686 if let Some(fb) = self.bound_draw_framebuffer.get() {
1687 fb.invalidate_texture(&texture);
1688 }
1689 }
1690
1691 #[allow(clippy::too_many_arguments)]
1692 pub(crate) fn compressed_tex_sub_image_2d(
1693 &self,
1694 target: u32,
1695 level: i32,
1696 xoffset: i32,
1697 yoffset: i32,
1698 width: i32,
1699 height: i32,
1700 format: u32,
1701 data: &[u8],
1702 ) {
1703 let validator = CompressedTexSubImage2DValidator::new(
1704 self,
1705 target,
1706 level,
1707 xoffset,
1708 yoffset,
1709 width,
1710 height,
1711 format,
1712 data.len(),
1713 );
1714 let CommonCompressedTexImage2DValidatorResult {
1715 texture: _,
1716 target,
1717 level,
1718 width,
1719 height,
1720 ..
1721 } = match validator.validate() {
1722 Ok(result) => result,
1723 Err(_) => return,
1724 };
1725
1726 let data = GenericSharedMemory::from_bytes(data);
1727
1728 self.send_command(WebGLCommand::CompressedTexSubImage2D {
1729 target: target.as_gl_constant(),
1730 level: level as i32,
1731 xoffset,
1732 yoffset,
1733 size: Size2D::new(width, height),
1734 format,
1735 data: data.into(),
1736 });
1737 }
1738
1739 pub(crate) fn uniform1iv(
1740 &self,
1741 location: Option<&WebGLUniformLocation>,
1742 val: Int32ArrayOrLongSequence,
1743 src_offset: u32,
1744 src_length: u32,
1745 ) {
1746 self.with_location(location, |location| {
1747 match location.type_() {
1748 constants::BOOL |
1749 constants::INT |
1750 constants::SAMPLER_2D |
1751 WebGL2RenderingContextConstants::SAMPLER_2D_ARRAY |
1752 WebGL2RenderingContextConstants::SAMPLER_3D |
1753 constants::SAMPLER_CUBE => {},
1754 _ => return Err(InvalidOperation),
1755 }
1756
1757 let val = self.uniform_vec_section_int(val, src_offset, src_length, 1, location)?;
1758
1759 match location.type_() {
1760 constants::SAMPLER_2D |
1761 constants::SAMPLER_CUBE |
1762 WebGL2RenderingContextConstants::SAMPLER_2D_ARRAY |
1763 WebGL2RenderingContextConstants::SAMPLER_3D => {
1764 for &v in val
1765 .iter()
1766 .take(cmp::min(location.size().unwrap_or(1) as usize, val.len()))
1767 {
1768 if v < 0 || v as u32 >= self.limits.max_combined_texture_image_units {
1769 return Err(InvalidValue);
1770 }
1771 }
1772 },
1773 _ => {},
1774 }
1775 self.send_command(WebGLCommand::Uniform1iv(location.id(), val));
1776 Ok(())
1777 });
1778 }
1779
1780 pub(crate) fn uniform1fv(
1781 &self,
1782 location: Option<&WebGLUniformLocation>,
1783 val: Float32ArrayOrUnrestrictedFloatSequence,
1784 src_offset: u32,
1785 src_length: u32,
1786 ) {
1787 self.with_location(location, |location| {
1788 match location.type_() {
1789 constants::BOOL | constants::FLOAT => {},
1790 _ => return Err(InvalidOperation),
1791 }
1792 let val = self.uniform_vec_section_float(val, src_offset, src_length, 1, location)?;
1793 self.send_command(WebGLCommand::Uniform1fv(location.id(), val));
1794 Ok(())
1795 });
1796 }
1797
1798 pub(crate) fn uniform2fv(
1799 &self,
1800 location: Option<&WebGLUniformLocation>,
1801 val: Float32ArrayOrUnrestrictedFloatSequence,
1802 src_offset: u32,
1803 src_length: u32,
1804 ) {
1805 self.with_location(location, |location| {
1806 match location.type_() {
1807 constants::BOOL_VEC2 | constants::FLOAT_VEC2 => {},
1808 _ => return Err(InvalidOperation),
1809 }
1810 let val = self.uniform_vec_section_float(val, src_offset, src_length, 2, location)?;
1811 self.send_command(WebGLCommand::Uniform2fv(location.id(), val));
1812 Ok(())
1813 });
1814 }
1815
1816 pub(crate) fn uniform2iv(
1817 &self,
1818 location: Option<&WebGLUniformLocation>,
1819 val: Int32ArrayOrLongSequence,
1820 src_offset: u32,
1821 src_length: u32,
1822 ) {
1823 self.with_location(location, |location| {
1824 match location.type_() {
1825 constants::BOOL_VEC2 | constants::INT_VEC2 => {},
1826 _ => return Err(InvalidOperation),
1827 }
1828 let val = self.uniform_vec_section_int(val, src_offset, src_length, 2, location)?;
1829 self.send_command(WebGLCommand::Uniform2iv(location.id(), val));
1830 Ok(())
1831 });
1832 }
1833
1834 pub(crate) fn uniform3fv(
1835 &self,
1836 location: Option<&WebGLUniformLocation>,
1837 val: Float32ArrayOrUnrestrictedFloatSequence,
1838 src_offset: u32,
1839 src_length: u32,
1840 ) {
1841 self.with_location(location, |location| {
1842 match location.type_() {
1843 constants::BOOL_VEC3 | constants::FLOAT_VEC3 => {},
1844 _ => return Err(InvalidOperation),
1845 }
1846 let val = self.uniform_vec_section_float(val, src_offset, src_length, 3, location)?;
1847 self.send_command(WebGLCommand::Uniform3fv(location.id(), val));
1848 Ok(())
1849 });
1850 }
1851
1852 pub(crate) fn uniform3iv(
1853 &self,
1854 location: Option<&WebGLUniformLocation>,
1855 val: Int32ArrayOrLongSequence,
1856 src_offset: u32,
1857 src_length: u32,
1858 ) {
1859 self.with_location(location, |location| {
1860 match location.type_() {
1861 constants::BOOL_VEC3 | constants::INT_VEC3 => {},
1862 _ => return Err(InvalidOperation),
1863 }
1864 let val = self.uniform_vec_section_int(val, src_offset, src_length, 3, location)?;
1865 self.send_command(WebGLCommand::Uniform3iv(location.id(), val));
1866 Ok(())
1867 });
1868 }
1869
1870 pub(crate) fn uniform4iv(
1871 &self,
1872 location: Option<&WebGLUniformLocation>,
1873 val: Int32ArrayOrLongSequence,
1874 src_offset: u32,
1875 src_length: u32,
1876 ) {
1877 self.with_location(location, |location| {
1878 match location.type_() {
1879 constants::BOOL_VEC4 | constants::INT_VEC4 => {},
1880 _ => return Err(InvalidOperation),
1881 }
1882 let val = self.uniform_vec_section_int(val, src_offset, src_length, 4, location)?;
1883 self.send_command(WebGLCommand::Uniform4iv(location.id(), val));
1884 Ok(())
1885 });
1886 }
1887
1888 pub(crate) fn uniform4fv(
1889 &self,
1890 location: Option<&WebGLUniformLocation>,
1891 val: Float32ArrayOrUnrestrictedFloatSequence,
1892 src_offset: u32,
1893 src_length: u32,
1894 ) {
1895 self.with_location(location, |location| {
1896 match location.type_() {
1897 constants::BOOL_VEC4 | constants::FLOAT_VEC4 => {},
1898 _ => return Err(InvalidOperation),
1899 }
1900 let val = self.uniform_vec_section_float(val, src_offset, src_length, 4, location)?;
1901 self.send_command(WebGLCommand::Uniform4fv(location.id(), val));
1902 Ok(())
1903 });
1904 }
1905
1906 pub(crate) fn uniform_matrix_2fv(
1907 &self,
1908 location: Option<&WebGLUniformLocation>,
1909 transpose: bool,
1910 val: Float32ArrayOrUnrestrictedFloatSequence,
1911 src_offset: u32,
1912 src_length: u32,
1913 ) {
1914 self.with_location(location, |location| {
1915 match location.type_() {
1916 constants::FLOAT_MAT2 => {},
1917 _ => return Err(InvalidOperation),
1918 }
1919 let val =
1920 self.uniform_matrix_section(val, src_offset, src_length, transpose, 4, location)?;
1921 self.send_command(WebGLCommand::UniformMatrix2fv(location.id(), val));
1922 Ok(())
1923 });
1924 }
1925
1926 pub(crate) fn uniform_matrix_3fv(
1927 &self,
1928 location: Option<&WebGLUniformLocation>,
1929 transpose: bool,
1930 val: Float32ArrayOrUnrestrictedFloatSequence,
1931 src_offset: u32,
1932 src_length: u32,
1933 ) {
1934 self.with_location(location, |location| {
1935 match location.type_() {
1936 constants::FLOAT_MAT3 => {},
1937 _ => return Err(InvalidOperation),
1938 }
1939 let val =
1940 self.uniform_matrix_section(val, src_offset, src_length, transpose, 9, location)?;
1941 self.send_command(WebGLCommand::UniformMatrix3fv(location.id(), val));
1942 Ok(())
1943 });
1944 }
1945
1946 pub(crate) fn uniform_matrix_4fv(
1947 &self,
1948 location: Option<&WebGLUniformLocation>,
1949 transpose: bool,
1950 val: Float32ArrayOrUnrestrictedFloatSequence,
1951 src_offset: u32,
1952 src_length: u32,
1953 ) {
1954 self.with_location(location, |location| {
1955 match location.type_() {
1956 constants::FLOAT_MAT4 => {},
1957 _ => return Err(InvalidOperation),
1958 }
1959 let val =
1960 self.uniform_matrix_section(val, src_offset, src_length, transpose, 16, location)?;
1961 self.send_command(WebGLCommand::UniformMatrix4fv(location.id(), val));
1962 Ok(())
1963 });
1964 }
1965
1966 pub(crate) fn get_buffer_param(
1967 &self,
1968 buffer: Option<DomRoot<WebGLBuffer>>,
1969 parameter: u32,
1970 mut retval: MutableHandleValue,
1971 ) {
1972 let buffer = handle_potential_webgl_error!(
1973 self,
1974 buffer.ok_or(InvalidOperation),
1975 return retval.set(NullValue())
1976 );
1977
1978 retval.set(match parameter {
1979 constants::BUFFER_SIZE => Int32Value(buffer.capacity() as i32),
1980 constants::BUFFER_USAGE => Int32Value(buffer.usage() as i32),
1981 _ => {
1982 self.webgl_error(InvalidEnum);
1983 NullValue()
1984 },
1985 })
1986 }
1987}
1988
1989impl CanvasContext for WebGLRenderingContext {
1990 type ID = WebGLContextId;
1991
1992 fn context_id(&self) -> Self::ID {
1993 self.droppable.webgl_sender.context_id()
1994 }
1995
1996 fn canvas(&self) -> Option<RootedHTMLCanvasElementOrOffscreenCanvas> {
1997 Some(RootedHTMLCanvasElementOrOffscreenCanvas::from(&self.canvas))
1998 }
1999
2000 fn resize(&self) {
2001 let size = self.size().cast();
2002 let (sender, receiver) = webgl_channel().unwrap();
2003 self.droppable
2004 .webgl_sender
2005 .send_resize(size, sender)
2006 .unwrap();
2007 self.size.set(size);
2010
2011 if let Err(msg) = receiver.recv().unwrap() {
2012 error!("Error resizing WebGLContext: {}", msg);
2013 return;
2014 };
2015
2016 let color = self.current_clear_color.get();
2019 self.send_command(WebGLCommand::ClearColor(color.0, color.1, color.2, color.3));
2020
2021 let rect = self.current_scissor.get();
2026 self.send_command(WebGLCommand::Scissor(rect.0, rect.1, rect.2, rect.3));
2027
2028 if let Some(texture) = self
2033 .textures
2034 .active_texture_slot(constants::TEXTURE_2D, self.webgl_version())
2035 .unwrap()
2036 .get()
2037 {
2038 self.send_command(WebGLCommand::BindTexture(
2039 constants::TEXTURE_2D,
2040 Some(texture.id()),
2041 ));
2042 }
2043
2044 if let Some(fbo) = self.bound_draw_framebuffer.get() {
2048 let id = WebGLFramebufferBindingRequest::Explicit(fbo.id());
2049 self.send_command(WebGLCommand::BindFramebuffer(constants::FRAMEBUFFER, id));
2050 }
2051 }
2052
2053 fn reset_bitmap(&self) {
2054 warn!("The WebGLRenderingContext 'reset_bitmap' is not implemented yet");
2055 }
2056
2057 fn get_image_data(&self) -> Option<Snapshot> {
2064 handle_potential_webgl_error!(self, self.validate_framebuffer(), return None);
2065 let mut size = self.size().cast();
2066
2067 let (fb_width, fb_height) = handle_potential_webgl_error!(
2068 self,
2069 self.get_current_framebuffer_size().ok_or(InvalidOperation),
2070 return None
2071 );
2072 size.width = cmp::min(size.width, fb_width as u32);
2073 size.height = cmp::min(size.height, fb_height as u32);
2074
2075 let (sender, receiver) = generic_channel::channel().unwrap();
2076 self.send_command(WebGLCommand::ReadPixels(
2077 Rect::from_size(size),
2078 constants::RGBA,
2079 constants::UNSIGNED_BYTE,
2080 sender,
2081 ));
2082 let (data, alpha_mode) = receiver.recv().unwrap();
2083 Some(Snapshot::from_vec(
2084 size.cast(),
2085 SnapshotPixelFormat::RGBA,
2086 alpha_mode,
2087 data.to_vec(),
2088 ))
2089 }
2090
2091 fn mark_as_dirty(&self) {
2092 if self.bound_draw_framebuffer.get().is_some() {
2094 return;
2095 }
2096
2097 if self.global().as_window().in_immersive_xr_session() {
2100 return;
2101 }
2102
2103 self.canvas.mark_as_dirty();
2104 }
2105}
2106
2107#[cfg(not(feature = "webgl_backtrace"))]
2108#[inline]
2109pub(crate) fn capture_webgl_backtrace() -> WebGLCommandBacktrace {
2110 WebGLCommandBacktrace {}
2111}
2112
2113#[cfg(feature = "webgl_backtrace")]
2114#[cfg_attr(feature = "webgl_backtrace", expect(unsafe_code))]
2115pub(crate) fn capture_webgl_backtrace() -> WebGLCommandBacktrace {
2116 let bt = Backtrace::new();
2117 unsafe {
2118 capture_stack!(in(*GlobalScope::get_cx()) let stack);
2119 WebGLCommandBacktrace {
2120 backtrace: format!("{:?}", bt),
2121 js_backtrace: stack.and_then(|s| s.as_string(None, js::jsapi::StackFormat::Default)),
2122 }
2123 }
2124}
2125
2126impl WebGLRenderingContextMethods<crate::DomTypeHolder> for WebGLRenderingContext {
2127 fn Canvas(&self) -> RootedHTMLCanvasElementOrOffscreenCanvas {
2129 RootedHTMLCanvasElementOrOffscreenCanvas::from(&self.canvas)
2130 }
2131
2132 fn Flush(&self) {
2134 self.send_command(WebGLCommand::Flush);
2135 }
2136
2137 fn Finish(&self) {
2139 let (sender, receiver) = webgl_channel().unwrap();
2140 self.send_command(WebGLCommand::Finish(sender));
2141 receiver.recv().unwrap()
2142 }
2143
2144 fn DrawingBufferWidth(&self) -> i32 {
2146 let (sender, receiver) = webgl_channel().unwrap();
2147 self.send_command(WebGLCommand::DrawingBufferWidth(sender));
2148 receiver.recv().unwrap()
2149 }
2150
2151 fn DrawingBufferHeight(&self) -> i32 {
2153 let (sender, receiver) = webgl_channel().unwrap();
2154 self.send_command(WebGLCommand::DrawingBufferHeight(sender));
2155 receiver.recv().unwrap()
2156 }
2157
2158 fn GetBufferParameter(
2160 &self,
2161 _cx: SafeJSContext,
2162 target: u32,
2163 parameter: u32,
2164 mut retval: MutableHandleValue,
2165 ) {
2166 let buffer = handle_potential_webgl_error!(
2167 self,
2168 self.bound_buffer(target),
2169 return retval.set(NullValue())
2170 );
2171 self.get_buffer_param(buffer, parameter, retval)
2172 }
2173
2174 #[expect(unsafe_code)]
2175 fn GetParameter(&self, cx: SafeJSContext, parameter: u32, mut retval: MutableHandleValue) {
2177 if !self
2178 .extension_manager
2179 .is_get_parameter_name_enabled(parameter)
2180 {
2181 self.webgl_error(WebGLError::InvalidEnum);
2182 return retval.set(NullValue());
2183 }
2184
2185 match parameter {
2186 constants::ARRAY_BUFFER_BINDING => {
2187 self.bound_buffer_array
2188 .get()
2189 .safe_to_jsval(cx, retval, CanGc::note());
2190 return;
2191 },
2192 constants::CURRENT_PROGRAM => {
2193 self.current_program
2194 .get()
2195 .safe_to_jsval(cx, retval, CanGc::note());
2196 return;
2197 },
2198 constants::ELEMENT_ARRAY_BUFFER_BINDING => {
2199 let buffer = self.current_vao().element_array_buffer().get();
2200 buffer.safe_to_jsval(cx, retval, CanGc::note());
2201 return;
2202 },
2203 constants::FRAMEBUFFER_BINDING => {
2204 self.bound_draw_framebuffer
2205 .get()
2206 .safe_to_jsval(cx, retval, CanGc::note());
2207 return;
2208 },
2209 constants::RENDERBUFFER_BINDING => {
2210 self.bound_renderbuffer
2211 .get()
2212 .safe_to_jsval(cx, retval, CanGc::note());
2213 return;
2214 },
2215 constants::TEXTURE_BINDING_2D => {
2216 let texture = self
2217 .textures
2218 .active_texture_slot(constants::TEXTURE_2D, self.webgl_version())
2219 .unwrap()
2220 .get();
2221 texture.safe_to_jsval(cx, retval, CanGc::note());
2222 return;
2223 },
2224 WebGL2RenderingContextConstants::TEXTURE_BINDING_2D_ARRAY => {
2225 let texture = self
2226 .textures
2227 .active_texture_slot(
2228 WebGL2RenderingContextConstants::TEXTURE_2D_ARRAY,
2229 self.webgl_version(),
2230 )
2231 .unwrap()
2232 .get();
2233 texture.safe_to_jsval(cx, retval, CanGc::note());
2234 return;
2235 },
2236 WebGL2RenderingContextConstants::TEXTURE_BINDING_3D => {
2237 let texture = self
2238 .textures
2239 .active_texture_slot(
2240 WebGL2RenderingContextConstants::TEXTURE_3D,
2241 self.webgl_version(),
2242 )
2243 .unwrap()
2244 .get();
2245 texture.safe_to_jsval(cx, retval, CanGc::note());
2246 return;
2247 },
2248 constants::TEXTURE_BINDING_CUBE_MAP => {
2249 let texture = self
2250 .textures
2251 .active_texture_slot(constants::TEXTURE_CUBE_MAP, self.webgl_version())
2252 .unwrap()
2253 .get();
2254 texture.safe_to_jsval(cx, retval, CanGc::note());
2255 return;
2256 },
2257 OESVertexArrayObjectConstants::VERTEX_ARRAY_BINDING_OES => {
2258 let vao = self.current_vao.get().filter(|vao| vao.id().is_some());
2259 vao.safe_to_jsval(cx, retval, CanGc::note());
2260 return;
2261 },
2262 constants::IMPLEMENTATION_COLOR_READ_FORMAT => {
2268 if self.validate_framebuffer().is_err() {
2269 self.webgl_error(InvalidOperation);
2270 return retval.set(NullValue());
2271 }
2272 return retval.set(Int32Value(constants::RGBA as i32));
2273 },
2274 constants::IMPLEMENTATION_COLOR_READ_TYPE => {
2275 if self.validate_framebuffer().is_err() {
2276 self.webgl_error(InvalidOperation);
2277 return retval.set(NullValue());
2278 }
2279 return retval.set(Int32Value(constants::UNSIGNED_BYTE as i32));
2280 },
2281 constants::COMPRESSED_TEXTURE_FORMATS => unsafe {
2282 let format_ids = self.extension_manager.get_tex_compression_ids();
2283
2284 rooted!(in(*cx) let mut rval = ptr::null_mut::<JSObject>());
2285 Uint32Array::create(*cx, CreateWith::Slice(&format_ids), rval.handle_mut())
2286 .unwrap();
2287 return retval.set(ObjectValue(rval.get()));
2288 },
2289 constants::VERSION => {
2290 "WebGL 1.0".safe_to_jsval(cx, retval, CanGc::note());
2291 return;
2292 },
2293 constants::RENDERER | constants::VENDOR => {
2294 "Mozilla/Servo".safe_to_jsval(cx, retval, CanGc::note());
2295 return;
2296 },
2297 constants::SHADING_LANGUAGE_VERSION => {
2298 "WebGL GLSL ES 1.0".safe_to_jsval(cx, retval, CanGc::note());
2299 return;
2300 },
2301 constants::UNPACK_FLIP_Y_WEBGL => {
2302 let unpack = self.texture_unpacking_settings.get();
2303 retval.set(BooleanValue(unpack.contains(TextureUnpacking::FLIP_Y_AXIS)));
2304 return;
2305 },
2306 constants::UNPACK_PREMULTIPLY_ALPHA_WEBGL => {
2307 let unpack = self.texture_unpacking_settings.get();
2308 retval.set(BooleanValue(
2309 unpack.contains(TextureUnpacking::PREMULTIPLY_ALPHA),
2310 ));
2311 return;
2312 },
2313 constants::PACK_ALIGNMENT => {
2314 retval.set(UInt32Value(self.texture_packing_alignment.get() as u32));
2315 return;
2316 },
2317 constants::UNPACK_ALIGNMENT => {
2318 retval.set(UInt32Value(self.texture_unpacking_alignment.get()));
2319 return;
2320 },
2321 constants::UNPACK_COLORSPACE_CONVERSION_WEBGL => {
2322 let unpack = self.texture_unpacking_settings.get();
2323 retval.set(UInt32Value(
2324 if unpack.contains(TextureUnpacking::CONVERT_COLORSPACE) {
2325 constants::BROWSER_DEFAULT_WEBGL
2326 } else {
2327 constants::NONE
2328 },
2329 ));
2330 return;
2331 },
2332 _ => {},
2333 }
2334
2335 let limit = match parameter {
2338 constants::MAX_VERTEX_ATTRIBS => Some(self.limits.max_vertex_attribs),
2339 constants::MAX_TEXTURE_SIZE => Some(self.limits.max_tex_size),
2340 constants::MAX_CUBE_MAP_TEXTURE_SIZE => Some(self.limits.max_cube_map_tex_size),
2341 constants::MAX_COMBINED_TEXTURE_IMAGE_UNITS => {
2342 Some(self.limits.max_combined_texture_image_units)
2343 },
2344 constants::MAX_FRAGMENT_UNIFORM_VECTORS => {
2345 Some(self.limits.max_fragment_uniform_vectors)
2346 },
2347 constants::MAX_RENDERBUFFER_SIZE => Some(self.limits.max_renderbuffer_size),
2348 constants::MAX_TEXTURE_IMAGE_UNITS => Some(self.limits.max_texture_image_units),
2349 constants::MAX_VARYING_VECTORS => Some(self.limits.max_varying_vectors),
2350 constants::MAX_VERTEX_TEXTURE_IMAGE_UNITS => {
2351 Some(self.limits.max_vertex_texture_image_units)
2352 },
2353 constants::MAX_VERTEX_UNIFORM_VECTORS => Some(self.limits.max_vertex_uniform_vectors),
2354 _ => None,
2355 };
2356 if let Some(limit) = limit {
2357 retval.set(UInt32Value(limit));
2358 return;
2359 }
2360
2361 if let Ok(value) = self.capabilities.is_enabled(parameter) {
2362 retval.set(BooleanValue(value));
2363 return;
2364 }
2365
2366 match handle_potential_webgl_error!(
2367 self,
2368 Parameter::from_u32(parameter),
2369 return retval.set(NullValue())
2370 ) {
2371 Parameter::Bool(param) => {
2372 let (sender, receiver) = webgl_channel().unwrap();
2373 self.send_command(WebGLCommand::GetParameterBool(param, sender));
2374 retval.set(BooleanValue(receiver.recv().unwrap()))
2375 },
2376 Parameter::Bool4(param) => {
2377 let (sender, receiver) = webgl_channel().unwrap();
2378 self.send_command(WebGLCommand::GetParameterBool4(param, sender));
2379 receiver
2380 .recv()
2381 .unwrap()
2382 .safe_to_jsval(cx, retval, CanGc::note());
2383 },
2384 Parameter::Int(param) => {
2385 let (sender, receiver) = webgl_channel().unwrap();
2386 self.send_command(WebGLCommand::GetParameterInt(param, sender));
2387 retval.set(Int32Value(receiver.recv().unwrap()))
2388 },
2389 Parameter::Int2(param) => unsafe {
2390 let (sender, receiver) = webgl_channel().unwrap();
2391 self.send_command(WebGLCommand::GetParameterInt2(param, sender));
2392 rooted!(in(*cx) let mut rval = ptr::null_mut::<JSObject>());
2393 Int32Array::create(
2394 *cx,
2395 CreateWith::Slice(&receiver.recv().unwrap()),
2396 rval.handle_mut(),
2397 )
2398 .unwrap();
2399 retval.set(ObjectValue(rval.get()))
2400 },
2401 Parameter::Int4(param) => unsafe {
2402 let (sender, receiver) = webgl_channel().unwrap();
2403 self.send_command(WebGLCommand::GetParameterInt4(param, sender));
2404 rooted!(in(*cx) let mut rval = ptr::null_mut::<JSObject>());
2405 Int32Array::create(
2406 *cx,
2407 CreateWith::Slice(&receiver.recv().unwrap()),
2408 rval.handle_mut(),
2409 )
2410 .unwrap();
2411 retval.set(ObjectValue(rval.get()))
2412 },
2413 Parameter::Float(param) => {
2414 let (sender, receiver) = webgl_channel().unwrap();
2415 self.send_command(WebGLCommand::GetParameterFloat(param, sender));
2416 retval.set(DoubleValue(receiver.recv().unwrap() as f64))
2417 },
2418 Parameter::Float2(param) => unsafe {
2419 let (sender, receiver) = webgl_channel().unwrap();
2420 self.send_command(WebGLCommand::GetParameterFloat2(param, sender));
2421 rooted!(in(*cx) let mut rval = ptr::null_mut::<JSObject>());
2422 Float32Array::create(
2423 *cx,
2424 CreateWith::Slice(&receiver.recv().unwrap()),
2425 rval.handle_mut(),
2426 )
2427 .unwrap();
2428 retval.set(ObjectValue(rval.get()))
2429 },
2430 Parameter::Float4(param) => unsafe {
2431 let (sender, receiver) = webgl_channel().unwrap();
2432 self.send_command(WebGLCommand::GetParameterFloat4(param, sender));
2433 rooted!(in(*cx) let mut rval = ptr::null_mut::<JSObject>());
2434 Float32Array::create(
2435 *cx,
2436 CreateWith::Slice(&receiver.recv().unwrap()),
2437 rval.handle_mut(),
2438 )
2439 .unwrap();
2440 retval.set(ObjectValue(rval.get()))
2441 },
2442 }
2443 }
2444
2445 fn GetTexParameter(
2447 &self,
2448 _cx: SafeJSContext,
2449 target: u32,
2450 pname: u32,
2451 mut retval: MutableHandleValue,
2452 ) {
2453 let texture_slot = handle_potential_webgl_error!(
2454 self,
2455 self.textures
2456 .active_texture_slot(target, self.webgl_version()),
2457 return retval.set(NullValue())
2458 );
2459 let texture = handle_potential_webgl_error!(
2460 self,
2461 texture_slot.get().ok_or(InvalidOperation),
2462 return retval.set(NullValue())
2463 );
2464
2465 if !self
2466 .extension_manager
2467 .is_get_tex_parameter_name_enabled(pname)
2468 {
2469 self.webgl_error(InvalidEnum);
2470 return retval.set(NullValue());
2471 }
2472
2473 match pname {
2474 constants::TEXTURE_MAG_FILTER => return retval.set(UInt32Value(texture.mag_filter())),
2475 constants::TEXTURE_MIN_FILTER => return retval.set(UInt32Value(texture.min_filter())),
2476 _ => {},
2477 }
2478
2479 let texparam = handle_potential_webgl_error!(
2480 self,
2481 TexParameter::from_u32(pname),
2482 return retval.set(NullValue())
2483 );
2484 if self.webgl_version() < texparam.required_webgl_version() {
2485 self.webgl_error(InvalidEnum);
2486 return retval.set(NullValue());
2487 }
2488
2489 if let Some(value) = texture.maybe_get_tex_parameter(texparam) {
2490 match value {
2491 TexParameterValue::Float(v) => retval.set(DoubleValue(v as f64)),
2492 TexParameterValue::Int(v) => retval.set(Int32Value(v)),
2493 TexParameterValue::Bool(v) => retval.set(BooleanValue(v)),
2494 }
2495 return;
2496 }
2497
2498 match texparam {
2499 TexParameter::Float(param) => {
2500 let (sender, receiver) = webgl_channel().unwrap();
2501 self.send_command(WebGLCommand::GetTexParameterFloat(target, param, sender));
2502 retval.set(DoubleValue(receiver.recv().unwrap() as f64))
2503 },
2504 TexParameter::Int(param) => {
2505 let (sender, receiver) = webgl_channel().unwrap();
2506 self.send_command(WebGLCommand::GetTexParameterInt(target, param, sender));
2507 retval.set(Int32Value(receiver.recv().unwrap()))
2508 },
2509 TexParameter::Bool(param) => {
2510 let (sender, receiver) = webgl_channel().unwrap();
2511 self.send_command(WebGLCommand::GetTexParameterBool(target, param, sender));
2512 retval.set(BooleanValue(receiver.recv().unwrap()))
2513 },
2514 }
2515 }
2516
2517 fn GetError(&self) -> u32 {
2519 let error_code = if let Some(error) = self.last_error.get() {
2520 match error {
2521 WebGLError::InvalidEnum => constants::INVALID_ENUM,
2522 WebGLError::InvalidFramebufferOperation => constants::INVALID_FRAMEBUFFER_OPERATION,
2523 WebGLError::InvalidValue => constants::INVALID_VALUE,
2524 WebGLError::InvalidOperation => constants::INVALID_OPERATION,
2525 WebGLError::OutOfMemory => constants::OUT_OF_MEMORY,
2526 WebGLError::ContextLost => constants::CONTEXT_LOST_WEBGL,
2527 }
2528 } else {
2529 constants::NO_ERROR
2530 };
2531 self.last_error.set(None);
2532 error_code
2533 }
2534
2535 fn GetContextAttributes(&self) -> Option<WebGLContextAttributes> {
2537 let (sender, receiver) = webgl_channel().unwrap();
2538
2539 let backtrace = capture_webgl_backtrace();
2541 if self
2542 .droppable
2543 .webgl_sender
2544 .send(WebGLCommand::GetContextAttributes(sender), backtrace)
2545 .is_err()
2546 {
2547 return None;
2548 }
2549
2550 let attrs = receiver.recv().unwrap();
2551
2552 Some(WebGLContextAttributes {
2553 alpha: attrs.alpha,
2554 antialias: attrs.antialias,
2555 depth: attrs.depth,
2556 failIfMajorPerformanceCaveat: false,
2557 preferLowPowerToHighPerformance: false,
2558 premultipliedAlpha: attrs.premultiplied_alpha,
2559 preserveDrawingBuffer: attrs.preserve_drawing_buffer,
2560 stencil: attrs.stencil,
2561 })
2562 }
2563
2564 fn IsContextLost(&self) -> bool {
2566 false
2567 }
2568
2569 fn GetSupportedExtensions(&self) -> Option<Vec<DOMString>> {
2571 self.extension_manager
2572 .init_once(|| self.get_gl_extensions());
2573 let extensions = self.extension_manager.get_supported_extensions();
2574 Some(
2575 extensions
2576 .iter()
2577 .map(|name| DOMString::from(*name))
2578 .collect(),
2579 )
2580 }
2581
2582 fn GetExtension(&self, _cx: SafeJSContext, name: DOMString) -> Option<NonNull<JSObject>> {
2584 self.extension_manager
2585 .init_once(|| self.get_gl_extensions());
2586 self.extension_manager.get_or_init_extension(&name, self)
2587 }
2588
2589 fn ActiveTexture(&self, texture: u32) {
2591 handle_potential_webgl_error!(self, self.textures.set_active_unit_enum(texture), return);
2592 self.send_command(WebGLCommand::ActiveTexture(texture));
2593 }
2594
2595 fn BlendColor(&self, r: f32, g: f32, b: f32, a: f32) {
2597 self.send_command(WebGLCommand::BlendColor(r, g, b, a));
2598 }
2599
2600 fn BlendEquation(&self, mode: u32) {
2602 handle_potential_webgl_error!(self, self.validate_blend_mode(mode), return);
2603 self.send_command(WebGLCommand::BlendEquation(mode))
2604 }
2605
2606 fn BlendEquationSeparate(&self, mode_rgb: u32, mode_alpha: u32) {
2608 handle_potential_webgl_error!(self, self.validate_blend_mode(mode_rgb), return);
2609 handle_potential_webgl_error!(self, self.validate_blend_mode(mode_alpha), return);
2610 self.send_command(WebGLCommand::BlendEquationSeparate(mode_rgb, mode_alpha));
2611 }
2612
2613 fn BlendFunc(&self, src_factor: u32, dest_factor: u32) {
2615 if has_invalid_blend_constants(src_factor, dest_factor) {
2621 return self.webgl_error(InvalidOperation);
2622 }
2623 if has_invalid_blend_constants(dest_factor, src_factor) {
2624 return self.webgl_error(InvalidOperation);
2625 }
2626
2627 self.send_command(WebGLCommand::BlendFunc(src_factor, dest_factor));
2628 }
2629
2630 fn BlendFuncSeparate(&self, src_rgb: u32, dest_rgb: u32, src_alpha: u32, dest_alpha: u32) {
2632 if has_invalid_blend_constants(src_rgb, dest_rgb) {
2638 return self.webgl_error(InvalidOperation);
2639 }
2640 if has_invalid_blend_constants(dest_rgb, src_rgb) {
2641 return self.webgl_error(InvalidOperation);
2642 }
2643
2644 self.send_command(WebGLCommand::BlendFuncSeparate(
2645 src_rgb, dest_rgb, src_alpha, dest_alpha,
2646 ));
2647 }
2648
2649 fn AttachShader(&self, program: &WebGLProgram, shader: &WebGLShader) {
2651 handle_potential_webgl_error!(self, self.validate_ownership(program), return);
2652 handle_potential_webgl_error!(self, self.validate_ownership(shader), return);
2653 handle_potential_webgl_error!(self, program.attach_shader(shader));
2654 }
2655
2656 fn DetachShader(&self, program: &WebGLProgram, shader: &WebGLShader) {
2658 handle_potential_webgl_error!(self, self.validate_ownership(program), return);
2659 handle_potential_webgl_error!(self, self.validate_ownership(shader), return);
2660 handle_potential_webgl_error!(self, program.detach_shader(shader));
2661 }
2662
2663 fn BindAttribLocation(&self, program: &WebGLProgram, index: u32, name: DOMString) {
2665 handle_potential_webgl_error!(self, self.validate_ownership(program), return);
2666 handle_potential_webgl_error!(self, program.bind_attrib_location(index, name));
2667 }
2668
2669 fn BindBuffer(&self, target: u32, buffer: Option<&WebGLBuffer>) {
2671 let current_vao;
2672 let slot = match target {
2673 constants::ARRAY_BUFFER => &self.bound_buffer_array,
2674 constants::ELEMENT_ARRAY_BUFFER => {
2675 current_vao = self.current_vao();
2676 current_vao.element_array_buffer()
2677 },
2678 _ => return self.webgl_error(InvalidEnum),
2679 };
2680 self.bind_buffer_maybe(slot, target, buffer);
2681 }
2682
2683 fn BindFramebuffer(&self, target: u32, framebuffer: Option<&WebGLFramebuffer>) {
2685 handle_potential_webgl_error!(
2686 self,
2687 self.validate_new_framebuffer_binding(framebuffer),
2688 return
2689 );
2690
2691 if target != constants::FRAMEBUFFER {
2692 return self.webgl_error(InvalidEnum);
2693 }
2694
2695 self.bind_framebuffer_to(target, framebuffer, &self.bound_draw_framebuffer)
2696 }
2697
2698 fn BindRenderbuffer(&self, target: u32, renderbuffer: Option<&WebGLRenderbuffer>) {
2700 if let Some(rb) = renderbuffer {
2701 handle_potential_webgl_error!(self, self.validate_ownership(rb), return);
2702 }
2703
2704 if target != constants::RENDERBUFFER {
2705 return self.webgl_error(InvalidEnum);
2706 }
2707
2708 match renderbuffer {
2709 Some(renderbuffer) if !renderbuffer.is_deleted() => {
2713 self.bound_renderbuffer.set(Some(renderbuffer));
2714 renderbuffer.bind(target);
2715 },
2716 _ => {
2717 if renderbuffer.is_some() {
2718 self.webgl_error(InvalidOperation);
2719 }
2720
2721 self.bound_renderbuffer.set(None);
2722 self.send_command(WebGLCommand::BindRenderbuffer(target, None));
2724 },
2725 }
2726 }
2727
2728 fn BindTexture(&self, target: u32, texture: Option<&WebGLTexture>) {
2730 if let Some(texture) = texture {
2731 handle_potential_webgl_error!(self, self.validate_ownership(texture), return);
2732 }
2733
2734 let texture_slot = handle_potential_webgl_error!(
2735 self,
2736 self.textures
2737 .active_texture_slot(target, self.webgl_version()),
2738 return
2739 );
2740
2741 if let Some(texture) = texture {
2742 handle_potential_webgl_error!(self, texture.bind(target), return);
2743 } else {
2744 self.send_command(WebGLCommand::BindTexture(target, None));
2745 }
2746 texture_slot.set(texture);
2747 }
2748
2749 fn GenerateMipmap(&self, target: u32) {
2751 let texture_slot = handle_potential_webgl_error!(
2752 self,
2753 self.textures
2754 .active_texture_slot(target, self.webgl_version()),
2755 return
2756 );
2757 let texture =
2758 handle_potential_webgl_error!(self, texture_slot.get().ok_or(InvalidOperation), return);
2759 handle_potential_webgl_error!(self, texture.generate_mipmap());
2760 }
2761
2762 fn BufferData_(&self, target: u32, data: Option<ArrayBufferViewOrArrayBuffer>, usage: u32) {
2764 let usage = handle_potential_webgl_error!(self, self.buffer_usage(usage), return);
2765 let bound_buffer = handle_potential_webgl_error!(self, self.bound_buffer(target), return);
2766 self.buffer_data(target, data, usage, bound_buffer)
2767 }
2768
2769 fn BufferData(&self, target: u32, size: i64, usage: u32) {
2771 let usage = handle_potential_webgl_error!(self, self.buffer_usage(usage), return);
2772 let bound_buffer = handle_potential_webgl_error!(self, self.bound_buffer(target), return);
2773 self.buffer_data_(target, size, usage, bound_buffer)
2774 }
2775
2776 fn BufferSubData(&self, target: u32, offset: i64, data: ArrayBufferViewOrArrayBuffer) {
2778 let bound_buffer = handle_potential_webgl_error!(self, self.bound_buffer(target), return);
2779 self.buffer_sub_data(target, offset, data, bound_buffer)
2780 }
2781
2782 #[expect(unsafe_code)]
2784 fn CompressedTexImage2D(
2785 &self,
2786 target: u32,
2787 level: i32,
2788 internal_format: u32,
2789 width: i32,
2790 height: i32,
2791 border: i32,
2792 data: CustomAutoRooterGuard<ArrayBufferView>,
2793 ) {
2794 let data = unsafe { data.as_slice() };
2795 self.compressed_tex_image_2d(target, level, internal_format, width, height, border, data)
2796 }
2797
2798 #[expect(unsafe_code)]
2800 fn CompressedTexSubImage2D(
2801 &self,
2802 target: u32,
2803 level: i32,
2804 xoffset: i32,
2805 yoffset: i32,
2806 width: i32,
2807 height: i32,
2808 format: u32,
2809 data: CustomAutoRooterGuard<ArrayBufferView>,
2810 ) {
2811 let data = unsafe { data.as_slice() };
2812 self.compressed_tex_sub_image_2d(
2813 target, level, xoffset, yoffset, width, height, format, data,
2814 )
2815 }
2816
2817 fn CopyTexImage2D(
2819 &self,
2820 target: u32,
2821 level: i32,
2822 internal_format: u32,
2823 x: i32,
2824 y: i32,
2825 width: i32,
2826 height: i32,
2827 border: i32,
2828 ) {
2829 handle_potential_webgl_error!(self, self.validate_framebuffer(), return);
2830
2831 let validator = CommonTexImage2DValidator::new(
2832 self,
2833 target,
2834 level,
2835 internal_format,
2836 width,
2837 height,
2838 border,
2839 );
2840 let CommonTexImage2DValidatorResult {
2841 texture,
2842 target,
2843 level,
2844 internal_format,
2845 width,
2846 height,
2847 border,
2848 } = match validator.validate() {
2849 Ok(result) => result,
2850 Err(_) => return,
2851 };
2852
2853 if texture.is_immutable() {
2854 return self.webgl_error(InvalidOperation);
2855 }
2856
2857 let framebuffer_format = match self.bound_draw_framebuffer.get() {
2858 Some(fb) => match fb.attachment(constants::COLOR_ATTACHMENT0) {
2859 Some(WebGLFramebufferAttachmentRoot::Renderbuffer(rb)) => {
2860 TexFormat::from_gl_constant(rb.internal_format())
2861 },
2862 Some(WebGLFramebufferAttachmentRoot::Texture(texture)) => texture
2863 .image_info_for_target(&target, 0)
2864 .map(|info| info.internal_format()),
2865 None => None,
2866 },
2867 None => {
2868 let attrs = self.GetContextAttributes().unwrap();
2869 Some(if attrs.alpha {
2870 TexFormat::RGBA
2871 } else {
2872 TexFormat::RGB
2873 })
2874 },
2875 };
2876
2877 let framebuffer_format = match framebuffer_format {
2878 Some(f) => f,
2879 None => {
2880 self.webgl_error(InvalidOperation);
2881 return;
2882 },
2883 };
2884
2885 match (framebuffer_format, internal_format) {
2886 (a, b) if a == b => (),
2887 (TexFormat::RGBA, TexFormat::RGB) => (),
2888 (TexFormat::RGBA, TexFormat::Alpha) => (),
2889 (TexFormat::RGBA, TexFormat::Luminance) => (),
2890 (TexFormat::RGBA, TexFormat::LuminanceAlpha) => (),
2891 (TexFormat::RGB, TexFormat::Luminance) => (),
2892 _ => {
2893 self.webgl_error(InvalidOperation);
2894 return;
2895 },
2896 }
2897
2898 handle_potential_webgl_error!(
2900 self,
2901 texture.initialize(target, width, height, 1, internal_format, level, None)
2902 );
2903
2904 let msg = WebGLCommand::CopyTexImage2D(
2905 target.as_gl_constant(),
2906 level as i32,
2907 internal_format.as_gl_constant(),
2908 x,
2909 y,
2910 width as i32,
2911 height as i32,
2912 border as i32,
2913 );
2914
2915 self.send_command(msg);
2916 }
2917
2918 fn CopyTexSubImage2D(
2920 &self,
2921 target: u32,
2922 level: i32,
2923 xoffset: i32,
2924 yoffset: i32,
2925 x: i32,
2926 y: i32,
2927 width: i32,
2928 height: i32,
2929 ) {
2930 handle_potential_webgl_error!(self, self.validate_framebuffer(), return);
2931
2932 let validator = CommonTexImage2DValidator::new(
2935 self,
2936 target,
2937 level,
2938 TexFormat::RGBA.as_gl_constant(),
2939 width,
2940 height,
2941 0,
2942 );
2943 let CommonTexImage2DValidatorResult {
2944 texture,
2945 target,
2946 level,
2947 width,
2948 height,
2949 ..
2950 } = match validator.validate() {
2951 Ok(result) => result,
2952 Err(_) => return,
2953 };
2954
2955 let image_info = match texture.image_info_for_target(&target, level) {
2956 Some(info) => info,
2957 None => return self.webgl_error(InvalidOperation),
2958 };
2959
2960 if xoffset < 0 ||
2965 (xoffset as u32 + width) > image_info.width() ||
2966 yoffset < 0 ||
2967 (yoffset as u32 + height) > image_info.height()
2968 {
2969 self.webgl_error(InvalidValue);
2970 return;
2971 }
2972
2973 let msg = WebGLCommand::CopyTexSubImage2D(
2974 target.as_gl_constant(),
2975 level as i32,
2976 xoffset,
2977 yoffset,
2978 x,
2979 y,
2980 width as i32,
2981 height as i32,
2982 );
2983
2984 self.send_command(msg);
2985 }
2986
2987 fn Clear(&self, mask: u32) {
2989 handle_potential_webgl_error!(self, self.validate_framebuffer(), return);
2990 if mask &
2991 !(constants::DEPTH_BUFFER_BIT |
2992 constants::STENCIL_BUFFER_BIT |
2993 constants::COLOR_BUFFER_BIT) !=
2994 0
2995 {
2996 return self.webgl_error(InvalidValue);
2997 }
2998
2999 self.send_command(WebGLCommand::Clear(mask));
3000 self.mark_as_dirty();
3001 }
3002
3003 fn ClearColor(&self, red: f32, green: f32, blue: f32, alpha: f32) {
3005 self.current_clear_color.set((red, green, blue, alpha));
3006 self.send_command(WebGLCommand::ClearColor(red, green, blue, alpha));
3007 }
3008
3009 fn ClearDepth(&self, depth: f32) {
3011 self.send_command(WebGLCommand::ClearDepth(depth))
3012 }
3013
3014 fn ClearStencil(&self, stencil: i32) {
3016 self.send_command(WebGLCommand::ClearStencil(stencil))
3017 }
3018
3019 fn ColorMask(&self, r: bool, g: bool, b: bool, a: bool) {
3021 self.send_command(WebGLCommand::ColorMask(r, g, b, a))
3022 }
3023
3024 fn CullFace(&self, mode: u32) {
3026 match mode {
3027 constants::FRONT | constants::BACK | constants::FRONT_AND_BACK => {
3028 self.send_command(WebGLCommand::CullFace(mode))
3029 },
3030 _ => self.webgl_error(InvalidEnum),
3031 }
3032 }
3033
3034 fn FrontFace(&self, mode: u32) {
3036 match mode {
3037 constants::CW | constants::CCW => self.send_command(WebGLCommand::FrontFace(mode)),
3038 _ => self.webgl_error(InvalidEnum),
3039 }
3040 }
3041 fn DepthFunc(&self, func: u32) {
3043 match func {
3044 constants::NEVER |
3045 constants::LESS |
3046 constants::EQUAL |
3047 constants::LEQUAL |
3048 constants::GREATER |
3049 constants::NOTEQUAL |
3050 constants::GEQUAL |
3051 constants::ALWAYS => self.send_command(WebGLCommand::DepthFunc(func)),
3052 _ => self.webgl_error(InvalidEnum),
3053 }
3054 }
3055
3056 fn DepthMask(&self, flag: bool) {
3058 self.send_command(WebGLCommand::DepthMask(flag))
3059 }
3060
3061 fn DepthRange(&self, near: f32, far: f32) {
3063 if near > far {
3065 return self.webgl_error(InvalidOperation);
3066 }
3067 self.send_command(WebGLCommand::DepthRange(near, far))
3068 }
3069
3070 fn Enable(&self, cap: u32) {
3072 if handle_potential_webgl_error!(self, self.capabilities.set(cap, true), return) {
3073 self.send_command(WebGLCommand::Enable(cap));
3074 }
3075 }
3076
3077 fn Disable(&self, cap: u32) {
3079 if handle_potential_webgl_error!(self, self.capabilities.set(cap, false), return) {
3080 self.send_command(WebGLCommand::Disable(cap));
3081 }
3082 }
3083
3084 fn CompileShader(&self, shader: &WebGLShader) {
3086 handle_potential_webgl_error!(self, self.validate_ownership(shader), return);
3087 handle_potential_webgl_error!(
3088 self,
3089 shader.compile(
3090 self.api_type,
3091 self.webgl_version,
3092 self.glsl_version,
3093 &self.limits,
3094 &self.extension_manager,
3095 )
3096 )
3097 }
3098
3099 fn CreateBuffer(&self) -> Option<DomRoot<WebGLBuffer>> {
3101 WebGLBuffer::maybe_new(self, CanGc::note())
3102 }
3103
3104 fn CreateFramebuffer(&self) -> Option<DomRoot<WebGLFramebuffer>> {
3106 WebGLFramebuffer::maybe_new(self, CanGc::note())
3107 }
3108
3109 fn CreateRenderbuffer(&self) -> Option<DomRoot<WebGLRenderbuffer>> {
3111 WebGLRenderbuffer::maybe_new(self)
3112 }
3113
3114 fn CreateTexture(&self) -> Option<DomRoot<WebGLTexture>> {
3116 WebGLTexture::maybe_new(self)
3117 }
3118
3119 fn CreateProgram(&self) -> Option<DomRoot<WebGLProgram>> {
3121 WebGLProgram::maybe_new(self, CanGc::note())
3122 }
3123
3124 fn CreateShader(&self, shader_type: u32) -> Option<DomRoot<WebGLShader>> {
3126 match shader_type {
3127 constants::VERTEX_SHADER | constants::FRAGMENT_SHADER => {},
3128 _ => {
3129 self.webgl_error(InvalidEnum);
3130 return None;
3131 },
3132 }
3133 WebGLShader::maybe_new(self, shader_type)
3134 }
3135
3136 fn DeleteBuffer(&self, buffer: Option<&WebGLBuffer>) {
3138 let buffer = match buffer {
3139 Some(buffer) => buffer,
3140 None => return,
3141 };
3142 handle_potential_webgl_error!(self, self.validate_ownership(buffer), return);
3143 if buffer.is_marked_for_deletion() {
3144 return;
3145 }
3146 self.current_vao().unbind_buffer(buffer);
3147 if self.bound_buffer_array.get().is_some_and(|b| buffer == &*b) {
3148 self.bound_buffer_array.set(None);
3149 buffer.decrement_attached_counter(Operation::Infallible);
3150 }
3151 buffer.mark_for_deletion(Operation::Infallible);
3152 }
3153
3154 fn DeleteFramebuffer(&self, framebuffer: Option<&WebGLFramebuffer>) {
3156 if let Some(framebuffer) = framebuffer {
3157 handle_potential_webgl_error!(self, framebuffer.validate_transparent(), return);
3161 handle_potential_webgl_error!(self, self.validate_ownership(framebuffer), return);
3162 handle_object_deletion!(
3163 self,
3164 self.bound_draw_framebuffer,
3165 framebuffer,
3166 Some(WebGLCommand::BindFramebuffer(
3167 framebuffer.target().unwrap(),
3168 WebGLFramebufferBindingRequest::Default
3169 ))
3170 );
3171 framebuffer.delete(Operation::Infallible)
3172 }
3173 }
3174
3175 fn DeleteRenderbuffer(&self, renderbuffer: Option<&WebGLRenderbuffer>) {
3177 if let Some(renderbuffer) = renderbuffer {
3178 handle_potential_webgl_error!(self, self.validate_ownership(renderbuffer), return);
3179 handle_object_deletion!(
3180 self,
3181 self.bound_renderbuffer,
3182 renderbuffer,
3183 Some(WebGLCommand::BindRenderbuffer(
3184 constants::RENDERBUFFER,
3185 None
3186 ))
3187 );
3188 renderbuffer.delete(Operation::Infallible)
3189 }
3190 }
3191
3192 fn DeleteTexture(&self, texture: Option<&WebGLTexture>) {
3194 if let Some(texture) = texture {
3195 handle_potential_webgl_error!(self, self.validate_ownership(texture), return);
3196
3197 let mut active_unit_enum = self.textures.active_unit_enum();
3206 for (unit_enum, slot) in self.textures.iter() {
3207 if let Some(target) = slot.unbind(texture) {
3208 if unit_enum != active_unit_enum {
3209 self.send_command(WebGLCommand::ActiveTexture(unit_enum));
3210 active_unit_enum = unit_enum;
3211 }
3212 self.send_command(WebGLCommand::BindTexture(target, None));
3213 }
3214 }
3215
3216 if active_unit_enum != self.textures.active_unit_enum() {
3218 self.send_command(WebGLCommand::ActiveTexture(
3219 self.textures.active_unit_enum(),
3220 ));
3221 }
3222
3223 texture.delete(Operation::Infallible)
3224 }
3225 }
3226
3227 fn DeleteProgram(&self, program: Option<&WebGLProgram>) {
3229 if let Some(program) = program {
3230 handle_potential_webgl_error!(self, self.validate_ownership(program), return);
3231 program.mark_for_deletion(Operation::Infallible)
3232 }
3233 }
3234
3235 fn DeleteShader(&self, shader: Option<&WebGLShader>) {
3237 if let Some(shader) = shader {
3238 handle_potential_webgl_error!(self, self.validate_ownership(shader), return);
3239 shader.mark_for_deletion(Operation::Infallible)
3240 }
3241 }
3242
3243 fn DrawArrays(&self, mode: u32, first: i32, count: i32) {
3245 handle_potential_webgl_error!(self, self.draw_arrays_instanced(mode, first, count, 1));
3246 }
3247
3248 fn DrawElements(&self, mode: u32, count: i32, type_: u32, offset: i64) {
3250 handle_potential_webgl_error!(
3251 self,
3252 self.draw_elements_instanced(mode, count, type_, offset, 1)
3253 );
3254 }
3255
3256 fn EnableVertexAttribArray(&self, attrib_id: u32) {
3258 if attrib_id >= self.limits.max_vertex_attribs {
3259 return self.webgl_error(InvalidValue);
3260 }
3261 match self.webgl_version() {
3262 WebGLVersion::WebGL1 => self
3263 .current_vao()
3264 .enabled_vertex_attrib_array(attrib_id, true),
3265 WebGLVersion::WebGL2 => self
3266 .current_vao_webgl2()
3267 .enabled_vertex_attrib_array(attrib_id, true),
3268 };
3269 self.send_command(WebGLCommand::EnableVertexAttribArray(attrib_id));
3270 }
3271
3272 fn DisableVertexAttribArray(&self, attrib_id: u32) {
3274 if attrib_id >= self.limits.max_vertex_attribs {
3275 return self.webgl_error(InvalidValue);
3276 }
3277 match self.webgl_version() {
3278 WebGLVersion::WebGL1 => self
3279 .current_vao()
3280 .enabled_vertex_attrib_array(attrib_id, false),
3281 WebGLVersion::WebGL2 => self
3282 .current_vao_webgl2()
3283 .enabled_vertex_attrib_array(attrib_id, false),
3284 };
3285 self.send_command(WebGLCommand::DisableVertexAttribArray(attrib_id));
3286 }
3287
3288 fn GetActiveUniform(
3290 &self,
3291 program: &WebGLProgram,
3292 index: u32,
3293 ) -> Option<DomRoot<WebGLActiveInfo>> {
3294 handle_potential_webgl_error!(self, self.validate_ownership(program), return None);
3295 match program.get_active_uniform(index, CanGc::note()) {
3296 Ok(ret) => Some(ret),
3297 Err(e) => {
3298 self.webgl_error(e);
3299 None
3300 },
3301 }
3302 }
3303
3304 fn GetActiveAttrib(
3306 &self,
3307 program: &WebGLProgram,
3308 index: u32,
3309 ) -> Option<DomRoot<WebGLActiveInfo>> {
3310 handle_potential_webgl_error!(self, self.validate_ownership(program), return None);
3311 handle_potential_webgl_error!(
3312 self,
3313 program.get_active_attrib(index, CanGc::note()).map(Some),
3314 None
3315 )
3316 }
3317
3318 fn GetAttribLocation(&self, program: &WebGLProgram, name: DOMString) -> i32 {
3320 handle_potential_webgl_error!(self, self.validate_ownership(program), return -1);
3321 handle_potential_webgl_error!(self, program.get_attrib_location(name), -1)
3322 }
3323
3324 fn GetFramebufferAttachmentParameter(
3326 &self,
3327 cx: SafeJSContext,
3328 target: u32,
3329 attachment: u32,
3330 pname: u32,
3331 mut retval: MutableHandleValue,
3332 ) {
3333 if let Some(fb) = self.bound_draw_framebuffer.get() {
3335 handle_potential_webgl_error!(
3338 self,
3339 fb.validate_transparent(),
3340 return retval.set(NullValue())
3341 );
3342 } else {
3343 self.webgl_error(InvalidOperation);
3344 return retval.set(NullValue());
3345 }
3346
3347 let target_matches = match target {
3349 constants::FRAMEBUFFER => true,
3352 _ => false,
3353 };
3354 let attachment_matches = match attachment {
3355 constants::COLOR_ATTACHMENT0 |
3358 constants::DEPTH_STENCIL_ATTACHMENT |
3359 constants::DEPTH_ATTACHMENT |
3360 constants::STENCIL_ATTACHMENT => true,
3361 _ => false,
3362 };
3363 let pname_matches = match pname {
3364 constants::FRAMEBUFFER_ATTACHMENT_OBJECT_NAME |
3374 constants::FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE |
3375 constants::FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE |
3376 constants::FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL => true,
3377 _ => false,
3378 };
3379
3380 let bound_attachment_matches = match self
3381 .bound_draw_framebuffer
3382 .get()
3383 .unwrap()
3384 .attachment(attachment)
3385 {
3386 Some(attachment_root) => match attachment_root {
3387 WebGLFramebufferAttachmentRoot::Renderbuffer(_) => matches!(
3388 pname,
3389 constants::FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE |
3390 constants::FRAMEBUFFER_ATTACHMENT_OBJECT_NAME
3391 ),
3392 WebGLFramebufferAttachmentRoot::Texture(_) => matches!(
3393 pname,
3394 constants::FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE |
3395 constants::FRAMEBUFFER_ATTACHMENT_OBJECT_NAME |
3396 constants::FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL |
3397 constants::FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE
3398 ),
3399 },
3400 _ => matches!(pname, constants::FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE),
3401 };
3402
3403 if !target_matches || !attachment_matches || !pname_matches || !bound_attachment_matches {
3404 self.webgl_error(InvalidEnum);
3405 return retval.set(NullValue());
3406 }
3407
3408 if pname == constants::FRAMEBUFFER_ATTACHMENT_OBJECT_NAME {
3415 let fb = self.bound_draw_framebuffer.get().unwrap();
3418 if let Some(webgl_attachment) = fb.attachment(attachment) {
3419 match webgl_attachment {
3420 WebGLFramebufferAttachmentRoot::Renderbuffer(rb) => {
3421 rb.safe_to_jsval(cx, retval, CanGc::note());
3422 return;
3423 },
3424 WebGLFramebufferAttachmentRoot::Texture(texture) => {
3425 texture.safe_to_jsval(cx, retval, CanGc::note());
3426 return;
3427 },
3428 }
3429 }
3430 self.webgl_error(InvalidEnum);
3431 return retval.set(NullValue());
3432 }
3433
3434 let (sender, receiver) = webgl_channel().unwrap();
3435 self.send_command(WebGLCommand::GetFramebufferAttachmentParameter(
3436 target, attachment, pname, sender,
3437 ));
3438
3439 retval.set(Int32Value(receiver.recv().unwrap()))
3440 }
3441
3442 fn GetRenderbufferParameter(
3444 &self,
3445 _cx: SafeJSContext,
3446 target: u32,
3447 pname: u32,
3448 mut retval: MutableHandleValue,
3449 ) {
3450 let target_matches = target == constants::RENDERBUFFER;
3453
3454 let pname_matches = matches!(
3455 pname,
3456 constants::RENDERBUFFER_WIDTH |
3457 constants::RENDERBUFFER_HEIGHT |
3458 constants::RENDERBUFFER_INTERNAL_FORMAT |
3459 constants::RENDERBUFFER_RED_SIZE |
3460 constants::RENDERBUFFER_GREEN_SIZE |
3461 constants::RENDERBUFFER_BLUE_SIZE |
3462 constants::RENDERBUFFER_ALPHA_SIZE |
3463 constants::RENDERBUFFER_DEPTH_SIZE |
3464 constants::RENDERBUFFER_STENCIL_SIZE
3465 );
3466
3467 if !target_matches || !pname_matches {
3468 self.webgl_error(InvalidEnum);
3469 return retval.set(NullValue());
3470 }
3471
3472 if self.bound_renderbuffer.get().is_none() {
3473 self.webgl_error(InvalidOperation);
3474 return retval.set(NullValue());
3475 }
3476
3477 let result = if pname == constants::RENDERBUFFER_INTERNAL_FORMAT {
3478 let rb = self.bound_renderbuffer.get().unwrap();
3479 rb.internal_format() as i32
3480 } else {
3481 let (sender, receiver) = webgl_channel().unwrap();
3482 self.send_command(WebGLCommand::GetRenderbufferParameter(
3483 target, pname, sender,
3484 ));
3485 receiver.recv().unwrap()
3486 };
3487
3488 retval.set(Int32Value(result))
3489 }
3490
3491 fn GetProgramInfoLog(&self, program: &WebGLProgram) -> Option<DOMString> {
3493 handle_potential_webgl_error!(self, self.validate_ownership(program), return None);
3494 match program.get_info_log() {
3495 Ok(value) => Some(DOMString::from(value)),
3496 Err(e) => {
3497 self.webgl_error(e);
3498 None
3499 },
3500 }
3501 }
3502
3503 fn GetProgramParameter(
3505 &self,
3506 _: SafeJSContext,
3507 program: &WebGLProgram,
3508 param: u32,
3509 mut retval: MutableHandleValue,
3510 ) {
3511 handle_potential_webgl_error!(
3512 self,
3513 self.validate_ownership(program),
3514 return retval.set(NullValue())
3515 );
3516 if program.is_deleted() {
3517 self.webgl_error(InvalidOperation);
3518 return retval.set(NullValue());
3519 }
3520 retval.set(match param {
3521 constants::DELETE_STATUS => BooleanValue(program.is_marked_for_deletion()),
3522 constants::LINK_STATUS => BooleanValue(program.is_linked()),
3523 constants::VALIDATE_STATUS => {
3524 let (sender, receiver) = webgl_channel().unwrap();
3527 self.send_command(WebGLCommand::GetProgramValidateStatus(program.id(), sender));
3528 BooleanValue(receiver.recv().unwrap())
3529 },
3530 constants::ATTACHED_SHADERS => {
3531 Int32Value(
3533 program
3534 .attached_shaders()
3535 .map(|shaders| shaders.len() as i32)
3536 .unwrap_or(0),
3537 )
3538 },
3539 constants::ACTIVE_ATTRIBUTES => Int32Value(program.active_attribs().len() as i32),
3540 constants::ACTIVE_UNIFORMS => Int32Value(program.active_uniforms().len() as i32),
3541 _ => {
3542 self.webgl_error(InvalidEnum);
3543 NullValue()
3544 },
3545 })
3546 }
3547
3548 fn GetShaderInfoLog(&self, shader: &WebGLShader) -> Option<DOMString> {
3550 handle_potential_webgl_error!(self, self.validate_ownership(shader), return None);
3551 Some(shader.info_log())
3552 }
3553
3554 fn GetShaderParameter(
3556 &self,
3557 _: SafeJSContext,
3558 shader: &WebGLShader,
3559 param: u32,
3560 mut retval: MutableHandleValue,
3561 ) {
3562 handle_potential_webgl_error!(
3563 self,
3564 self.validate_ownership(shader),
3565 return retval.set(NullValue())
3566 );
3567 if shader.is_deleted() {
3568 self.webgl_error(InvalidValue);
3569 return retval.set(NullValue());
3570 }
3571 retval.set(match param {
3572 constants::DELETE_STATUS => BooleanValue(shader.is_marked_for_deletion()),
3573 constants::COMPILE_STATUS => BooleanValue(shader.successfully_compiled()),
3574 constants::SHADER_TYPE => UInt32Value(shader.gl_type()),
3575 _ => {
3576 self.webgl_error(InvalidEnum);
3577 NullValue()
3578 },
3579 })
3580 }
3581
3582 fn GetShaderPrecisionFormat(
3584 &self,
3585 shader_type: u32,
3586 precision_type: u32,
3587 ) -> Option<DomRoot<WebGLShaderPrecisionFormat>> {
3588 match shader_type {
3589 constants::FRAGMENT_SHADER | constants::VERTEX_SHADER => (),
3590 _ => {
3591 self.webgl_error(InvalidEnum);
3592 return None;
3593 },
3594 }
3595
3596 match precision_type {
3597 constants::LOW_FLOAT |
3598 constants::MEDIUM_FLOAT |
3599 constants::HIGH_FLOAT |
3600 constants::LOW_INT |
3601 constants::MEDIUM_INT |
3602 constants::HIGH_INT => (),
3603 _ => {
3604 self.webgl_error(InvalidEnum);
3605 return None;
3606 },
3607 }
3608
3609 let (sender, receiver) = webgl_channel().unwrap();
3610 self.send_command(WebGLCommand::GetShaderPrecisionFormat(
3611 shader_type,
3612 precision_type,
3613 sender,
3614 ));
3615
3616 let (range_min, range_max, precision) = receiver.recv().unwrap();
3617 Some(WebGLShaderPrecisionFormat::new(
3618 self.global().as_window(),
3619 range_min,
3620 range_max,
3621 precision,
3622 CanGc::note(),
3623 ))
3624 }
3625
3626 fn GetUniformLocation(
3628 &self,
3629 program: &WebGLProgram,
3630 name: DOMString,
3631 ) -> Option<DomRoot<WebGLUniformLocation>> {
3632 handle_potential_webgl_error!(self, self.validate_ownership(program), return None);
3633 handle_potential_webgl_error!(
3634 self,
3635 program.get_uniform_location(name, CanGc::note()),
3636 None
3637 )
3638 }
3639
3640 #[expect(unsafe_code)]
3641 fn GetVertexAttrib(
3643 &self,
3644 cx: SafeJSContext,
3645 index: u32,
3646 param: u32,
3647 mut retval: MutableHandleValue,
3648 ) {
3649 let mut get_attrib = |data: Ref<'_, VertexAttribData>| {
3650 if param == constants::CURRENT_VERTEX_ATTRIB {
3651 let attrib = self.current_vertex_attribs.borrow()[index as usize];
3652 match attrib {
3653 VertexAttrib::Float(x, y, z, w) => {
3654 let value = [x, y, z, w];
3655 unsafe {
3656 rooted!(in(*cx) let mut result = ptr::null_mut::<JSObject>());
3657 Float32Array::create(
3658 *cx,
3659 CreateWith::Slice(&value),
3660 result.handle_mut(),
3661 )
3662 .unwrap();
3663 return retval.set(ObjectValue(result.get()));
3664 }
3665 },
3666 VertexAttrib::Int(x, y, z, w) => {
3667 let value = [x, y, z, w];
3668 unsafe {
3669 rooted!(in(*cx) let mut result = ptr::null_mut::<JSObject>());
3670 Int32Array::create(*cx, CreateWith::Slice(&value), result.handle_mut())
3671 .unwrap();
3672 return retval.set(ObjectValue(result.get()));
3673 }
3674 },
3675 VertexAttrib::Uint(x, y, z, w) => {
3676 let value = [x, y, z, w];
3677 unsafe {
3678 rooted!(in(*cx) let mut result = ptr::null_mut::<JSObject>());
3679 Uint32Array::create(
3680 *cx,
3681 CreateWith::Slice(&value),
3682 result.handle_mut(),
3683 )
3684 .unwrap();
3685 return retval.set(ObjectValue(result.get()));
3686 }
3687 },
3688 };
3689 }
3690 if !self
3691 .extension_manager
3692 .is_get_vertex_attrib_name_enabled(param)
3693 {
3694 self.webgl_error(WebGLError::InvalidEnum);
3695 return retval.set(NullValue());
3696 }
3697
3698 match param {
3699 constants::VERTEX_ATTRIB_ARRAY_ENABLED => {
3700 retval.set(BooleanValue(data.enabled_as_array))
3701 },
3702 constants::VERTEX_ATTRIB_ARRAY_SIZE => retval.set(Int32Value(data.size as i32)),
3703 constants::VERTEX_ATTRIB_ARRAY_TYPE => retval.set(Int32Value(data.type_ as i32)),
3704 constants::VERTEX_ATTRIB_ARRAY_NORMALIZED => {
3705 retval.set(BooleanValue(data.normalized))
3706 },
3707 constants::VERTEX_ATTRIB_ARRAY_STRIDE => retval.set(Int32Value(data.stride as i32)),
3708 constants::VERTEX_ATTRIB_ARRAY_BUFFER_BINDING => {
3709 if let Some(buffer) = data.buffer() {
3710 buffer.safe_to_jsval(cx, retval.reborrow(), CanGc::note());
3711 } else {
3712 retval.set(NullValue());
3713 }
3714 },
3715 ANGLEInstancedArraysConstants::VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE => {
3716 retval.set(UInt32Value(data.divisor))
3717 },
3718 _ => {
3719 self.webgl_error(InvalidEnum);
3720 retval.set(NullValue())
3721 },
3722 }
3723 };
3724
3725 match self.webgl_version() {
3726 WebGLVersion::WebGL1 => {
3727 let current_vao = self.current_vao();
3728 let data = handle_potential_webgl_error!(
3729 self,
3730 current_vao.get_vertex_attrib(index).ok_or(InvalidValue),
3731 return retval.set(NullValue())
3732 );
3733 get_attrib(data)
3734 },
3735 WebGLVersion::WebGL2 => {
3736 let current_vao = self.current_vao_webgl2();
3737 let data = handle_potential_webgl_error!(
3738 self,
3739 current_vao.get_vertex_attrib(index).ok_or(InvalidValue),
3740 return retval.set(NullValue())
3741 );
3742 get_attrib(data)
3743 },
3744 }
3745 }
3746
3747 fn GetVertexAttribOffset(&self, index: u32, pname: u32) -> i64 {
3749 if pname != constants::VERTEX_ATTRIB_ARRAY_POINTER {
3750 self.webgl_error(InvalidEnum);
3751 return 0;
3752 }
3753 match self.webgl_version() {
3754 WebGLVersion::WebGL1 => {
3755 let current_vao = self.current_vao();
3756 let data = handle_potential_webgl_error!(
3757 self,
3758 current_vao.get_vertex_attrib(index).ok_or(InvalidValue),
3759 return 0
3760 );
3761 data.offset as i64
3762 },
3763 WebGLVersion::WebGL2 => {
3764 let current_vao = self.current_vao_webgl2();
3765 let data = handle_potential_webgl_error!(
3766 self,
3767 current_vao.get_vertex_attrib(index).ok_or(InvalidValue),
3768 return 0
3769 );
3770 data.offset as i64
3771 },
3772 }
3773 }
3774
3775 fn Hint(&self, target: u32, mode: u32) {
3777 if target != constants::GENERATE_MIPMAP_HINT &&
3778 !self.extension_manager.is_hint_target_enabled(target)
3779 {
3780 return self.webgl_error(InvalidEnum);
3781 }
3782
3783 match mode {
3784 constants::FASTEST | constants::NICEST | constants::DONT_CARE => (),
3785
3786 _ => return self.webgl_error(InvalidEnum),
3787 }
3788
3789 self.send_command(WebGLCommand::Hint(target, mode));
3790 }
3791
3792 fn IsBuffer(&self, buffer: Option<&WebGLBuffer>) -> bool {
3794 buffer.is_some_and(|buf| {
3795 self.validate_ownership(buf).is_ok() && buf.target().is_some() && !buf.is_deleted()
3796 })
3797 }
3798
3799 fn IsEnabled(&self, cap: u32) -> bool {
3801 handle_potential_webgl_error!(self, self.capabilities.is_enabled(cap), false)
3802 }
3803
3804 fn IsFramebuffer(&self, frame_buffer: Option<&WebGLFramebuffer>) -> bool {
3806 frame_buffer.is_some_and(|buf| {
3807 self.validate_ownership(buf).is_ok() && buf.target().is_some() && !buf.is_deleted()
3808 })
3809 }
3810
3811 fn IsProgram(&self, program: Option<&WebGLProgram>) -> bool {
3813 program.is_some_and(|p| self.validate_ownership(p).is_ok() && !p.is_deleted())
3814 }
3815
3816 fn IsRenderbuffer(&self, render_buffer: Option<&WebGLRenderbuffer>) -> bool {
3818 render_buffer.is_some_and(|buf| {
3819 self.validate_ownership(buf).is_ok() && buf.ever_bound() && !buf.is_deleted()
3820 })
3821 }
3822
3823 fn IsShader(&self, shader: Option<&WebGLShader>) -> bool {
3825 shader.is_some_and(|s| self.validate_ownership(s).is_ok() && !s.is_deleted())
3826 }
3827
3828 fn IsTexture(&self, texture: Option<&WebGLTexture>) -> bool {
3830 texture.is_some_and(|tex| {
3831 self.validate_ownership(tex).is_ok() && tex.target().is_some() && !tex.is_invalid()
3832 })
3833 }
3834
3835 fn LineWidth(&self, width: f32) {
3837 if width.is_nan() || width <= 0f32 {
3838 return self.webgl_error(InvalidValue);
3839 }
3840
3841 self.send_command(WebGLCommand::LineWidth(width))
3842 }
3843
3844 fn PixelStorei(&self, param_name: u32, param_value: i32) {
3849 let mut texture_settings = self.texture_unpacking_settings.get();
3850 match param_name {
3851 constants::UNPACK_FLIP_Y_WEBGL => {
3852 texture_settings.set(TextureUnpacking::FLIP_Y_AXIS, param_value != 0);
3853 },
3854 constants::UNPACK_PREMULTIPLY_ALPHA_WEBGL => {
3855 texture_settings.set(TextureUnpacking::PREMULTIPLY_ALPHA, param_value != 0);
3856 },
3857 constants::UNPACK_COLORSPACE_CONVERSION_WEBGL => {
3858 let convert = match param_value as u32 {
3859 constants::BROWSER_DEFAULT_WEBGL => true,
3860 constants::NONE => false,
3861 _ => return self.webgl_error(InvalidEnum),
3862 };
3863 texture_settings.set(TextureUnpacking::CONVERT_COLORSPACE, convert);
3864 },
3865 constants::UNPACK_ALIGNMENT => {
3866 match param_value {
3867 1 | 2 | 4 | 8 => (),
3868 _ => return self.webgl_error(InvalidValue),
3869 }
3870 self.texture_unpacking_alignment.set(param_value as u32);
3871 return;
3872 },
3873 constants::PACK_ALIGNMENT => {
3874 match param_value {
3875 1 | 2 | 4 | 8 => (),
3876 _ => return self.webgl_error(InvalidValue),
3877 }
3878 self.texture_packing_alignment.set(param_value as u8);
3882 return;
3883 },
3884 _ => return self.webgl_error(InvalidEnum),
3885 }
3886 self.texture_unpacking_settings.set(texture_settings);
3887 }
3888
3889 fn PolygonOffset(&self, factor: f32, units: f32) {
3891 self.send_command(WebGLCommand::PolygonOffset(factor, units))
3892 }
3893
3894 #[expect(unsafe_code)]
3896 fn ReadPixels(
3897 &self,
3898 x: i32,
3899 y: i32,
3900 width: i32,
3901 height: i32,
3902 format: u32,
3903 pixel_type: u32,
3904 mut pixels: CustomAutoRooterGuard<Option<ArrayBufferView>>,
3905 ) {
3906 handle_potential_webgl_error!(self, self.validate_framebuffer(), return);
3907
3908 let pixels =
3909 handle_potential_webgl_error!(self, pixels.as_mut().ok_or(InvalidValue), return);
3910
3911 if width < 0 || height < 0 {
3912 return self.webgl_error(InvalidValue);
3913 }
3914
3915 if format != constants::RGBA || pixel_type != constants::UNSIGNED_BYTE {
3916 return self.webgl_error(InvalidOperation);
3917 }
3918
3919 if pixels.get_array_type() != Type::Uint8 {
3920 return self.webgl_error(InvalidOperation);
3921 }
3922
3923 let (fb_width, fb_height) = handle_potential_webgl_error!(
3924 self,
3925 self.get_current_framebuffer_size().ok_or(InvalidOperation),
3926 return
3927 );
3928
3929 if width == 0 || height == 0 {
3930 return;
3931 }
3932
3933 let bytes_per_pixel = 4;
3934
3935 let row_len = handle_potential_webgl_error!(
3936 self,
3937 width.checked_mul(bytes_per_pixel).ok_or(InvalidOperation),
3938 return
3939 );
3940
3941 let pack_alignment = self.texture_packing_alignment.get() as i32;
3942 let dest_padding = match row_len % pack_alignment {
3943 0 => 0,
3944 remainder => pack_alignment - remainder,
3945 };
3946 let dest_stride = row_len + dest_padding;
3947
3948 let full_rows_len = handle_potential_webgl_error!(
3949 self,
3950 dest_stride.checked_mul(height - 1).ok_or(InvalidOperation),
3951 return
3952 );
3953 let required_dest_len = handle_potential_webgl_error!(
3954 self,
3955 full_rows_len.checked_add(row_len).ok_or(InvalidOperation),
3956 return
3957 );
3958
3959 let dest = unsafe { pixels.as_mut_slice() };
3960 if dest.len() < required_dest_len as usize {
3961 return self.webgl_error(InvalidOperation);
3962 }
3963
3964 let src_origin = Point2D::new(x, y);
3965 let src_size = Size2D::new(width as u32, height as u32);
3966 let fb_size = Size2D::new(fb_width as u32, fb_height as u32);
3967 let src_rect = match pixels::clip(src_origin, src_size.to_u32(), fb_size.to_u32()) {
3968 Some(rect) => rect,
3969 None => return,
3970 };
3971
3972 let src_rect = src_rect.to_u32();
3976
3977 let mut dest_offset = 0;
3978 if x < 0 {
3979 dest_offset += -x * bytes_per_pixel;
3980 }
3981 if y < 0 {
3982 dest_offset += -y * row_len;
3983 }
3984
3985 let (sender, receiver) = generic_channel::channel().unwrap();
3986 self.send_command(WebGLCommand::ReadPixels(
3987 src_rect, format, pixel_type, sender,
3988 ));
3989 let (src, _) = receiver.recv().unwrap();
3990
3991 let src_row_len = src_rect.size.width as usize * bytes_per_pixel as usize;
3992 for i in 0..src_rect.size.height {
3993 let dest_start = dest_offset as usize + i as usize * dest_stride as usize;
3994 let dest_end = dest_start + src_row_len;
3995 let src_start = i as usize * src_row_len;
3996 let src_end = src_start + src_row_len;
3997 dest[dest_start..dest_end].copy_from_slice(&src[src_start..src_end]);
3998 }
3999 }
4000
4001 fn SampleCoverage(&self, value: f32, invert: bool) {
4003 self.send_command(WebGLCommand::SampleCoverage(value, invert));
4004 }
4005
4006 fn Scissor(&self, x: i32, y: i32, width: i32, height: i32) {
4008 if width < 0 || height < 0 {
4009 return self.webgl_error(InvalidValue);
4010 }
4011
4012 let width = width as u32;
4013 let height = height as u32;
4014
4015 self.current_scissor.set((x, y, width, height));
4016 self.send_command(WebGLCommand::Scissor(x, y, width, height));
4017 }
4018
4019 fn StencilFunc(&self, func: u32, ref_: i32, mask: u32) {
4021 match func {
4022 constants::NEVER |
4023 constants::LESS |
4024 constants::EQUAL |
4025 constants::LEQUAL |
4026 constants::GREATER |
4027 constants::NOTEQUAL |
4028 constants::GEQUAL |
4029 constants::ALWAYS => self.send_command(WebGLCommand::StencilFunc(func, ref_, mask)),
4030 _ => self.webgl_error(InvalidEnum),
4031 }
4032 }
4033
4034 fn StencilFuncSeparate(&self, face: u32, func: u32, ref_: i32, mask: u32) {
4036 match face {
4037 constants::FRONT | constants::BACK | constants::FRONT_AND_BACK => (),
4038 _ => return self.webgl_error(InvalidEnum),
4039 }
4040
4041 match func {
4042 constants::NEVER |
4043 constants::LESS |
4044 constants::EQUAL |
4045 constants::LEQUAL |
4046 constants::GREATER |
4047 constants::NOTEQUAL |
4048 constants::GEQUAL |
4049 constants::ALWAYS => {
4050 self.send_command(WebGLCommand::StencilFuncSeparate(face, func, ref_, mask))
4051 },
4052 _ => self.webgl_error(InvalidEnum),
4053 }
4054 }
4055
4056 fn StencilMask(&self, mask: u32) {
4058 self.send_command(WebGLCommand::StencilMask(mask))
4059 }
4060
4061 fn StencilMaskSeparate(&self, face: u32, mask: u32) {
4063 match face {
4064 constants::FRONT | constants::BACK | constants::FRONT_AND_BACK => {
4065 self.send_command(WebGLCommand::StencilMaskSeparate(face, mask))
4066 },
4067 _ => self.webgl_error(InvalidEnum),
4068 };
4069 }
4070
4071 fn StencilOp(&self, fail: u32, zfail: u32, zpass: u32) {
4073 if self.validate_stencil_actions(fail) &&
4074 self.validate_stencil_actions(zfail) &&
4075 self.validate_stencil_actions(zpass)
4076 {
4077 self.send_command(WebGLCommand::StencilOp(fail, zfail, zpass));
4078 } else {
4079 self.webgl_error(InvalidEnum)
4080 }
4081 }
4082
4083 fn StencilOpSeparate(&self, face: u32, fail: u32, zfail: u32, zpass: u32) {
4085 match face {
4086 constants::FRONT | constants::BACK | constants::FRONT_AND_BACK => (),
4087 _ => return self.webgl_error(InvalidEnum),
4088 }
4089
4090 if self.validate_stencil_actions(fail) &&
4091 self.validate_stencil_actions(zfail) &&
4092 self.validate_stencil_actions(zpass)
4093 {
4094 self.send_command(WebGLCommand::StencilOpSeparate(face, fail, zfail, zpass))
4095 } else {
4096 self.webgl_error(InvalidEnum)
4097 }
4098 }
4099
4100 fn LinkProgram(&self, program: &WebGLProgram) {
4102 handle_potential_webgl_error!(self, self.validate_ownership(program), return);
4103 if program.is_deleted() {
4104 return self.webgl_error(InvalidValue);
4105 }
4106 handle_potential_webgl_error!(self, program.link());
4107 }
4108
4109 fn ShaderSource(&self, shader: &WebGLShader, source: DOMString) {
4111 handle_potential_webgl_error!(self, self.validate_ownership(shader), return);
4112 shader.set_source(source)
4113 }
4114
4115 fn GetShaderSource(&self, shader: &WebGLShader) -> Option<DOMString> {
4117 handle_potential_webgl_error!(self, self.validate_ownership(shader), return None);
4118 Some(shader.source())
4119 }
4120
4121 fn Uniform1f(&self, location: Option<&WebGLUniformLocation>, val: f32) {
4123 self.with_location(location, |location| {
4124 match location.type_() {
4125 constants::BOOL | constants::FLOAT => {},
4126 _ => return Err(InvalidOperation),
4127 }
4128 self.send_command(WebGLCommand::Uniform1f(location.id(), val));
4129 Ok(())
4130 });
4131 }
4132
4133 fn Uniform1i(&self, location: Option<&WebGLUniformLocation>, val: i32) {
4135 self.with_location(location, |location| {
4136 match location.type_() {
4137 constants::BOOL | constants::INT => {},
4138 constants::SAMPLER_2D |
4139 WebGL2RenderingContextConstants::SAMPLER_3D |
4140 WebGL2RenderingContextConstants::SAMPLER_2D_ARRAY |
4141 constants::SAMPLER_CUBE => {
4142 if val < 0 || val as u32 >= self.limits.max_combined_texture_image_units {
4143 return Err(InvalidValue);
4144 }
4145 },
4146 _ => return Err(InvalidOperation),
4147 }
4148 self.send_command(WebGLCommand::Uniform1i(location.id(), val));
4149 Ok(())
4150 });
4151 }
4152
4153 fn Uniform1iv(&self, location: Option<&WebGLUniformLocation>, val: Int32ArrayOrLongSequence) {
4155 self.uniform1iv(location, val, 0, 0)
4156 }
4157
4158 fn Uniform1fv(
4160 &self,
4161 location: Option<&WebGLUniformLocation>,
4162 val: Float32ArrayOrUnrestrictedFloatSequence,
4163 ) {
4164 self.uniform1fv(location, val, 0, 0)
4165 }
4166
4167 fn Uniform2f(&self, location: Option<&WebGLUniformLocation>, x: f32, y: f32) {
4169 self.with_location(location, |location| {
4170 match location.type_() {
4171 constants::BOOL_VEC2 | constants::FLOAT_VEC2 => {},
4172 _ => return Err(InvalidOperation),
4173 }
4174 self.send_command(WebGLCommand::Uniform2f(location.id(), x, y));
4175 Ok(())
4176 });
4177 }
4178
4179 fn Uniform2fv(
4181 &self,
4182 location: Option<&WebGLUniformLocation>,
4183 val: Float32ArrayOrUnrestrictedFloatSequence,
4184 ) {
4185 self.uniform2fv(location, val, 0, 0)
4186 }
4187
4188 fn Uniform2i(&self, location: Option<&WebGLUniformLocation>, x: i32, y: i32) {
4190 self.with_location(location, |location| {
4191 match location.type_() {
4192 constants::BOOL_VEC2 | constants::INT_VEC2 => {},
4193 _ => return Err(InvalidOperation),
4194 }
4195 self.send_command(WebGLCommand::Uniform2i(location.id(), x, y));
4196 Ok(())
4197 });
4198 }
4199
4200 fn Uniform2iv(&self, location: Option<&WebGLUniformLocation>, val: Int32ArrayOrLongSequence) {
4202 self.uniform2iv(location, val, 0, 0)
4203 }
4204
4205 fn Uniform3f(&self, location: Option<&WebGLUniformLocation>, x: f32, y: f32, z: f32) {
4207 self.with_location(location, |location| {
4208 match location.type_() {
4209 constants::BOOL_VEC3 | constants::FLOAT_VEC3 => {},
4210 _ => return Err(InvalidOperation),
4211 }
4212 self.send_command(WebGLCommand::Uniform3f(location.id(), x, y, z));
4213 Ok(())
4214 });
4215 }
4216
4217 fn Uniform3fv(
4219 &self,
4220 location: Option<&WebGLUniformLocation>,
4221 val: Float32ArrayOrUnrestrictedFloatSequence,
4222 ) {
4223 self.uniform3fv(location, val, 0, 0)
4224 }
4225
4226 fn Uniform3i(&self, location: Option<&WebGLUniformLocation>, x: i32, y: i32, z: i32) {
4228 self.with_location(location, |location| {
4229 match location.type_() {
4230 constants::BOOL_VEC3 | constants::INT_VEC3 => {},
4231 _ => return Err(InvalidOperation),
4232 }
4233 self.send_command(WebGLCommand::Uniform3i(location.id(), x, y, z));
4234 Ok(())
4235 });
4236 }
4237
4238 fn Uniform3iv(&self, location: Option<&WebGLUniformLocation>, val: Int32ArrayOrLongSequence) {
4240 self.uniform3iv(location, val, 0, 0)
4241 }
4242
4243 fn Uniform4i(&self, location: Option<&WebGLUniformLocation>, x: i32, y: i32, z: i32, w: i32) {
4245 self.with_location(location, |location| {
4246 match location.type_() {
4247 constants::BOOL_VEC4 | constants::INT_VEC4 => {},
4248 _ => return Err(InvalidOperation),
4249 }
4250 self.send_command(WebGLCommand::Uniform4i(location.id(), x, y, z, w));
4251 Ok(())
4252 });
4253 }
4254
4255 fn Uniform4iv(&self, location: Option<&WebGLUniformLocation>, val: Int32ArrayOrLongSequence) {
4257 self.uniform4iv(location, val, 0, 0)
4258 }
4259
4260 fn Uniform4f(&self, location: Option<&WebGLUniformLocation>, x: f32, y: f32, z: f32, w: f32) {
4262 self.with_location(location, |location| {
4263 match location.type_() {
4264 constants::BOOL_VEC4 | constants::FLOAT_VEC4 => {},
4265 _ => return Err(InvalidOperation),
4266 }
4267 self.send_command(WebGLCommand::Uniform4f(location.id(), x, y, z, w));
4268 Ok(())
4269 });
4270 }
4271
4272 fn Uniform4fv(
4274 &self,
4275 location: Option<&WebGLUniformLocation>,
4276 val: Float32ArrayOrUnrestrictedFloatSequence,
4277 ) {
4278 self.uniform4fv(location, val, 0, 0)
4279 }
4280
4281 fn UniformMatrix2fv(
4283 &self,
4284 location: Option<&WebGLUniformLocation>,
4285 transpose: bool,
4286 val: Float32ArrayOrUnrestrictedFloatSequence,
4287 ) {
4288 self.uniform_matrix_2fv(location, transpose, val, 0, 0)
4289 }
4290
4291 fn UniformMatrix3fv(
4293 &self,
4294 location: Option<&WebGLUniformLocation>,
4295 transpose: bool,
4296 val: Float32ArrayOrUnrestrictedFloatSequence,
4297 ) {
4298 self.uniform_matrix_3fv(location, transpose, val, 0, 0)
4299 }
4300
4301 fn UniformMatrix4fv(
4303 &self,
4304 location: Option<&WebGLUniformLocation>,
4305 transpose: bool,
4306 val: Float32ArrayOrUnrestrictedFloatSequence,
4307 ) {
4308 self.uniform_matrix_4fv(location, transpose, val, 0, 0)
4309 }
4310
4311 #[expect(unsafe_code)]
4313 fn GetUniform(
4314 &self,
4315 cx: SafeJSContext,
4316 program: &WebGLProgram,
4317 location: &WebGLUniformLocation,
4318 mut rval: MutableHandleValue,
4319 ) {
4320 handle_potential_webgl_error!(
4321 self,
4322 self.uniform_check_program(program, location),
4323 return rval.set(NullValue())
4324 );
4325
4326 let triple = (self, program.id(), location.id());
4327
4328 match location.type_() {
4329 constants::BOOL => rval.set(BooleanValue(uniform_get(
4330 triple,
4331 WebGLCommand::GetUniformBool,
4332 ))),
4333 constants::BOOL_VEC2 => uniform_get(triple, WebGLCommand::GetUniformBool2)
4334 .safe_to_jsval(cx, rval, CanGc::note()),
4335 constants::BOOL_VEC3 => uniform_get(triple, WebGLCommand::GetUniformBool3)
4336 .safe_to_jsval(cx, rval, CanGc::note()),
4337 constants::BOOL_VEC4 => uniform_get(triple, WebGLCommand::GetUniformBool4)
4338 .safe_to_jsval(cx, rval, CanGc::note()),
4339 constants::INT |
4340 constants::SAMPLER_2D |
4341 constants::SAMPLER_CUBE |
4342 WebGL2RenderingContextConstants::SAMPLER_2D_ARRAY |
4343 WebGL2RenderingContextConstants::SAMPLER_3D => {
4344 rval.set(Int32Value(uniform_get(triple, WebGLCommand::GetUniformInt)))
4345 },
4346 constants::INT_VEC2 => unsafe {
4347 uniform_typed::<Int32>(
4348 *cx,
4349 &uniform_get(triple, WebGLCommand::GetUniformInt2),
4350 rval,
4351 )
4352 },
4353 constants::INT_VEC3 => unsafe {
4354 uniform_typed::<Int32>(
4355 *cx,
4356 &uniform_get(triple, WebGLCommand::GetUniformInt3),
4357 rval,
4358 )
4359 },
4360 constants::INT_VEC4 => unsafe {
4361 uniform_typed::<Int32>(
4362 *cx,
4363 &uniform_get(triple, WebGLCommand::GetUniformInt4),
4364 rval,
4365 )
4366 },
4367 constants::FLOAT => rval
4368 .set(DoubleValue(
4369 uniform_get(triple, WebGLCommand::GetUniformFloat) as f64,
4370 )),
4371 constants::FLOAT_VEC2 => unsafe {
4372 uniform_typed::<Float32>(
4373 *cx,
4374 &uniform_get(triple, WebGLCommand::GetUniformFloat2),
4375 rval,
4376 )
4377 },
4378 constants::FLOAT_VEC3 => unsafe {
4379 uniform_typed::<Float32>(
4380 *cx,
4381 &uniform_get(triple, WebGLCommand::GetUniformFloat3),
4382 rval,
4383 )
4384 },
4385 constants::FLOAT_VEC4 | constants::FLOAT_MAT2 => unsafe {
4386 uniform_typed::<Float32>(
4387 *cx,
4388 &uniform_get(triple, WebGLCommand::GetUniformFloat4),
4389 rval,
4390 )
4391 },
4392 constants::FLOAT_MAT3 => unsafe {
4393 uniform_typed::<Float32>(
4394 *cx,
4395 &uniform_get(triple, WebGLCommand::GetUniformFloat9),
4396 rval,
4397 )
4398 },
4399 constants::FLOAT_MAT4 => unsafe {
4400 uniform_typed::<Float32>(
4401 *cx,
4402 &uniform_get(triple, WebGLCommand::GetUniformFloat16),
4403 rval,
4404 )
4405 },
4406 _ => panic!("wrong uniform type"),
4407 }
4408 }
4409
4410 fn UseProgram(&self, program: Option<&WebGLProgram>) {
4412 if let Some(program) = program {
4413 handle_potential_webgl_error!(self, self.validate_ownership(program), return);
4414 if program.is_deleted() || !program.is_linked() {
4415 return self.webgl_error(InvalidOperation);
4416 }
4417 if program.is_in_use() {
4418 return;
4419 }
4420 program.in_use(true);
4421 }
4422 match self.current_program.get() {
4423 Some(ref current) if program != Some(&**current) => current.in_use(false),
4424 _ => {},
4425 }
4426 self.send_command(WebGLCommand::UseProgram(program.map(|p| p.id())));
4427 self.current_program.set(program);
4428 }
4429
4430 fn ValidateProgram(&self, program: &WebGLProgram) {
4432 handle_potential_webgl_error!(self, self.validate_ownership(program), return);
4433 if let Err(e) = program.validate() {
4434 self.webgl_error(e);
4435 }
4436 }
4437
4438 fn VertexAttrib1f(&self, indx: u32, x: f32) {
4440 self.vertex_attrib(indx, x, 0f32, 0f32, 1f32)
4441 }
4442
4443 fn VertexAttrib1fv(&self, indx: u32, v: Float32ArrayOrUnrestrictedFloatSequence) {
4445 let values = match v {
4446 Float32ArrayOrUnrestrictedFloatSequence::Float32Array(v) => v.to_vec(),
4447 Float32ArrayOrUnrestrictedFloatSequence::UnrestrictedFloatSequence(v) => v,
4448 };
4449 if values.is_empty() {
4450 return self.webgl_error(InvalidValue);
4452 }
4453 self.vertex_attrib(indx, values[0], 0f32, 0f32, 1f32);
4454 }
4455
4456 fn VertexAttrib2f(&self, indx: u32, x: f32, y: f32) {
4458 self.vertex_attrib(indx, x, y, 0f32, 1f32)
4459 }
4460
4461 fn VertexAttrib2fv(&self, indx: u32, v: Float32ArrayOrUnrestrictedFloatSequence) {
4463 let values = match v {
4464 Float32ArrayOrUnrestrictedFloatSequence::Float32Array(v) => v.to_vec(),
4465 Float32ArrayOrUnrestrictedFloatSequence::UnrestrictedFloatSequence(v) => v,
4466 };
4467 if values.len() < 2 {
4468 return self.webgl_error(InvalidValue);
4470 }
4471 self.vertex_attrib(indx, values[0], values[1], 0f32, 1f32);
4472 }
4473
4474 fn VertexAttrib3f(&self, indx: u32, x: f32, y: f32, z: f32) {
4476 self.vertex_attrib(indx, x, y, z, 1f32)
4477 }
4478
4479 fn VertexAttrib3fv(&self, indx: u32, v: Float32ArrayOrUnrestrictedFloatSequence) {
4481 let values = match v {
4482 Float32ArrayOrUnrestrictedFloatSequence::Float32Array(v) => v.to_vec(),
4483 Float32ArrayOrUnrestrictedFloatSequence::UnrestrictedFloatSequence(v) => v,
4484 };
4485 if values.len() < 3 {
4486 return self.webgl_error(InvalidValue);
4488 }
4489 self.vertex_attrib(indx, values[0], values[1], values[2], 1f32);
4490 }
4491
4492 fn VertexAttrib4f(&self, indx: u32, x: f32, y: f32, z: f32, w: f32) {
4494 self.vertex_attrib(indx, x, y, z, w)
4495 }
4496
4497 fn VertexAttrib4fv(&self, indx: u32, v: Float32ArrayOrUnrestrictedFloatSequence) {
4499 let values = match v {
4500 Float32ArrayOrUnrestrictedFloatSequence::Float32Array(v) => v.to_vec(),
4501 Float32ArrayOrUnrestrictedFloatSequence::UnrestrictedFloatSequence(v) => v,
4502 };
4503 if values.len() < 4 {
4504 return self.webgl_error(InvalidValue);
4506 }
4507 self.vertex_attrib(indx, values[0], values[1], values[2], values[3]);
4508 }
4509
4510 fn VertexAttribPointer(
4512 &self,
4513 index: u32,
4514 size: i32,
4515 type_: u32,
4516 normalized: bool,
4517 stride: i32,
4518 offset: i64,
4519 ) {
4520 let res = match self.webgl_version() {
4521 WebGLVersion::WebGL1 => self
4522 .current_vao()
4523 .vertex_attrib_pointer(index, size, type_, normalized, stride, offset),
4524 WebGLVersion::WebGL2 => self
4525 .current_vao_webgl2()
4526 .vertex_attrib_pointer(index, size, type_, normalized, stride, offset),
4527 };
4528 handle_potential_webgl_error!(self, res);
4529 }
4530
4531 fn Viewport(&self, x: i32, y: i32, width: i32, height: i32) {
4533 if width < 0 || height < 0 {
4534 return self.webgl_error(InvalidValue);
4535 }
4536
4537 self.send_command(WebGLCommand::SetViewport(x, y, width, height))
4538 }
4539
4540 #[expect(unsafe_code)]
4542 fn TexImage2D(
4543 &self,
4544 target: u32,
4545 level: i32,
4546 internal_format: i32,
4547 width: i32,
4548 height: i32,
4549 border: i32,
4550 format: u32,
4551 data_type: u32,
4552 pixels: CustomAutoRooterGuard<Option<ArrayBufferView>>,
4553 ) -> ErrorResult {
4554 if !self.extension_manager.is_tex_type_enabled(data_type) {
4555 self.webgl_error(InvalidEnum);
4556 return Ok(());
4557 }
4558
4559 let validator = TexImage2DValidator::new(
4560 self,
4561 target,
4562 level,
4563 internal_format as u32,
4564 width,
4565 height,
4566 border,
4567 format,
4568 data_type,
4569 );
4570
4571 let TexImage2DValidatorResult {
4572 texture,
4573 target,
4574 width,
4575 height,
4576 level,
4577 border,
4578 internal_format,
4579 format,
4580 data_type,
4581 } = match validator.validate() {
4582 Ok(result) => result,
4583 Err(_) => return Ok(()), };
4585
4586 if !internal_format.compatible_data_types().contains(&data_type) {
4587 return {
4588 self.webgl_error(InvalidOperation);
4589 Ok(())
4590 };
4591 }
4592 if texture.is_immutable() {
4593 return {
4594 self.webgl_error(InvalidOperation);
4595 Ok(())
4596 };
4597 }
4598
4599 let unpacking_alignment = self.texture_unpacking_alignment.get();
4600
4601 let expected_byte_length = match self.validate_tex_image_2d_data(
4602 width,
4603 height,
4604 format,
4605 data_type,
4606 unpacking_alignment,
4607 pixels.as_ref(),
4608 ) {
4609 Ok(byte_length) => byte_length,
4610 Err(()) => return Ok(()),
4611 };
4612
4613 let buff = match *pixels {
4616 None => GenericSharedMemory::from_bytes(&vec![0u8; expected_byte_length as usize]),
4617 Some(ref data) => GenericSharedMemory::from_bytes(unsafe { data.as_slice() }),
4618 };
4619
4620 if buff.len() < expected_byte_length as usize {
4627 return {
4628 self.webgl_error(InvalidOperation);
4629 Ok(())
4630 };
4631 }
4632
4633 let size = Size2D::new(width, height);
4634
4635 if !self.validate_filterable_texture(
4636 &texture,
4637 target,
4638 level,
4639 internal_format,
4640 size,
4641 data_type,
4642 ) {
4643 return Ok(());
4646 }
4647
4648 let size = Size2D::new(width, height);
4649
4650 let (alpha_treatment, y_axis_treatment) =
4651 self.get_current_unpack_state(Alpha::NotPremultiplied);
4652
4653 self.tex_image_2d(
4654 &texture,
4655 target,
4656 data_type,
4657 internal_format,
4658 format,
4659 level,
4660 border,
4661 unpacking_alignment,
4662 size,
4663 TexSource::Pixels(TexPixels::from_array(
4664 buff,
4665 size,
4666 alpha_treatment,
4667 y_axis_treatment,
4668 )),
4669 );
4670
4671 Ok(())
4672 }
4673
4674 fn TexImage2D_(
4676 &self,
4677 target: u32,
4678 level: i32,
4679 internal_format: i32,
4680 format: u32,
4681 data_type: u32,
4682 source: TexImageSource,
4683 ) -> ErrorResult {
4684 if !self.extension_manager.is_tex_type_enabled(data_type) {
4685 self.webgl_error(InvalidEnum);
4686 return Ok(());
4687 }
4688
4689 let pixels = match self.get_image_pixels(source)? {
4690 Some(pixels) => pixels,
4691 None => return Ok(()),
4692 };
4693
4694 let validator = TexImage2DValidator::new(
4695 self,
4696 target,
4697 level,
4698 internal_format as u32,
4699 pixels.size().width as i32,
4700 pixels.size().height as i32,
4701 0,
4702 format,
4703 data_type,
4704 );
4705
4706 let TexImage2DValidatorResult {
4707 texture,
4708 target,
4709 level,
4710 border,
4711 internal_format,
4712 format,
4713 data_type,
4714 ..
4715 } = match validator.validate() {
4716 Ok(result) => result,
4717 Err(_) => return Ok(()), };
4719
4720 if !internal_format.compatible_data_types().contains(&data_type) {
4721 return {
4722 self.webgl_error(InvalidOperation);
4723 Ok(())
4724 };
4725 }
4726 if texture.is_immutable() {
4727 return {
4728 self.webgl_error(InvalidOperation);
4729 Ok(())
4730 };
4731 }
4732
4733 if !self.validate_filterable_texture(
4734 &texture,
4735 target,
4736 level,
4737 internal_format,
4738 pixels.size(),
4739 data_type,
4740 ) {
4741 return Ok(());
4744 }
4745
4746 self.tex_image_2d(
4747 &texture,
4748 target,
4749 data_type,
4750 internal_format,
4751 format,
4752 level,
4753 border,
4754 1,
4755 pixels.size(),
4756 TexSource::Pixels(pixels),
4757 );
4758 Ok(())
4759 }
4760
4761 #[expect(unsafe_code)]
4763 fn TexSubImage2D(
4764 &self,
4765 target: u32,
4766 level: i32,
4767 xoffset: i32,
4768 yoffset: i32,
4769 width: i32,
4770 height: i32,
4771 format: u32,
4772 data_type: u32,
4773 pixels: CustomAutoRooterGuard<Option<ArrayBufferView>>,
4774 ) -> ErrorResult {
4775 let validator = TexImage2DValidator::new(
4776 self, target, level, format, width, height, 0, format, data_type,
4777 );
4778 let TexImage2DValidatorResult {
4779 texture,
4780 target,
4781 width,
4782 height,
4783 level,
4784 format,
4785 data_type,
4786 ..
4787 } = match validator.validate() {
4788 Ok(result) => result,
4789 Err(_) => return Ok(()), };
4791
4792 let unpacking_alignment = self.texture_unpacking_alignment.get();
4793
4794 let expected_byte_length = match self.validate_tex_image_2d_data(
4795 width,
4796 height,
4797 format,
4798 data_type,
4799 unpacking_alignment,
4800 pixels.as_ref(),
4801 ) {
4802 Ok(byte_length) => byte_length,
4803 Err(()) => return Ok(()),
4804 };
4805
4806 let buff = handle_potential_webgl_error!(
4807 self,
4808 pixels
4809 .as_ref()
4810 .map(|p| GenericSharedMemory::from_bytes(unsafe { p.as_slice() }))
4811 .ok_or(InvalidValue),
4812 return Ok(())
4813 );
4814
4815 if buff.len() < expected_byte_length as usize {
4822 return {
4823 self.webgl_error(InvalidOperation);
4824 Ok(())
4825 };
4826 }
4827
4828 let (alpha_treatment, y_axis_treatment) =
4829 self.get_current_unpack_state(Alpha::NotPremultiplied);
4830
4831 self.tex_sub_image_2d(
4832 texture,
4833 target,
4834 level,
4835 xoffset,
4836 yoffset,
4837 format,
4838 data_type,
4839 unpacking_alignment,
4840 TexPixels::from_array(
4841 buff,
4842 Size2D::new(width, height),
4843 alpha_treatment,
4844 y_axis_treatment,
4845 ),
4846 );
4847 Ok(())
4848 }
4849
4850 fn TexSubImage2D_(
4852 &self,
4853 target: u32,
4854 level: i32,
4855 xoffset: i32,
4856 yoffset: i32,
4857 format: u32,
4858 data_type: u32,
4859 source: TexImageSource,
4860 ) -> ErrorResult {
4861 let pixels = match self.get_image_pixels(source)? {
4862 Some(pixels) => pixels,
4863 None => return Ok(()),
4864 };
4865
4866 let validator = TexImage2DValidator::new(
4867 self,
4868 target,
4869 level,
4870 format,
4871 pixels.size().width as i32,
4872 pixels.size().height as i32,
4873 0,
4874 format,
4875 data_type,
4876 );
4877 let TexImage2DValidatorResult {
4878 texture,
4879 target,
4880 level,
4881 format,
4882 data_type,
4883 ..
4884 } = match validator.validate() {
4885 Ok(result) => result,
4886 Err(_) => return Ok(()), };
4888
4889 self.tex_sub_image_2d(
4890 texture, target, level, xoffset, yoffset, format, data_type, 1, pixels,
4891 );
4892 Ok(())
4893 }
4894
4895 fn TexParameterf(&self, target: u32, name: u32, value: f32) {
4897 self.tex_parameter(target, name, TexParameterValue::Float(value))
4898 }
4899
4900 fn TexParameteri(&self, target: u32, name: u32, value: i32) {
4902 self.tex_parameter(target, name, TexParameterValue::Int(value))
4903 }
4904
4905 fn CheckFramebufferStatus(&self, target: u32) -> u32 {
4907 if target != constants::FRAMEBUFFER {
4913 self.webgl_error(InvalidEnum);
4914 return 0;
4915 }
4916
4917 match self.bound_draw_framebuffer.get() {
4918 Some(fb) => fb.check_status(),
4919 None => constants::FRAMEBUFFER_COMPLETE,
4920 }
4921 }
4922
4923 fn RenderbufferStorage(&self, target: u32, internal_format: u32, width: i32, height: i32) {
4925 self.renderbuffer_storage(target, 0, internal_format, width, height)
4926 }
4927
4928 fn FramebufferRenderbuffer(
4930 &self,
4931 target: u32,
4932 attachment: u32,
4933 renderbuffertarget: u32,
4934 rb: Option<&WebGLRenderbuffer>,
4935 ) {
4936 if let Some(rb) = rb {
4937 handle_potential_webgl_error!(self, self.validate_ownership(rb), return);
4938 }
4939
4940 if target != constants::FRAMEBUFFER || renderbuffertarget != constants::RENDERBUFFER {
4941 return self.webgl_error(InvalidEnum);
4942 }
4943
4944 match self.bound_draw_framebuffer.get() {
4945 Some(fb) => handle_potential_webgl_error!(self, fb.renderbuffer(attachment, rb)),
4946 None => self.webgl_error(InvalidOperation),
4947 };
4948 }
4949
4950 fn FramebufferTexture2D(
4952 &self,
4953 target: u32,
4954 attachment: u32,
4955 textarget: u32,
4956 texture: Option<&WebGLTexture>,
4957 level: i32,
4958 ) {
4959 if let Some(texture) = texture {
4960 handle_potential_webgl_error!(self, self.validate_ownership(texture), return);
4961 }
4962
4963 if target != constants::FRAMEBUFFER {
4964 return self.webgl_error(InvalidEnum);
4965 }
4966
4967 if level != 0 {
4973 return self.webgl_error(InvalidValue);
4974 }
4975
4976 match self.bound_draw_framebuffer.get() {
4977 Some(fb) => handle_potential_webgl_error!(
4978 self,
4979 fb.texture2d(attachment, textarget, texture, level)
4980 ),
4981 None => self.webgl_error(InvalidOperation),
4982 };
4983 }
4984
4985 fn GetAttachedShaders(&self, program: &WebGLProgram) -> Option<Vec<DomRoot<WebGLShader>>> {
4987 handle_potential_webgl_error!(self, self.validate_ownership(program), return None);
4988 handle_potential_webgl_error!(self, program.attached_shaders().map(Some), None)
4989 }
4990
4991 #[cfg(feature = "webxr")]
4993 fn MakeXRCompatible(&self, can_gc: CanGc) -> Rc<Promise> {
4994 let p = Promise::new(&self.global(), can_gc);
4996 p.resolve_native(&(), can_gc);
4997 p
4998 }
4999}
5000
5001#[derive(Default, JSTraceable, MallocSizeOf)]
5002struct Capabilities {
5003 value: Cell<CapFlags>,
5004}
5005
5006impl Capabilities {
5007 fn set(&self, cap: u32, set: bool) -> WebGLResult<bool> {
5008 let cap = CapFlags::from_enum(cap)?;
5009 let mut value = self.value.get();
5010 if value.contains(cap) == set {
5011 return Ok(false);
5012 }
5013 value.set(cap, set);
5014 self.value.set(value);
5015 Ok(true)
5016 }
5017
5018 fn is_enabled(&self, cap: u32) -> WebGLResult<bool> {
5019 Ok(self.value.get().contains(CapFlags::from_enum(cap)?))
5020 }
5021}
5022
5023impl Default for CapFlags {
5024 fn default() -> Self {
5025 CapFlags::DITHER
5026 }
5027}
5028
5029macro_rules! capabilities {
5030 ($name:ident, $next:ident, $($rest:ident,)*) => {
5031 capabilities!($name, $next, $($rest,)* [$name = 1;]);
5032 };
5033 ($prev:ident, $name:ident, $($rest:ident,)* [$($tt:tt)*]) => {
5034 capabilities!($name, $($rest,)* [$($tt)* $name = Self::$prev.bits() << 1;]);
5035 };
5036 ($prev:ident, [$($name:ident = $value:expr;)*]) => {
5037 #[derive(Clone, Copy, JSTraceable, MallocSizeOf)]
5038 pub(crate) struct CapFlags(u16);
5039
5040 bitflags! {
5041 impl CapFlags: u16 {
5042 $(const $name = $value;)*
5043 }
5044 }
5045
5046 impl CapFlags {
5047 fn from_enum(cap: u32) -> WebGLResult<Self> {
5048 match cap {
5049 $(constants::$name => Ok(Self::$name),)*
5050 _ => Err(InvalidEnum),
5051 }
5052 }
5053 }
5054 };
5055}
5056
5057capabilities! {
5058 BLEND,
5059 CULL_FACE,
5060 DEPTH_TEST,
5061 DITHER,
5062 POLYGON_OFFSET_FILL,
5063 SAMPLE_ALPHA_TO_COVERAGE,
5064 SAMPLE_COVERAGE,
5065 SCISSOR_TEST,
5066 STENCIL_TEST,
5067}
5068
5069#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
5070#[derive(JSTraceable, MallocSizeOf)]
5071pub(crate) struct Textures {
5072 active_unit: Cell<u32>,
5073 units: Box<[TextureUnit]>,
5074}
5075
5076impl Textures {
5077 fn new(max_combined_textures: u32) -> Self {
5078 Self {
5079 active_unit: Default::default(),
5080 units: (0..max_combined_textures)
5081 .map(|_| Default::default())
5082 .collect::<Vec<_>>()
5083 .into(),
5084 }
5085 }
5086
5087 pub(crate) fn active_unit_enum(&self) -> u32 {
5088 self.active_unit.get() + constants::TEXTURE0
5089 }
5090
5091 fn set_active_unit_enum(&self, index: u32) -> WebGLResult<()> {
5092 if index < constants::TEXTURE0 || (index - constants::TEXTURE0) as usize > self.units.len()
5093 {
5094 return Err(InvalidEnum);
5095 }
5096 self.active_unit.set(index - constants::TEXTURE0);
5097 Ok(())
5098 }
5099
5100 pub(crate) fn active_texture_slot(
5101 &self,
5102 target: u32,
5103 webgl_version: WebGLVersion,
5104 ) -> WebGLResult<&MutNullableDom<WebGLTexture>> {
5105 let active_unit = self.active_unit();
5106 let is_webgl2 = webgl_version == WebGLVersion::WebGL2;
5107 match target {
5108 constants::TEXTURE_2D => Ok(&active_unit.tex_2d),
5109 constants::TEXTURE_CUBE_MAP => Ok(&active_unit.tex_cube_map),
5110 WebGL2RenderingContextConstants::TEXTURE_2D_ARRAY if is_webgl2 => {
5111 Ok(&active_unit.tex_2d_array)
5112 },
5113 WebGL2RenderingContextConstants::TEXTURE_3D if is_webgl2 => Ok(&active_unit.tex_3d),
5114 _ => Err(InvalidEnum),
5115 }
5116 }
5117
5118 pub(crate) fn active_texture_for_image_target(
5119 &self,
5120 target: TexImageTarget,
5121 ) -> Option<DomRoot<WebGLTexture>> {
5122 let active_unit = self.active_unit();
5123 match target {
5124 TexImageTarget::Texture2D => active_unit.tex_2d.get(),
5125 TexImageTarget::Texture2DArray => active_unit.tex_2d_array.get(),
5126 TexImageTarget::Texture3D => active_unit.tex_3d.get(),
5127 TexImageTarget::CubeMap |
5128 TexImageTarget::CubeMapPositiveX |
5129 TexImageTarget::CubeMapNegativeX |
5130 TexImageTarget::CubeMapPositiveY |
5131 TexImageTarget::CubeMapNegativeY |
5132 TexImageTarget::CubeMapPositiveZ |
5133 TexImageTarget::CubeMapNegativeZ => active_unit.tex_cube_map.get(),
5134 }
5135 }
5136
5137 fn active_unit(&self) -> &TextureUnit {
5138 &self.units[self.active_unit.get() as usize]
5139 }
5140
5141 fn iter(&self) -> impl Iterator<Item = (u32, &TextureUnit)> {
5142 self.units
5143 .iter()
5144 .enumerate()
5145 .map(|(index, unit)| (index as u32 + constants::TEXTURE0, unit))
5146 }
5147}
5148
5149#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
5150#[derive(Default, JSTraceable, MallocSizeOf)]
5151struct TextureUnit {
5152 tex_2d: MutNullableDom<WebGLTexture>,
5153 tex_cube_map: MutNullableDom<WebGLTexture>,
5154 tex_2d_array: MutNullableDom<WebGLTexture>,
5155 tex_3d: MutNullableDom<WebGLTexture>,
5156}
5157
5158impl TextureUnit {
5159 fn unbind(&self, texture: &WebGLTexture) -> Option<u32> {
5160 let fields = [
5161 (&self.tex_2d, constants::TEXTURE_2D),
5162 (&self.tex_cube_map, constants::TEXTURE_CUBE_MAP),
5163 (
5164 &self.tex_2d_array,
5165 WebGL2RenderingContextConstants::TEXTURE_2D_ARRAY,
5166 ),
5167 (&self.tex_3d, WebGL2RenderingContextConstants::TEXTURE_3D),
5168 ];
5169 for &(slot, target) in &fields {
5170 if slot.get().is_some_and(|t| texture == &*t) {
5171 slot.set(None);
5172 return Some(target);
5173 }
5174 }
5175 None
5176 }
5177}
5178
5179pub(crate) struct TexPixels {
5180 data: GenericSharedMemory,
5181 size: Size2D<u32>,
5182 pixel_format: Option<PixelFormat>,
5183 alpha_treatment: Option<AlphaTreatment>,
5184 y_axis_treatment: YAxisTreatment,
5185}
5186
5187impl TexPixels {
5188 fn new(
5189 data: GenericSharedMemory,
5190 size: Size2D<u32>,
5191 pixel_format: PixelFormat,
5192 alpha_treatment: Option<AlphaTreatment>,
5193 y_axis_treatment: YAxisTreatment,
5194 ) -> Self {
5195 Self {
5196 data,
5197 size,
5198 pixel_format: Some(pixel_format),
5199 alpha_treatment,
5200 y_axis_treatment,
5201 }
5202 }
5203
5204 pub(crate) fn from_array(
5205 data: GenericSharedMemory,
5206 size: Size2D<u32>,
5207 alpha_treatment: Option<AlphaTreatment>,
5208 y_axis_treatment: YAxisTreatment,
5209 ) -> Self {
5210 Self {
5211 data,
5212 size,
5213 pixel_format: None,
5214 alpha_treatment,
5215 y_axis_treatment,
5216 }
5217 }
5218
5219 pub(crate) fn size(&self) -> Size2D<u32> {
5220 self.size
5221 }
5222
5223 pub(crate) fn pixel_format(&self) -> Option<PixelFormat> {
5224 self.pixel_format
5225 }
5226
5227 pub(crate) fn alpha_treatment(&self) -> Option<AlphaTreatment> {
5228 self.alpha_treatment
5229 }
5230
5231 pub(crate) fn y_axis_treatment(&self) -> YAxisTreatment {
5232 self.y_axis_treatment
5233 }
5234
5235 pub(crate) fn into_shared_memory(self) -> GenericSharedMemory {
5236 self.data
5237 }
5238}
5239
5240pub(crate) enum TexSource {
5241 Pixels(TexPixels),
5242 BufferOffset(i64),
5243}
5244
5245#[derive(JSTraceable)]
5246pub(crate) struct WebGLCommandSender {
5247 #[no_trace]
5248 sender: WebGLChan,
5249}
5250
5251impl WebGLCommandSender {
5252 pub(crate) fn new(sender: WebGLChan) -> WebGLCommandSender {
5253 WebGLCommandSender { sender }
5254 }
5255
5256 pub(crate) fn send(&self, msg: WebGLMsg) -> WebGLSendResult {
5257 self.sender.send(msg)
5258 }
5259}
5260
5261fn array_buffer_type_to_sized_type(type_: Type) -> Option<SizedDataType> {
5262 match type_ {
5263 Type::Uint8 | Type::Uint8Clamped => Some(SizedDataType::Uint8),
5264 Type::Uint16 => Some(SizedDataType::Uint16),
5265 Type::Uint32 => Some(SizedDataType::Uint32),
5266 Type::Int8 => Some(SizedDataType::Int8),
5267 Type::Int16 => Some(SizedDataType::Int16),
5268 Type::Int32 => Some(SizedDataType::Int32),
5269 Type::Float32 => Some(SizedDataType::Float32),
5270 Type::Float16 |
5271 Type::Float64 |
5272 Type::BigInt64 |
5273 Type::BigUint64 |
5274 Type::MaxTypedArrayViewType |
5275 Type::Int64 |
5276 Type::Simd128 => None,
5277 }
5278}