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