Skip to content

Truly independent web browser

LibWeb: Implement WebGL in Rust

Aliaksandr Kalenik9c19683fc8c3
diff --git a/Libraries/LibWeb/Bindings/Rust/generate/webgl_wire.rs b/Libraries/LibWeb/Bindings/Rust/generate/webgl_wire.rs
index cb03e0365f5..dbc06312468 100644
--- a/Libraries/LibWeb/Bindings/Rust/generate/webgl_wire.rs
+++ b/Libraries/LibWeb/Bindings/Rust/generate/webgl_wire.rs
@@ -102,7 +102,13 @@ fn write_type_enum(out: &mut String, enum_name: &str, count_name: &str, descript
writeln!(out, " {name},").unwrap();
}
out.push_str("}\n\n");
- writeln!(out, "pub(crate) const {count_name}: u16 = {};\n", names.len()).unwrap();
+ // NB: Only the tests of the vocabulary ask how many types there are.
+ writeln!(
+ out,
+ "#[cfg(test)]\npub(crate) const {count_name}: u16 = {};\n",
+ names.len()
+ )
+ .unwrap();
}
fn write_layout_words(out: &mut String, rust_path: &str, layout: &WireStruct) {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
index 815d3f4a0aa..631b795c68b 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
@@ -8,6 +8,8 @@
//! https://webidl.spec.whatwg.org/#es-type-mapping
use core::mem::MaybeUninit;
+use core::ops::Range;
+use std::borrow::Cow;
use ak::{Utf16String, Utf16StringUnits, convert_valid_utf16_to_utf8, utf8_length_from_valid_utf16};
use libjs_rust::api::{
@@ -23,6 +25,7 @@ use crate::bindings::interface::{Interface, Ref, create_dictionary_object, wrap}
use crate::bindings::services::web_bindings_object_implements_interface;
/// A USVString, a string without lone surrogates. Its UTF-16 code units are always well-formed.
+#[derive(Clone)]
pub(crate) struct UsvString(Utf16String);
impl UsvString {
@@ -376,59 +379,125 @@ impl From<ArrayBufferView> for BufferSource {
}
}
+pub(crate) struct BufferSourceExtent {
+ pub(crate) buffer: Gc<ArrayBuffer>,
+ pub(crate) is_out_of_bounds: bool,
+ pub(crate) byte_offset: usize,
+ pub(crate) byte_length: usize,
+ pub(crate) element_size: usize,
+}
+
impl BufferSource {
- /// Calls the function with the bytes that the buffer source holds, https://webidl.spec.whatwg.org/#dfn-get-buffer-source-copy,
- /// without copying them unless their buffer is shared. A detached buffer and a view that is out of bounds hold
- /// no bytes.
- ///
- /// # Safety
- ///
- /// The function must not run script or allocate a cell, either of which could detach, resize or free the buffer
- /// that the bytes are in.
- pub(crate) unsafe fn with_bytes<R>(&self, function: impl FnOnce(&[u8]) -> R) -> R {
- let (buffer, offset, length) = match self {
+ pub(crate) fn extent(&self) -> BufferSourceExtent {
+ match self {
Self::TypedArray(typed_array) => {
let record = make_typed_array_with_buffer_witness_record(typed_array, ArrayBufferOrder::SeqCst);
// AD-HOC: The WebIDL spec has not been updated for resizable ArrayBuffer objects. This check follows
// the behavior of step 7 of the TypedArray.prototype.buffer getter.
- if is_typed_array_out_of_bounds(&record) {
- return function(&[]);
+ let is_out_of_bounds = is_typed_array_out_of_bounds(&record);
+ let byte_length = if is_out_of_bounds {
+ 0
+ } else {
+ typed_array_byte_length(&record) as usize
+ };
+ BufferSourceExtent {
+ buffer: typed_array.viewed_array_buffer(),
+ is_out_of_bounds,
+ byte_offset: typed_array.byte_offset() as usize,
+ byte_length,
+ element_size: typed_array.element_size() as usize,
}
- let length = typed_array_byte_length(&record) as usize;
- (
- typed_array.viewed_array_buffer(),
- typed_array.byte_offset() as usize,
- length,
- )
}
Self::DataView(view) => {
let record = make_data_view_with_buffer_witness_record(*view, ArrayBufferOrder::SeqCst);
// AD-HOC: The WebIDL spec has not been updated for resizable ArrayBuffer objects. This check follows
// the behavior of step 7 of the DataView.prototype.buffer getter.
- if is_view_out_of_bounds(&record) {
- return function(&[]);
+ let is_out_of_bounds = is_view_out_of_bounds(&record);
+ let byte_length = if is_out_of_bounds {
+ 0
+ } else {
+ get_view_byte_length(&record) as usize
+ };
+ BufferSourceExtent {
+ buffer: view.viewed_array_buffer(),
+ is_out_of_bounds,
+ byte_offset: view.byte_offset() as usize,
+ byte_length,
+ element_size: 1,
}
- let length = get_view_byte_length(&record) as usize;
- (view.viewed_array_buffer(), view.byte_offset() as usize, length)
}
- Self::ArrayBuffer(buffer) => (*buffer, 0, buffer.byte_length()),
- };
+ Self::ArrayBuffer(buffer) => BufferSourceExtent {
+ buffer: *buffer,
+ is_out_of_bounds: false,
+ byte_offset: 0,
+ byte_length: buffer.byte_length(),
+ element_size: 1,
+ },
+ }
+ }
+ /// https://webidl.spec.whatwg.org/#dfn-get-buffer-source-copy, without copying the bytes unless their buffer is
+ /// shared.
+ ///
+ /// # Safety
+ ///
+ /// The function must not run script or allocate a cell, either of which could detach, resize or free the buffer
+ /// that the bytes are in.
+ pub(crate) unsafe fn with_bytes<R>(&self, function: impl FnOnce(&[u8]) -> R) -> R {
+ let extent = self.extent();
// 7. If IsDetachedBuffer(jsArrayBuffer) is true, then return the empty byte sequence.
- if buffer.is_detached() || length == 0 {
- return function(&[]);
- }
+ let held_byte_length = if extent.buffer.is_detached() {
+ 0
+ } else {
+ extent.byte_length
+ };
+ let held_bytes = extent.byte_offset..extent.byte_offset + held_byte_length;
+ // SAFETY: The caller keeps the function from running script and from allocating.
+ unsafe { with_bytes_of_buffer(&extent.buffer, held_bytes, function) }
+ .expect("a buffer has the bytes of its views that are in bounds")
+ }
+}
- // NB: Another thread can write the bytes of a shared buffer at any time, so the function gets a copy of them.
- if buffer.is_shared_array_buffer() {
- return function(&buffer.copy_to_byte_buffer(offset, length));
- }
- let bytes = buffer.with_data_block(|data_block| data_block.data_at(offset));
- assert!(!bytes.is_null());
- // SAFETY: The buffer is not detached and holds `length` bytes from `offset`, which nothing writes while the
- // function runs, as the buffer is not shared and the caller keeps script from running.
- function(unsafe { core::slice::from_raw_parts(bytes, length) })
+/// # Safety
+///
+/// The function must not run script or allocate a cell, either of which could detach, resize or free the buffer that
+/// the bytes are in.
+pub(crate) unsafe fn with_bytes_of_buffer<R>(
+ buffer: &ArrayBuffer,
+ bytes: Range<usize>,
+ function: impl FnOnce(&[u8]) -> R,
+) -> Option<R> {
+ // SAFETY: The caller keeps the function from running script and from allocating.
+ unsafe { borrowed_or_copied_bytes_of_buffer(buffer, bytes) }.map(|bytes| function(&bytes))
+}
+
+/// `None` when the buffer does not have the bytes.
+pub(crate) fn copy_of_bytes_of_buffer(buffer: &ArrayBuffer, bytes: Range<usize>) -> Option<Vec<u8>> {
+ // SAFETY: The bytes are borrowed only while they are copied, which neither runs script nor allocates a cell.
+ unsafe { borrowed_or_copied_bytes_of_buffer(buffer, bytes) }.map(Cow::into_owned)
+}
+
+/// # Safety
+///
+/// Nothing may run script or allocate a cell while the bytes are borrowed, either of which could detach, resize or
+/// free the buffer that they are in.
+unsafe fn borrowed_or_copied_bytes_of_buffer(buffer: &ArrayBuffer, bytes: Range<usize>) -> Option<Cow<'_, [u8]>> {
+ if bytes.is_empty() {
+ return Some(Cow::Borrowed(&[]));
+ }
+ if buffer.is_detached() || bytes.end > buffer.byte_length() {
+ return None;
+ }
+
+ // NB: Another thread can write the bytes of a shared buffer at any time, so they are copied.
+ if buffer.is_shared_array_buffer() {
+ return Some(Cow::Owned(buffer.copy_to_byte_buffer(bytes.start, bytes.len())));
}
+ let data = buffer.with_data_block(|data_block| data_block.data_at(bytes.start));
+ assert!(!data.is_null());
+ // SAFETY: The buffer is not detached and has the bytes, which nothing writes while they are borrowed, as the
+ // buffer is not shared and the caller keeps script from running.
+ Some(Cow::Borrowed(unsafe { core::slice::from_raw_parts(data, bytes.len()) }))
}
impl ArrayBufferView {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
index d351a57c596..4f9d86a462f 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
@@ -48,7 +48,14 @@ pub(crate) mod streams;
allow(dead_code, reason = "only the generated bindings use the interfaces")
)]
pub(crate) mod url_pattern;
-#[allow(dead_code, reason = "no interface is implemented with it yet")]
+#[cfg_attr(
+ not(web_idl_bindings),
+ allow(dead_code, reason = "only the generated bindings use the interfaces")
+)]
+#[allow(
+ clippy::unnecessary_wraps,
+ reason = "the bindings call every attribute and operation as one that can throw"
+)]
pub(crate) mod web_gl;
// The generators of the build script, whose tests run with those of the crate.
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/angle_instanced_arrays.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/angle_instanced_arrays.rs
new file mode 100644
index 00000000000..9450fbdd398
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/angle_instanced_arrays.rs
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://registry.khronos.org/webgl/extensions/ANGLE_instanced_arrays/
+
+use libjs_rust::api::{Gc, Realm, Trace, Vm};
+
+use super::state::{ContextRef, ContextState};
+use crate::bindings::interface::{Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, WebIdlResult};
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct ANGLEInstancedArrays {
+ context: ContextRef,
+}
+
+impl Wrappable for ANGLEInstancedArrays {
+ fn relevant_realm(&self, _vm: &Vm) -> Option<Gc<Realm>> {
+ self.context.state().canvas().relevant_realm()
+ }
+}
+
+impl ANGLEInstancedArrays {
+ pub(crate) fn create(vm: &Vm, context: &ContextState) -> Ref<Self> {
+ allocate(
+ vm,
+ Self {
+ context: context.context_ref(),
+ },
+ )
+ }
+
+ pub(crate) fn draw_arrays_instanced_angle(
+ &self,
+ _: &mut CallContext,
+ mode: u32,
+ first: i32,
+ count: i32,
+ primcount: i32,
+ ) -> WebIdlResult<()> {
+ self.context
+ .state()
+ .proxy
+ .draw_arrays_instanced_angle(mode, first, count, primcount);
+ Ok(())
+ }
+
+ pub(crate) fn draw_elements_instanced_angle(
+ &self,
+ _: &mut CallContext,
+ mode: u32,
+ count: i32,
+ r#type: u32,
+ offset: i64,
+ primcount: i32,
+ ) -> WebIdlResult<()> {
+ self.context
+ .state()
+ .proxy
+ .draw_elements_instanced_angle(mode, count, r#type, offset, primcount);
+ Ok(())
+ }
+
+ pub(crate) fn vertex_attrib_divisor_angle(
+ &self,
+ _: &mut CallContext,
+ index: u32,
+ divisor: u32,
+ ) -> WebIdlResult<()> {
+ self.context.state().proxy.vertex_attrib_divisor_angle(index, divisor);
+ Ok(())
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/buffer_kind.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/buffer_kind.rs
new file mode 100644
index 00000000000..98f51bc7b3f
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/buffer_kind.rs
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://registry.khronos.org/webgl/specs/latest/2.0/#5.1
+//!
+//! A buffer holds indices or other data, and which of the two is decided by the first target that it is bound to. A
+//! target that an operation does not bind buffers to has no kind, so that a bind that fails for its target cannot
+//! decide the kind of a buffer.
+
+use core::cell::Cell;
+
+use super::constants::{GL_ELEMENT_ARRAY_BUFFER, GL_TRANSFORM_FEEDBACK_BUFFER, GL_UNIFORM_BUFFER};
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum BufferKind {
+ ElementArray,
+ OtherData,
+}
+
+impl BufferKind {
+ pub(crate) fn of_buffers_at_indexed_target(target: u32) -> Option<Self> {
+ matches!(target, GL_TRANSFORM_FEEDBACK_BUFFER | GL_UNIFORM_BUFFER).then_some(Self::OtherData)
+ }
+}
+
+#[derive(Default)]
+pub(crate) struct KindOfFirstBinding(Cell<Option<BufferKind>>);
+
+impl KindOfFirstBinding {
+ /// Operations ask before they look at the target, so it can be one that they do not bind buffers to. A buffer of
+ /// the wrong kind for it is refused all the same, and only a buffer that is not refused goes on to fail for it.
+ pub(crate) fn allows_binding_to(&self, target: u32) -> bool {
+ match self.0.get() {
+ None => true,
+ Some(BufferKind::ElementArray) => target == GL_ELEMENT_ARRAY_BUFFER,
+ Some(BufferKind::OtherData) => target != GL_ELEMENT_ARRAY_BUFFER,
+ }
+ }
+
+ pub(crate) fn record_binding_as(&self, kind: BufferKind) {
+ if self.0.get().is_none() {
+ self.0.set(Some(kind));
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::web_gl::constants::GL_ARRAY_BUFFER;
+
+ const TARGET_THAT_NO_OPERATION_BINDS_BUFFERS_TO: u32 = 0x1234;
+
+ #[test]
+ fn asking_whether_a_buffer_can_be_bound_does_not_decide_its_kind() {
+ let kind = KindOfFirstBinding::default();
+ assert!(kind.allows_binding_to(GL_ARRAY_BUFFER));
+ assert!(kind.allows_binding_to(GL_ELEMENT_ARRAY_BUFFER));
+ assert!(kind.allows_binding_to(TARGET_THAT_NO_OPERATION_BINDS_BUFFERS_TO));
+ assert!(kind.allows_binding_to(GL_ARRAY_BUFFER));
+ }
+
+ #[test]
+ fn a_buffer_keeps_the_kind_of_its_first_binding() {
+ let kind = KindOfFirstBinding::default();
+ kind.record_binding_as(BufferKind::ElementArray);
+ assert!(kind.allows_binding_to(GL_ELEMENT_ARRAY_BUFFER));
+ assert!(!kind.allows_binding_to(GL_ARRAY_BUFFER));
+ assert!(!kind.allows_binding_to(GL_UNIFORM_BUFFER));
+
+ kind.record_binding_as(BufferKind::OtherData);
+ assert!(kind.allows_binding_to(GL_ELEMENT_ARRAY_BUFFER));
+ assert!(!kind.allows_binding_to(GL_ARRAY_BUFFER));
+
+ let kind = KindOfFirstBinding::default();
+ kind.record_binding_as(BufferKind::OtherData);
+ assert!(kind.allows_binding_to(GL_ARRAY_BUFFER));
+ assert!(kind.allows_binding_to(GL_UNIFORM_BUFFER));
+ assert!(!kind.allows_binding_to(GL_ELEMENT_ARRAY_BUFFER));
+ }
+
+ #[test]
+ fn a_target_that_binds_no_buffers_refuses_only_a_buffer_of_indices() {
+ let kind = KindOfFirstBinding::default();
+ kind.record_binding_as(BufferKind::ElementArray);
+ assert!(!kind.allows_binding_to(TARGET_THAT_NO_OPERATION_BINDS_BUFFERS_TO));
+
+ let kind = KindOfFirstBinding::default();
+ kind.record_binding_as(BufferKind::OtherData);
+ assert!(kind.allows_binding_to(TARGET_THAT_NO_OPERATION_BINDS_BUFFERS_TO));
+ }
+
+ #[test]
+ fn bind_buffer_base_and_range_give_a_kind_only_at_their_indexed_targets() {
+ assert_eq!(
+ BufferKind::of_buffers_at_indexed_target(GL_TRANSFORM_FEEDBACK_BUFFER),
+ Some(BufferKind::OtherData)
+ );
+ assert_eq!(
+ BufferKind::of_buffers_at_indexed_target(GL_UNIFORM_BUFFER),
+ Some(BufferKind::OtherData)
+ );
+ assert_eq!(BufferKind::of_buffers_at_indexed_target(GL_ARRAY_BUFFER), None);
+ assert_eq!(BufferKind::of_buffers_at_indexed_target(GL_ELEMENT_ARRAY_BUFFER), None);
+ assert_eq!(
+ BufferKind::of_buffers_at_indexed_target(TARGET_THAT_NO_OPERATION_BINDS_BUFFERS_TO),
+ None
+ );
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/buffer_source.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/buffer_source.rs
new file mode 100644
index 00000000000..134a60bf3c8
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/buffer_source.rs
@@ -0,0 +1,307 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Borrowing and copying the script memory that WebGL operations read and write. Which bytes an operation may have
+//! is the arithmetic of byte_ranges.rs.
+
+use core::ops::Range;
+
+use libjs_rust::api::{ArrayBuffer, Gc, TypedArrayBase};
+
+use super::byte_ranges::{
+ Extent, GlSize, ListTail, OutOfRange, UploadRange, destination_range, destination_range_of_get_buffer_sub_data,
+ list_range, offset_in_buffer_of_checked_write, sequence_list_tail, typed_array_list_range, typed_array_list_tail,
+ upload_range, upload_range_of_2d_texture,
+};
+use super::canvas::{is_valid_2d_pixel_unpack_state, required_2d_texture_data_size};
+use super::proxy::recorder::{PlainNumber, bytes_of};
+use super::state::ContextState;
+use super::types::Float32List;
+use super::web_gl_rendering_context_overloads::Int32List;
+use super::web_gl2_rendering_context_base::Uint32List;
+use crate::bindings::conversions::{
+ ArrayBufferView, BufferSource, BufferSourceExtent, copy_of_bytes_of_buffer, with_bytes_of_buffer,
+};
+
+fn buffer_and_extent_of(source: &BufferSource) -> (Gc<ArrayBuffer>, Extent) {
+ let BufferSourceExtent {
+ buffer,
+ is_out_of_bounds,
+ byte_offset,
+ byte_length,
+ element_size,
+ } = source.extent();
+ let extent = Extent {
+ buffer_is_detached: buffer.is_detached(),
+ buffer_byte_length: buffer.byte_length(),
+ is_out_of_bounds,
+ byte_offset,
+ byte_length,
+ element_size,
+ };
+ (buffer, extent)
+}
+
+fn extent_of(source: &BufferSource) -> Extent {
+ let (_, extent) = buffer_and_extent_of(source);
+ extent
+}
+
+pub(crate) struct SourceBytes {
+ buffer: Gc<ArrayBuffer>,
+ range: UploadRange,
+}
+
+pub(crate) fn source_bytes(
+ source: BufferSource,
+ src_offset: u64,
+ src_length_override: u32,
+) -> Result<SourceBytes, OutOfRange> {
+ let (buffer, extent) = buffer_and_extent_of(&source);
+ let range = upload_range(&extent, src_offset, src_length_override)?;
+ Ok(SourceBytes { buffer, range })
+}
+
+impl SourceBytes {
+ pub(crate) fn len(&self) -> usize {
+ self.range.length().get()
+ }
+
+ pub(crate) fn gl_size(&self) -> i32 {
+ self.range.length().as_gl_sizei()
+ }
+
+ /// # Safety
+ ///
+ /// The function must not run script or allocate a cell, either of which could detach, resize or free the buffer
+ /// that the bytes are in.
+ unsafe fn with<R>(&self, function: impl FnOnce(&[u8]) -> R) -> R {
+ // SAFETY: The caller keeps the function from running script and from allocating.
+ unsafe { with_bytes_of_buffer(&self.buffer, self.range.bytes_in_buffer(), function) }
+ .expect("nothing has run since the bytes were found")
+ }
+}
+
+impl ContextState {
+ /// # Safety
+ ///
+ /// `record` gets the bytes while they are borrowed from script memory, so it must not run script or allocate a
+ /// cell, either of which could detach, resize or free the buffer that they are in. Recording one command with
+ /// them does neither.
+ pub(crate) unsafe fn upload<R>(&self, bytes: &SourceBytes, record: impl FnOnce(&[u8]) -> R) -> R {
+ // SAFETY: The caller keeps `record` from running script and from allocating, and the recorder defers what
+ // would call out of the process until the bytes are given back.
+ self.proxy
+ .record_with_borrowed_data(bytes.len(), || unsafe { bytes.with(record) })
+ }
+
+ /// `record` gets `None` when the source has no bytes from the offset of the upload on, and otherwise the data,
+ /// even if the upload records none of it.
+ ///
+ /// # Safety
+ ///
+ /// As for upload().
+ pub(crate) unsafe fn upload_through_nullable_pointer<R>(
+ &self,
+ bytes: &SourceBytes,
+ record: impl FnOnce(Option<&[u8]>) -> R,
+ ) -> R {
+ let source_has_bytes = bytes.range.source_has_bytes();
+ // SAFETY: The caller keeps `record` from running script and from allocating.
+ unsafe { self.upload(bytes, |bytes| record(source_has_bytes.then_some(bytes))) }
+ }
+
+ pub(crate) fn texture_data_for_2d_upload(
+ &self,
+ source: ArrayBufferView,
+ src_offset: u64,
+ width: i32,
+ height: i32,
+ format: u32,
+ r#type: u32,
+ ) -> Result<SourceBytes, OutOfRange> {
+ let unpack_state = self.unpack_state.get();
+ if !is_valid_2d_pixel_unpack_state(width, &unpack_state) {
+ return Err(OutOfRange);
+ }
+ let size_that_the_image_takes = required_2d_texture_data_size(width, height, format, r#type, &unpack_state);
+ let (buffer, extent) = buffer_and_extent_of(&BufferSource::from(source));
+ let range = upload_range_of_2d_texture(&extent, src_offset, size_that_the_image_takes)?;
+ Ok(SourceBytes { buffer, range })
+ }
+}
+
+pub(crate) fn destination_bytes(view: &ArrayBufferView, dst_offset: u64) -> Result<Range<usize>, OutOfRange> {
+ destination_range(&extent_of(&BufferSource::from(*view)), dst_offset)
+}
+
+pub(crate) fn destination_bytes_of_get_buffer_sub_data(
+ dst_buffer: &ArrayBufferView,
+ dst_offset: u64,
+ length: u32,
+) -> Result<Option<Range<usize>>, OutOfRange> {
+ destination_range_of_get_buffer_sub_data(&extent_of(&BufferSource::from(*dst_buffer)), dst_offset, length)
+}
+
+pub(crate) fn write_checked(view: &ArrayBufferView, bytes: &[u8], starting_offset: usize) -> Result<(), OutOfRange> {
+ let (buffer, extent) = buffer_and_extent_of(&BufferSource::from(*view));
+ if let Some(write_offset) = offset_in_buffer_of_checked_write(&extent, bytes.len(), starting_offset)? {
+ buffer.overwrite(write_offset, bytes);
+ }
+ Ok(())
+}
+
+/// A copy, so the numbers stay what they are whatever script does.
+pub(crate) struct ListBytes {
+ bytes: Vec<u8>,
+ element_count: GlSize,
+}
+
+impl ListBytes {
+ pub(crate) fn gl_count(&self) -> i32 {
+ self.element_count.as_gl_sizei()
+ }
+
+ pub(crate) fn gl_count_of_whole_groups_of(&self, group_size: usize) -> Option<i32> {
+ self.element_count.count_of_whole_groups_of(group_size)
+ }
+
+ pub(crate) fn as_bytes(&self) -> &[u8] {
+ &self.bytes
+ }
+}
+
+pub(crate) trait NumberList {
+ type Number: PlainNumber;
+
+ fn typed_array(&self) -> Option<Gc<TypedArrayBase>>;
+ fn sequence(&self) -> &[Self::Number];
+}
+
+impl NumberList for Float32List {
+ type Number = f32;
+
+ fn typed_array(&self) -> Option<Gc<TypedArrayBase>> {
+ match self {
+ Self::Float32Array(typed_array) => Some(*typed_array),
+ Self::Sequence(_) => None,
+ }
+ }
+
+ fn sequence(&self) -> &[f32] {
+ match self {
+ Self::Float32Array(_) => &[],
+ Self::Sequence(numbers) => numbers,
+ }
+ }
+}
+
+impl NumberList for Int32List {
+ type Number = i32;
+
+ fn typed_array(&self) -> Option<Gc<TypedArrayBase>> {
+ match self {
+ Self::Int32Array(typed_array) => Some(*typed_array),
+ Self::Sequence(_) => None,
+ }
+ }
+
+ fn sequence(&self) -> &[i32] {
+ match self {
+ Self::Int32Array(_) => &[],
+ Self::Sequence(numbers) => numbers,
+ }
+ }
+}
+
+impl NumberList for Uint32List {
+ type Number = u32;
+
+ fn typed_array(&self) -> Option<Gc<TypedArrayBase>> {
+ match self {
+ Self::Uint32Array(typed_array) => Some(*typed_array),
+ Self::Sequence(_) => None,
+ }
+ }
+
+ fn sequence(&self) -> &[u32] {
+ match self {
+ Self::Uint32Array(_) => &[],
+ Self::Sequence(numbers) => numbers,
+ }
+ }
+}
+
+pub(crate) fn list_bytes<L: NumberList>(
+ list: &L,
+ src_offset: u64,
+ src_length_override: u32,
+) -> Result<ListBytes, OutOfRange> {
+ let Some(typed_array) = list.typed_array() else {
+ let numbers = list.sequence();
+ let range = list_range(numbers.len(), size_of::<L::Number>(), src_offset, src_length_override)?;
+ let numbers = numbers.get(range.elements).ok_or(OutOfRange)?;
+ return Ok(ListBytes {
+ bytes: bytes_of(numbers).to_vec(),
+ element_count: range.element_count,
+ });
+ };
+
+ let (buffer, extent) = buffer_and_extent_of(&BufferSource::TypedArray(typed_array));
+ let range = typed_array_list_range(&extent, src_offset, src_length_override)?;
+ let bytes = copy_of_bytes_of_buffer(&buffer, range.bytes_in_buffer).ok_or(OutOfRange)?;
+ Ok(ListBytes {
+ bytes,
+ element_count: range.element_count,
+ })
+}
+
+enum NumbersOfList<'list, N> {
+ Sequence(&'list [N]),
+ TypedArray(Gc<ArrayBuffer>),
+}
+
+/// For an operation that records only the first few numbers of a list from an offset on. GL is not told how many
+/// numbers the list has, so unlike list_bytes() this takes a list of any length, and copies only what is recorded.
+pub(crate) struct NumbersFromOffset<'list, N> {
+ numbers: NumbersOfList<'list, N>,
+ tail: ListTail,
+}
+
+pub(crate) fn numbers_from_offset<L: NumberList>(
+ list: &L,
+ src_offset: u64,
+) -> Result<NumbersFromOffset<'_, L::Number>, OutOfRange> {
+ let Some(typed_array) = list.typed_array() else {
+ let numbers = list.sequence();
+ return Ok(NumbersFromOffset {
+ tail: sequence_list_tail(numbers.len(), size_of::<L::Number>(), src_offset)?,
+ numbers: NumbersOfList::Sequence(numbers),
+ });
+ };
+
+ let (buffer, extent) = buffer_and_extent_of(&BufferSource::TypedArray(typed_array));
+ Ok(NumbersFromOffset {
+ tail: typed_array_list_tail(&extent, src_offset)?,
+ numbers: NumbersOfList::TypedArray(buffer),
+ })
+}
+
+impl<N: PlainNumber> NumbersFromOffset<'_, N> {
+ /// `None` when the list has fewer numbers from the offset on.
+ pub(crate) fn copy_of_first(&self, count: usize) -> Option<Vec<u8>> {
+ let bytes = self.tail.bytes_of_leading_elements(count)?;
+ match self.numbers {
+ NumbersOfList::Sequence(numbers) => bytes_of(numbers).get(bytes).map(<[u8]>::to_vec),
+ NumbersOfList::TypedArray(buffer) => copy_of_bytes_of_buffer(&buffer, bytes),
+ }
+ }
+}
+
+/// `None` when the list has fewer numbers.
+pub(crate) fn copy_of_first_numbers<L: NumberList>(list: &L, count: usize) -> Option<Vec<u8>> {
+ numbers_from_offset(list, 0).ok()?.copy_of_first(count)
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/byte_ranges.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/byte_ranges.rs
new file mode 100644
index 00000000000..7341ef15bb2
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/byte_ranges.rs
@@ -0,0 +1,1106 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Which bytes of script memory a WebGL operation means and which sizes it tells GL, as arithmetic on plain numbers
+//! that the tests of the crate cover without the JS runtime. buffer_source.rs reads the numbers from script objects
+//! and borrows the bytes.
+
+use core::ops::Range;
+
+/// Which GL error this is depends on the operation.
+#[derive(Debug, PartialEq, Eq)]
+pub(crate) struct OutOfRange;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) struct GlSize {
+ size: usize,
+ size_as_gl_sizei: i32,
+}
+
+impl GlSize {
+ fn new(size: usize) -> Result<Self, OutOfRange> {
+ let size_as_gl_sizei = i32::try_from(size).map_err(|_| OutOfRange)?;
+ Ok(Self { size, size_as_gl_sizei })
+ }
+
+ pub(crate) fn get(self) -> usize {
+ self.size
+ }
+
+ pub(crate) fn as_gl_sizei(self) -> i32 {
+ self.size_as_gl_sizei
+ }
+
+ pub(crate) fn count_of_whole_groups_of(self, group_size: usize) -> Option<i32> {
+ if !self.size.is_multiple_of(group_size) {
+ return None;
+ }
+ i32::try_from(self.size.checked_div(group_size)?).ok()
+ }
+}
+
+pub(crate) const fn gl_sizei_of_array_length(length: usize) -> i32 {
+ assert!(length <= i32::MAX as usize);
+ length as i32
+}
+
+#[derive(Clone, Copy, Debug)]
+pub(crate) struct Extent {
+ pub(crate) buffer_is_detached: bool,
+ pub(crate) buffer_byte_length: usize,
+ /// True for every view of a detached buffer as well. Such a view has no bytes.
+ pub(crate) is_out_of_bounds: bool,
+ pub(crate) byte_offset: usize,
+ pub(crate) byte_length: usize,
+ pub(crate) element_size: usize,
+}
+
+impl Extent {
+ fn validate(&self) -> Result<(), OutOfRange> {
+ if self.buffer_is_detached || self.is_out_of_bounds {
+ return Err(OutOfRange);
+ }
+ let byte_end = self.byte_offset.checked_add(self.byte_length).ok_or(OutOfRange)?;
+ if byte_end > self.buffer_byte_length {
+ return Err(OutOfRange);
+ }
+ Ok(())
+ }
+
+ fn bytes_in_buffer(&self, bytes_of_source: &Range<usize>) -> Result<Range<usize>, OutOfRange> {
+ let start = self.byte_offset.checked_add(bytes_of_source.start).ok_or(OutOfRange)?;
+ let end = self.byte_offset.checked_add(bytes_of_source.end).ok_or(OutOfRange)?;
+ Ok(start..end)
+ }
+}
+
+/// `src_offset` and `src_length_override` count elements. The range is of the bytes of the source, not of its buffer.
+fn source_range(extent: &Extent, src_offset: u64, src_length_override: u32) -> Result<Range<usize>, OutOfRange> {
+ if extent.buffer_is_detached {
+ return Err(OutOfRange);
+ }
+ if extent.is_out_of_bounds {
+ if src_offset != 0 || src_length_override != 0 {
+ return Err(OutOfRange);
+ }
+ return Ok(0..0);
+ }
+
+ let start = usize::try_from(src_offset)
+ .ok()
+ .and_then(|offset| offset.checked_mul(extent.element_size));
+ let start = start.filter(|&start| start <= extent.byte_length).ok_or(OutOfRange)?;
+ let mut length = extent.byte_length - start;
+ if src_length_override != 0 {
+ let requested_length = usize::try_from(src_length_override)
+ .ok()
+ .and_then(|length| length.checked_mul(extent.element_size));
+ length = requested_length
+ .filter(|&requested_length| requested_length <= length)
+ .ok_or(OutOfRange)?;
+ }
+
+ let bytes_of_source = start..start + length;
+ if extent.bytes_in_buffer(&bytes_of_source)?.end > extent.buffer_byte_length {
+ return Err(OutOfRange);
+ }
+ Ok(bytes_of_source)
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) struct UploadRange {
+ bytes_in_buffer: Range<usize>,
+ length: GlSize,
+ source_has_bytes: bool,
+}
+
+impl UploadRange {
+ fn leading_bytes_of(extent: &Extent, source_range: &Range<usize>, length: usize) -> Result<Self, OutOfRange> {
+ let length = GlSize::new(length)?;
+ let end_of_leading_bytes = source_range.start.checked_add(length.get()).ok_or(OutOfRange)?;
+ Ok(Self {
+ bytes_in_buffer: extent.bytes_in_buffer(&(source_range.start..end_of_leading_bytes))?,
+ length,
+ source_has_bytes: !source_range.is_empty(),
+ })
+ }
+
+ pub(crate) fn bytes_in_buffer(&self) -> Range<usize> {
+ self.bytes_in_buffer.clone()
+ }
+
+ pub(crate) fn length(&self) -> GlSize {
+ self.length
+ }
+
+ /// From the offset of the upload on, whether or not the upload records any of them.
+ pub(crate) fn source_has_bytes(&self) -> bool {
+ self.source_has_bytes
+ }
+}
+
+pub(crate) fn upload_range(
+ extent: &Extent,
+ src_offset: u64,
+ src_length_override: u32,
+) -> Result<UploadRange, OutOfRange> {
+ let source_range = source_range(extent, src_offset, src_length_override)?;
+ UploadRange::leading_bytes_of(extent, &source_range, source_range.len())
+}
+
+/// The whole source when the size of the image is unknown or more than the source has, which leaves it to GL to say
+/// what is wrong.
+pub(crate) fn upload_range_of_2d_texture(
+ extent: &Extent,
+ src_offset: u64,
+ size_that_the_image_takes: Option<usize>,
+) -> Result<UploadRange, OutOfRange> {
+ let source_range = source_range(extent, src_offset, 0)?;
+ let length = match size_that_the_image_takes {
+ Some(size) if size <= source_range.len() => size,
+ _ => source_range.len(),
+ };
+ UploadRange::leading_bytes_of(extent, &source_range, length)
+}
+
+pub(crate) fn size_of_zero_filled_texture(
+ bytes_per_pixel: usize,
+ width: i32,
+ height: i32,
+) -> Result<GlSize, OutOfRange> {
+ let width = usize::try_from(width).map_err(|_| OutOfRange)?;
+ let height = usize::try_from(height).map_err(|_| OutOfRange)?;
+ let size = bytes_per_pixel
+ .checked_mul(width)
+ .and_then(|size| size.checked_mul(height));
+ GlSize::new(size.ok_or(OutOfRange)?)
+}
+
+pub(crate) fn destination_range(extent: &Extent, dst_offset: u64) -> Result<Range<usize>, OutOfRange> {
+ extent.validate()?;
+ source_range(extent, dst_offset, 0)
+}
+
+/// https://registry.khronos.org/webgl/specs/latest/2.0/#3.7.3
+pub(crate) fn destination_range_of_get_buffer_sub_data(
+ extent: &Extent,
+ dst_offset: u64,
+ length: u32,
+) -> Result<Option<Range<usize>>, OutOfRange> {
+ // If dstBuffer is a DataView, let elementSize be 1; otherwise, let elementSize be dstBuffer.BYTES_PER_ELEMENT.
+ let element_size = extent.element_size;
+ let dst_offset = usize::try_from(dst_offset).map_err(|_| OutOfRange)?;
+
+ // If length is 0:
+ let copy_length = if length == 0 {
+ // If dstBuffer is a DataView, let copyLength be dstBuffer.byteLength - dstOffset; the typed elements in the
+ // text below are bytes. Otherwise, let copyLength be dstBuffer.length - dstOffset.
+ let destination_element_count = extent.byte_length.checked_div(element_size).ok_or(OutOfRange)?;
+ destination_element_count.checked_sub(dst_offset).ok_or(OutOfRange)?
+ }
+ // Otherwise, let copyLength be length.
+ else {
+ usize::try_from(length).map_err(|_| OutOfRange)?
+ };
+
+ // If copyLength is 0, no data is written to dstBuffer, but this does not cause a GL error to be generated.
+ if copy_length == 0 {
+ return Ok(None);
+ }
+
+ // If dstOffset is greater than dstBuffer.length (or dstBuffer.byteLength in the case of DataView), generates an
+ // INVALID_VALUE error.
+ let start = dst_offset
+ .checked_mul(element_size)
+ .filter(|&start| start <= extent.byte_length)
+ .ok_or(OutOfRange)?;
+
+ // If dstOffset + copyLength is greater than dstBuffer.length (or dstBuffer.byteLength in the case of DataView),
+ // generates an INVALID_VALUE error.
+ let end = copy_length
+ .checked_mul(element_size)
+ .and_then(|copy_byte_length| start.checked_add(copy_byte_length))
+ .filter(|&end| end <= extent.byte_length)
+ .ok_or(OutOfRange)?;
+ Ok(Some(start..end))
+}
+
+/// `starting_offset` counts bytes. No bytes go nowhere, even to a view that is detached or out of bounds.
+pub(crate) fn offset_in_buffer_of_checked_write(
+ extent: &Extent,
+ byte_count: usize,
+ starting_offset: usize,
+) -> Result<Option<usize>, OutOfRange> {
+ if starting_offset > extent.byte_length || byte_count > extent.byte_length - starting_offset {
+ return Err(OutOfRange);
+ }
+ // NB: The elements of a DataView are bytes.
+ if !byte_count.is_multiple_of(extent.element_size) {
+ return Err(OutOfRange);
+ }
+ if byte_count == 0 {
+ return Ok(None);
+ }
+
+ extent.validate()?;
+ let write_offset = extent.byte_offset.checked_add(starting_offset).ok_or(OutOfRange)?;
+ if write_offset > extent.buffer_byte_length || byte_count > extent.buffer_byte_length - write_offset {
+ return Err(OutOfRange);
+ }
+ Ok(Some(write_offset))
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) struct ListRange {
+ pub(crate) elements: Range<usize>,
+ bytes: Range<usize>,
+ pub(crate) element_count: GlSize,
+}
+
+fn elements_of_list(list_length: usize, src_offset: u64, src_length_override: u32) -> Result<Range<usize>, OutOfRange> {
+ let first_element = usize::try_from(src_offset).map_err(|_| OutOfRange)?;
+ let src_length_override = usize::try_from(src_length_override).map_err(|_| OutOfRange)?;
+ let end_of_override = first_element.checked_add(src_length_override).ok_or(OutOfRange)?;
+ if end_of_override > list_length {
+ return Err(OutOfRange);
+ }
+ Ok(if src_length_override == 0 {
+ first_element..list_length
+ } else {
+ first_element..end_of_override
+ })
+}
+
+/// A typed array that is detached or out of bounds holds no numbers.
+fn typed_array_list_length(extent: &Extent) -> Result<usize, OutOfRange> {
+ extent.byte_length.checked_div(extent.element_size).ok_or(OutOfRange)
+}
+
+pub(crate) fn list_range(
+ list_length: usize,
+ element_size: usize,
+ src_offset: u64,
+ src_length_override: u32,
+) -> Result<ListRange, OutOfRange> {
+ let elements = elements_of_list(list_length, src_offset, src_length_override)?;
+
+ let first_byte = elements.start.checked_mul(element_size).ok_or(OutOfRange)?;
+ let byte_length = GlSize::new(elements.len().checked_mul(element_size).ok_or(OutOfRange)?)?;
+ let end_byte = first_byte.checked_add(byte_length.get()).ok_or(OutOfRange)?;
+ Ok(ListRange {
+ element_count: GlSize::new(elements.len())?,
+ elements,
+ bytes: first_byte..end_byte,
+ })
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) struct TypedArrayListRange {
+ pub(crate) bytes_in_buffer: Range<usize>,
+ pub(crate) element_count: GlSize,
+}
+
+pub(crate) fn typed_array_list_range(
+ extent: &Extent,
+ src_offset: u64,
+ src_length_override: u32,
+) -> Result<TypedArrayListRange, OutOfRange> {
+ let range = list_range(
+ typed_array_list_length(extent)?,
+ extent.element_size,
+ src_offset,
+ src_length_override,
+ )?;
+ Ok(TypedArrayListRange {
+ bytes_in_buffer: extent.bytes_in_buffer(&range.bytes)?,
+ element_count: range.element_count,
+ })
+}
+
+/// The elements of a list from an offset on, for an operation that records only the first few of them. GL is not
+/// told how many elements the list has, so unlike a ListRange this one is not bounded to what a GLsizei counts.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) struct ListTail {
+ elements: Range<usize>,
+ element_size: usize,
+ /// In its buffer for a typed array, and 0 for a sequence.
+ byte_offset_of_list: usize,
+}
+
+impl ListTail {
+ fn new(elements: Range<usize>, element_size: usize, byte_offset_of_list: usize) -> Result<Self, OutOfRange> {
+ // NB: With the end of the tail counted once, the bytes of its leading elements are counted without overflow.
+ elements
+ .end
+ .checked_mul(element_size)
+ .and_then(|end| end.checked_add(byte_offset_of_list))
+ .ok_or(OutOfRange)?;
+ Ok(Self {
+ elements,
+ element_size,
+ byte_offset_of_list,
+ })
+ }
+
+ /// `None` when the list has fewer elements from the offset on.
+ pub(crate) fn bytes_of_leading_elements(&self, count: usize) -> Option<Range<usize>> {
+ if count > self.elements.len() {
+ return None;
+ }
+ let start = self.byte_offset_of_list + self.elements.start * self.element_size;
+ Some(start..start + count * self.element_size)
+ }
+}
+
+/// The bytes are those of the sequence.
+pub(crate) fn sequence_list_tail(
+ list_length: usize,
+ element_size: usize,
+ src_offset: u64,
+) -> Result<ListTail, OutOfRange> {
+ ListTail::new(elements_of_list(list_length, src_offset, 0)?, element_size, 0)
+}
+
+/// The bytes are those of the buffer of the typed array.
+pub(crate) fn typed_array_list_tail(extent: &Extent, src_offset: u64) -> Result<ListTail, OutOfRange> {
+ ListTail::new(
+ elements_of_list(typed_array_list_length(extent)?, src_offset, 0)?,
+ extent.element_size,
+ extent.byte_offset,
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const I32_MAX: usize = i32::MAX as usize;
+
+ fn array_buffer(byte_length: usize) -> Extent {
+ Extent {
+ buffer_is_detached: false,
+ buffer_byte_length: byte_length,
+ is_out_of_bounds: false,
+ byte_offset: 0,
+ byte_length,
+ element_size: 1,
+ }
+ }
+
+ fn view(buffer_byte_length: usize, byte_offset: usize, element_count: usize, element_size: usize) -> Extent {
+ Extent {
+ buffer_is_detached: false,
+ buffer_byte_length,
+ is_out_of_bounds: false,
+ byte_offset,
+ byte_length: element_count * element_size,
+ element_size,
+ }
+ }
+
+ fn out_of_bounds(view: Extent, buffer_byte_length: usize) -> Extent {
+ Extent {
+ buffer_byte_length,
+ is_out_of_bounds: true,
+ byte_length: 0,
+ ..view
+ }
+ }
+
+ fn detached_array_buffer() -> Extent {
+ Extent {
+ buffer_is_detached: true,
+ ..array_buffer(0)
+ }
+ }
+
+ fn detached_view(view: Extent) -> Extent {
+ Extent {
+ buffer_is_detached: true,
+ ..out_of_bounds(view, 0)
+ }
+ }
+
+ fn uploaded(bytes_in_buffer: Range<usize>, source_has_bytes: bool) -> Result<UploadRange, OutOfRange> {
+ Ok(UploadRange {
+ length: GlSize::new(bytes_in_buffer.len()).unwrap(),
+ bytes_in_buffer,
+ source_has_bytes,
+ })
+ }
+
+ #[test]
+ fn a_gl_size_counts_what_a_glsizei_counts() {
+ assert_eq!(GlSize::new(0).unwrap().as_gl_sizei(), 0);
+ assert_eq!(GlSize::new(I32_MAX).unwrap().as_gl_sizei(), i32::MAX);
+ assert_eq!(GlSize::new(I32_MAX).unwrap().get(), I32_MAX);
+ assert_eq!(GlSize::new(I32_MAX + 1), Err(OutOfRange));
+ assert_eq!(GlSize::new(usize::MAX), Err(OutOfRange));
+
+ assert_eq!(const { gl_sizei_of_array_length(0) }, 0);
+ assert_eq!(const { gl_sizei_of_array_length(256) }, 256);
+ assert_eq!(const { gl_sizei_of_array_length(I32_MAX) }, i32::MAX);
+ }
+
+ #[test]
+ fn elements_are_counted_in_groups_when_they_are_whole_groups() {
+ let count =
+ |element_count: usize, group_size| GlSize::new(element_count).unwrap().count_of_whole_groups_of(group_size);
+ assert_eq!(count(0, 4), Some(0));
+ assert_eq!(count(16, 1), Some(16));
+ assert_eq!(count(16, 4), Some(4));
+ assert_eq!(count(16, 16), Some(1));
+ assert_eq!(count(32, 16), Some(2));
+ assert_eq!(count(15, 4), None);
+ assert_eq!(count(17, 16), None);
+ assert_eq!(count(3, 4), None);
+ assert_eq!(count(I32_MAX, 1), Some(i32::MAX));
+ assert_eq!(count(I32_MAX - 1, 2), Some(i32::MAX / 2));
+ assert_eq!(count(0, 0), None);
+ assert_eq!(count(4, 0), None);
+ }
+
+ #[test]
+ fn the_source_range_of_a_buffer_is_its_bytes_from_an_offset_on() {
+ let buffer = array_buffer(16);
+ assert_eq!(source_range(&buffer, 0, 0), Ok(0..16));
+ assert_eq!(source_range(&buffer, 4, 0), Ok(4..16));
+ assert_eq!(source_range(&buffer, 4, 8), Ok(4..12));
+ assert_eq!(source_range(&buffer, 4, 12), Ok(4..16));
+ assert_eq!(source_range(&buffer, 0, 16), Ok(0..16));
+ assert_eq!(source_range(&array_buffer(0), 0, 0), Ok(0..0));
+ }
+
+ #[test]
+ fn the_source_range_of_a_view_counts_its_elements() {
+ // A Uint16Array of two elements at byte 4 of a buffer of 16 bytes.
+ let uint16_array = view(16, 4, 2, 2);
+ assert_eq!(source_range(&uint16_array, 0, 0), Ok(0..4));
+ assert_eq!(source_range(&uint16_array, 1, 0), Ok(2..4));
+ assert_eq!(source_range(&uint16_array, 0, 1), Ok(0..2));
+ assert_eq!(source_range(&uint16_array, 1, 1), Ok(2..4));
+ assert_eq!(source_range(&uint16_array, 3, 0), Err(OutOfRange));
+
+ // A DataView of four bytes at byte 8 of the same buffer.
+ let data_view = view(16, 8, 4, 1);
+ assert_eq!(source_range(&data_view, 2, 2), Ok(2..4));
+ assert_eq!(source_range(&data_view, 2, 0), Ok(2..4));
+ assert_eq!(source_range(&data_view, 2, 3), Err(OutOfRange));
+
+ let float64_array = view(64, 8, 4, 8);
+ assert_eq!(source_range(&float64_array, 1, 2), Ok(8..24));
+ assert_eq!(source_range(&float64_array, 3, 0), Ok(24..32));
+ assert_eq!(source_range(&float64_array, 3, 2), Err(OutOfRange));
+ }
+
+ #[test]
+ fn an_upload_takes_the_bytes_of_a_view_from_where_the_view_is_in_its_buffer() {
+ let buffer: Vec<u8> = (0x10..0x20).collect();
+ let uploaded_bytes = |extent: &Extent, src_offset, src_length_override| {
+ upload_range(extent, src_offset, src_length_override).map(|range| buffer[range.bytes_in_buffer()].to_vec())
+ };
+
+ // A Uint16Array of two elements at byte 4 of the buffer.
+ let uint16_array = view(16, 4, 2, 2);
+ assert_eq!(uploaded_bytes(&uint16_array, 1, 0), Ok(vec![0x16, 0x17]));
+ assert_eq!(uploaded_bytes(&uint16_array, 0, 0), Ok(vec![0x14, 0x15, 0x16, 0x17]));
+ assert_eq!(uploaded_bytes(&uint16_array, 0, 1), Ok(vec![0x14, 0x15]));
+ assert_eq!(uploaded_bytes(&uint16_array, 2, 0), Ok(vec![]));
+ assert_eq!(uploaded_bytes(&uint16_array, 3, 0), Err(OutOfRange));
+
+ // A DataView of four bytes at byte 8 of the buffer.
+ let data_view = view(16, 8, 4, 1);
+ assert_eq!(uploaded_bytes(&data_view, 2, 2), Ok(vec![0x1a, 0x1b]));
+ assert_eq!(uploaded_bytes(&data_view, 1, 0), Ok(vec![0x19, 0x1a, 0x1b]));
+
+ let image_bytes = |extent: &Extent, src_offset, size_that_the_image_takes| {
+ upload_range_of_2d_texture(extent, src_offset, Some(size_that_the_image_takes))
+ .map(|range| buffer[range.bytes_in_buffer()].to_vec())
+ };
+ assert_eq!(image_bytes(&uint16_array, 1, 1), Ok(vec![0x16]));
+ assert_eq!(image_bytes(&data_view, 1, 2), Ok(vec![0x19, 0x1a]));
+ assert_eq!(image_bytes(&data_view, 3, 2), Ok(vec![0x1b]));
+ }
+
+ #[test]
+ fn an_offset_at_the_end_of_a_source_leaves_no_bytes_and_one_past_it_is_out_of_range() {
+ let buffer = array_buffer(16);
+ assert_eq!(source_range(&buffer, 16, 0), Ok(16..16));
+ assert_eq!(source_range(&buffer, 17, 0), Err(OutOfRange));
+ assert_eq!(source_range(&buffer, 16, 1), Err(OutOfRange));
+
+ let uint32_array = view(64, 16, 4, 4);
+ assert_eq!(source_range(&uint32_array, 4, 0), Ok(16..16));
+ assert_eq!(source_range(&uint32_array, 5, 0), Err(OutOfRange));
+ assert_eq!(source_range(&uint32_array, 4, 1), Err(OutOfRange));
+ }
+
+ #[test]
+ fn a_length_override_past_the_end_of_a_source_is_out_of_range() {
+ let buffer = array_buffer(16);
+ assert_eq!(source_range(&buffer, 0, 17), Err(OutOfRange));
+ assert_eq!(source_range(&buffer, 8, 9), Err(OutOfRange));
+ assert_eq!(source_range(&buffer, 0, u32::MAX), Err(OutOfRange));
+
+ let uint32_array = view(64, 16, 4, 4);
+ assert_eq!(source_range(&uint32_array, 0, 4), Ok(0..16));
+ assert_eq!(source_range(&uint32_array, 0, 5), Err(OutOfRange));
+ assert_eq!(source_range(&uint32_array, 3, 2), Err(OutOfRange));
+ assert_eq!(source_range(&uint32_array, 0, u32::MAX), Err(OutOfRange));
+ }
+
+ #[test]
+ fn offsets_and_lengths_that_overflow_are_out_of_range() {
+ let float64_array = view(64, 8, 4, 8);
+ assert_eq!(source_range(&float64_array, u64::MAX, 0), Err(OutOfRange));
+ assert_eq!(source_range(&float64_array, 1 << 61, 0), Err(OutOfRange));
+ assert_eq!(source_range(&float64_array, (1 << 61) - 1, 0), Err(OutOfRange));
+ assert_eq!(source_range(&float64_array, u64::MAX, u32::MAX), Err(OutOfRange));
+ assert_eq!(source_range(&array_buffer(16), u64::MAX, 0), Err(OutOfRange));
+
+ // NB: No view says this of itself. It is here for the additions, which do not rely on that.
+ let view_at_the_end_of_memory = Extent {
+ byte_offset: usize::MAX - 2,
+ ..view(usize::MAX, 0, 4, 1)
+ };
+ assert_eq!(source_range(&view_at_the_end_of_memory, 0, 0), Err(OutOfRange));
+ assert_eq!(source_range(&view_at_the_end_of_memory, 3, 0), Err(OutOfRange));
+ assert_eq!(source_range(&view_at_the_end_of_memory, 4, 0), Err(OutOfRange));
+ assert_eq!(
+ upload_range(&view_at_the_end_of_memory, 0, 2),
+ uploaded(usize::MAX - 2..usize::MAX, true)
+ );
+ assert_eq!(destination_range(&view_at_the_end_of_memory, 0), Err(OutOfRange));
+ assert_eq!(
+ typed_array_list_range(&view_at_the_end_of_memory, 0, 0),
+ Err(OutOfRange)
+ );
+ assert_eq!(
+ typed_array_list_range(&view_at_the_end_of_memory, 3, 0),
+ Err(OutOfRange)
+ );
+ assert_eq!(
+ typed_array_list_range(&view_at_the_end_of_memory, 0, 2).map(|range| range.bytes_in_buffer),
+ Ok(usize::MAX - 2..usize::MAX)
+ );
+ assert_eq!(
+ offset_in_buffer_of_checked_write(&view_at_the_end_of_memory, 1, 3),
+ Err(OutOfRange)
+ );
+ assert_eq!(typed_array_list_tail(&view_at_the_end_of_memory, 0), Err(OutOfRange));
+ assert_eq!(typed_array_list_tail(&view_at_the_end_of_memory, 2), Err(OutOfRange));
+ assert_eq!(sequence_list_tail(usize::MAX, 4, 0), Err(OutOfRange));
+ assert_eq!(
+ sequence_list_tail(usize::MAX / 4, 4, 0).map(|tail| tail.bytes_of_leading_elements(1)),
+ Ok(Some(0..4))
+ );
+ }
+
+ #[test]
+ fn a_view_that_its_buffer_is_too_short_for_has_no_source_range() {
+ // NB: A view that is not out of bounds does not say this of itself either.
+ let view_past_its_buffer = view(8, 4, 8, 1);
+ assert_eq!(source_range(&view_past_its_buffer, 0, 0), Err(OutOfRange));
+ assert_eq!(source_range(&view_past_its_buffer, 0, 4), Ok(0..4));
+ assert_eq!(source_range(&view_past_its_buffer, 4, 0), Err(OutOfRange));
+ assert_eq!(source_range(&view_past_its_buffer, 5, 0), Err(OutOfRange));
+ assert_eq!(destination_range(&view_past_its_buffer, 0), Err(OutOfRange));
+ }
+
+ #[test]
+ fn an_out_of_bounds_source_has_no_bytes_from_no_offset_on() {
+ // A Uint8Array and a DataView of four bytes at byte 8 of a buffer that was resized from 16 bytes to 4.
+ let view_of_bytes = out_of_bounds(view(16, 8, 4, 1), 4);
+ assert_eq!(source_range(&view_of_bytes, 0, 0), Ok(0..0));
+ assert_eq!(source_range(&view_of_bytes, 1, 0), Err(OutOfRange));
+ assert_eq!(source_range(&view_of_bytes, 0, 1), Err(OutOfRange));
+ assert_eq!(upload_range(&view_of_bytes, 0, 0), uploaded(8..8, false));
+
+ let uint16_array = out_of_bounds(view(16, 4, 4, 2), 8);
+ assert_eq!(source_range(&uint16_array, 0, 0), Ok(0..0));
+ assert_eq!(source_range(&uint16_array, 1, 0), Err(OutOfRange));
+ assert_eq!(source_range(&uint16_array, 0, 1), Err(OutOfRange));
+ }
+
+ #[test]
+ fn a_detached_source_has_no_source_range() {
+ for source in [
+ detached_array_buffer(),
+ detached_view(view(16, 4, 2, 2)),
+ detached_view(view(16, 0, 16, 1)),
+ ] {
+ assert_eq!(source_range(&source, 0, 0), Err(OutOfRange));
+ assert_eq!(source_range(&source, 1, 0), Err(OutOfRange));
+ assert_eq!(source_range(&source, 0, 1), Err(OutOfRange));
+ assert_eq!(upload_range(&source, 0, 0), Err(OutOfRange));
+ assert_eq!(upload_range_of_2d_texture(&source, 0, Some(0)), Err(OutOfRange));
+ }
+ }
+
+ #[test]
+ fn an_upload_records_no_more_bytes_than_gl_can_count() {
+ let largest_upload = array_buffer(I32_MAX);
+ assert_eq!(upload_range(&largest_upload, 0, 0), uploaded(0..I32_MAX, true));
+ assert_eq!(
+ upload_range(&largest_upload, 0, 0).unwrap().length().as_gl_sizei(),
+ i32::MAX
+ );
+
+ let two_gib = array_buffer(I32_MAX + 1);
+ assert_eq!(upload_range(&two_gib, 0, 0), Err(OutOfRange));
+ assert_eq!(upload_range(&two_gib, 1, 0), uploaded(1..I32_MAX + 1, true));
+ assert_eq!(upload_range(&two_gib, 0, 64), uploaded(0..64, true));
+ assert_eq!(
+ upload_range(&two_gib, 1 << 31, 0),
+ uploaded(I32_MAX + 1..I32_MAX + 1, false)
+ );
+
+ let four_gib_of_floats = view(1 << 32, 0, 1 << 30, 4);
+ assert_eq!(upload_range(&four_gib_of_floats, 0, 0), Err(OutOfRange));
+ assert_eq!(upload_range(&four_gib_of_floats, 0, 1 << 29), Err(OutOfRange));
+ assert_eq!(
+ upload_range(&four_gib_of_floats, 0, (1 << 29) - 1),
+ uploaded(0..I32_MAX - 3, true)
+ );
+ assert_eq!(
+ upload_range(&four_gib_of_floats, (1 << 30) - 16, 0),
+ uploaded((1 << 32) - 64..1 << 32, true)
+ );
+ }
+
+ #[test]
+ fn an_upload_tells_a_source_without_bytes_from_one_that_it_records_no_bytes_of() {
+ let buffer = array_buffer(16);
+ assert_eq!(upload_range(&buffer, 4, 0), uploaded(4..16, true));
+ assert_eq!(upload_range(&buffer, 4, 0).unwrap().bytes_in_buffer(), 4..16);
+ assert!(upload_range(&buffer, 4, 0).unwrap().source_has_bytes());
+ assert_eq!(upload_range(&buffer, 16, 0), uploaded(16..16, false));
+ assert_eq!(upload_range(&array_buffer(0), 0, 0), uploaded(0..0, false));
+
+ assert_eq!(upload_range_of_2d_texture(&buffer, 4, Some(0)), uploaded(4..4, true));
+ assert_eq!(
+ upload_range_of_2d_texture(&buffer, 16, Some(0)),
+ uploaded(16..16, false)
+ );
+ assert_eq!(
+ upload_range_of_2d_texture(&buffer, 16, Some(4)),
+ uploaded(16..16, false)
+ );
+ assert_eq!(upload_range_of_2d_texture(&buffer, 16, None), uploaded(16..16, false));
+ assert_eq!(
+ upload_range_of_2d_texture(&array_buffer(0), 0, Some(0)),
+ uploaded(0..0, false)
+ );
+ }
+
+ #[test]
+ fn an_upload_of_a_2d_image_records_the_bytes_that_the_image_takes() {
+ let buffer = array_buffer(64);
+ assert_eq!(upload_range_of_2d_texture(&buffer, 0, Some(16)), uploaded(0..16, true));
+ assert_eq!(upload_range_of_2d_texture(&buffer, 8, Some(16)), uploaded(8..24, true));
+ assert_eq!(upload_range_of_2d_texture(&buffer, 0, Some(64)), uploaded(0..64, true));
+ assert_eq!(
+ upload_range_of_2d_texture(&buffer, 48, Some(16)),
+ uploaded(48..64, true)
+ );
+
+ // A source that is too short for the image is recorded whole, and so is one of an image of unknown size.
+ assert_eq!(upload_range_of_2d_texture(&buffer, 0, Some(65)), uploaded(0..64, true));
+ assert_eq!(
+ upload_range_of_2d_texture(&buffer, 56, Some(16)),
+ uploaded(56..64, true)
+ );
+ assert_eq!(
+ upload_range_of_2d_texture(&buffer, 0, Some(usize::MAX)),
+ uploaded(0..64, true)
+ );
+ assert_eq!(upload_range_of_2d_texture(&buffer, 8, None), uploaded(8..64, true));
+
+ assert_eq!(upload_range_of_2d_texture(&buffer, 65, Some(0)), Err(OutOfRange));
+
+ let uint16_array = view(64, 8, 16, 2);
+ assert_eq!(
+ upload_range_of_2d_texture(&uint16_array, 2, Some(6)),
+ uploaded(12..18, true)
+ );
+ assert_eq!(
+ upload_range_of_2d_texture(&uint16_array, 14, Some(6)),
+ uploaded(36..40, true)
+ );
+ }
+
+ #[test]
+ fn an_upload_of_a_2d_image_from_a_large_source_is_bounded_by_what_it_records() {
+ // NB: This is the heap of a program that was compiled to WebAssembly, which uploads from where its pixels
+ // are in it.
+ let four_gib_heap = array_buffer(1 << 32);
+ assert_eq!(
+ upload_range_of_2d_texture(&four_gib_heap, 1 << 20, Some(4096)),
+ uploaded(1 << 20..(1 << 20) + 4096, true)
+ );
+ assert_eq!(
+ upload_range_of_2d_texture(&four_gib_heap, 0, Some(I32_MAX)),
+ uploaded(0..I32_MAX, true)
+ );
+ assert_eq!(
+ upload_range_of_2d_texture(&four_gib_heap, 0, Some(I32_MAX + 1)),
+ Err(OutOfRange)
+ );
+ assert_eq!(upload_range_of_2d_texture(&four_gib_heap, 0, None), Err(OutOfRange));
+ assert_eq!(
+ upload_range_of_2d_texture(&four_gib_heap, 16, Some(usize::MAX)),
+ Err(OutOfRange)
+ );
+ assert_eq!(
+ upload_range_of_2d_texture(&four_gib_heap, (1 << 32) - 16, None),
+ uploaded((1 << 32) - 16..1 << 32, true)
+ );
+ }
+
+ #[test]
+ fn a_texture_without_pixels_is_filled_with_as_many_zeros_as_gl_can_count() {
+ let size = |bytes_per_pixel, width, height| {
+ size_of_zero_filled_texture(bytes_per_pixel, width, height).map(GlSize::as_gl_sizei)
+ };
+ assert_eq!(size(4, 256, 256), Ok(4 * 256 * 256));
+ assert_eq!(size(1, 1, 1), Ok(1));
+ assert_eq!(size(3, 5, 7), Ok(105));
+ assert_eq!(size(4, 0, 16), Ok(0));
+ assert_eq!(size(4, 16, 0), Ok(0));
+ assert_eq!(size(4, 0, 0), Ok(0));
+ assert_eq!(size(1, i32::MAX, 1), Ok(i32::MAX));
+ assert_eq!(size(1, 1, i32::MAX), Ok(i32::MAX));
+ assert_eq!(size(4, 16384, 16384), Ok(1 << 30));
+
+ assert_eq!(size(1, -1, 1), Err(OutOfRange));
+ assert_eq!(size(1, 1, -1), Err(OutOfRange));
+ assert_eq!(size(2, -1, -1), Err(OutOfRange));
+ assert_eq!(size(4, i32::MIN, 1), Err(OutOfRange));
+ assert_eq!(size(4, 0, -1), Err(OutOfRange));
+ assert_eq!(size(4, -1, 0), Err(OutOfRange));
+
+ assert_eq!(size(4, 32768, 32768), Err(OutOfRange));
+ assert_eq!(size(2, i32::MAX, 1), Err(OutOfRange));
+ assert_eq!(size(1, 1 << 16, 1 << 15), Err(OutOfRange));
+ assert_eq!(size(4, i32::MAX, i32::MAX), Err(OutOfRange));
+ assert_eq!(size(usize::MAX, 2, 1), Err(OutOfRange));
+ assert_eq!(size(usize::MAX, i32::MAX, i32::MAX), Err(OutOfRange));
+ }
+
+ #[test]
+ fn a_read_back_writes_to_the_bytes_of_a_valid_view_from_an_offset_on() {
+ let uint16_array = view(16, 4, 4, 2);
+ assert_eq!(destination_range(&uint16_array, 0), Ok(0..8));
+ assert_eq!(destination_range(&uint16_array, 3), Ok(6..8));
+ assert_eq!(destination_range(&uint16_array, 4), Ok(8..8));
+ assert_eq!(destination_range(&uint16_array, 5), Err(OutOfRange));
+ assert_eq!(destination_range(&uint16_array, u64::MAX), Err(OutOfRange));
+
+ let data_view = view(16, 8, 4, 1);
+ assert_eq!(destination_range(&data_view, 1), Ok(1..4));
+
+ // NB: A source of an upload that is out of bounds is one without bytes. A destination has to be valid.
+ let out_of_bounds_view = out_of_bounds(view(16, 8, 4, 1), 4);
+ assert_eq!(destination_range(&out_of_bounds_view, 0), Err(OutOfRange));
+ assert_eq!(destination_range(&detached_view(uint16_array), 0), Err(OutOfRange));
+
+ // NB: How a destination of more bytes than a GLsizei counts fails depends on the operation.
+ let two_gib_view = view(I32_MAX + 1, 0, I32_MAX + 1, 1);
+ assert_eq!(destination_range(&two_gib_view, 0), Ok(0..I32_MAX + 1));
+ }
+
+ #[test]
+ fn get_buffer_sub_data_copies_to_the_elements_of_the_view_from_an_offset_on() {
+ let range = destination_range_of_get_buffer_sub_data;
+ let uint16_array = view(64, 8, 8, 2);
+ assert_eq!(range(&uint16_array, 0, 0), Ok(Some(0..16)));
+ assert_eq!(range(&uint16_array, 3, 0), Ok(Some(6..16)));
+ assert_eq!(range(&uint16_array, 3, 2), Ok(Some(6..10)));
+ assert_eq!(range(&uint16_array, 0, 8), Ok(Some(0..16)));
+ assert_eq!(range(&uint16_array, 7, 1), Ok(Some(14..16)));
+
+ let data_view = view(64, 8, 16, 1);
+ assert_eq!(range(&data_view, 0, 0), Ok(Some(0..16)));
+ assert_eq!(range(&data_view, 5, 0), Ok(Some(5..16)));
+ assert_eq!(range(&data_view, 5, 11), Ok(Some(5..16)));
+ }
+
+ #[test]
+ fn get_buffer_sub_data_copies_nothing_when_the_copy_length_is_zero() {
+ let range = destination_range_of_get_buffer_sub_data;
+ let uint16_array = view(64, 8, 8, 2);
+ assert_eq!(range(&uint16_array, 8, 0), Ok(None));
+ assert_eq!(range(&view(64, 8, 0, 2), 0, 0), Ok(None));
+ assert_eq!(range(&out_of_bounds(uint16_array, 4), 0, 0), Ok(None));
+ assert_eq!(range(&detached_view(uint16_array), 0, 0), Ok(None));
+ }
+
+ #[test]
+ fn get_buffer_sub_data_does_not_copy_past_the_end_of_the_view() {
+ let range = destination_range_of_get_buffer_sub_data;
+ let uint16_array = view(64, 8, 8, 2);
+ assert_eq!(range(&uint16_array, 9, 0), Err(OutOfRange));
+ assert_eq!(range(&uint16_array, 0, 9), Err(OutOfRange));
+ assert_eq!(range(&uint16_array, 7, 2), Err(OutOfRange));
+ assert_eq!(range(&uint16_array, 8, 1), Err(OutOfRange));
+ assert_eq!(range(&uint16_array, 9, 1), Err(OutOfRange));
+ assert_eq!(range(&uint16_array, u64::MAX, 0), Err(OutOfRange));
+ assert_eq!(range(&uint16_array, u64::MAX, 1), Err(OutOfRange));
+ assert_eq!(range(&uint16_array, u64::MAX / 2 + 1, 1), Err(OutOfRange));
+ assert_eq!(range(&uint16_array, 0, u32::MAX), Err(OutOfRange));
+ assert_eq!(range(&view(64, 0, 8, 8), 1, u32::MAX), Err(OutOfRange));
+
+ let out_of_bounds_view = out_of_bounds(uint16_array, 4);
+ assert_eq!(range(&out_of_bounds_view, 1, 0), Err(OutOfRange));
+ assert_eq!(range(&out_of_bounds_view, 0, 1), Err(OutOfRange));
+ assert_eq!(range(&detached_view(uint16_array), 0, 1), Err(OutOfRange));
+ }
+
+ #[test]
+ fn a_checked_write_goes_to_where_the_view_is_in_its_buffer() {
+ let offset = offset_in_buffer_of_checked_write;
+ // A Uint16Array of two elements at byte 4 of a buffer of 16 bytes, and a DataView of four bytes at byte 8.
+ let uint16_array = view(16, 4, 2, 2);
+ let data_view = view(16, 8, 4, 1);
+ assert_eq!(offset(&uint16_array, 2, 2), Ok(Some(6)));
+ assert_eq!(offset(&uint16_array, 4, 0), Ok(Some(4)));
+ assert_eq!(offset(&data_view, 2, 1), Ok(Some(9)));
+ assert_eq!(offset(&data_view, 4, 0), Ok(Some(8)));
+ assert_eq!(offset(&data_view, 1, 3), Ok(Some(11)));
+ }
+
+ #[test]
+ fn a_checked_write_needs_room_in_the_view() {
+ let offset = offset_in_buffer_of_checked_write;
+ let uint16_array = view(16, 4, 2, 2);
+ let data_view = view(16, 8, 4, 1);
+ assert_eq!(offset(&uint16_array, 6, 0), Err(OutOfRange));
+ assert_eq!(offset(&uint16_array, 4, 2), Err(OutOfRange));
+ assert_eq!(offset(&uint16_array, 2, 4), Err(OutOfRange));
+ assert_eq!(offset(&uint16_array, 0, 5), Err(OutOfRange));
+ assert_eq!(offset(&data_view, 5, 0), Err(OutOfRange));
+ assert_eq!(offset(&data_view, 1, 4), Err(OutOfRange));
+ assert_eq!(offset(&data_view, usize::MAX, 0), Err(OutOfRange));
+ assert_eq!(offset(&data_view, 1, usize::MAX), Err(OutOfRange));
+ assert_eq!(offset(&data_view, usize::MAX, usize::MAX), Err(OutOfRange));
+ }
+
+ #[test]
+ fn a_checked_write_to_a_typed_array_is_of_whole_elements() {
+ let offset = offset_in_buffer_of_checked_write;
+ let uint16_array = view(16, 4, 2, 2);
+ assert_eq!(offset(&uint16_array, 1, 0), Err(OutOfRange));
+ assert_eq!(offset(&uint16_array, 3, 0), Err(OutOfRange));
+ // NB: Only the number of bytes has to be whole elements. Where they go is counted in bytes.
+ assert_eq!(offset(&uint16_array, 2, 1), Ok(Some(5)));
+
+ let float32_array = view(64, 16, 4, 4);
+ assert_eq!(offset(&float32_array, 4, 4), Ok(Some(20)));
+ assert_eq!(offset(&float32_array, 8, 8), Ok(Some(24)));
+ assert_eq!(offset(&float32_array, 16, 0), Ok(Some(16)));
+ assert_eq!(offset(&float32_array, 2, 0), Err(OutOfRange));
+ assert_eq!(offset(&float32_array, 6, 4), Err(OutOfRange));
+
+ // The elements of a DataView are bytes.
+ let data_view = view(16, 8, 4, 1);
+ assert_eq!(offset(&data_view, 1, 0), Ok(Some(8)));
+ assert_eq!(offset(&data_view, 3, 1), Ok(Some(9)));
+ }
+
+ #[test]
+ fn a_checked_write_of_no_bytes_goes_nowhere() {
+ let offset = offset_in_buffer_of_checked_write;
+ let uint16_array = view(16, 4, 2, 2);
+ assert_eq!(offset(&uint16_array, 0, 0), Ok(None));
+ assert_eq!(offset(&uint16_array, 0, 4), Ok(None));
+ assert_eq!(offset(&uint16_array, 0, 3), Ok(None));
+ }
+
+ #[test]
+ fn a_checked_write_to_a_view_that_is_out_of_bounds_or_detached_is_of_no_bytes() {
+ let offset = offset_in_buffer_of_checked_write;
+ for view in [
+ out_of_bounds(view(16, 8, 4, 1), 4),
+ out_of_bounds(view(16, 8, 2, 2), 4),
+ detached_view(view(4, 0, 2, 2)),
+ detached_view(view(4, 0, 4, 1)),
+ ] {
+ assert_eq!(offset(&view, 0, 0), Ok(None));
+ assert_eq!(offset(&view, 0, 1), Err(OutOfRange));
+ assert_eq!(offset(&view, 1, 0), Err(OutOfRange));
+ assert_eq!(offset(&view, 2, 0), Err(OutOfRange));
+ }
+ }
+
+ #[test]
+ fn a_list_is_its_numbers_from_an_offset_on() {
+ let list = |list_length, src_offset, src_length_override| {
+ list_range(list_length, 4, src_offset, src_length_override)
+ .map(|range| (range.elements, range.bytes, range.element_count.as_gl_sizei()))
+ };
+ assert_eq!(list(8, 0, 0), Ok((0..8, 0..32, 8)));
+ assert_eq!(list(8, 3, 0), Ok((3..8, 12..32, 5)));
+ assert_eq!(list(8, 3, 2), Ok((3..5, 12..20, 2)));
+ assert_eq!(list(8, 0, 8), Ok((0..8, 0..32, 8)));
+ assert_eq!(list(8, 7, 1), Ok((7..8, 28..32, 1)));
+ assert_eq!(list(8, 8, 0), Ok((8..8, 32..32, 0)));
+ assert_eq!(list(0, 0, 0), Ok((0..0, 0..0, 0)));
+
+ assert_eq!(list(8, 9, 0), Err(OutOfRange));
+ assert_eq!(list(8, 0, 9), Err(OutOfRange));
+ assert_eq!(list(8, 7, 2), Err(OutOfRange));
+ assert_eq!(list(8, 8, 1), Err(OutOfRange));
+ assert_eq!(list(0, 1, 0), Err(OutOfRange));
+ assert_eq!(list(0, 0, 1), Err(OutOfRange));
+ assert_eq!(list(8, u64::MAX, 0), Err(OutOfRange));
+ assert_eq!(list(8, u64::MAX, 1), Err(OutOfRange));
+ assert_eq!(list(8, u64::MAX, u32::MAX), Err(OutOfRange));
+ assert_eq!(list(8, 0, u32::MAX), Err(OutOfRange));
+ }
+
+ #[test]
+ fn a_list_is_no_more_bytes_than_gl_can_count() {
+ let element_count_of = |list_length, element_size, src_offset, src_length_override| {
+ list_range(list_length, element_size, src_offset, src_length_override)
+ .map(|range| range.element_count.as_gl_sizei())
+ };
+ let largest_list_of_floats = I32_MAX / 4;
+ assert_eq!(element_count_of(largest_list_of_floats, 4, 0, 0), Ok(i32::MAX / 4));
+ assert_eq!(element_count_of(largest_list_of_floats + 1, 4, 0, 0), Err(OutOfRange));
+ assert_eq!(element_count_of(largest_list_of_floats + 1, 4, 1, 0), Ok(i32::MAX / 4));
+ assert_eq!(element_count_of(1 << 30, 4, 0, 16), Ok(16));
+ assert_eq!(element_count_of(1 << 30, 4, (1 << 30) - 16, 0), Ok(16));
+ assert_eq!(
+ list_range(1 << 30, 4, (1 << 30) - 16, 0).unwrap().bytes,
+ (1 << 32) - 64..1 << 32
+ );
+ assert_eq!(element_count_of(I32_MAX, 1, 0, 0), Ok(i32::MAX));
+ assert_eq!(element_count_of(I32_MAX + 1, 1, 0, 0), Err(OutOfRange));
+ assert_eq!(element_count_of(usize::MAX, 4, 0, 0), Err(OutOfRange));
+ assert_eq!(element_count_of(usize::MAX, 4, 1 << 62, 1), Err(OutOfRange));
+ assert_eq!(element_count_of(usize::MAX, 4, (1 << 62) - 1, 1), Err(OutOfRange));
+ assert_eq!(element_count_of(usize::MAX, 4, (1 << 62) - 2, 1), Ok(1));
+ }
+
+ #[test]
+ fn a_typed_array_is_a_list_of_the_numbers_that_it_holds() {
+ // A Float32Array of eight elements at byte 16 of a buffer of 64 bytes.
+ let float32_array = view(64, 16, 8, 4);
+ let range = typed_array_list_range(&float32_array, 3, 2).unwrap();
+ assert_eq!(range.bytes_in_buffer, 28..36);
+ assert_eq!(range.element_count.as_gl_sizei(), 2);
+ let bytes_in_buffer = |src_offset, src_length_override| {
+ typed_array_list_range(&float32_array, src_offset, src_length_override).map(|range| range.bytes_in_buffer)
+ };
+ assert_eq!(bytes_in_buffer(0, 0), Ok(16..48));
+ assert_eq!(bytes_in_buffer(7, 0), Ok(44..48));
+ assert_eq!(bytes_in_buffer(8, 0), Ok(48..48));
+ assert_eq!(bytes_in_buffer(0, 1), Ok(16..20));
+ assert_eq!(typed_array_list_range(&float32_array, 9, 0), Err(OutOfRange));
+ assert_eq!(typed_array_list_range(&float32_array, 7, 2), Err(OutOfRange));
+
+ let half_gib_of_floats = view(1 << 31, 0, 1 << 29, 4);
+ assert_eq!(typed_array_list_range(&half_gib_of_floats, 0, 0), Err(OutOfRange));
+ assert_eq!(
+ typed_array_list_range(&half_gib_of_floats, 1, 0)
+ .unwrap()
+ .element_count
+ .as_gl_sizei(),
+ (1 << 29) - 1
+ );
+ }
+
+ #[test]
+ fn a_list_tail_leads_with_the_elements_of_a_list_from_an_offset_on() {
+ let leading_bytes = |list_length, src_offset, count| {
+ sequence_list_tail(list_length, 4, src_offset).map(|tail| tail.bytes_of_leading_elements(count))
+ };
+ assert_eq!(leading_bytes(8, 0, 4), Ok(Some(0..16)));
+ assert_eq!(leading_bytes(8, 3, 4), Ok(Some(12..28)));
+ assert_eq!(leading_bytes(8, 4, 4), Ok(Some(16..32)));
+ assert_eq!(leading_bytes(8, 7, 1), Ok(Some(28..32)));
+ assert_eq!(leading_bytes(8, 8, 0), Ok(Some(32..32)));
+ assert_eq!(leading_bytes(8, 3, 0), Ok(Some(12..12)));
+
+ assert_eq!(leading_bytes(8, 5, 4), Ok(None));
+ assert_eq!(leading_bytes(8, 8, 1), Ok(None));
+ assert_eq!(leading_bytes(0, 0, 1), Ok(None));
+
+ assert_eq!(leading_bytes(8, 9, 0), Err(OutOfRange));
+ assert_eq!(leading_bytes(0, 1, 0), Err(OutOfRange));
+ assert_eq!(leading_bytes(8, u64::MAX, 1), Err(OutOfRange));
+ }
+
+ #[test]
+ fn a_typed_array_list_tail_leads_with_where_the_typed_array_is_in_its_buffer() {
+ // A Float32Array of eight elements at byte 16 of a buffer of 64 bytes.
+ let float32_array = view(64, 16, 8, 4);
+ let leading_bytes_in_buffer = |src_offset, count| {
+ typed_array_list_tail(&float32_array, src_offset).map(|tail| tail.bytes_of_leading_elements(count))
+ };
+ assert_eq!(leading_bytes_in_buffer(0, 4), Ok(Some(16..32)));
+ assert_eq!(leading_bytes_in_buffer(3, 4), Ok(Some(28..44)));
+ assert_eq!(leading_bytes_in_buffer(4, 4), Ok(Some(32..48)));
+ assert_eq!(leading_bytes_in_buffer(7, 1), Ok(Some(44..48)));
+ assert_eq!(leading_bytes_in_buffer(5, 4), Ok(None));
+ assert_eq!(leading_bytes_in_buffer(8, 1), Ok(None));
+ assert_eq!(leading_bytes_in_buffer(9, 0), Err(OutOfRange));
+
+ for typed_array in [out_of_bounds(view(32, 16, 4, 4), 4), detached_view(view(32, 16, 4, 4))] {
+ assert_eq!(
+ typed_array_list_tail(&typed_array, 0).map(|tail| tail.bytes_of_leading_elements(1)),
+ Ok(None)
+ );
+ assert_eq!(typed_array_list_tail(&typed_array, 1), Err(OutOfRange));
+ }
+ }
+
+ #[test]
+ fn a_list_tail_is_not_bounded_to_what_gl_can_count() {
+ // NB: This is the heap of a program that was compiled to WebAssembly, which hands GL the whole heap and where
+ // its numbers are in it.
+ let four_gib_heap_of_floats = view(1 << 32, 0, 1 << 30, 4);
+ for address_of_numbers in [0x10, 0x10_0000, 0x4000_0000, 0x7fff_fff0, 0x8000_0400] {
+ let src_offset = u64::try_from(address_of_numbers / 4).unwrap();
+ assert_eq!(
+ typed_array_list_tail(&four_gib_heap_of_floats, src_offset)
+ .map(|tail| tail.bytes_of_leading_elements(4)),
+ Ok(Some(address_of_numbers..address_of_numbers + 16))
+ );
+ }
+ assert_eq!(typed_array_list_range(&four_gib_heap_of_floats, 4, 0), Err(OutOfRange));
+ assert_eq!(
+ typed_array_list_tail(&four_gib_heap_of_floats, (1 << 30) - 1)
+ .map(|tail| tail.bytes_of_leading_elements(4)),
+ Ok(None)
+ );
+ assert_eq!(
+ typed_array_list_tail(&four_gib_heap_of_floats, (1 << 30) + 1),
+ Err(OutOfRange)
+ );
+
+ assert_eq!(
+ sequence_list_tail(I32_MAX + 1, 1, 0).map(|tail| tail.bytes_of_leading_elements(4)),
+ Ok(Some(0..4))
+ );
+ }
+
+ #[test]
+ fn a_typed_array_that_is_out_of_bounds_or_detached_is_an_empty_list() {
+ for element_size in [4, 1] {
+ for typed_array in [
+ out_of_bounds(view(32, 16, 4, element_size), 4),
+ detached_view(view(32, 16, 4, element_size)),
+ ] {
+ let whole_list = typed_array_list_range(&typed_array, 0, 0).unwrap();
+ assert!(whole_list.bytes_in_buffer.is_empty());
+ assert_eq!(whole_list.element_count.as_gl_sizei(), 0);
+ assert_eq!(typed_array_list_range(&typed_array, 1, 0), Err(OutOfRange));
+ assert_eq!(typed_array_list_range(&typed_array, 0, 1), Err(OutOfRange));
+ }
+ }
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/canvas.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/canvas.rs
new file mode 100644
index 00000000000..b2e28de50d5
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/canvas.rs
@@ -0,0 +1,189 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! What a WebGL context asks of the rest of LibWeb, which is C++: its canvas, the sources of texture images, and
+//! the helpers that LibCompositing shares between the two sides of the command stream.
+//! Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp defines these functions.
+
+use core::ffi::c_void;
+use core::ptr::NonNull;
+
+use libjs_rust::api::{Gc, Object, Realm};
+
+use super::host::Frame;
+use crate::bindings::conversions::CppInterface;
+
+/// Mirrors `Compositing::WebGL::PixelUnpackState`.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(C)]
+pub(crate) struct PixelUnpackState {
+ pub(crate) alignment: usize,
+ pub(crate) row_length: usize,
+ pub(crate) skip_pixels: usize,
+ pub(crate) skip_rows: usize,
+}
+
+impl Default for PixelUnpackState {
+ fn default() -> Self {
+ Self {
+ alignment: 4,
+ row_length: 0,
+ skip_pixels: 0,
+ skip_rows: 0,
+ }
+ }
+}
+
+/// In the order of the C++ enum of the same name.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
+pub(crate) enum TexImageSourceKind {
+ ImageBitmap,
+ ImageData,
+ HTMLImageElement,
+ HTMLCanvasElement,
+ HTMLVideoElement,
+ OffscreenCanvas,
+}
+
+/// The values of the C++ enum `TexImageSourceResult`.
+const TEX_IMAGE_SOURCE_RESULT_FRAME: u8 = 0;
+const TEX_IMAGE_SOURCE_RESULT_NO_FRAME: u8 = 1;
+const TEX_IMAGE_SOURCE_RESULT_INVALID_VALUE: u8 = 2;
+
+unsafe extern "C" {
+ fn web_webgl_canvas_did_change_content(canvas_host: *mut c_void);
+ fn web_webgl_canvas_bitmap_size(canvas_host: *mut c_void, out_width: *mut i32, out_height: *mut i32);
+ fn web_webgl_canvas_wrapper(canvas: *mut c_void, canvas_is_offscreen: bool, realm: *mut c_void) -> *mut c_void;
+ fn web_webgl_canvas_relevant_realm(canvas_host: *mut c_void) -> *mut c_void;
+ fn web_webgl_expose_experimental_interfaces() -> bool;
+ fn web_webgl_is_valid_2d_pixel_unpack_state(width: i32, unpack_state: *const PixelUnpackState) -> bool;
+ fn web_webgl_required_2d_texture_data_size(
+ width: i32,
+ height: i32,
+ format: u32,
+ r#type: u32,
+ unpack_state: *const PixelUnpackState,
+ out_size: *mut usize,
+ ) -> bool;
+ fn web_webgl_read_tex_image_source(
+ source_wrapper: *mut c_void,
+ source_kind: TexImageSourceKind,
+ format: u32,
+ r#type: u32,
+ out_frame: *mut *mut c_void,
+ ) -> u8;
+ fn web_webgl_make_xr_compatible(context: *mut c_void) -> *mut c_void;
+}
+
+#[derive(Clone, Copy)]
+pub(crate) struct Canvas {
+ /// The cell of the canvas, which the context keeps alive through a slot of its own.
+ pub(crate) cell: NonNull<c_void>,
+ pub(crate) host: NonNull<c_void>,
+ pub(crate) is_offscreen: bool,
+}
+
+// SAFETY (of every call below): The context that holds the canvas keeps its cell alive, and the host is the same
+// object.
+impl Canvas {
+ pub(crate) fn did_change_content(self) {
+ unsafe { web_webgl_canvas_did_change_content(self.host.as_ptr()) };
+ }
+
+ pub(crate) fn bitmap_size(self) -> (i32, i32) {
+ let (mut width, mut height) = (0, 0);
+ unsafe { web_webgl_canvas_bitmap_size(self.host.as_ptr(), &raw mut width, &raw mut height) };
+ (width, height)
+ }
+
+ pub(crate) fn wrapper(self, realm: Gc<Realm>) -> CppInterface {
+ let wrapper = unsafe { web_webgl_canvas_wrapper(self.cell.as_ptr(), self.is_offscreen, realm.as_ptr().cast()) };
+ let wrapper = NonNull::new(wrapper.cast::<Object>()).expect("LibWeb returns the wrapper of the canvas");
+ // SAFETY: LibWeb returns a live wrapper of an HTMLCanvasElement or an OffscreenCanvas.
+ unsafe { CppInterface::from_wrapper(Gc::from_non_null(wrapper)) }
+ }
+
+ /// The realm of the relevant global object of the canvas, once that global object has a wrapper.
+ pub(crate) fn relevant_realm(self) -> Option<Gc<Realm>> {
+ let realm = unsafe { web_webgl_canvas_relevant_realm(self.host.as_ptr()) };
+ // SAFETY: LibWeb returns a live realm, or null.
+ NonNull::new(realm.cast::<Realm>()).map(|realm| unsafe { Gc::from_non_null(realm) })
+ }
+}
+
+pub(crate) fn expose_experimental_interfaces() -> bool {
+ // SAFETY: The function has no preconditions.
+ unsafe { web_webgl_expose_experimental_interfaces() }
+}
+
+pub(crate) fn is_valid_2d_pixel_unpack_state(width: i32, unpack_state: &PixelUnpackState) -> bool {
+ // SAFETY: The state is live for the call.
+ unsafe { web_webgl_is_valid_2d_pixel_unpack_state(width, unpack_state) }
+}
+
+pub(crate) fn required_2d_texture_data_size(
+ width: i32,
+ height: i32,
+ format: u32,
+ r#type: u32,
+ unpack_state: &PixelUnpackState,
+) -> Option<usize> {
+ let mut size = 0;
+ // SAFETY: The state is live for the call, and the size is stored when the function returns true.
+ unsafe { web_webgl_required_2d_texture_data_size(width, height, format, r#type, unpack_state, &raw mut size) }
+ .then_some(size)
+}
+
+pub(crate) enum TexImageSourceFrame {
+ Frame(Frame),
+ /// The source has no image, or no image is uploaded with this format and type.
+ NoFrame,
+ InvalidValue,
+}
+
+pub(crate) fn read_tex_image_source(
+ source: CppInterface,
+ source_kind: TexImageSourceKind,
+ format: u32,
+ r#type: u32,
+) -> TexImageSourceFrame {
+ let mut frame = core::ptr::null_mut();
+ // SAFETY: The wrapper is live and of the interface that the kind names, and the frame is stored when the
+ // function returns that there is one.
+ let result = unsafe {
+ web_webgl_read_tex_image_source(
+ source.wrapper().as_ptr().cast(),
+ source_kind,
+ format,
+ r#type,
+ &raw mut frame,
+ )
+ };
+ match result {
+ TEX_IMAGE_SOURCE_RESULT_FRAME => {
+ let frame = NonNull::new(frame).expect("LibWeb returns the frame");
+ // SAFETY: LibWeb hands over a frame that it allocated.
+ TexImageSourceFrame::Frame(unsafe { Frame::from_raw(frame) })
+ }
+ TEX_IMAGE_SOURCE_RESULT_NO_FRAME => TexImageSourceFrame::NoFrame,
+ TEX_IMAGE_SOURCE_RESULT_INVALID_VALUE => TexImageSourceFrame::InvalidValue,
+ unknown_result => unreachable!("LibWeb returned {unknown_result} for the reading of a texture image source"),
+ }
+}
+
+/// LibWeb's C++ code settles the promise.
+///
+/// # Safety
+///
+/// `context` is the cell of a WebGL context.
+pub(crate) unsafe fn make_xr_compatible(context: *mut c_void) -> Gc<Object> {
+ // SAFETY: The caller passes the cell of a context.
+ let promise = unsafe { web_webgl_make_xr_compatible(context) };
+ let promise = NonNull::new(promise.cast::<Object>()).expect("LibWeb returns the promise");
+ // SAFETY: LibWeb returns a live promise.
+ unsafe { Gc::from_non_null(promise) }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/constants.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/constants.rs
index 189d2971188..d26fe47e494 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/constants.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/constants.rs
@@ -10,6 +10,10 @@
non_upper_case_globals,
reason = "GL has lower case letters in the names of some constants"
)]
+#![allow(
+ dead_code,
+ reason = "these are all the constants of the interfaces, of which the implementation names some"
+)]
include!(concat!(env!("OUT_DIR"), "/webgl_constants.rs"));
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/exports.rs
new file mode 100644
index 00000000000..1728cf03033
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/exports.rs
@@ -0,0 +1,321 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The C ABI that Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp declares, and calls with the cell of a
+//! context of either kind.
+
+use core::ffi::c_void;
+use core::ptr::NonNull;
+
+use super::canvas::Canvas;
+use super::fingerprint::verify_that_rust_and_cpp_agree_on_layouts_and_constants;
+use super::host::CppTransport;
+use super::proxy::recorder::Proxy;
+use super::state::{
+ ContextParameters, ContextRef, ContextState, MAX_WEBGL_DRAWING_BUFFER_DIMENSION, RenderingContext, WebGL1, WebGL2,
+ WebGLVersion,
+};
+use super::web_gl_rendering_context::WebGLPowerPreference;
+use super::web_gl_rendering_context_base::WebGLContextAttributes;
+use crate::bindings::interface::{Interface, allocate, cell_into_abi, realm_arguments};
+
+#[repr(C)]
+pub struct ByteSpan {
+ data: *const u8,
+ size: usize,
+}
+
+/// # Safety
+///
+/// The spans are live, and each is the bytes of a string.
+unsafe fn extension_names(names: *const ByteSpan, name_count: usize) -> Vec<Vec<u8>> {
+ if name_count == 0 {
+ return Vec::new();
+ }
+ // SAFETY: The caller passes `name_count` live spans.
+ let names = unsafe { core::slice::from_raw_parts(names, name_count) };
+ names
+ .iter()
+ .map(|name| {
+ if name.size == 0 {
+ return Vec::new();
+ }
+ // SAFETY: The caller passes the bytes of a string.
+ unsafe { core::slice::from_raw_parts(name.data, name.size) }.to_vec()
+ })
+ .collect()
+}
+
+/// Mirrors `Web::WebGL::RustContextAttributes`.
+#[derive(Clone, Copy)]
+#[repr(C)]
+pub struct ContextAttributes {
+ alpha: bool,
+ depth: bool,
+ stencil: bool,
+ antialias: bool,
+ premultiplied_alpha: bool,
+ preserve_drawing_buffer: bool,
+ /// 0 is "default", 1 is "low-power" and 2 is "high-performance".
+ power_preference: u8,
+ fail_if_major_performance_caveat: bool,
+ desynchronized: bool,
+ xr_compatible: bool,
+}
+
+impl From<ContextAttributes> for WebGLContextAttributes {
+ fn from(attributes: ContextAttributes) -> Self {
+ Self {
+ alpha: attributes.alpha,
+ depth: attributes.depth,
+ stencil: attributes.stencil,
+ antialias: attributes.antialias,
+ premultiplied_alpha: attributes.premultiplied_alpha,
+ preserve_drawing_buffer: attributes.preserve_drawing_buffer,
+ power_preference: match attributes.power_preference {
+ 0 => WebGLPowerPreference::Default,
+ 1 => WebGLPowerPreference::LowPower,
+ 2 => WebGLPowerPreference::HighPerformance,
+ unknown => unreachable!("LibWeb passed {unknown} for a power preference"),
+ },
+ fail_if_major_performance_caveat: attributes.fail_if_major_performance_caveat,
+ desynchronized: attributes.desynchronized,
+ xr_compatible: attributes.xr_compatible,
+ }
+ }
+}
+
+impl From<WebGLContextAttributes> for ContextAttributes {
+ fn from(attributes: WebGLContextAttributes) -> Self {
+ Self {
+ alpha: attributes.alpha,
+ depth: attributes.depth,
+ stencil: attributes.stencil,
+ antialias: attributes.antialias,
+ premultiplied_alpha: attributes.premultiplied_alpha,
+ preserve_drawing_buffer: attributes.preserve_drawing_buffer,
+ power_preference: match attributes.power_preference {
+ WebGLPowerPreference::Default => 0,
+ WebGLPowerPreference::LowPower => 1,
+ WebGLPowerPreference::HighPerformance => 2,
+ },
+ fail_if_major_performance_caveat: attributes.fail_if_major_performance_caveat,
+ desynchronized: attributes.desynchronized,
+ xr_compatible: attributes.xr_compatible,
+ }
+ }
+}
+
+/// Mirrors `Web::WebGL::ContextCreationArguments`.
+#[repr(C)]
+pub struct ContextCreationArguments {
+ /// A RemoteWebGLTransport that has created its context, with a reference that the new context takes over.
+ transport: *mut c_void,
+ is_webgl2: bool,
+ realm: *mut c_void,
+ canvas: *mut c_void,
+ canvas_host: *mut c_void,
+ canvas_is_offscreen: bool,
+ context_attributes: ContextAttributes,
+ supported_extensions: *const ByteSpan,
+ supported_extension_count: usize,
+}
+
+/// # Safety
+///
+/// `context` is the live cell of a WebGLRenderingContext or of a WebGL2RenderingContext.
+unsafe fn with_context<R>(context: *mut c_void, function: impl FnOnce(&ContextState) -> R) -> R {
+ let cell = NonNull::new(context).expect("C++ passes the cell of a context");
+ // SAFETY: The caller passes a live cell of one of the two classes, which the downcasts tell apart.
+ unsafe {
+ if let Some(context) = RenderingContext::<WebGL1>::CELL_CLASS.downcast(cell) {
+ return function(&context);
+ }
+ let context = RenderingContext::<WebGL2>::CELL_CLASS
+ .downcast(cell)
+ .expect("the cell is a WebGL context");
+ function(&context)
+ }
+}
+
+/// # Safety
+///
+/// The pointers are the live VM and what [`ContextCreationArguments`] describes.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_webgl_context_create(
+ vm: *mut c_void,
+ arguments: *const ContextCreationArguments,
+) -> *mut c_void {
+ // SAFETY: The caller passes live arguments.
+ let arguments = unsafe { &*arguments };
+ // SAFETY: The caller passes the live VM and a live realm.
+ let (vm, realm) = unsafe { realm_arguments(vm, arguments.realm) };
+ verify_that_rust_and_cpp_agree_on_layouts_and_constants();
+
+ let transport = NonNull::new(arguments.transport).expect("C++ passes the transport");
+ let canvas = Canvas {
+ cell: NonNull::new(arguments.canvas).expect("C++ passes the canvas"),
+ host: NonNull::new(arguments.canvas_host).expect("C++ passes the canvas"),
+ is_offscreen: arguments.canvas_is_offscreen,
+ };
+ let version = if arguments.is_webgl2 {
+ WebGLVersion::WebGL2
+ } else {
+ WebGLVersion::WebGL1
+ };
+ let state = ContextState::new(ContextParameters {
+ // SAFETY: The caller hands over a reference to the transport.
+ proxy: Proxy::new(unsafe { CppTransport::from_raw(transport) }),
+ version,
+ realm,
+ canvas,
+ context_attributes: arguments.context_attributes.into(),
+ // SAFETY: The caller passes live names.
+ supported_opengl_extensions: unsafe {
+ extension_names(arguments.supported_extensions, arguments.supported_extension_count)
+ },
+ });
+ match version {
+ WebGLVersion::WebGL1 => {
+ let context = allocate(vm, RenderingContext::<WebGL1>::new(state));
+ context.set_context_ref(ContextRef::WebGL1(context));
+ cell_into_abi(context)
+ }
+ WebGLVersion::WebGL2 => {
+ let context = allocate(vm, RenderingContext::<WebGL2>::new(state));
+ context.set_context_ref(ContextRef::WebGL2(context));
+ cell_into_abi(context)
+ }
+ }
+}
+
+// SAFETY (of every function below): The caller passes the live cell of a context, and live pointers to what a
+// function stores.
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_webgl_context_canvas_host(context: *mut c_void) -> *mut c_void {
+ unsafe { with_context(context, |context| context.canvas().host.as_ptr()) }
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_webgl_context_realm(context: *mut c_void) -> *mut c_void {
+ unsafe { with_context(context, |context| context.realm().as_ptr().cast()) }
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_webgl_context_is_webgl2(context: *mut c_void) -> bool {
+ unsafe { with_context(context, ContextState::is_webgl2) }
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_webgl_context_is_lost(context: *mut c_void) -> bool {
+ unsafe { with_context(context, ContextState::is_context_lost) }
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_webgl_context_canvas_id(context: *mut c_void, out_canvas_id: *mut u64) -> bool {
+ let Some(canvas_id) = (unsafe { with_context(context, |context| context.proxy.canvas_id()) }) else {
+ return false;
+ };
+ unsafe { out_canvas_id.write(canvas_id) };
+ true
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_webgl_context_set_size(context: *mut c_void, width: i32, height: i32) {
+ unsafe {
+ with_context(context, |context| {
+ context.proxy.set_size(
+ width.clamp(1, MAX_WEBGL_DRAWING_BUFFER_DIMENSION),
+ height.clamp(1, MAX_WEBGL_DRAWING_BUFFER_DIMENSION),
+ );
+ });
+ }
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_webgl_context_present_for_compositing(context: *mut c_void) {
+ unsafe {
+ with_context(context, |context| {
+ let preserve_drawing_buffer = context.context_creation_parameters.preserve_drawing_buffer;
+ context.proxy.present_canvas_for_compositing(preserve_drawing_buffer);
+ });
+ }
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_webgl_context_clear_drawing_buffer(context: *mut c_void) {
+ unsafe { with_context(context, |context| context.proxy.clear_drawing_buffer()) };
+}
+
+/// A Gfx::Bitmap with a reference that the caller takes over, or null.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_webgl_context_read_back_drawing_buffer(
+ context: *mut c_void,
+ x: i32,
+ y: i32,
+ width: i32,
+ height: i32,
+) -> *mut c_void {
+ let bitmap = unsafe {
+ with_context(context, |context| {
+ context.proxy.read_back_drawing_buffer(x, y, width, height)
+ })
+ };
+ bitmap.map_or(core::ptr::null_mut(), super::host::Bitmap::into_raw)
+}
+
+/// False when the context was lost already.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_webgl_context_mark_lost(context: *mut c_void) -> bool {
+ unsafe { with_context(context, ContextState::mark_lost) }
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_webgl_context_set_restore_requested(context: *mut c_void, requested: bool) {
+ unsafe { with_context(context, |context| context.set_context_restore_requested(requested)) };
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_webgl_context_wants_restoring(context: *mut c_void) -> bool {
+ unsafe { with_context(context, ContextState::wants_restoring) }
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_webgl_context_actual_context_parameters(
+ context: *mut c_void,
+ out_context_attributes: *mut ContextAttributes,
+) {
+ let context_attributes = unsafe { with_context(context, |context| context.actual_context_parameters) };
+ unsafe { out_context_attributes.write(context_attributes.into()) };
+}
+
+/// The context takes over the reference to `transport`.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_webgl_context_restore(
+ context: *mut c_void,
+ transport: *mut c_void,
+ supported_extensions: *const ByteSpan,
+ supported_extension_count: usize,
+) {
+ let transport = NonNull::new(transport).expect("C++ passes the transport");
+ unsafe {
+ let supported_opengl_extensions = extension_names(supported_extensions, supported_extension_count);
+ with_context(context, |context| {
+ context.restore(CppTransport::from_raw(transport), supported_opengl_extensions);
+ });
+ }
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_webgl_context_xr_compatible(context: *mut c_void) -> bool {
+ unsafe { with_context(context, ContextState::xr_compatible) }
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_webgl_context_set_xr_compatible(context: *mut c_void, xr_compatible: bool) {
+ unsafe { with_context(context, |context| context.set_xr_compatible(xr_compatible)) };
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/extensions.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/extensions.rs
new file mode 100644
index 00000000000..69f07b74849
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/extensions.rs
@@ -0,0 +1,323 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use ak::Utf16String;
+use libjs_rust::api::{Gc, GcWeak, Object, Trace, Vm};
+
+use super::canvas::expose_experimental_interfaces;
+use super::gl_string::ascii_bytes;
+use super::state::{ContextState, WebGLVersion};
+use crate::bindings::CallContext;
+use crate::bindings::interface::{Ref, create_dictionary_object, wrap};
+use crate::bindings::realm_data::{WrapperWorld, wrapper_world_of};
+
+macro_rules! enums_of_extension_interfaces {
+ ($($module:ident :: $interface:ident),+ $(,)?) => {
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
+ enum ExtensionInterface {
+ $($interface,)+
+ }
+
+ impl ExtensionInterface {
+ fn create(self, vm: &Vm, context: &ContextState) -> ExtensionObject {
+ match self {
+ $(Self::$interface => {
+ ExtensionObject::$interface(super::$module::$interface::create(vm, context))
+ })+
+ }
+ }
+ }
+
+ #[derive(Clone, Copy, Trace)]
+ #[gc(crate = libjs_rust)]
+ pub(crate) enum ExtensionObject {
+ $($interface(Ref<super::$module::$interface>),)+
+ }
+
+ impl ExtensionObject {
+ fn wrap(self, cx: &CallContext) -> Gc<Object> {
+ match self {
+ $(Self::$interface(extension) => wrap(cx, extension),)+
+ }
+ }
+ }
+ };
+}
+
+// Every extension interface that a row of AVAILABLE_WEBGL_EXTENSIONS can name, as `module::Interface`. Expands to
+//
+// enum ExtensionInterface { ANGLEInstancedArrays, .. }
+// impl ExtensionInterface { fn create(self, vm: &Vm, context: &ContextState) -> ExtensionObject { .. } }
+// pub(crate) enum ExtensionObject { ANGLEInstancedArrays(Ref<ANGLEInstancedArrays>), .. }
+// impl ExtensionObject { fn wrap(self, cx: &CallContext) -> Gc<Object> { .. } }
+enums_of_extension_interfaces! {
+ angle_instanced_arrays::ANGLEInstancedArrays,
+ ext_blend_min_max::EXTBlendMinMax,
+ ext_color_buffer_float::EXTColorBufferFloat,
+ ext_render_snorm::EXTRenderSnorm,
+ ext_texture_filter_anisotropic::EXTTextureFilterAnisotropic,
+ ext_texture_norm16::EXTTextureNorm16,
+ oes_element_index_uint::OESElementIndexUint,
+ oes_standard_derivatives::OESStandardDerivatives,
+ oes_vertex_array_object::OESVertexArrayObject,
+ web_gl_compressed_texture_s3tc::WebGLCompressedTextureS3tc,
+ web_gl_compressed_texture_s3tc_srgb::WebGLCompressedTextureS3tcSrgb,
+ web_gl_debug_renderer_info::WebGLDebugRendererInfo,
+ web_gl_draw_buffers::WebGLDrawBuffers,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum Kind {
+ Interface(ExtensionInterface),
+ EmptyObject,
+ /// Offered only while the experimental interfaces are exposed.
+ NotImplemented,
+}
+
+struct Extension {
+ name: &'static str,
+ required_angle_extensions: &'static [&'static str],
+ kind: Kind,
+ only_for_webgl_version: Option<WebGLVersion>,
+}
+
+// NB: The order is that of getSupportedExtensions(), which pages can observe, and it is not alphabetical.
+#[rustfmt::skip]
+static AVAILABLE_WEBGL_EXTENSIONS: [Extension; 53] = [
+ Extension { name: "OES_fbo_render_mipmap", required_angle_extensions: &["GL_OES_fbo_render_mipmap"], kind: Kind::NotImplemented, only_for_webgl_version: Some(WebGLVersion::WebGL1) },
+ Extension { name: "OES_texture_float", required_angle_extensions: &["GL_OES_texture_float"], kind: Kind::NotImplemented, only_for_webgl_version: Some(WebGLVersion::WebGL1) },
+ Extension { name: "EXT_texture_mirror_clamp_to_edge", required_angle_extensions: &["GL_EXT_texture_mirror_clamp_to_edge"], kind: Kind::NotImplemented, only_for_webgl_version: None },
+ Extension { name: "WEBGL_lose_context", required_angle_extensions: &[], kind: Kind::NotImplemented, only_for_webgl_version: None },
+ Extension { name: "EXT_texture_norm16", required_angle_extensions: &["GL_EXT_texture_norm16"], kind: Kind::Interface(ExtensionInterface::EXTTextureNorm16), only_for_webgl_version: Some(WebGLVersion::WebGL2) },
+ Extension { name: "NV_shader_noperspective_interpolation", required_angle_extensions: &["GL_NV_shader_noperspective_interpolation"], kind: Kind::NotImplemented, only_for_webgl_version: Some(WebGLVersion::WebGL2) },
+ Extension { name: "OES_element_index_uint", required_angle_extensions: &["GL_OES_element_index_uint"], kind: Kind::Interface(ExtensionInterface::OESElementIndexUint), only_for_webgl_version: Some(WebGLVersion::WebGL1) },
+ Extension { name: "OES_standard_derivatives", required_angle_extensions: &["GL_OES_standard_derivatives"], kind: Kind::Interface(ExtensionInterface::OESStandardDerivatives), only_for_webgl_version: Some(WebGLVersion::WebGL1) },
+ Extension { name: "EXT_float_blend", required_angle_extensions: &["GL_EXT_float_blend"], kind: Kind::EmptyObject, only_for_webgl_version: None },
+ Extension { name: "EXT_frag_depth", required_angle_extensions: &["GL_EXT_frag_depth"], kind: Kind::NotImplemented, only_for_webgl_version: Some(WebGLVersion::WebGL1) },
+ Extension { name: "EXT_color_buffer_half_float", required_angle_extensions: &["GL_EXT_color_buffer_half_float"], kind: Kind::NotImplemented, only_for_webgl_version: None },
+ Extension { name: "EXT_sRGB", required_angle_extensions: &["GL_EXT_sRGB"], kind: Kind::NotImplemented, only_for_webgl_version: Some(WebGLVersion::WebGL1) },
+ Extension { name: "WEBGL_compressed_texture_astc", required_angle_extensions: &["KHR_texture_compression_astc_hdr", "KHR_texture_compression_astc_ldr"], kind: Kind::NotImplemented, only_for_webgl_version: None },
+ Extension { name: "WEBGL_depth_texture", required_angle_extensions: &["GL_ANGLE_depth_texture"], kind: Kind::NotImplemented, only_for_webgl_version: Some(WebGLVersion::WebGL1) },
+ Extension { name: "WEBGL_color_buffer_float", required_angle_extensions: &["EXT_color_buffer_half_float", "OES_texture_float"], kind: Kind::NotImplemented, only_for_webgl_version: Some(WebGLVersion::WebGL1) },
+ Extension { name: "EXT_disjoint_timer_query", required_angle_extensions: &["GL_EXT_disjoint_timer_query"], kind: Kind::NotImplemented, only_for_webgl_version: Some(WebGLVersion::WebGL1) },
+ Extension { name: "WEBGL_compressed_texture_s3tc_srgb", required_angle_extensions: &["GL_EXT_texture_compression_s3tc_srgb"], kind: Kind::Interface(ExtensionInterface::WebGLCompressedTextureS3tcSrgb), only_for_webgl_version: None },
+ Extension { name: "EXT_texture_filter_anisotropic", required_angle_extensions: &["GL_EXT_texture_filter_anisotropic"], kind: Kind::Interface(ExtensionInterface::EXTTextureFilterAnisotropic), only_for_webgl_version: None },
+ Extension { name: "EXT_disjoint_timer_query_webgl2", required_angle_extensions: &["GL_EXT_disjoint_timer_query"], kind: Kind::NotImplemented, only_for_webgl_version: Some(WebGLVersion::WebGL2) },
+ Extension { name: "OES_texture_float_linear", required_angle_extensions: &["GL_OES_texture_float_linear"], kind: Kind::EmptyObject, only_for_webgl_version: None },
+ Extension { name: "OES_vertex_array_object", required_angle_extensions: &["GL_OES_vertex_array_object"], kind: Kind::Interface(ExtensionInterface::OESVertexArrayObject), only_for_webgl_version: Some(WebGLVersion::WebGL1) },
+ Extension { name: "WEBGL_clip_cull_distance", required_angle_extensions: &["GL_EXT_clip_cull_distance"], kind: Kind::NotImplemented, only_for_webgl_version: Some(WebGLVersion::WebGL2) },
+ Extension { name: "ANGLE_instanced_arrays", required_angle_extensions: &["GL_ANGLE_instanced_arrays"], kind: Kind::Interface(ExtensionInterface::ANGLEInstancedArrays), only_for_webgl_version: Some(WebGLVersion::WebGL1) },
+ Extension { name: "EXT_shader_texture_lod", required_angle_extensions: &["GL_EXT_shader_texture_lod"], kind: Kind::NotImplemented, only_for_webgl_version: Some(WebGLVersion::WebGL1) },
+ Extension { name: "OES_texture_half_float", required_angle_extensions: &["GL_OES_texture_half_float"], kind: Kind::NotImplemented, only_for_webgl_version: Some(WebGLVersion::WebGL1) },
+ Extension { name: "KHR_parallel_shader_compile", required_angle_extensions: &["GL_KHR_parallel_shader_compile"], kind: Kind::NotImplemented, only_for_webgl_version: None },
+ Extension { name: "WEBGL_compressed_texture_pvrtc", required_angle_extensions: &["GL_IMG_texture_compression_pvrtc"], kind: Kind::NotImplemented, only_for_webgl_version: None },
+ Extension { name: "EXT_clip_control", required_angle_extensions: &["GL_EXT_clip_control"], kind: Kind::NotImplemented, only_for_webgl_version: None },
+ Extension { name: "EXT_blend_minmax", required_angle_extensions: &["GL_EXT_blend_minmax"], kind: Kind::Interface(ExtensionInterface::EXTBlendMinMax), only_for_webgl_version: Some(WebGLVersion::WebGL1) },
+ Extension { name: "WEBGL_debug_renderer_info", required_angle_extensions: &[], kind: Kind::Interface(ExtensionInterface::WebGLDebugRendererInfo), only_for_webgl_version: None },
+ Extension { name: "OES_sample_variables", required_angle_extensions: &["GL_OES_sample_variables"], kind: Kind::NotImplemented, only_for_webgl_version: Some(WebGLVersion::WebGL2) },
+ Extension { name: "WEBGL_render_shared_exponent", required_angle_extensions: &["GL_QCOM_render_shared_exponent"], kind: Kind::NotImplemented, only_for_webgl_version: Some(WebGLVersion::WebGL2) },
+ Extension { name: "WEBGL_debug_shaders", required_angle_extensions: &[], kind: Kind::NotImplemented, only_for_webgl_version: None },
+ Extension { name: "OES_shader_multisample_interpolation", required_angle_extensions: &["GL_OES_shader_multisample_interpolation"], kind: Kind::NotImplemented, only_for_webgl_version: Some(WebGLVersion::WebGL2) },
+ Extension { name: "EXT_color_buffer_float", required_angle_extensions: &["GL_EXT_color_buffer_float"], kind: Kind::Interface(ExtensionInterface::EXTColorBufferFloat), only_for_webgl_version: Some(WebGLVersion::WebGL2) },
+ Extension { name: "OES_texture_half_float_linear", required_angle_extensions: &["GL_OES_texture_half_float_linear"], kind: Kind::NotImplemented, only_for_webgl_version: Some(WebGLVersion::WebGL1) },
+ Extension { name: "EXT_texture_compression_rgtc", required_angle_extensions: &["GL_EXT_texture_compression_rgtc"], kind: Kind::NotImplemented, only_for_webgl_version: None },
+ Extension { name: "EXT_render_snorm", required_angle_extensions: &["GL_EXT_render_snorm"], kind: Kind::Interface(ExtensionInterface::EXTRenderSnorm), only_for_webgl_version: Some(WebGLVersion::WebGL2) },
+ Extension { name: "WEBGL_blend_func_extended", required_angle_extensions: &["GL_EXT_blend_func_extended"], kind: Kind::NotImplemented, only_for_webgl_version: None },
+ Extension { name: "EXT_polygon_offset_clamp", required_angle_extensions: &["GL_EXT_polygon_offset_clamp"], kind: Kind::NotImplemented, only_for_webgl_version: None },
+ Extension { name: "EXT_texture_compression_bptc", required_angle_extensions: &["GL_EXT_texture_compression_bptc"], kind: Kind::NotImplemented, only_for_webgl_version: None },
+ Extension { name: "WEBGL_polygon_mode", required_angle_extensions: &["GL_ANGLE_polygon_mode"], kind: Kind::NotImplemented, only_for_webgl_version: None },
+ Extension { name: "EXT_depth_clamp", required_angle_extensions: &["GL_EXT_depth_clamp"], kind: Kind::NotImplemented, only_for_webgl_version: None },
+ Extension { name: "WEBGL_compressed_texture_etc", required_angle_extensions: &["GL_ANGLE_compressed_texture_etc"], kind: Kind::NotImplemented, only_for_webgl_version: None },
+ Extension { name: "WEBGL_provoking_vertex", required_angle_extensions: &["GL_ANGLE_provoking_vertex"], kind: Kind::NotImplemented, only_for_webgl_version: Some(WebGLVersion::WebGL2) },
+ Extension { name: "WEBGL_draw_buffers", required_angle_extensions: &["GL_EXT_draw_buffers"], kind: Kind::Interface(ExtensionInterface::WebGLDrawBuffers), only_for_webgl_version: Some(WebGLVersion::WebGL1) },
+ Extension { name: "OVR_multiview2", required_angle_extensions: &["GL_OVR_multiview2"], kind: Kind::NotImplemented, only_for_webgl_version: Some(WebGLVersion::WebGL2) },
+ Extension { name: "WEBGL_compressed_texture_etc1", required_angle_extensions: &["GL_OES_compressed_ETC1_RGB8_texture"], kind: Kind::NotImplemented, only_for_webgl_version: None },
+ Extension { name: "WEBGL_compressed_texture_s3tc", required_angle_extensions: &["GL_EXT_texture_compression_dxt1", "GL_ANGLE_texture_compression_dxt3", "GL_ANGLE_texture_compression_dxt5"], kind: Kind::Interface(ExtensionInterface::WebGLCompressedTextureS3tc), only_for_webgl_version: None },
+ Extension { name: "WEBGL_multi_draw", required_angle_extensions: &["GL_ANGLE_multi_draw"], kind: Kind::NotImplemented, only_for_webgl_version: None },
+ Extension { name: "EXT_conservative_depth", required_angle_extensions: &["GL_EXT_conservative_depth"], kind: Kind::NotImplemented, only_for_webgl_version: Some(WebGLVersion::WebGL2) },
+ Extension { name: "WEBGL_stencil_texturing", required_angle_extensions: &["GL_ANGLE_stencil_texturing"], kind: Kind::NotImplemented, only_for_webgl_version: Some(WebGLVersion::WebGL2) },
+ Extension { name: "OES_draw_buffers_indexed", required_angle_extensions: &["GL_OES_draw_buffers_indexed"], kind: Kind::NotImplemented, only_for_webgl_version: None },
+];
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct EnabledExtension {
+ #[gc(untraced)]
+ name: &'static str,
+ object: ExtensionObject,
+}
+
+pub(crate) struct EnabledEmptyExtension {
+ name: &'static str,
+ objects: Vec<(WrapperWorld, GcWeak<Object>)>,
+}
+
+fn is_supported(context: &ContextState, extension: &Extension) -> bool {
+ if extension
+ .only_for_webgl_version
+ .is_some_and(|version| version != context.version())
+ {
+ return false;
+ }
+ if extension.kind == Kind::NotImplemented && !expose_experimental_interfaces() {
+ return false;
+ }
+ let opengl_extensions = context.supported_opengl_extensions.borrow();
+ extension.required_angle_extensions.iter().all(|required| {
+ opengl_extensions
+ .iter()
+ .any(|supported| supported == required.as_bytes())
+ })
+}
+
+impl ContextState {
+ pub(crate) fn supported_extensions(&self) -> Vec<Utf16String> {
+ AVAILABLE_WEBGL_EXTENSIONS
+ .iter()
+ .filter(|extension| is_supported(self, extension))
+ .map(|extension| Utf16String::from_ascii(extension.name.as_bytes()))
+ .collect()
+ }
+
+ /// https://registry.khronos.org/webgl/specs/latest/1.0/#5.14.14
+ pub(crate) fn extension(&self, cx: &CallContext, name: &Utf16String) -> Option<Gc<Object>> {
+ // Returns an object if, and only if, name is an ASCII case-insensitive match [HTML] for one of the names
+ // returned from getSupportedExtensions; otherwise, returns null. The object returned from getExtension
+ // contains any constants or functions provided by the extension. A returned object may have no constants or
+ // functions if the extension does not define any, but a unique object must still be returned. That object is
+ // used to indicate that the extension has been enabled.
+ let name = ascii_bytes(name)?;
+ let extension = AVAILABLE_WEBGL_EXTENSIONS
+ .iter()
+ .find(|extension| extension.name.as_bytes().eq_ignore_ascii_case(&name) && is_supported(self, extension))?;
+
+ // "Multiple calls to getExtension with the same extension string, taking into account case-insensitive
+ // comparison, must return the same object as long as the extension is enabled."
+ let enabled_object = self
+ .enabled_extensions
+ .borrow()
+ .iter()
+ .find(|enabled| enabled.name == extension.name)
+ .map(|enabled| enabled.object);
+ if let Some(object) = enabled_object {
+ return Some(object.wrap(cx));
+ }
+ let wrapper_world = wrapper_world_of(cx.vm(), cx.realm());
+ let enabled_empty_object = self
+ .enabled_empty_extensions
+ .borrow()
+ .iter()
+ .find(|enabled| enabled.name == extension.name)
+ .and_then(|enabled| enabled.objects.iter().find(|(world, _)| *world == wrapper_world))
+ .and_then(|(_, object)| object.get());
+ if let Some(object) = enabled_empty_object {
+ return Some(object);
+ }
+
+ if extension.kind == Kind::NotImplemented {
+ return None;
+ }
+ for required_extension in extension.required_angle_extensions {
+ self.proxy.request_extension_angle(required_extension.as_bytes());
+ }
+
+ match extension.kind {
+ Kind::Interface(interface) => {
+ let object = interface.create(cx.vm(), self);
+ self.enabled_extensions.borrow_mut().push(EnabledExtension {
+ name: extension.name,
+ object,
+ });
+ Some(object.wrap(cx))
+ }
+ Kind::EmptyObject => {
+ let object = create_dictionary_object(cx);
+ let weak_object = GcWeak::new(cx.vm().heap(), object);
+ let mut enabled_empty_extensions = self.enabled_empty_extensions.borrow_mut();
+ let index = match enabled_empty_extensions
+ .iter()
+ .position(|enabled| enabled.name == extension.name)
+ {
+ Some(index) => index,
+ None => {
+ enabled_empty_extensions.push(EnabledEmptyExtension {
+ name: extension.name,
+ objects: Vec::new(),
+ });
+ enabled_empty_extensions.len() - 1
+ }
+ };
+ let objects = &mut enabled_empty_extensions[index].objects;
+ objects.retain(|(world, _)| *world != wrapper_world);
+ objects.push((wrapper_world, weak_object));
+ Some(object)
+ }
+ Kind::NotImplemented => unreachable!("returned above"),
+ }
+ }
+
+ // FIXME: Make this and any other instance of extension names an interned string, as the names of HTML tags are.
+ pub(crate) fn extension_enabled(&self, name: &str) -> bool {
+ let is_enabled = self
+ .enabled_extensions
+ .borrow()
+ .iter()
+ .any(|enabled| enabled.name.eq_ignore_ascii_case(name));
+ is_enabled
+ || self
+ .enabled_empty_extensions
+ .borrow()
+ .iter()
+ .any(|enabled| enabled.name.eq_ignore_ascii_case(name))
+ }
+
+ pub(crate) fn enable_compressed_texture_format(&self, format: u32) {
+ self.enabled_compressed_texture_formats.borrow_mut().push(format);
+ }
+}
+
+/// An entry is `module::Interface`, or `module::Interface { compressed_texture_formats_enabled_when_created: [..] }`
+/// with the formats in the order that getParameter(COMPRESSED_TEXTURE_FORMATS) reports them in.
+macro_rules! modules_of_extension_interfaces_without_operations {
+ ($(
+ $(#[$specification_link:meta])*
+ $module:ident :: $interface:ident
+ $({ compressed_texture_formats_enabled_when_created: [$($format:ident),+ $(,)?] $(,)? })?
+ ),+ $(,)?) => {$(
+ $(#[$specification_link])*
+ pub(crate) mod $module {
+ use libjs_rust::api::{Gc, Realm, Trace, Vm};
+
+ use $crate::bindings::interface::{Ref, Wrappable, allocate};
+ use $crate::web_gl::state::{ContextRef, ContextState};
+
+ #[derive(Trace)]
+ #[gc(crate = libjs_rust)]
+ pub(crate) struct $interface {
+ context: ContextRef,
+ }
+
+ impl Wrappable for $interface {
+ fn relevant_realm(&self, _vm: &Vm) -> Option<Gc<Realm>> {
+ self.context.state().canvas().relevant_realm()
+ }
+ }
+
+ impl $interface {
+ pub(crate) fn create(vm: &Vm, context: &ContextState) -> Ref<Self> {
+ $($(context.enable_compressed_texture_format($crate::web_gl::constants::$format);)+)?
+ allocate(
+ vm,
+ Self {
+ context: context.context_ref(),
+ },
+ )
+ }
+ }
+ }
+ )+};
+}
+pub(crate) use modules_of_extension_interfaces_without_operations;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/fingerprint.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/fingerprint.rs
index 34c63d8c1c1..2a0dcfe4ebc 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/fingerprint.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/fingerprint.rs
@@ -4,16 +4,18 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! The check that the recorder and the replayer mean the same bytes. Both get their structs from GLFunctions.json,
-//! but through two generators, and what is not generated, such as the framing, is a constant on each side. A
-//! difference would not fail a build, and would make the replayer read garbage, so the two sides are compared before
-//! the first context records.
+//! The check that Rust and C++ agree on what each of them states for itself. The recorder and the replayer get their
+//! structs from GLFunctions.json, but through two generators, and the framing of the command stream, the capacity of
+//! its shared data region and the largest drawing buffer are constants on each side. A difference would not fail a
+//! build, and would make the replayer read garbage or the context report a drawing buffer that the compositor does not
+//! allocate, so the two sides are compared before the first context records.
use std::sync::Once;
use super::proxy::recorder::{DEFAULT_SHARED_DATA_REGION_CAPACITY, SHARED_DATA_REGION_OFFSET};
use super::proxy::vocabulary::WIRE_STRUCT_LAYOUTS;
use super::proxy::wire::{HEADER_PAYLOAD_SIZE_OFFSET, HEADER_SIZE, RECORD_ALIGNMENT};
+use super::state::MAX_WEBGL_DRAWING_BUFFER_DIMENSION;
/// RemoteWebGLTransportFFI.cpp has a struct of the same name, and reports the constants of the C++ side as one.
#[derive(Debug, Default, PartialEq, Eq)]
@@ -24,6 +26,7 @@ struct ConstantsRestatedInRust {
header_payload_size_offset: usize,
shared_data_region_offset: usize,
shared_data_region_capacity: usize,
+ max_drawing_buffer_dimension: usize,
}
unsafe extern "C" {
@@ -31,7 +34,7 @@ unsafe extern "C" {
fn web_webgl_constants_restated_in_rust(out_constants: *mut ConstantsRestatedInRust);
}
-pub(crate) fn verify_that_the_replayer_reads_what_the_recorder_writes() {
+pub(crate) fn verify_that_rust_and_cpp_agree_on_layouts_and_constants() {
static VERIFIED: Once = Once::new();
VERIFIED.call_once(|| {
let mut constants_of_the_cpp_side = ConstantsRestatedInRust::default();
@@ -43,6 +46,8 @@ pub(crate) fn verify_that_the_replayer_reads_what_the_recorder_writes() {
header_payload_size_offset: HEADER_PAYLOAD_SIZE_OFFSET,
shared_data_region_offset: SHARED_DATA_REGION_OFFSET,
shared_data_region_capacity: DEFAULT_SHARED_DATA_REGION_CAPACITY,
+ max_drawing_buffer_dimension: usize::try_from(MAX_WEBGL_DRAWING_BUFFER_DIMENSION)
+ .expect("the largest dimension of a drawing buffer is positive"),
};
assert!(
constants_of_the_cpp_side == constants_of_the_rust_side,
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/gl_string.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/gl_string.rs
new file mode 100644
index 00000000000..4c07d8e570e
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/gl_string.rs
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use ak::{Utf16String, Utf16StringUnits, append_utf16_as_utf8_up_to_unpaired_surrogate};
+
+/// UTF-8, except that a surrogate that is not half of a pair is encoded as if it were a code point.
+pub(crate) fn utf8_bytes(string: &Utf16String) -> Vec<u8> {
+ let mut code_units = match string.as_units() {
+ Utf16StringUnits::Ascii(bytes) => return bytes.to_vec(),
+ Utf16StringUnits::Utf16(code_units) => code_units,
+ };
+ let mut bytes = Vec::with_capacity(code_units.len());
+ while !code_units.is_empty() {
+ let encoded_code_units = append_utf16_as_utf8_up_to_unpaired_surrogate(&mut bytes, code_units);
+ code_units = &code_units[encoded_code_units..];
+ if let [surrogate, rest @ ..] = code_units {
+ let surrogate = u32::from(*surrogate);
+ bytes.extend_from_slice(&[
+ 0xE0 | (surrogate >> 12) as u8,
+ 0x80 | ((surrogate >> 6) & 0x3F) as u8,
+ 0x80 | (surrogate & 0x3F) as u8,
+ ]);
+ code_units = rest;
+ }
+ }
+ bytes
+}
+
+pub(crate) fn ascii_bytes(string: &Utf16String) -> Option<Vec<u8>> {
+ match string.as_units() {
+ Utf16StringUnits::Ascii(bytes) => Some(bytes.to_vec()),
+ Utf16StringUnits::Utf16(code_units) => code_units
+ .iter()
+ .map(|&code_unit| u8::try_from(code_unit).ok().filter(u8::is_ascii))
+ .collect(),
+ }
+}
+
+/// Lossy, as a driver can return bytes that are not UTF-8.
+pub(crate) fn utf16_string_from_gl_string(bytes: &[u8]) -> Utf16String {
+ if bytes.is_ascii() {
+ return Utf16String::from_ascii(bytes);
+ }
+ Utf16String::from_utf8(&String::from_utf8_lossy(bytes))
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/mod.rs
index 4edaff4c0d6..052f65f6e77 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/mod.rs
@@ -7,9 +7,141 @@
//! The WebContent half of WebGL, which validates what script asks for, keeps track of the state that it can read
//! back, and records everything else as commands for the Compositor, which runs GL.
+pub(crate) mod buffer_kind;
+pub(crate) mod byte_ranges;
pub(crate) mod constants;
+pub(crate) mod proxy;
+
+// What follows runs on the JS runtime, which the tests of the crate do not link.
+#[cfg(not(test))]
+pub(crate) mod angle_instanced_arrays;
+#[cfg(not(test))]
+pub(crate) mod buffer_source;
+#[cfg(not(test))]
+pub(crate) mod canvas;
+#[cfg(not(test))]
+pub(crate) mod exports;
+#[cfg(not(test))]
+pub(crate) mod extensions;
#[cfg(not(test))]
pub(crate) mod fingerprint;
#[cfg(not(test))]
+pub(crate) mod gl_string;
+#[cfg(not(test))]
pub(crate) mod host;
-pub(crate) mod proxy;
+#[cfg(not(test))]
+pub(crate) mod oes_vertex_array_object;
+#[cfg(not(test))]
+pub(crate) mod parameters;
+#[cfg(not(test))]
+pub(crate) mod state;
+#[cfg(not(test))]
+pub(crate) mod types;
+#[cfg(not(test))]
+pub(crate) mod values;
+#[cfg(not(test))]
+pub(crate) mod web_gl2_rendering_context;
+#[cfg(not(test))]
+pub(crate) mod web_gl2_rendering_context_base;
+#[cfg(not(test))]
+pub(crate) mod web_gl2_rendering_context_overloads;
+#[cfg(not(test))]
+pub(crate) mod web_gl_active_info;
+#[cfg(not(test))]
+pub(crate) mod web_gl_buffer;
+#[cfg(not(test))]
+pub(crate) mod web_gl_draw_buffers;
+#[cfg(not(test))]
+pub(crate) mod web_gl_framebuffer;
+#[cfg(not(test))]
+pub(crate) mod web_gl_object;
+#[cfg(not(test))]
+pub(crate) mod web_gl_program;
+#[cfg(not(test))]
+pub(crate) mod web_gl_rendering_context;
+#[cfg(not(test))]
+pub(crate) mod web_gl_rendering_context_base;
+#[cfg(not(test))]
+pub(crate) mod web_gl_rendering_context_overloads;
+#[cfg(not(test))]
+pub(crate) mod web_gl_shader;
+#[cfg(not(test))]
+pub(crate) mod web_gl_shader_precision_format;
+#[cfg(not(test))]
+pub(crate) mod web_gl_sync;
+#[cfg(not(test))]
+pub(crate) mod web_gl_uniform_location;
+
+// The interfaces of the two lists below differ only in their entries, so they have no file: an entry expands to the
+// module that the generated bindings look up for its interface.
+
+// An entry expands to
+//
+// pub(crate) mod ext_blend_min_max {
+// pub(crate) struct EXTBlendMinMax { context: ContextRef }
+// impl Wrappable for EXTBlendMinMax { .. }
+// impl EXTBlendMinMax { pub(crate) fn create(vm: &Vm, context: &ContextState) -> Ref<Self> { .. } }
+// }
+#[cfg(not(test))]
+extensions::modules_of_extension_interfaces_without_operations! {
+ /// https://registry.khronos.org/webgl/extensions/EXT_blend_minmax/
+ ext_blend_min_max::EXTBlendMinMax,
+ /// https://registry.khronos.org/webgl/extensions/EXT_color_buffer_float/
+ ext_color_buffer_float::EXTColorBufferFloat,
+ /// https://registry.khronos.org/webgl/extensions/EXT_render_snorm/
+ ext_render_snorm::EXTRenderSnorm,
+ /// https://registry.khronos.org/webgl/extensions/EXT_texture_filter_anisotropic/
+ ext_texture_filter_anisotropic::EXTTextureFilterAnisotropic,
+ /// https://registry.khronos.org/webgl/extensions/EXT_texture_norm16/
+ ext_texture_norm16::EXTTextureNorm16,
+ /// https://registry.khronos.org/webgl/extensions/OES_element_index_uint/
+ oes_element_index_uint::OESElementIndexUint,
+ /// https://registry.khronos.org/webgl/extensions/OES_standard_derivatives/
+ oes_standard_derivatives::OESStandardDerivatives,
+ /// https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc/
+ web_gl_compressed_texture_s3tc::WebGLCompressedTextureS3tc {
+ compressed_texture_formats_enabled_when_created: [
+ GL_COMPRESSED_RGB_S3TC_DXT1_EXT,
+ GL_COMPRESSED_RGBA_S3TC_DXT1_EXT,
+ GL_COMPRESSED_RGBA_S3TC_DXT3_EXT,
+ GL_COMPRESSED_RGBA_S3TC_DXT5_EXT,
+ ],
+ },
+ /// https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
+ web_gl_compressed_texture_s3tc_srgb::WebGLCompressedTextureS3tcSrgb {
+ compressed_texture_formats_enabled_when_created: [
+ GL_COMPRESSED_SRGB_S3TC_DXT1_EXT,
+ GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,
+ GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT,
+ GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT,
+ ],
+ },
+ /// https://registry.khronos.org/webgl/extensions/WEBGL_debug_renderer_info/
+ web_gl_debug_renderer_info::WebGLDebugRendererInfo,
+}
+
+// An entry expands to
+//
+// pub(crate) mod web_gl_query {
+// pub(crate) struct WebGLQuery { object: WebGLObject }
+// impl Wrappable for WebGLQuery { .. }
+// impl Inherits<WebGLObject> for WebGLQuery { .. }
+// impl WebGLQuery { pub(crate) fn create(vm: &Vm, context: &ContextState, handle: u32) -> Ref<Self> { .. } }
+// }
+#[cfg(not(test))]
+web_gl_object::modules_of_interfaces_that_only_inherit_from_web_gl_object! {
+ /// https://registry.khronos.org/webgl/specs/latest/2.0/#3.2
+ web_gl_query::WebGLQuery,
+ /// https://registry.khronos.org/webgl/specs/latest/1.0/#5.7
+ web_gl_renderbuffer::WebGLRenderbuffer,
+ /// https://registry.khronos.org/webgl/specs/latest/2.0/#3.3
+ web_gl_sampler::WebGLSampler,
+ /// https://registry.khronos.org/webgl/specs/latest/1.0/#5.9
+ web_gl_texture::WebGLTexture,
+ /// https://registry.khronos.org/webgl/specs/latest/2.0/#3.5
+ web_gl_transform_feedback::WebGLTransformFeedback,
+ /// https://registry.khronos.org/webgl/specs/latest/2.0/#3.6
+ web_gl_vertex_array_object::WebGLVertexArrayObject,
+ /// https://registry.khronos.org/webgl/extensions/OES_vertex_array_object/
+ web_gl_vertex_array_object_oes::WebGLVertexArrayObjectOES,
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/oes_vertex_array_object.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/oes_vertex_array_object.rs
new file mode 100644
index 00000000000..ea4b7c8b9fb
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/oes_vertex_array_object.rs
@@ -0,0 +1,109 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://registry.khronos.org/webgl/extensions/OES_vertex_array_object/
+
+use libjs_rust::api::{Gc, Realm, Trace, Vm};
+
+use super::state::VertexArrayBinding;
+use super::state::{ContextRef, ContextState};
+use super::web_gl_vertex_array_object_oes::WebGLVertexArrayObjectOES;
+use crate::bindings::interface::Inherits;
+use crate::bindings::interface::{Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, WebIdlResult};
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct OESVertexArrayObject {
+ context: ContextRef,
+}
+
+impl Wrappable for OESVertexArrayObject {
+ fn relevant_realm(&self, _vm: &Vm) -> Option<Gc<Realm>> {
+ self.context.state().canvas().relevant_realm()
+ }
+}
+
+impl OESVertexArrayObject {
+ pub(crate) fn create(vm: &Vm, context: &ContextState) -> Ref<Self> {
+ allocate(
+ vm,
+ Self {
+ context: context.context_ref(),
+ },
+ )
+ }
+
+ fn is_bound(&self, array_object: Ref<WebGLVertexArrayObjectOES>) -> bool {
+ matches!(
+ self.context.state().current_vertex_array.get(),
+ Some(VertexArrayBinding::Oes(bound)) if bound.as_ptr() == array_object.as_ptr()
+ )
+ }
+
+ pub(crate) fn create_vertex_array_oes(&self, cx: &mut CallContext) -> WebIdlResult<Ref<WebGLVertexArrayObjectOES>> {
+ let context = self.context.state();
+ let mut handle = [0];
+ context.proxy.gen_vertex_arrays_oes(&mut handle);
+ Ok(WebGLVertexArrayObjectOES::create(cx.vm(), context, handle[0]))
+ }
+
+ pub(crate) fn delete_vertex_array_oes(
+ &self,
+ _: &mut CallContext,
+ array_object: Option<Ref<WebGLVertexArrayObjectOES>>,
+ ) -> WebIdlResult<()> {
+ let context = self.context.state();
+ let Some(array_object) = array_object else {
+ return Ok(());
+ };
+ // FIXME: An object of another context is an INVALID_OPERATION error.
+ let Ok(Some(handle)) = array_object.parent().handle_for_deletion(context) else {
+ return Ok(());
+ };
+ context.proxy.delete_vertex_arrays_oes(1, &[handle]);
+ if self.is_bound(array_object) {
+ context.current_vertex_array.set(None);
+ }
+ Ok(())
+ }
+
+ pub(crate) fn is_vertex_array_oes(
+ &self,
+ _: &mut CallContext,
+ array_object: Option<Ref<WebGLVertexArrayObjectOES>>,
+ ) -> WebIdlResult<bool> {
+ let context = self.context.state();
+ let Some(array_object) = array_object else {
+ return Ok(false);
+ };
+ let Ok(Some(handle)) = array_object.parent().handle_for_query(context) else {
+ return Ok(false);
+ };
+ Ok(context.proxy.is_vertex_array_oes(handle))
+ }
+
+ pub(crate) fn bind_vertex_array_oes(
+ &self,
+ _: &mut CallContext,
+ array_object: Option<Ref<WebGLVertexArrayObjectOES>>,
+ ) -> WebIdlResult<()> {
+ let context = self.context.state();
+ let mut handle = 0;
+ if let Some(array_object) = array_object {
+ // FIXME: An object that the context cannot use is an INVALID_OPERATION error.
+ let Ok(array_object_handle) = array_object.parent().handle(context) else {
+ return Ok(());
+ };
+ handle = array_object_handle;
+ }
+ context.proxy.bind_vertex_array_oes(handle);
+ context
+ .current_vertex_array
+ .set(array_object.map(VertexArrayBinding::Oes));
+ Ok(())
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/parameters.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/parameters.rs
new file mode 100644
index 00000000000..56e49dbe550
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/parameters.rs
@@ -0,0 +1,634 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use libjs_rust::api::Value;
+
+use super::byte_ranges::gl_sizei_of_array_length;
+use super::constants::{
+ GL_ACTIVE_ATTRIBUTES, GL_ACTIVE_TEXTURE, GL_ACTIVE_UNIFORM_BLOCKS, GL_ACTIVE_UNIFORMS, GL_ALIASED_LINE_WIDTH_RANGE,
+ GL_ALIASED_POINT_SIZE_RANGE, GL_ALPHA_BITS, GL_ARRAY_BUFFER_BINDING, GL_ATTACHED_SHADERS, GL_BLEND, GL_BLEND_COLOR,
+ GL_BLEND_DST_ALPHA, GL_BLEND_DST_RGB, GL_BLEND_EQUATION_ALPHA, GL_BLEND_EQUATION_RGB, GL_BLEND_SRC_ALPHA,
+ GL_BLEND_SRC_RGB, GL_BLUE_BITS, GL_BUFFER_SIZE, GL_BUFFER_USAGE, GL_COLOR_CLEAR_VALUE, GL_COLOR_WRITEMASK,
+ GL_COMPILE_STATUS, GL_COMPRESSED_TEXTURE_FORMATS, GL_COPY_READ_BUFFER_BINDING, GL_COPY_WRITE_BUFFER_BINDING,
+ GL_CULL_FACE, GL_CULL_FACE_MODE, GL_CURRENT_PROGRAM, GL_CURRENT_VERTEX_ATTRIB, GL_DELETE_STATUS, GL_DEPTH_BITS,
+ GL_DEPTH_CLEAR_VALUE, GL_DEPTH_FUNC, GL_DEPTH_RANGE, GL_DEPTH_TEST, GL_DEPTH_WRITEMASK, GL_DITHER,
+ GL_ELEMENT_ARRAY_BUFFER_BINDING, GL_FRAGMENT_SHADER_DERIVATIVE_HINT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,
+ GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE,
+ GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL, GL_FRAMEBUFFER_BINDING, GL_FRONT_FACE, GL_GENERATE_MIPMAP_HINT,
+ GL_GREEN_BITS, GL_IMPLEMENTATION_COLOR_READ_FORMAT, GL_IMPLEMENTATION_COLOR_READ_TYPE, GL_INVALID_ENUM,
+ GL_INVALID_OPERATION, GL_LINE_WIDTH, GL_LINK_STATUS, GL_MAX_3D_TEXTURE_SIZE, GL_MAX_ARRAY_TEXTURE_LAYERS,
+ GL_MAX_CLIENT_WAIT_TIMEOUT_WEBGL, GL_MAX_COLOR_ATTACHMENTS, GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS,
+ GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, GL_MAX_COMBINED_UNIFORM_BLOCKS, GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS,
+ GL_MAX_CUBE_MAP_TEXTURE_SIZE, GL_MAX_DRAW_BUFFERS, GL_MAX_ELEMENT_INDEX, GL_MAX_ELEMENTS_INDICES,
+ GL_MAX_ELEMENTS_VERTICES, GL_MAX_FRAGMENT_INPUT_COMPONENTS, GL_MAX_FRAGMENT_UNIFORM_BLOCKS,
+ GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, GL_MAX_FRAGMENT_UNIFORM_VECTORS, GL_MAX_PROGRAM_TEXEL_OFFSET,
+ GL_MAX_RENDERBUFFER_SIZE, GL_MAX_SAMPLES, GL_MAX_SERVER_WAIT_TIMEOUT, GL_MAX_TEXTURE_IMAGE_UNITS,
+ GL_MAX_TEXTURE_LOD_BIAS, GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, GL_MAX_TEXTURE_SIZE,
+ GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS, GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS,
+ GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS, GL_MAX_UNIFORM_BLOCK_SIZE, GL_MAX_UNIFORM_BUFFER_BINDINGS,
+ GL_MAX_VARYING_COMPONENTS, GL_MAX_VARYING_VECTORS, GL_MAX_VERTEX_ATTRIBS, GL_MAX_VERTEX_OUTPUT_COMPONENTS,
+ GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, GL_MAX_VERTEX_UNIFORM_BLOCKS, GL_MAX_VERTEX_UNIFORM_COMPONENTS,
+ GL_MAX_VERTEX_UNIFORM_VECTORS, GL_MAX_VIEWPORT_DIMS, GL_MIN_PROGRAM_TEXEL_OFFSET, GL_NONE, GL_PACK_ALIGNMENT,
+ GL_PACK_ROW_LENGTH, GL_PACK_SKIP_PIXELS, GL_PACK_SKIP_ROWS, GL_PIXEL_PACK_BUFFER_BINDING,
+ GL_PIXEL_UNPACK_BUFFER_BINDING, GL_POLYGON_OFFSET_FACTOR, GL_POLYGON_OFFSET_FILL, GL_POLYGON_OFFSET_UNITS,
+ GL_RASTERIZER_DISCARD, GL_RED_BITS, GL_RENDERBUFFER, GL_RENDERBUFFER_ALPHA_SIZE, GL_RENDERBUFFER_BINDING,
+ GL_RENDERBUFFER_BLUE_SIZE, GL_RENDERBUFFER_DEPTH_SIZE, GL_RENDERBUFFER_GREEN_SIZE, GL_RENDERBUFFER_HEIGHT,
+ GL_RENDERBUFFER_INTERNAL_FORMAT, GL_RENDERBUFFER_RED_SIZE, GL_RENDERBUFFER_SAMPLES, GL_RENDERBUFFER_STENCIL_SIZE,
+ GL_RENDERBUFFER_WIDTH, GL_RENDERER, GL_SAMPLE_ALPHA_TO_COVERAGE, GL_SAMPLE_BUFFERS, GL_SAMPLE_COVERAGE,
+ GL_SAMPLE_COVERAGE_INVERT, GL_SAMPLE_COVERAGE_VALUE, GL_SAMPLER_BINDING, GL_SAMPLES, GL_SCISSOR_BOX,
+ GL_SCISSOR_TEST, GL_SHADER_TYPE, GL_SHADING_LANGUAGE_VERSION, GL_STENCIL_BACK_FAIL, GL_STENCIL_BACK_FUNC,
+ GL_STENCIL_BACK_PASS_DEPTH_FAIL, GL_STENCIL_BACK_PASS_DEPTH_PASS, GL_STENCIL_BACK_REF, GL_STENCIL_BACK_VALUE_MASK,
+ GL_STENCIL_BACK_WRITEMASK, GL_STENCIL_BITS, GL_STENCIL_CLEAR_VALUE, GL_STENCIL_FAIL, GL_STENCIL_FUNC,
+ GL_STENCIL_PASS_DEPTH_FAIL, GL_STENCIL_PASS_DEPTH_PASS, GL_STENCIL_REF, GL_STENCIL_TEST, GL_STENCIL_VALUE_MASK,
+ GL_STENCIL_WRITEMASK, GL_SUBPIXEL_BITS, GL_TEXTURE, GL_TEXTURE_BASE_LEVEL, GL_TEXTURE_BINDING_2D,
+ GL_TEXTURE_BINDING_2D_ARRAY, GL_TEXTURE_BINDING_CUBE_MAP, GL_TEXTURE_COMPARE_FUNC, GL_TEXTURE_COMPARE_MODE,
+ GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, GL_TEXTURE_CUBE_MAP_POSITIVE_X, GL_TEXTURE_IMMUTABLE_FORMAT,
+ GL_TEXTURE_IMMUTABLE_LEVELS, GL_TEXTURE_MAG_FILTER, GL_TEXTURE_MAX_ANISOTROPY_EXT, GL_TEXTURE_MAX_LEVEL,
+ GL_TEXTURE_MAX_LOD, GL_TEXTURE_MIN_FILTER, GL_TEXTURE_MIN_LOD, GL_TEXTURE_WRAP_R, GL_TEXTURE_WRAP_S,
+ GL_TEXTURE_WRAP_T, GL_TRANSFORM_FEEDBACK_ACTIVE, GL_TRANSFORM_FEEDBACK_BINDING,
+ GL_TRANSFORM_FEEDBACK_BUFFER_BINDING, GL_TRANSFORM_FEEDBACK_BUFFER_MODE, GL_TRANSFORM_FEEDBACK_PAUSED,
+ GL_TRANSFORM_FEEDBACK_VARYINGS, GL_TRUE, GL_UNIFORM_BUFFER_BINDING, GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT,
+ GL_UNMASKED_RENDERER_WEBGL, GL_UNMASKED_VENDOR_WEBGL, GL_UNPACK_ALIGNMENT, GL_UNPACK_COLORSPACE_CONVERSION_WEBGL,
+ GL_UNPACK_FLIP_Y_WEBGL, GL_UNPACK_IMAGE_HEIGHT, GL_UNPACK_PREMULTIPLY_ALPHA_WEBGL, GL_UNPACK_ROW_LENGTH,
+ GL_UNPACK_SKIP_IMAGES, GL_UNPACK_SKIP_PIXELS, GL_UNPACK_SKIP_ROWS, GL_VALIDATE_STATUS, GL_VENDOR, GL_VERSION,
+ GL_VERTEX_ARRAY_BINDING, GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING, GL_VERTEX_ATTRIB_ARRAY_DIVISOR,
+ GL_VERTEX_ATTRIB_ARRAY_ENABLED, GL_VERTEX_ATTRIB_ARRAY_INTEGER, GL_VERTEX_ATTRIB_ARRAY_NORMALIZED,
+ GL_VERTEX_ATTRIB_ARRAY_SIZE, GL_VERTEX_ATTRIB_ARRAY_STRIDE, GL_VERTEX_ATTRIB_ARRAY_TYPE, GL_VIEWPORT,
+};
+use super::gl_string::utf16_string_from_gl_string;
+use super::state::{ContextState, RenderingContext, Version, VertexArrayBinding};
+use super::values::{object_or_null, string_value};
+use super::web_gl_buffer::WebGLBuffer;
+use super::web_gl_program::WebGLProgram;
+use super::web_gl_rendering_context_base::{is_valid_framebuffer_attachment, is_valid_framebuffer_binding_target};
+use super::web_gl_sampler::WebGLSampler;
+use super::web_gl_shader::WebGLShader;
+use super::web_gl_uniform_location::WebGLUniformLocation;
+use crate::bindings::interface::{Ref, wrap};
+use crate::bindings::{CallContext, WebIdlResult};
+
+fn is_cube_map_face(target: u32) -> bool {
+ (GL_TEXTURE_CUBE_MAP_POSITIVE_X..=GL_TEXTURE_CUBE_MAP_NEGATIVE_Z).contains(&target)
+}
+
+fn is_gl_true(integer_that_gl_returned_for_a_boolean: i32) -> bool {
+ u32::try_from(integer_that_gl_returned_for_a_boolean) == Ok(GL_TRUE)
+}
+
+fn number_value(unsigned_integer_or_float: impl Into<f64>) -> Value {
+ Value::from_f64(unsigned_integer_or_float.into())
+}
+
+fn null_with_invalid_enum_error(context: &ContextState) -> Value {
+ context.set_error(GL_INVALID_ENUM);
+ Value::NULL
+}
+
+fn integer_parameter(context: &ContextState, pname: u32) -> i32 {
+ let mut result = [0];
+ context.proxy.get_integerv_robust_angle(pname, 1, &mut result);
+ result[0]
+}
+
+fn integer64_parameter(context: &ContextState, pname: u32) -> i64 {
+ let mut result = [0];
+ context.proxy.get_integer64v_robust_angle(pname, 1, &mut result);
+ result[0]
+}
+
+fn float_parameter(context: &ContextState, pname: u32) -> f32 {
+ let mut result = [0.0];
+ context.proxy.get_floatv_robust_angle(pname, 1, &mut result);
+ result[0]
+}
+
+fn boolean_parameter(context: &ContextState, pname: u32) -> bool {
+ let mut result = [0];
+ context.proxy.get_booleanv_robust_angle(pname, 1, &mut result);
+ u32::from(result[0]) == GL_TRUE
+}
+
+fn int32_array_parameter<const LENGTH: usize>(context: &ContextState, cx: &CallContext, pname: u32) -> Value {
+ let mut result = [0; LENGTH];
+ context
+ .proxy
+ .get_integerv_robust_angle(pname, const { gl_sizei_of_array_length(LENGTH) }, &mut result);
+ context.int32_array(cx, &result)
+}
+
+fn float32_array_parameter<const LENGTH: usize>(context: &ContextState, cx: &CallContext, pname: u32) -> Value {
+ let mut result = [0.0; LENGTH];
+ context
+ .proxy
+ .get_floatv_robust_angle(pname, const { gl_sizei_of_array_length(LENGTH) }, &mut result);
+ context.float32_array(cx, &result)
+}
+
+fn string_parameter(context: &ContextState, cx: &CallContext, name: u32) -> Value {
+ string_value(cx, utf16_string_from_gl_string(&context.proxy.get_string(name)))
+}
+
+fn integer_tex_parameter(context: &ContextState, target: u32, pname: u32) -> i32 {
+ let mut result = [0];
+ context
+ .proxy
+ .get_tex_parameteriv_robust_angle(target, pname, 1, &mut result);
+ result[0]
+}
+
+fn integer_vertex_attrib(context: &ContextState, index: u32, pname: u32) -> i32 {
+ let mut result = [0];
+ context
+ .proxy
+ .get_vertex_attribiv_robust_angle(index, pname, 1, &mut result);
+ result[0]
+}
+
+fn parameter_of_either_version(context: &ContextState, cx: &CallContext, pname: u32) -> Option<Value> {
+ Some(match pname {
+ GL_ACTIVE_TEXTURE
+ | GL_ALPHA_BITS
+ | GL_BLEND_DST_ALPHA
+ | GL_BLEND_DST_RGB
+ | GL_BLEND_EQUATION_ALPHA
+ | GL_BLEND_EQUATION_RGB
+ | GL_BLEND_SRC_ALPHA
+ | GL_BLEND_SRC_RGB
+ | GL_BLUE_BITS
+ | GL_CULL_FACE_MODE
+ | GL_DEPTH_BITS
+ | GL_DEPTH_FUNC
+ | GL_FRONT_FACE
+ | GL_GENERATE_MIPMAP_HINT
+ | GL_GREEN_BITS
+ | GL_IMPLEMENTATION_COLOR_READ_FORMAT
+ | GL_IMPLEMENTATION_COLOR_READ_TYPE
+ | GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS
+ | GL_MAX_CUBE_MAP_TEXTURE_SIZE
+ | GL_MAX_FRAGMENT_UNIFORM_VECTORS
+ | GL_MAX_RENDERBUFFER_SIZE
+ | GL_MAX_TEXTURE_IMAGE_UNITS
+ | GL_MAX_TEXTURE_SIZE
+ | GL_MAX_VARYING_VECTORS
+ | GL_MAX_VERTEX_ATTRIBS
+ | GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS
+ | GL_MAX_VERTEX_UNIFORM_VECTORS
+ | GL_PACK_ALIGNMENT
+ | GL_RED_BITS
+ | GL_SAMPLE_BUFFERS
+ | GL_SAMPLES
+ | GL_STENCIL_BACK_FAIL
+ | GL_STENCIL_BACK_FUNC
+ | GL_STENCIL_BACK_PASS_DEPTH_FAIL
+ | GL_STENCIL_BACK_PASS_DEPTH_PASS
+ | GL_STENCIL_BACK_REF
+ | GL_STENCIL_BACK_VALUE_MASK
+ | GL_STENCIL_BACK_WRITEMASK
+ | GL_STENCIL_BITS
+ | GL_STENCIL_CLEAR_VALUE
+ | GL_STENCIL_FAIL
+ | GL_STENCIL_FUNC
+ | GL_STENCIL_PASS_DEPTH_FAIL
+ | GL_STENCIL_PASS_DEPTH_PASS
+ | GL_STENCIL_REF
+ | GL_STENCIL_VALUE_MASK
+ | GL_STENCIL_WRITEMASK
+ | GL_SUBPIXEL_BITS
+ | GL_UNPACK_ALIGNMENT => Value::from_i32(integer_parameter(context, pname)),
+
+ GL_DEPTH_CLEAR_VALUE
+ | GL_LINE_WIDTH
+ | GL_POLYGON_OFFSET_FACTOR
+ | GL_POLYGON_OFFSET_UNITS
+ | GL_SAMPLE_COVERAGE_VALUE => number_value(float_parameter(context, pname)),
+
+ GL_BLEND
+ | GL_CULL_FACE
+ | GL_DEPTH_TEST
+ | GL_DEPTH_WRITEMASK
+ | GL_DITHER
+ | GL_POLYGON_OFFSET_FILL
+ | GL_SAMPLE_ALPHA_TO_COVERAGE
+ | GL_SAMPLE_COVERAGE
+ | GL_SAMPLE_COVERAGE_INVERT
+ | GL_SCISSOR_TEST
+ | GL_STENCIL_TEST => Value::from_bool(boolean_parameter(context, pname)),
+
+ GL_ALIASED_LINE_WIDTH_RANGE | GL_ALIASED_POINT_SIZE_RANGE | GL_DEPTH_RANGE => {
+ float32_array_parameter::<2>(context, cx, pname)
+ }
+ GL_BLEND_COLOR | GL_COLOR_CLEAR_VALUE => float32_array_parameter::<4>(context, cx, pname),
+ GL_MAX_VIEWPORT_DIMS => int32_array_parameter::<2>(context, cx, pname),
+ GL_SCISSOR_BOX | GL_VIEWPORT => int32_array_parameter::<4>(context, cx, pname),
+ GL_COLOR_WRITEMASK => {
+ let mut result = [0; 4];
+ context
+ .proxy
+ .get_booleanv_robust_angle(GL_COLOR_WRITEMASK, 4, &mut result);
+ context.boolean_array(cx, &result.map(|is_written| is_written != 0))
+ }
+
+ GL_RENDERER | GL_SHADING_LANGUAGE_VERSION | GL_VENDOR | GL_VERSION => string_parameter(context, cx, pname),
+
+ GL_ARRAY_BUFFER_BINDING => object_or_null(cx, context.array_buffer_binding.get()),
+ GL_CURRENT_PROGRAM => object_or_null(cx, context.current_program.get()),
+ GL_ELEMENT_ARRAY_BUFFER_BINDING => object_or_null(cx, context.element_array_buffer_binding.get()),
+ GL_FRAMEBUFFER_BINDING => object_or_null(cx, context.framebuffer_binding.get()),
+ GL_RENDERBUFFER_BINDING => object_or_null(cx, context.renderbuffer_binding.get()),
+ GL_TEXTURE_BINDING_2D => object_or_null(cx, context.texture_binding_2d.get()),
+ GL_TEXTURE_BINDING_CUBE_MAP => object_or_null(cx, context.texture_binding_cube_map.get()),
+
+ GL_UNMASKED_VENDOR_WEBGL => {
+ if context.extension_enabled("WEBGL_debug_renderer_info") {
+ string_parameter(context, cx, GL_VENDOR)
+ } else {
+ null_with_invalid_enum_error(context)
+ }
+ }
+ GL_UNMASKED_RENDERER_WEBGL => {
+ if context.extension_enabled("WEBGL_debug_renderer_info") {
+ string_parameter(context, cx, GL_RENDERER)
+ } else {
+ null_with_invalid_enum_error(context)
+ }
+ }
+
+ // NB: This has the same value as FRAGMENT_SHADER_DERIVATIVE_HINT_OES.
+ GL_FRAGMENT_SHADER_DERIVATIVE_HINT => {
+ if context.extension_enabled("OES_standard_derivatives") || context.is_webgl2() {
+ Value::from_i32(integer_parameter(context, pname))
+ } else {
+ null_with_invalid_enum_error(context)
+ }
+ }
+ // NB: This has the same value as MAX_COLOR_ATTACHMENTS_WEBGL.
+ GL_MAX_COLOR_ATTACHMENTS => {
+ if context.extension_enabled("WEBGL_draw_buffers") || context.is_webgl2() {
+ Value::from_i32(integer_parameter(context, pname))
+ } else {
+ null_with_invalid_enum_error(context)
+ }
+ }
+ GL_MAX_DRAW_BUFFERS => {
+ // FIXME: Allow this code path for MAX_DRAW_BUFFERS_WEBGL
+ if context.is_webgl2() {
+ Value::from_i32(integer_parameter(context, pname))
+ } else {
+ null_with_invalid_enum_error(context)
+ }
+ }
+ GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT => {
+ if context.extension_enabled("EXT_texture_filter_anisotropic") {
+ number_value(float_parameter(context, pname))
+ } else {
+ null_with_invalid_enum_error(context)
+ }
+ }
+ // NB: This has the same value as VERTEX_ARRAY_BINDING_OES.
+ GL_VERTEX_ARRAY_BINDING => {
+ if context.extension_enabled("OES_vertex_array_object") || context.is_webgl2() {
+ match context.current_vertex_array.get() {
+ Some(VertexArrayBinding::WebGL2(vertex_array)) => Value::from_object(wrap(cx, vertex_array)),
+ Some(VertexArrayBinding::Oes(vertex_array)) => Value::from_object(wrap(cx, vertex_array)),
+ None => Value::NULL,
+ }
+ } else {
+ null_with_invalid_enum_error(context)
+ }
+ }
+
+ GL_COMPRESSED_TEXTURE_FORMATS => {
+ let formats = context.enabled_compressed_texture_formats.borrow().clone();
+ context.uint32_array(cx, &formats)
+ }
+ GL_UNPACK_FLIP_Y_WEBGL => Value::from_bool(context.unpack_flip_y.get()),
+ GL_UNPACK_PREMULTIPLY_ALPHA_WEBGL => Value::from_bool(context.unpack_premultiply_alpha.get()),
+ GL_UNPACK_COLORSPACE_CONVERSION_WEBGL => number_value(context.unpack_colorspace_conversion.get()),
+
+ _ => return None,
+ })
+}
+
+fn parameter_of_webgl2(context: &ContextState, cx: &CallContext, pname: u32) -> Option<Value> {
+ Some(match pname {
+ GL_MAX_SAMPLES
+ | GL_MAX_3D_TEXTURE_SIZE
+ | GL_MAX_ARRAY_TEXTURE_LAYERS
+ | GL_MAX_VERTEX_UNIFORM_COMPONENTS
+ | GL_MAX_UNIFORM_BUFFER_BINDINGS
+ | GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT
+ | GL_MAX_VERTEX_UNIFORM_BLOCKS
+ | GL_MAX_FRAGMENT_INPUT_COMPONENTS
+ | GL_MAX_FRAGMENT_UNIFORM_COMPONENTS
+ | GL_MAX_COMBINED_UNIFORM_BLOCKS
+ | GL_MAX_FRAGMENT_UNIFORM_BLOCKS
+ | GL_MAX_VARYING_COMPONENTS
+ | GL_MAX_ELEMENTS_INDICES
+ | GL_MAX_ELEMENTS_VERTICES
+ | GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS
+ | GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS
+ | GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS
+ | GL_MIN_PROGRAM_TEXEL_OFFSET
+ | GL_MAX_PROGRAM_TEXEL_OFFSET
+ | GL_MAX_VERTEX_OUTPUT_COMPONENTS
+ | GL_PACK_ROW_LENGTH
+ | GL_PACK_SKIP_ROWS
+ | GL_PACK_SKIP_PIXELS
+ | GL_UNPACK_IMAGE_HEIGHT
+ | GL_UNPACK_ROW_LENGTH
+ | GL_UNPACK_SKIP_IMAGES
+ | GL_UNPACK_SKIP_PIXELS
+ | GL_UNPACK_SKIP_ROWS => Value::from_i32(integer_parameter(context, pname)),
+
+ GL_MAX_UNIFORM_BLOCK_SIZE
+ | GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS
+ | GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS
+ | GL_MAX_ELEMENT_INDEX
+ | GL_MAX_SERVER_WAIT_TIMEOUT => Value::from_f64(integer64_parameter(context, pname) as f64),
+
+ GL_MAX_TEXTURE_LOD_BIAS => number_value(float_parameter(context, pname)),
+
+ GL_TRANSFORM_FEEDBACK_ACTIVE | GL_TRANSFORM_FEEDBACK_PAUSED | GL_RASTERIZER_DISCARD => {
+ Value::from_bool(boolean_parameter(context, pname))
+ }
+
+ GL_COPY_READ_BUFFER_BINDING => object_or_null(cx, context.copy_read_buffer_binding.get()),
+ GL_COPY_WRITE_BUFFER_BINDING => object_or_null(cx, context.copy_write_buffer_binding.get()),
+ GL_PIXEL_PACK_BUFFER_BINDING => object_or_null(cx, context.pixel_pack_buffer_binding.get()),
+ GL_PIXEL_UNPACK_BUFFER_BINDING => object_or_null(cx, context.pixel_unpack_buffer_binding.get()),
+ GL_TEXTURE_BINDING_2D_ARRAY => object_or_null(cx, context.texture_binding_2d_array.get()),
+ GL_TRANSFORM_FEEDBACK_BINDING => object_or_null(cx, context.transform_feedback_binding.get()),
+ GL_TRANSFORM_FEEDBACK_BUFFER_BINDING => object_or_null(cx, context.transform_feedback_buffer_binding.get()),
+ GL_UNIFORM_BUFFER_BINDING => object_or_null(cx, context.uniform_buffer_binding.get()),
+ // FIXME: Return the sampler that was bound, or null without one, instead of a new object for the name that GL
+ // has bound.
+ GL_SAMPLER_BINDING => {
+ let handle = integer_parameter(context, pname).cast_unsigned();
+ Value::from_object(wrap(cx, WebGLSampler::create(cx.vm(), context, handle)))
+ }
+
+ // A page must never be able to block the compositor, so clientWaitSync never waits; the host clamps the
+ // timeout to zero to match.
+ GL_MAX_CLIENT_WAIT_TIMEOUT_WEBGL => Value::from_i32(0),
+
+ _ => return None,
+ })
+}
+
+impl<V: Version> RenderingContext<V> {
+ pub(crate) fn get_buffer_parameter(&self, _: &mut CallContext, target: u32, pname: u32) -> WebIdlResult<Value> {
+ match pname {
+ GL_BUFFER_SIZE | GL_BUFFER_USAGE => {
+ let mut result = [0];
+ self.proxy
+ .get_buffer_parameteriv_robust_angle(target, pname, 1, &mut result);
+ Ok(Value::from_i32(result[0]))
+ }
+ _ => Ok(null_with_invalid_enum_error(self)),
+ }
+ }
+
+ pub(crate) fn get_parameter(&self, cx: &mut CallContext, pname: u32) -> WebIdlResult<Value> {
+ if let Some(value) = parameter_of_either_version(self, cx, pname) {
+ return Ok(value);
+ }
+ if self.is_webgl2()
+ && let Some(value) = parameter_of_webgl2(self, cx, pname)
+ {
+ return Ok(value);
+ }
+ Ok(null_with_invalid_enum_error(self))
+ }
+
+ pub(crate) fn get_framebuffer_attachment_parameter(
+ &self,
+ cx: &mut CallContext,
+ target: u32,
+ attachment: u32,
+ pname: u32,
+ ) -> WebIdlResult<Value> {
+ if !is_valid_framebuffer_binding_target(self.version(), target) {
+ return Ok(null_with_invalid_enum_error(self));
+ }
+
+ let Some(framebuffer) = self.framebuffer_binding.get() else {
+ self.set_error(GL_INVALID_OPERATION);
+ return Ok(Value::NULL);
+ };
+
+ if !is_valid_framebuffer_attachment(self.version(), self.extension_enabled("WEBGL_draw_buffers"), attachment) {
+ return Ok(null_with_invalid_enum_error(self));
+ }
+
+ let Some(framebuffer_attachment) = framebuffer.attachment(attachment) else {
+ if pname == GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE {
+ return Ok(number_value(GL_NONE));
+ }
+ if pname == GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME && self.is_webgl2() {
+ return Ok(Value::NULL);
+ }
+ self.set_error(if self.is_webgl2() {
+ GL_INVALID_OPERATION
+ } else {
+ GL_INVALID_ENUM
+ });
+ return Ok(Value::NULL);
+ };
+
+ let is_texture_attached = framebuffer_attachment.texture.is_some();
+ match pname {
+ GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE => Ok(number_value(if is_texture_attached {
+ GL_TEXTURE
+ } else {
+ GL_RENDERBUFFER
+ })),
+ GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME => match framebuffer_attachment.texture {
+ Some(texture) => Ok(Value::from_object(wrap(cx, texture))),
+ None => Ok(object_or_null(cx, framebuffer_attachment.renderbuffer)),
+ },
+ GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL if is_texture_attached => {
+ Ok(Value::from_i32(framebuffer_attachment.texture_level))
+ }
+ GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE if is_texture_attached => {
+ let texture_target = framebuffer_attachment.texture_target;
+ Ok(number_value(if is_cube_map_face(texture_target) {
+ texture_target
+ } else {
+ 0
+ }))
+ }
+ _ => Ok(null_with_invalid_enum_error(self)),
+ }
+ }
+
+ pub(crate) fn get_program_parameter(
+ &self,
+ _: &mut CallContext,
+ program: Ref<WebGLProgram>,
+ pname: u32,
+ ) -> WebIdlResult<Value> {
+ let Some(program_handle) = self.handle_of(program) else {
+ return Ok(Value::NULL);
+ };
+
+ let mut result = [0];
+ self.proxy
+ .get_programiv_robust_angle(program_handle, pname, 1, &mut result);
+ let result = result[0];
+ match pname {
+ GL_ATTACHED_SHADERS | GL_ACTIVE_ATTRIBUTES | GL_ACTIVE_UNIFORMS => Ok(Value::from_i32(result)),
+
+ GL_TRANSFORM_FEEDBACK_BUFFER_MODE | GL_TRANSFORM_FEEDBACK_VARYINGS | GL_ACTIVE_UNIFORM_BLOCKS => {
+ if self.is_webgl2() {
+ Ok(Value::from_i32(result))
+ } else {
+ Ok(null_with_invalid_enum_error(self))
+ }
+ }
+
+ GL_DELETE_STATUS | GL_LINK_STATUS | GL_VALIDATE_STATUS => Ok(Value::from_bool(is_gl_true(result))),
+ _ => Ok(null_with_invalid_enum_error(self)),
+ }
+ }
+
+ pub(crate) fn get_renderbuffer_parameter(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ pname: u32,
+ ) -> WebIdlResult<Value> {
+ match pname {
+ GL_RENDERBUFFER_WIDTH
+ | GL_RENDERBUFFER_HEIGHT
+ | GL_RENDERBUFFER_INTERNAL_FORMAT
+ | GL_RENDERBUFFER_RED_SIZE
+ | GL_RENDERBUFFER_GREEN_SIZE
+ | GL_RENDERBUFFER_BLUE_SIZE
+ | GL_RENDERBUFFER_ALPHA_SIZE
+ | GL_RENDERBUFFER_DEPTH_SIZE
+ | GL_RENDERBUFFER_SAMPLES
+ | GL_RENDERBUFFER_STENCIL_SIZE => {
+ let mut result = [0];
+ self.proxy
+ .get_renderbuffer_parameteriv_robust_angle(target, pname, 1, &mut result);
+ Ok(Value::from_i32(result[0]))
+ }
+ // If pname is not in the table above, generates an INVALID_ENUM error.
+ _ => Ok(null_with_invalid_enum_error(self)),
+ }
+ }
+
+ pub(crate) fn get_shader_parameter(
+ &self,
+ _: &mut CallContext,
+ shader: Ref<WebGLShader>,
+ pname: u32,
+ ) -> WebIdlResult<Value> {
+ let Some(shader_handle) = self.handle_of(shader) else {
+ return Ok(Value::NULL);
+ };
+
+ let mut result = [0];
+ self.proxy
+ .get_shaderiv_robust_angle(shader_handle, pname, 1, &mut result);
+ let result = result[0];
+ match pname {
+ GL_SHADER_TYPE => Ok(Value::from_i32(result)),
+ GL_DELETE_STATUS | GL_COMPILE_STATUS => Ok(Value::from_bool(is_gl_true(result))),
+ _ => Ok(null_with_invalid_enum_error(self)),
+ }
+ }
+
+ pub(crate) fn get_tex_parameter(&self, _: &mut CallContext, target: u32, pname: u32) -> WebIdlResult<Value> {
+ match pname {
+ GL_TEXTURE_MAG_FILTER | GL_TEXTURE_MIN_FILTER | GL_TEXTURE_WRAP_S | GL_TEXTURE_WRAP_T => {
+ return Ok(Value::from_i32(integer_tex_parameter(self, target, pname)));
+ }
+ GL_TEXTURE_MAX_ANISOTROPY_EXT => {
+ if self.extension_enabled("EXT_texture_filter_anisotropic") {
+ return Ok(Value::from_i32(integer_tex_parameter(self, target, pname)));
+ }
+ return Ok(null_with_invalid_enum_error(self));
+ }
+ _ => {}
+ }
+
+ if self.is_webgl2() {
+ match pname {
+ GL_TEXTURE_BASE_LEVEL
+ | GL_TEXTURE_COMPARE_FUNC
+ | GL_TEXTURE_COMPARE_MODE
+ | GL_TEXTURE_IMMUTABLE_LEVELS
+ | GL_TEXTURE_MAX_LEVEL
+ | GL_TEXTURE_WRAP_R => {
+ return Ok(Value::from_i32(integer_tex_parameter(self, target, pname)));
+ }
+ GL_TEXTURE_IMMUTABLE_FORMAT => {
+ return Ok(Value::from_bool(is_gl_true(integer_tex_parameter(self, target, pname))));
+ }
+ // FIXME: Return the level of detail, instead of whether TEXTURE_IMMUTABLE_FORMAT is set.
+ GL_TEXTURE_MAX_LOD | GL_TEXTURE_MIN_LOD => {
+ let mut result = [0.0];
+ self.proxy
+ .get_tex_parameterfv_robust_angle(target, GL_TEXTURE_IMMUTABLE_FORMAT, 1, &mut result);
+ return Ok(Value::from_bool(result[0] == 1.0));
+ }
+ _ => {}
+ }
+ }
+
+ Ok(null_with_invalid_enum_error(self))
+ }
+
+ pub(crate) fn get_uniform(
+ &self,
+ _: &mut CallContext,
+ _: Ref<WebGLProgram>,
+ _: Ref<WebGLUniformLocation>,
+ ) -> WebIdlResult<Value> {
+ // FIXME: Implement this.
+ Ok(Value::from_i32(0))
+ }
+
+ pub(crate) fn get_vertex_attrib(&self, cx: &mut CallContext, index: u32, pname: u32) -> WebIdlResult<Value> {
+ match pname {
+ GL_CURRENT_VERTEX_ATTRIB => {
+ let mut result = [0.0; 4];
+ self.proxy
+ .get_vertex_attribfv_robust_angle(index, GL_CURRENT_VERTEX_ATTRIB, 4, &mut result);
+ Ok(self.float32_array(cx, &result))
+ }
+ // FIXME: Return the buffer that was bound, or null without one, instead of a new object for the name that
+ // GL has bound.
+ GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING => {
+ let handle = integer_vertex_attrib(self, index, pname).cast_unsigned();
+ Ok(Value::from_object(wrap(cx, WebGLBuffer::create(cx.vm(), self, handle))))
+ }
+ // NB: This has the same value as VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE.
+ GL_VERTEX_ATTRIB_ARRAY_DIVISOR => {
+ if self.extension_enabled("ANGLE_instanced_arrays") || self.is_webgl2() {
+ Ok(Value::from_i32(integer_vertex_attrib(self, index, pname)))
+ } else {
+ Ok(null_with_invalid_enum_error(self))
+ }
+ }
+ GL_VERTEX_ATTRIB_ARRAY_ENABLED | GL_VERTEX_ATTRIB_ARRAY_NORMALIZED => {
+ Ok(Value::from_bool(is_gl_true(integer_vertex_attrib(self, index, pname))))
+ }
+ GL_VERTEX_ATTRIB_ARRAY_INTEGER => {
+ if self.is_webgl2() {
+ Ok(Value::from_bool(is_gl_true(integer_vertex_attrib(self, index, pname))))
+ } else {
+ Ok(null_with_invalid_enum_error(self))
+ }
+ }
+ GL_VERTEX_ATTRIB_ARRAY_SIZE | GL_VERTEX_ATTRIB_ARRAY_STRIDE | GL_VERTEX_ATTRIB_ARRAY_TYPE => {
+ Ok(Value::from_i32(integer_vertex_attrib(self, index, pname)))
+ }
+ _ => Ok(null_with_invalid_enum_error(self)),
+ }
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/generated.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/generated.rs
index 2f9a8ff73ba..0c4b3685608 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/generated.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/generated.rs
@@ -7,6 +7,11 @@
//! The methods of the recorder that follow from the signature of a GL function. The build script writes them from
//! GLFunctions.json (generate/webgl_proxy.rs).
+#![allow(
+ dead_code,
+ reason = "the recorder has a method for every GL function of the replayer, of which the contexts call some"
+)]
+
use super::recorder::{
Proxy, bytes_of, bytes_of_mut, copy_reply_data, gen_count, leading_bytes, leading_bytes_mut, payload_size,
until_nul,
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/state.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/state.rs
new file mode 100644
index 00000000000..0f01ed9ea1c
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/state.rs
@@ -0,0 +1,453 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The state that both kinds of WebGL context share: the error, the objects a context may use, and what is bound to
+//! what.
+
+use core::cell::{Cell, RefCell};
+use core::ffi::c_void;
+use core::marker::PhantomData;
+use core::ops::Deref;
+
+use libjs_rust::api::{ForeignCellSlot, Gc, Realm, Trace, Visitor, Vm};
+
+use super::canvas::{Canvas, PixelUnpackState, TexImageSourceFrame, TexImageSourceKind, read_tex_image_source};
+use super::constants::{
+ GL_BROWSER_DEFAULT_WEBGL, GL_CONTEXT_LOST_WEBGL, GL_INVALID_OPERATION, GL_INVALID_VALUE, GL_NO_ERROR,
+};
+use super::extensions::{EnabledEmptyExtension, EnabledExtension};
+use super::host::{CppTransport, Frame};
+use super::proxy::custom::FrameUpload;
+use super::proxy::recorder::Proxy;
+use super::web_gl_buffer::WebGLBuffer;
+use super::web_gl_framebuffer::WebGLFramebuffer;
+use super::web_gl_object::WebGLObject;
+use super::web_gl_program::WebGLProgram;
+use super::web_gl_query::WebGLQuery;
+use super::web_gl_renderbuffer::WebGLRenderbuffer;
+use super::web_gl_rendering_context_base::WebGLContextAttributes;
+use super::web_gl_rendering_context_overloads::TexImageSource;
+use super::web_gl_texture::WebGLTexture;
+use super::web_gl_transform_feedback::WebGLTransformFeedback;
+use super::web_gl_uniform_location::WebGLUniformLocation;
+use super::web_gl_vertex_array_object::WebGLVertexArrayObject;
+use super::web_gl_vertex_array_object_oes::WebGLVertexArrayObjectOES;
+use crate::bindings::interface::{Inherits, Interface, Ref, Wrappable, cell_into_abi};
+
+pub(crate) const MAX_WEBGL_DRAWING_BUFFER_DIMENSION: i32 = 16384;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum WebGLVersion {
+ WebGL1,
+ WebGL2,
+}
+
+pub(crate) trait Version: Sized + 'static {}
+
+pub(crate) struct WebGL1;
+pub(crate) struct WebGL2;
+
+impl Version for WebGL1 {}
+impl Version for WebGL2 {}
+
+/// The operations that WebGLRenderingContext and WebGL2RenderingContext share are implemented once, for every `V`.
+pub(crate) struct RenderingContext<V: Version> {
+ state: ContextState,
+ version: PhantomData<V>,
+}
+
+impl<V: Version> RenderingContext<V> {
+ pub(crate) fn new(state: ContextState) -> Self {
+ Self {
+ state,
+ version: PhantomData,
+ }
+ }
+}
+
+impl<V: Version> Deref for RenderingContext<V> {
+ type Target = ContextState;
+
+ fn deref(&self) -> &ContextState {
+ &self.state
+ }
+}
+
+// SAFETY: The state holds every cell that a context can reach.
+unsafe impl<V: Version> Trace for RenderingContext<V> {
+ fn trace(&self, visitor: &mut Visitor) {
+ self.state.trace(visitor);
+ }
+}
+
+impl<V: Version> Wrappable for RenderingContext<V> {
+ fn relevant_realm(&self, _vm: &Vm) -> Option<Gc<Realm>> {
+ self.state.canvas().relevant_realm()
+ }
+}
+
+#[derive(Clone, Copy, Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) enum ContextRef {
+ WebGL1(Ref<RenderingContext<WebGL1>>),
+ WebGL2(Ref<RenderingContext<WebGL2>>),
+}
+
+impl ContextRef {
+ pub(crate) fn state(&self) -> &ContextState {
+ match self {
+ Self::WebGL1(context) => &context.state,
+ Self::WebGL2(context) => &context.state,
+ }
+ }
+
+ pub(crate) fn cell(&self) -> *mut c_void {
+ match *self {
+ Self::WebGL1(context) => cell_into_abi(context),
+ Self::WebGL2(context) => cell_into_abi(context),
+ }
+ }
+}
+
+#[derive(Clone, Copy, Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) enum VertexArrayBinding {
+ WebGL2(Ref<WebGLVertexArrayObject>),
+ Oes(Ref<WebGLVertexArrayObjectOES>),
+}
+
+pub(crate) type Binding<T> = Cell<Option<Ref<T>>>;
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct ContextState {
+ #[gc(untraced)]
+ pub(crate) proxy: Proxy<CppTransport>,
+ #[gc(untraced)]
+ version: WebGLVersion,
+ context_ref: Cell<Option<ContextRef>>,
+ realm: Gc<Realm>,
+ canvas_cell: ForeignCellSlot,
+ #[gc(untraced)]
+ canvas: Canvas,
+
+ /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#context-creation-parameters
+ #[gc(untraced)]
+ pub(crate) context_creation_parameters: WebGLContextAttributes,
+ /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#actual-context-parameters
+ #[gc(untraced)]
+ pub(crate) actual_context_parameters: WebGLContextAttributes,
+ #[gc(untraced)]
+ pub(crate) supported_opengl_extensions: RefCell<Vec<Vec<u8>>>,
+
+ #[gc(untraced)]
+ error: Cell<u32>,
+ /// https://registry.khronos.org/webgl/specs/latest/2.0/#webgl-context-lost-flag
+ #[gc(untraced)]
+ context_lost: Cell<bool>,
+ #[gc(untraced)]
+ context_restore_requested: Cell<bool>,
+ /// https://immersive-web.github.io/webxr/#xr-compatible
+ #[gc(untraced)]
+ xr_compatible: Cell<bool>,
+ #[gc(untraced)]
+ context_generation: Cell<u64>,
+
+ #[gc(untraced)]
+ pub(crate) unpack_state: Cell<PixelUnpackState>,
+ #[gc(untraced)]
+ pub(crate) unpack_flip_y: Cell<bool>,
+ #[gc(untraced)]
+ pub(crate) unpack_premultiply_alpha: Cell<bool>,
+ #[gc(untraced)]
+ pub(crate) unpack_colorspace_conversion: Cell<u32>,
+
+ #[gc(untraced)]
+ pub(crate) enabled_compressed_texture_formats: RefCell<Vec<u32>>,
+ pub(crate) enabled_extensions: RefCell<Vec<EnabledExtension>>,
+ #[gc(untraced)]
+ pub(crate) enabled_empty_extensions: RefCell<Vec<EnabledEmptyExtension>>,
+
+ pub(crate) array_buffer_binding: Binding<WebGLBuffer>,
+ pub(crate) element_array_buffer_binding: Binding<WebGLBuffer>,
+ pub(crate) current_program: Binding<WebGLProgram>,
+ pub(crate) framebuffer_binding: Binding<WebGLFramebuffer>,
+ pub(crate) renderbuffer_binding: Binding<WebGLRenderbuffer>,
+ pub(crate) texture_binding_2d: Binding<WebGLTexture>,
+ pub(crate) texture_binding_cube_map: Binding<WebGLTexture>,
+ // FIXME: The bindings from here on are of WebGL 2 only, but operations that the two kinds share use them.
+ pub(crate) uniform_buffer_binding: Binding<WebGLBuffer>,
+ pub(crate) copy_read_buffer_binding: Binding<WebGLBuffer>,
+ pub(crate) copy_write_buffer_binding: Binding<WebGLBuffer>,
+ pub(crate) transform_feedback_buffer_binding: Binding<WebGLBuffer>,
+ pub(crate) pixel_pack_buffer_binding: Binding<WebGLBuffer>,
+ pub(crate) pixel_unpack_buffer_binding: Binding<WebGLBuffer>,
+ pub(crate) texture_binding_2d_array: Binding<WebGLTexture>,
+ pub(crate) texture_binding_3d: Binding<WebGLTexture>,
+ pub(crate) transform_feedback_binding: Binding<WebGLTransformFeedback>,
+ pub(crate) any_samples_passed: Binding<WebGLQuery>,
+ pub(crate) any_samples_passed_conservative: Binding<WebGLQuery>,
+ pub(crate) transform_feedback_primitives_written: Binding<WebGLQuery>,
+ pub(crate) current_vertex_array: Cell<Option<VertexArrayBinding>>,
+}
+
+pub(crate) struct ContextParameters {
+ pub(crate) proxy: Proxy<CppTransport>,
+ pub(crate) version: WebGLVersion,
+ pub(crate) realm: Gc<Realm>,
+ pub(crate) canvas: Canvas,
+ pub(crate) context_attributes: WebGLContextAttributes,
+ pub(crate) supported_opengl_extensions: Vec<Vec<u8>>,
+}
+
+impl ContextState {
+ pub(crate) fn new(parameters: ContextParameters) -> Self {
+ let canvas_cell = ForeignCellSlot::empty();
+ // SAFETY: The canvas is a live cell of the heap that the runtime allocates from.
+ unsafe { canvas_cell.set(Some(parameters.canvas.cell)) };
+ Self {
+ proxy: parameters.proxy,
+ version: parameters.version,
+ context_ref: Cell::new(None),
+ realm: parameters.realm,
+ canvas_cell,
+ canvas: parameters.canvas,
+ context_creation_parameters: parameters.context_attributes,
+ actual_context_parameters: parameters.context_attributes,
+ supported_opengl_extensions: RefCell::new(parameters.supported_opengl_extensions),
+ error: Cell::new(GL_NO_ERROR),
+ context_lost: Cell::new(false),
+ context_restore_requested: Cell::new(false),
+ xr_compatible: Cell::new(false),
+ context_generation: Cell::new(0),
+ unpack_state: Cell::new(PixelUnpackState::default()),
+ unpack_flip_y: Cell::new(false),
+ unpack_premultiply_alpha: Cell::new(false),
+ unpack_colorspace_conversion: Cell::new(GL_BROWSER_DEFAULT_WEBGL),
+ enabled_compressed_texture_formats: RefCell::new(Vec::new()),
+ enabled_extensions: RefCell::new(Vec::new()),
+ enabled_empty_extensions: RefCell::new(Vec::new()),
+ array_buffer_binding: Cell::new(None),
+ element_array_buffer_binding: Cell::new(None),
+ current_program: Cell::new(None),
+ framebuffer_binding: Cell::new(None),
+ renderbuffer_binding: Cell::new(None),
+ texture_binding_2d: Cell::new(None),
+ texture_binding_cube_map: Cell::new(None),
+ uniform_buffer_binding: Cell::new(None),
+ copy_read_buffer_binding: Cell::new(None),
+ copy_write_buffer_binding: Cell::new(None),
+ transform_feedback_buffer_binding: Cell::new(None),
+ pixel_pack_buffer_binding: Cell::new(None),
+ pixel_unpack_buffer_binding: Cell::new(None),
+ texture_binding_2d_array: Cell::new(None),
+ texture_binding_3d: Cell::new(None),
+ transform_feedback_binding: Cell::new(None),
+ any_samples_passed: Cell::new(None),
+ any_samples_passed_conservative: Cell::new(None),
+ transform_feedback_primitives_written: Cell::new(None),
+ current_vertex_array: Cell::new(None),
+ }
+ }
+
+ pub(crate) fn set_context_ref(&self, context_ref: ContextRef) {
+ self.context_ref.set(Some(context_ref));
+ }
+
+ pub(crate) fn context_ref(&self) -> ContextRef {
+ self.context_ref
+ .get()
+ .expect("a context knows its cell from its creation on")
+ }
+
+ pub(crate) fn version(&self) -> WebGLVersion {
+ self.version
+ }
+
+ pub(crate) fn is_webgl2(&self) -> bool {
+ self.version == WebGLVersion::WebGL2
+ }
+
+ pub(crate) fn realm(&self) -> Gc<Realm> {
+ self.realm
+ }
+
+ pub(crate) fn canvas(&self) -> Canvas {
+ self.canvas
+ }
+
+ pub(crate) fn context_generation(&self) -> u64 {
+ self.context_generation.get()
+ }
+
+ pub(crate) fn is_context_lost(&self) -> bool {
+ self.context_lost.get()
+ }
+
+ pub(crate) fn xr_compatible(&self) -> bool {
+ self.xr_compatible.get()
+ }
+
+ pub(crate) fn set_xr_compatible(&self, xr_compatible: bool) {
+ self.xr_compatible.set(xr_compatible);
+ }
+
+ /// Makes `error` the error of the context, unless it has one already.
+ // TODO: The specification of glGetError allows for a queue of errors, which this could keep.
+ pub(crate) fn set_error(&self, error: u32) {
+ if self.error.get() == GL_NO_ERROR {
+ self.error.set(error);
+ }
+ }
+
+ pub(crate) fn take_error(&self) -> u32 {
+ if self.context_lost.get() {
+ return self.error.replace(GL_NO_ERROR);
+ }
+ let local_error = self.proxy.take_pending_local_error();
+ if local_error != GL_NO_ERROR {
+ return local_error;
+ }
+ let context_error = self.proxy.get_error();
+ if context_error != GL_NO_ERROR {
+ return context_error;
+ }
+ self.error.replace(GL_NO_ERROR)
+ }
+
+ pub(crate) fn handle_of<O: Interface + Inherits<WebGLObject>>(&self, object: Ref<O>) -> Option<u32> {
+ let handle = object.parent().handle(self).ok();
+ if handle.is_none() {
+ self.set_error(GL_INVALID_OPERATION);
+ }
+ handle
+ }
+
+ pub(crate) fn handle_for_deletion_of<O: Interface + Inherits<WebGLObject>>(&self, object: Ref<O>) -> Option<u32> {
+ match object.parent().handle_for_deletion(self) {
+ Ok(handle) => handle,
+ Err(_) => {
+ self.set_error(GL_INVALID_OPERATION);
+ None
+ }
+ }
+ }
+
+ pub(crate) fn handle_for_query_of<O: Interface + Inherits<WebGLObject>>(&self, object: Ref<O>) -> Option<u32> {
+ match object.parent().handle_for_query(self) {
+ Ok(handle) => handle,
+ Err(_) => {
+ self.set_error(GL_INVALID_OPERATION);
+ None
+ }
+ }
+ }
+
+ pub(crate) fn read_texture_image_source(
+ &self,
+ source: &TexImageSource,
+ format: u32,
+ r#type: u32,
+ ) -> Option<(Frame, FrameUpload)> {
+ let (source_kind, source_object) = match *source {
+ TexImageSource::ImageBitmap(object) => (TexImageSourceKind::ImageBitmap, object),
+ TexImageSource::ImageData(object) => (TexImageSourceKind::ImageData, object),
+ TexImageSource::HTMLImageElement(object) => (TexImageSourceKind::HTMLImageElement, object),
+ TexImageSource::HTMLCanvasElement(object) => (TexImageSourceKind::HTMLCanvasElement, object),
+ TexImageSource::HTMLVideoElement(object) => (TexImageSourceKind::HTMLVideoElement, object),
+ TexImageSource::OffscreenCanvas(object) => (TexImageSourceKind::OffscreenCanvas, object),
+ };
+ let frame = match read_tex_image_source(source_object, source_kind, format, r#type) {
+ TexImageSourceFrame::Frame(frame) => frame,
+ TexImageSourceFrame::NoFrame => return None,
+ TexImageSourceFrame::InvalidValue => {
+ self.set_error(GL_INVALID_VALUE);
+ return None;
+ }
+ };
+ // The first pixel transferred from the source to the WebGL implementation corresponds to the upper left
+ // corner of the source. This behavior is modified by the UNPACK_FLIP_Y_WEBGL pixel storage parameter,
+ // except for ImageBitmap arguments, as described in the abovementioned section.
+ let flip_y = self.unpack_flip_y.get() && source_kind != TexImageSourceKind::ImageBitmap;
+ let upload = FrameUpload {
+ destination_size: None,
+ flip_y,
+ premultiply_alpha: self.unpack_premultiply_alpha.get(),
+ };
+ Some((frame, upload))
+ }
+
+ pub(crate) fn uniform_location_handle(&self, location: Ref<WebGLUniformLocation>) -> Option<i32> {
+ let handle = location.handle(self.current_program.get()).ok();
+ if handle.is_none() {
+ self.set_error(GL_INVALID_OPERATION);
+ }
+ handle
+ }
+
+ pub(crate) fn did_update_canvas_content(&self) {
+ self.canvas.did_change_content();
+ }
+
+ /// https://registry.khronos.org/webgl/specs/latest/1.0/#CONTEXT_LOST
+ pub(crate) fn mark_lost(&self) -> bool {
+ if self.context_lost.replace(true) {
+ return false;
+ }
+ self.proxy.set_lost();
+ // NB: The next getError() has to return CONTEXT_LOST_WEBGL, once.
+ self.error.set(GL_CONTEXT_LOST_WEBGL);
+ true
+ }
+
+ pub(crate) fn set_context_restore_requested(&self, requested: bool) {
+ self.context_restore_requested.set(requested);
+ }
+
+ pub(crate) fn wants_restoring(&self) -> bool {
+ self.context_lost.get() && self.context_restore_requested.get()
+ }
+
+ /// The new replayer context has no GL objects: the page creates its objects anew once told of the restore.
+ pub(crate) fn restore(&self, transport: CppTransport, supported_opengl_extensions: Vec<Vec<u8>>) {
+ self.proxy.restore(transport);
+ self.supported_opengl_extensions.replace(supported_opengl_extensions);
+
+ self.context_generation.set(self.context_generation.get() + 1);
+ self.unpack_state.set(PixelUnpackState::default());
+ self.unpack_flip_y.set(false);
+ self.unpack_premultiply_alpha.set(false);
+ self.unpack_colorspace_conversion.set(GL_BROWSER_DEFAULT_WEBGL);
+ self.reset_client_side_state();
+
+ self.context_lost.set(false);
+ self.context_restore_requested.set(false);
+ self.error.set(GL_NO_ERROR);
+ }
+
+ fn reset_client_side_state(&self) {
+ self.array_buffer_binding.set(None);
+ self.element_array_buffer_binding.set(None);
+ self.current_program.set(None);
+ self.framebuffer_binding.set(None);
+ self.renderbuffer_binding.set(None);
+ self.texture_binding_2d.set(None);
+ self.texture_binding_cube_map.set(None);
+ self.uniform_buffer_binding.set(None);
+ self.copy_read_buffer_binding.set(None);
+ self.copy_write_buffer_binding.set(None);
+ self.transform_feedback_buffer_binding.set(None);
+ self.pixel_pack_buffer_binding.set(None);
+ self.pixel_unpack_buffer_binding.set(None);
+ self.texture_binding_2d_array.set(None);
+ self.texture_binding_3d.set(None);
+ self.transform_feedback_binding.set(None);
+ self.current_vertex_array.set(None);
+ self.any_samples_passed.set(None);
+ self.any_samples_passed_conservative.set(None);
+ self.transform_feedback_primitives_written.set(None);
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/types.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/types.rs
new file mode 100644
index 00000000000..99721f0e520
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/types.rs
@@ -0,0 +1,14 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://registry.khronos.org/webgl/specs/latest/1.0/#5.1
+
+use libjs_rust::api::{Gc, TypedArrayBase};
+
+pub(crate) enum Float32List {
+ Float32Array(Gc<TypedArrayBase>),
+ Sequence(Vec<f32>),
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/values.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/values.rs
new file mode 100644
index 00000000000..cb3e1879639
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/values.rs
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use ak::Utf16String;
+use libjs_rust::api::{
+ Array, ArrayBuffer, ArrayBufferShared, PrimitiveString, TypedArrayKind, Value, create_typed_array_on_buffer,
+};
+
+use super::proxy::recorder::bytes_of;
+use super::state::ContextState;
+use crate::bindings::CallContext;
+use crate::bindings::interface::{Interface, Ref, wrap};
+
+impl ContextState {
+ fn typed_array(&self, cx: &CallContext, kind: TypedArrayKind, bytes: &[u8], length: usize) -> Value {
+ let array_buffer = ArrayBuffer::create_from_bytes(cx.vm(), self.realm(), bytes, ArrayBufferShared::No);
+ let length = u32::try_from(length).expect("a typed array of a few numbers");
+ Value::from_object(create_typed_array_on_buffer(
+ cx.vm(),
+ self.realm(),
+ kind,
+ length,
+ array_buffer,
+ ))
+ }
+
+ pub(crate) fn int32_array(&self, cx: &CallContext, numbers: &[i32]) -> Value {
+ self.typed_array(cx, TypedArrayKind::Int32Array, bytes_of(numbers), numbers.len())
+ }
+
+ pub(crate) fn uint32_array(&self, cx: &CallContext, numbers: &[u32]) -> Value {
+ self.typed_array(cx, TypedArrayKind::Uint32Array, bytes_of(numbers), numbers.len())
+ }
+
+ pub(crate) fn float32_array(&self, cx: &CallContext, numbers: &[f32]) -> Value {
+ self.typed_array(cx, TypedArrayKind::Float32Array, bytes_of(numbers), numbers.len())
+ }
+
+ /// A `sequence<GLboolean>` returned as `any` is a JS array.
+ pub(crate) fn boolean_array(&self, cx: &CallContext, booleans: &[bool]) -> Value {
+ let elements: Vec<Value> = booleans.iter().map(|&boolean| Value::from_bool(boolean)).collect();
+ Value::from_object(Array::create_from(cx.vm(), self.realm(), &elements))
+ }
+}
+
+pub(crate) fn string_value(cx: &CallContext, string: Utf16String) -> Value {
+ Value::from_string(PrimitiveString::create(cx.vm(), string))
+}
+
+pub(crate) fn object_or_null<T: Interface>(cx: &CallContext, object: Option<Ref<T>>) -> Value {
+ object.map_or(Value::NULL, |object| Value::from_object(wrap(cx, object)))
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl2_rendering_context.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl2_rendering_context.rs
new file mode 100644
index 00000000000..a2d3f695290
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl2_rendering_context.rs
@@ -0,0 +1,11 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://registry.khronos.org/webgl/specs/latest/2.0/#3.7
+
+use super::state::{RenderingContext, WebGL2};
+
+pub(crate) type WebGL2RenderingContext = RenderingContext<WebGL2>;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl2_rendering_context_base.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl2_rendering_context_base.rs
new file mode 100644
index 00000000000..d62807ba2a4
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl2_rendering_context_base.rs
@@ -0,0 +1,1706 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://registry.khronos.org/webgl/specs/latest/2.0/#3.7
+
+use ak::Utf16String;
+use libjs_rust::api::{Array, Gc, TypedArrayBase, Value};
+
+use super::buffer_kind::BufferKind;
+use super::buffer_source::{
+ copy_of_first_numbers, destination_bytes_of_get_buffer_sub_data, list_bytes, numbers_from_offset, source_bytes,
+ write_checked,
+};
+use super::constants::{
+ GL_ANY_SAMPLES_PASSED, GL_ANY_SAMPLES_PASSED_CONSERVATIVE, GL_COLOR, GL_CURRENT_QUERY, GL_DEPTH, GL_INVALID_ENUM,
+ GL_INVALID_INDEX, GL_INVALID_OPERATION, GL_INVALID_VALUE, GL_NUM_SAMPLE_COUNTS, GL_QUERY_RESULT,
+ GL_QUERY_RESULT_AVAILABLE, GL_SAMPLES, GL_STENCIL, GL_TEXTURE_COMPARE_FUNC, GL_TEXTURE_COMPARE_MODE,
+ GL_TEXTURE_MAG_FILTER, GL_TEXTURE_MAX_ANISOTROPY_EXT, GL_TEXTURE_MAX_LOD, GL_TEXTURE_MIN_FILTER,
+ GL_TEXTURE_MIN_LOD, GL_TEXTURE_WRAP_R, GL_TEXTURE_WRAP_S, GL_TEXTURE_WRAP_T,
+ GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN, GL_TRUE, GL_UNIFORM_ARRAY_STRIDE,
+ GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, GL_UNIFORM_BLOCK_BINDING,
+ GL_UNIFORM_BLOCK_DATA_SIZE, GL_UNIFORM_BLOCK_INDEX, GL_UNIFORM_BLOCK_NAME_LENGTH,
+ GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER, GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER,
+ GL_UNIFORM_IS_ROW_MAJOR, GL_UNIFORM_MATRIX_STRIDE, GL_UNIFORM_OFFSET, GL_UNIFORM_SIZE, GL_UNIFORM_TYPE,
+ GL_WAIT_FAILED,
+};
+use super::gl_string::{utf8_bytes, utf16_string_from_gl_string};
+use super::proxy::recorder::bytes_of;
+use super::state::{Binding, RenderingContext, VertexArrayBinding, WebGL2};
+use super::types::Float32List;
+use super::web_gl_buffer::WebGLBuffer;
+use super::web_gl_program::WebGLProgram;
+use super::web_gl_query::WebGLQuery;
+use super::web_gl_rendering_context_overloads::{Int32List, TexImageSource};
+use super::web_gl_sampler::WebGLSampler;
+use super::web_gl_sync::WebGLSync;
+use super::web_gl_texture::WebGLTexture;
+use super::web_gl_transform_feedback::WebGLTransformFeedback;
+use super::web_gl_uniform_location::WebGLUniformLocation;
+use super::web_gl_vertex_array_object::WebGLVertexArrayObject;
+use crate::bindings::conversions::ArrayBufferView;
+use crate::bindings::interface::Ref;
+use crate::bindings::{CallContext, WebIdlResult};
+
+pub(crate) enum Uint32List {
+ Uint32Array(Gc<TypedArrayBase>),
+ Sequence(Vec<u32>),
+}
+
+fn element_count_from_gl(count: i32) -> usize {
+ usize::try_from(count).expect("a count that GL returns is not negative")
+}
+
+fn clear_value_count(buffer: u32) -> Option<usize> {
+ match buffer {
+ GL_COLOR => Some(4),
+ GL_DEPTH | GL_STENCIL => Some(1),
+ _ => None,
+ }
+}
+
+#[expect(
+ clippy::too_many_arguments,
+ reason = "the operations have the arguments of the GL functions"
+)]
+impl RenderingContext<WebGL2> {
+ pub(crate) fn copy_buffer_sub_data(
+ &self,
+ _: &mut CallContext,
+ read_target: u32,
+ write_target: u32,
+ read_offset: i64,
+ write_offset: i64,
+ size: i64,
+ ) -> WebIdlResult<()> {
+ self.proxy
+ .copy_buffer_sub_data(read_target, write_target, read_offset, write_offset, size);
+ Ok(())
+ }
+
+ /// https://registry.khronos.org/webgl/specs/latest/2.0/#3.7.3
+ pub(crate) fn get_buffer_sub_data(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ src_byte_offset: i64,
+ dst_buffer: ArrayBufferView,
+ dst_offset: u64,
+ length: u32,
+ ) -> WebIdlResult<()> {
+ let Ok(destination_bytes) = destination_bytes_of_get_buffer_sub_data(&dst_buffer, dst_offset, length) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Some(destination_bytes) = destination_bytes else {
+ return Ok(());
+ };
+
+ // If copyLength is greater than zero, copy copyLength typed elements (each of size elementSize) from buf into
+ // dstBuffer, reading buf starting at byte index srcByteOffset and writing into dstBuffer starting at element
+ // index dstOffset.
+ self.proxy
+ .read_buffer_sub_data(target, src_byte_offset, destination_bytes.len(), |data| {
+ if write_checked(&dst_buffer, data, destination_bytes.start).is_err() {
+ self.set_error(GL_INVALID_VALUE);
+ }
+ });
+ Ok(())
+ }
+
+ pub(crate) fn blit_framebuffer(
+ &self,
+ _: &mut CallContext,
+ src_x0: i32,
+ src_y0: i32,
+ src_x1: i32,
+ src_y1: i32,
+ dst_x0: i32,
+ dst_y0: i32,
+ dst_x1: i32,
+ dst_y1: i32,
+ mask: u32,
+ filter: u32,
+ ) -> WebIdlResult<()> {
+ self.did_update_canvas_content();
+ self.proxy.blit_framebuffer(
+ src_x0, src_y0, src_x1, src_y1, dst_x0, dst_y0, dst_x1, dst_y1, mask, filter,
+ );
+ Ok(())
+ }
+
+ pub(crate) fn framebuffer_texture_layer(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ attachment: u32,
+ texture: Option<Ref<WebGLTexture>>,
+ level: i32,
+ layer: i32,
+ ) -> WebIdlResult<()> {
+ let mut texture_handle = 0;
+ if let Some(texture) = texture {
+ let Some(handle) = self.handle_of(texture) else {
+ return Ok(());
+ };
+ texture_handle = handle;
+ }
+ self.proxy
+ .framebuffer_texture_layer(target, attachment, texture_handle, level, layer);
+ Ok(())
+ }
+
+ pub(crate) fn invalidate_framebuffer(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ attachments: Vec<u32>,
+ ) -> WebIdlResult<()> {
+ let Ok(attachment_count) = i32::try_from(attachments.len()) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy
+ .invalidate_framebuffer(target, attachment_count, bytes_of(&attachments));
+ self.did_update_canvas_content();
+ Ok(())
+ }
+
+ pub(crate) fn invalidate_sub_framebuffer(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ attachments: Vec<u32>,
+ x: i32,
+ y: i32,
+ width: i32,
+ height: i32,
+ ) -> WebIdlResult<()> {
+ let Ok(attachment_count) = i32::try_from(attachments.len()) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy
+ .invalidate_sub_framebuffer(target, attachment_count, bytes_of(&attachments), x, y, width, height);
+ self.did_update_canvas_content();
+ Ok(())
+ }
+
+ pub(crate) fn read_buffer(&self, _: &mut CallContext, src: u32) -> WebIdlResult<()> {
+ self.proxy.read_buffer(src);
+ Ok(())
+ }
+
+ pub(crate) fn get_internalformat_parameter(
+ &self,
+ cx: &mut CallContext,
+ target: u32,
+ internalformat: u32,
+ pname: u32,
+ ) -> WebIdlResult<Value> {
+ match pname {
+ GL_SAMPLES => {
+ let mut num_sample_counts = [0];
+ self.proxy.get_internalformativ_robust_angle(
+ target,
+ internalformat,
+ GL_NUM_SAMPLE_COUNTS,
+ 1,
+ &mut num_sample_counts,
+ );
+ let [num_sample_counts] = num_sample_counts;
+ let mut samples = vec![0; element_count_from_gl(num_sample_counts)];
+ self.proxy.get_internalformativ_robust_angle(
+ target,
+ internalformat,
+ GL_SAMPLES,
+ num_sample_counts,
+ &mut samples,
+ );
+ Ok(self.int32_array(cx, &samples))
+ }
+ _ => {
+ self.set_error(GL_INVALID_ENUM);
+ Ok(Value::NULL)
+ }
+ }
+ }
+
+ pub(crate) fn renderbuffer_storage_multisample(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ samples: i32,
+ internalformat: u32,
+ width: i32,
+ height: i32,
+ ) -> WebIdlResult<()> {
+ self.proxy
+ .renderbuffer_storage_multisample(target, samples, internalformat, width, height);
+ Ok(())
+ }
+
+ pub(crate) fn tex_storage2d(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ levels: i32,
+ internalformat: u32,
+ width: i32,
+ height: i32,
+ ) -> WebIdlResult<()> {
+ self.proxy.tex_storage2d(target, levels, internalformat, width, height);
+ Ok(())
+ }
+
+ pub(crate) fn tex_storage3d(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ levels: i32,
+ internalformat: u32,
+ width: i32,
+ height: i32,
+ depth: i32,
+ ) -> WebIdlResult<()> {
+ self.proxy
+ .tex_storage3d(target, levels, internalformat, width, height, depth);
+ Ok(())
+ }
+
+ pub(crate) fn tex_image3d_with_source(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ level: i32,
+ internalformat: i32,
+ width: i32,
+ height: i32,
+ depth: i32,
+ border: i32,
+ format: u32,
+ r#type: u32,
+ source: TexImageSource,
+ ) -> WebIdlResult<()> {
+ // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage3D.xhtml
+ // border: This value must be 0.
+ if border != 0 {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ }
+
+ let Some((frame, mut upload)) = self.read_texture_image_source(&source, format, r#type) else {
+ return Ok(());
+ };
+ upload.destination_size = Some((width, height));
+ self.proxy
+ .tex_image3d_from_bitmap(target, level, internalformat, depth, format, r#type, frame, upload);
+ Ok(())
+ }
+
+ pub(crate) fn tex_image3d(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ level: i32,
+ internalformat: i32,
+ width: i32,
+ height: i32,
+ depth: i32,
+ border: i32,
+ format: u32,
+ r#type: u32,
+ src_data: Option<ArrayBufferView>,
+ ) -> WebIdlResult<()> {
+ let Some(src_data) = src_data else {
+ self.proxy.tex_image3d_robust_angle(
+ target,
+ level,
+ internalformat,
+ width,
+ height,
+ depth,
+ border,
+ format,
+ r#type,
+ 0,
+ None,
+ );
+ return Ok(());
+ };
+
+ let Ok(bytes) = source_bytes(src_data.into(), 0, 0) else {
+ self.set_error(GL_INVALID_OPERATION);
+ return Ok(());
+ };
+ let buf_size = bytes.gl_size();
+ // SAFETY: Recording the command neither runs script nor allocates a cell.
+ unsafe {
+ self.upload_through_nullable_pointer(&bytes, |bytes| {
+ self.proxy.tex_image3d_robust_angle(
+ target,
+ level,
+ internalformat,
+ width,
+ height,
+ depth,
+ border,
+ format,
+ r#type,
+ buf_size,
+ bytes,
+ );
+ });
+ }
+ Ok(())
+ }
+
+ pub(crate) fn tex_image3d_with_offset(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ level: i32,
+ internalformat: i32,
+ width: i32,
+ height: i32,
+ depth: i32,
+ border: i32,
+ format: u32,
+ r#type: u32,
+ src_data: ArrayBufferView,
+ src_offset: u64,
+ ) -> WebIdlResult<()> {
+ let Ok(bytes) = source_bytes(src_data.into(), src_offset, 0) else {
+ self.set_error(GL_INVALID_OPERATION);
+ return Ok(());
+ };
+ let buf_size = bytes.gl_size();
+ // SAFETY: Recording the command neither runs script nor allocates a cell.
+ unsafe {
+ self.upload_through_nullable_pointer(&bytes, |bytes| {
+ self.proxy.tex_image3d_robust_angle(
+ target,
+ level,
+ internalformat,
+ width,
+ height,
+ depth,
+ border,
+ format,
+ r#type,
+ buf_size,
+ bytes,
+ );
+ });
+ }
+ Ok(())
+ }
+
+ pub(crate) fn tex_sub_image3d_with_source(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ level: i32,
+ xoffset: i32,
+ yoffset: i32,
+ zoffset: i32,
+ width: i32,
+ height: i32,
+ depth: i32,
+ format: u32,
+ r#type: u32,
+ source: TexImageSource,
+ ) -> WebIdlResult<()> {
+ let Some((frame, mut upload)) = self.read_texture_image_source(&source, format, r#type) else {
+ return Ok(());
+ };
+ upload.destination_size = Some((width, height));
+ self.proxy.tex_sub_image3d_from_bitmap(
+ target, level, xoffset, yoffset, zoffset, depth, format, r#type, frame, upload,
+ );
+ Ok(())
+ }
+
+ pub(crate) fn tex_sub_image3d(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ level: i32,
+ xoffset: i32,
+ yoffset: i32,
+ zoffset: i32,
+ width: i32,
+ height: i32,
+ depth: i32,
+ format: u32,
+ r#type: u32,
+ src_data: Option<ArrayBufferView>,
+ src_offset: u64,
+ ) -> WebIdlResult<()> {
+ let Some(src_data) = src_data else {
+ self.proxy.tex_sub_image3d_robust_angle(
+ target, level, xoffset, yoffset, zoffset, width, height, depth, format, r#type, 0, None,
+ );
+ return Ok(());
+ };
+
+ let Ok(bytes) = source_bytes(src_data.into(), src_offset, 0) else {
+ self.set_error(GL_INVALID_OPERATION);
+ return Ok(());
+ };
+ let buf_size = bytes.gl_size();
+ // SAFETY: Recording the command neither runs script nor allocates a cell.
+ unsafe {
+ self.upload_through_nullable_pointer(&bytes, |bytes| {
+ self.proxy.tex_sub_image3d_robust_angle(
+ target, level, xoffset, yoffset, zoffset, width, height, depth, format, r#type, buf_size, bytes,
+ );
+ });
+ }
+ Ok(())
+ }
+
+ pub(crate) fn compressed_tex_image3d(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ level: i32,
+ internalformat: u32,
+ width: i32,
+ height: i32,
+ depth: i32,
+ border: i32,
+ src_data: ArrayBufferView,
+ src_offset: u64,
+ src_length_override: u32,
+ ) -> WebIdlResult<()> {
+ if !self
+ .enabled_compressed_texture_formats
+ .borrow()
+ .contains(&internalformat)
+ {
+ self.set_error(GL_INVALID_ENUM);
+ return Ok(());
+ }
+
+ let Ok(bytes) = source_bytes(src_data.into(), src_offset, src_length_override) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let size = bytes.gl_size();
+ // SAFETY: Recording the command neither runs script nor allocates a cell.
+ unsafe {
+ self.upload(&bytes, |bytes| {
+ self.proxy.compressed_tex_image3d_robust_angle(
+ target,
+ level,
+ internalformat,
+ width,
+ height,
+ depth,
+ border,
+ size,
+ size,
+ bytes,
+ );
+ });
+ }
+ Ok(())
+ }
+
+ pub(crate) fn compressed_tex_sub_image3d(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ level: i32,
+ xoffset: i32,
+ yoffset: i32,
+ zoffset: i32,
+ width: i32,
+ height: i32,
+ depth: i32,
+ format: u32,
+ src_data: ArrayBufferView,
+ src_offset: u64,
+ src_length_override: u32,
+ ) -> WebIdlResult<()> {
+ if !self.enabled_compressed_texture_formats.borrow().contains(&format) {
+ self.set_error(GL_INVALID_ENUM);
+ return Ok(());
+ }
+
+ let Ok(bytes) = source_bytes(src_data.into(), src_offset, src_length_override) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let size = bytes.gl_size();
+ // SAFETY: Recording the command neither runs script nor allocates a cell.
+ unsafe {
+ self.upload(&bytes, |bytes| {
+ self.proxy.compressed_tex_sub_image3d_robust_angle(
+ target, level, xoffset, yoffset, zoffset, width, height, depth, format, size, size, bytes,
+ );
+ });
+ }
+ Ok(())
+ }
+
+ pub(crate) fn uniform1ui(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ v0: u32,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ self.proxy.uniform1ui(location_handle, v0);
+ Ok(())
+ }
+
+ pub(crate) fn uniform2ui(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ v0: u32,
+ v1: u32,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ self.proxy.uniform2ui(location_handle, v0, v1);
+ Ok(())
+ }
+
+ pub(crate) fn uniform3ui(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ v0: u32,
+ v1: u32,
+ v2: u32,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ self.proxy.uniform3ui(location_handle, v0, v1, v2);
+ Ok(())
+ }
+
+ pub(crate) fn uniform4ui(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ v0: u32,
+ v1: u32,
+ v2: u32,
+ v3: u32,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ self.proxy.uniform4ui(location_handle, v0, v1, v2, v3);
+ Ok(())
+ }
+
+ pub(crate) fn uniform1uiv(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ data: Uint32List,
+ src_offset: u64,
+ src_length: u32,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ let Ok(values) = list_bytes(&data, src_offset, src_length) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy
+ .uniform1uiv(location_handle, values.gl_count(), values.as_bytes());
+ Ok(())
+ }
+
+ pub(crate) fn uniform2uiv(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ data: Uint32List,
+ src_offset: u64,
+ src_length: u32,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ let Ok(values) = list_bytes(&data, src_offset, src_length) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Some(count) = values.gl_count_of_whole_groups_of(2) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy.uniform2uiv(location_handle, count, values.as_bytes());
+ Ok(())
+ }
+
+ pub(crate) fn uniform3uiv(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ data: Uint32List,
+ src_offset: u64,
+ src_length: u32,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ let Ok(values) = list_bytes(&data, src_offset, src_length) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Some(count) = values.gl_count_of_whole_groups_of(3) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy.uniform3uiv(location_handle, count, values.as_bytes());
+ Ok(())
+ }
+
+ pub(crate) fn uniform4uiv(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ data: Uint32List,
+ src_offset: u64,
+ src_length: u32,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ let Ok(values) = list_bytes(&data, src_offset, src_length) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Some(count) = values.gl_count_of_whole_groups_of(4) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy.uniform4uiv(location_handle, count, values.as_bytes());
+ Ok(())
+ }
+
+ pub(crate) fn uniform_matrix3x2fv(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ transpose: bool,
+ data: Float32List,
+ src_offset: u64,
+ src_length: u32,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ const MATRIX_SIZE: usize = 3 * 2;
+ let Ok(values) = list_bytes(&data, src_offset, src_length) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Some(count) = values.gl_count_of_whole_groups_of(MATRIX_SIZE) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy
+ .uniform_matrix3x2fv(location_handle, count, transpose, values.as_bytes());
+ Ok(())
+ }
+
+ pub(crate) fn uniform_matrix4x2fv(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ transpose: bool,
+ data: Float32List,
+ src_offset: u64,
+ src_length: u32,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ const MATRIX_SIZE: usize = 4 * 2;
+ let Ok(values) = list_bytes(&data, src_offset, src_length) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Some(count) = values.gl_count_of_whole_groups_of(MATRIX_SIZE) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy
+ .uniform_matrix4x2fv(location_handle, count, transpose, values.as_bytes());
+ Ok(())
+ }
+
+ pub(crate) fn uniform_matrix2x3fv(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ transpose: bool,
+ data: Float32List,
+ src_offset: u64,
+ src_length: u32,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ const MATRIX_SIZE: usize = 2 * 3;
+ let Ok(values) = list_bytes(&data, src_offset, src_length) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Some(count) = values.gl_count_of_whole_groups_of(MATRIX_SIZE) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy
+ .uniform_matrix2x3fv(location_handle, count, transpose, values.as_bytes());
+ Ok(())
+ }
+
+ pub(crate) fn uniform_matrix4x3fv(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ transpose: bool,
+ data: Float32List,
+ src_offset: u64,
+ src_length: u32,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ const MATRIX_SIZE: usize = 4 * 3;
+ let Ok(values) = list_bytes(&data, src_offset, src_length) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Some(count) = values.gl_count_of_whole_groups_of(MATRIX_SIZE) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy
+ .uniform_matrix4x3fv(location_handle, count, transpose, values.as_bytes());
+ Ok(())
+ }
+
+ pub(crate) fn uniform_matrix2x4fv(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ transpose: bool,
+ data: Float32List,
+ src_offset: u64,
+ src_length: u32,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ const MATRIX_SIZE: usize = 2 * 4;
+ let Ok(values) = list_bytes(&data, src_offset, src_length) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Some(count) = values.gl_count_of_whole_groups_of(MATRIX_SIZE) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy
+ .uniform_matrix2x4fv(location_handle, count, transpose, values.as_bytes());
+ Ok(())
+ }
+
+ pub(crate) fn uniform_matrix3x4fv(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ transpose: bool,
+ data: Float32List,
+ src_offset: u64,
+ src_length: u32,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ const MATRIX_SIZE: usize = 3 * 4;
+ let Ok(values) = list_bytes(&data, src_offset, src_length) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Some(count) = values.gl_count_of_whole_groups_of(MATRIX_SIZE) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy
+ .uniform_matrix3x4fv(location_handle, count, transpose, values.as_bytes());
+ Ok(())
+ }
+
+ pub(crate) fn vertex_attrib_i4i(
+ &self,
+ _: &mut CallContext,
+ index: u32,
+ x: i32,
+ y: i32,
+ z: i32,
+ w: i32,
+ ) -> WebIdlResult<()> {
+ self.proxy.vertex_attrib_i4i(index, x, y, z, w);
+ Ok(())
+ }
+
+ pub(crate) fn vertex_attrib_i4iv(&self, _: &mut CallContext, index: u32, values: Int32List) -> WebIdlResult<()> {
+ let Some(values) = copy_of_first_numbers(&values, 4) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy.vertex_attrib_i4iv(index, &values);
+ Ok(())
+ }
+
+ pub(crate) fn vertex_attrib_i4ui(
+ &self,
+ _: &mut CallContext,
+ index: u32,
+ x: u32,
+ y: u32,
+ z: u32,
+ w: u32,
+ ) -> WebIdlResult<()> {
+ self.proxy.vertex_attrib_i4ui(index, x, y, z, w);
+ Ok(())
+ }
+
+ pub(crate) fn vertex_attrib_i4uiv(&self, _: &mut CallContext, index: u32, values: Uint32List) -> WebIdlResult<()> {
+ let Some(values) = copy_of_first_numbers(&values, 4) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy.vertex_attrib_i4uiv(index, &values);
+ Ok(())
+ }
+
+ pub(crate) fn vertex_attrib_i_pointer(
+ &self,
+ _: &mut CallContext,
+ index: u32,
+ size: i32,
+ r#type: u32,
+ stride: i32,
+ offset: i64,
+ ) -> WebIdlResult<()> {
+ self.proxy.vertex_attrib_i_pointer(index, size, r#type, stride, offset);
+ Ok(())
+ }
+
+ pub(crate) fn vertex_attrib_divisor(&self, _: &mut CallContext, index: u32, divisor: u32) -> WebIdlResult<()> {
+ self.proxy.vertex_attrib_divisor(index, divisor);
+ Ok(())
+ }
+
+ pub(crate) fn draw_arrays_instanced(
+ &self,
+ _: &mut CallContext,
+ mode: u32,
+ first: i32,
+ count: i32,
+ instance_count: i32,
+ ) -> WebIdlResult<()> {
+ self.did_update_canvas_content();
+ self.proxy.draw_arrays_instanced(mode, first, count, instance_count);
+ Ok(())
+ }
+
+ pub(crate) fn draw_elements_instanced(
+ &self,
+ _: &mut CallContext,
+ mode: u32,
+ count: i32,
+ r#type: u32,
+ offset: i64,
+ instance_count: i32,
+ ) -> WebIdlResult<()> {
+ self.proxy
+ .draw_elements_instanced(mode, count, r#type, offset, instance_count);
+ self.did_update_canvas_content();
+ Ok(())
+ }
+
+ pub(crate) fn draw_range_elements(
+ &self,
+ _: &mut CallContext,
+ mode: u32,
+ start: u32,
+ end: u32,
+ count: i32,
+ r#type: u32,
+ offset: i64,
+ ) -> WebIdlResult<()> {
+ self.did_update_canvas_content();
+ self.proxy.draw_range_elements(mode, start, end, count, r#type, offset);
+ Ok(())
+ }
+
+ pub(crate) fn draw_buffers(&self, _: &mut CallContext, buffers: Vec<u32>) -> WebIdlResult<()> {
+ let Ok(buffer_count) = i32::try_from(buffers.len()) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy.draw_buffers(buffer_count, bytes_of(&buffers));
+ Ok(())
+ }
+
+ pub(crate) fn clear_bufferfv(
+ &self,
+ _: &mut CallContext,
+ buffer: u32,
+ drawbuffer: i32,
+ values: Float32List,
+ src_offset: u64,
+ ) -> WebIdlResult<()> {
+ let Ok(values) = numbers_from_offset(&values, src_offset) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Some(clear_value_count) = clear_value_count(buffer) else {
+ self.set_error(GL_INVALID_ENUM);
+ return Ok(());
+ };
+ let Some(values) = values.copy_of_first(clear_value_count) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy.clear_bufferfv(buffer, drawbuffer, &values);
+ self.did_update_canvas_content();
+ Ok(())
+ }
+
+ pub(crate) fn clear_bufferiv(
+ &self,
+ _: &mut CallContext,
+ buffer: u32,
+ drawbuffer: i32,
+ values: Int32List,
+ src_offset: u64,
+ ) -> WebIdlResult<()> {
+ let Ok(values) = numbers_from_offset(&values, src_offset) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Some(clear_value_count) = clear_value_count(buffer) else {
+ self.set_error(GL_INVALID_ENUM);
+ return Ok(());
+ };
+ let Some(values) = values.copy_of_first(clear_value_count) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy.clear_bufferiv(buffer, drawbuffer, &values);
+ self.did_update_canvas_content();
+ Ok(())
+ }
+
+ pub(crate) fn clear_bufferuiv(
+ &self,
+ _: &mut CallContext,
+ buffer: u32,
+ drawbuffer: i32,
+ values: Uint32List,
+ src_offset: u64,
+ ) -> WebIdlResult<()> {
+ let Ok(values) = numbers_from_offset(&values, src_offset) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Some(clear_value_count) = clear_value_count(buffer) else {
+ self.set_error(GL_INVALID_ENUM);
+ return Ok(());
+ };
+ let Some(values) = values.copy_of_first(clear_value_count) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy.clear_bufferuiv(buffer, drawbuffer, &values);
+ self.did_update_canvas_content();
+ Ok(())
+ }
+
+ pub(crate) fn clear_bufferfi(
+ &self,
+ _: &mut CallContext,
+ buffer: u32,
+ drawbuffer: i32,
+ depth: f32,
+ stencil: i32,
+ ) -> WebIdlResult<()> {
+ self.did_update_canvas_content();
+ self.proxy.clear_bufferfi(buffer, drawbuffer, depth, stencil);
+ Ok(())
+ }
+
+ pub(crate) fn create_query(&self, cx: &mut CallContext) -> WebIdlResult<Ref<WebGLQuery>> {
+ let mut handle = [0];
+ self.proxy.gen_queries(&mut handle);
+ Ok(WebGLQuery::create(cx.vm(), self, handle[0]))
+ }
+
+ pub(crate) fn delete_query(&self, _: &mut CallContext, query: Option<Ref<WebGLQuery>>) -> WebIdlResult<()> {
+ let Some(query) = query else {
+ return Ok(());
+ };
+ let Some(handle) = self.handle_for_deletion_of(query) else {
+ return Ok(());
+ };
+ self.proxy.delete_queries(1, &[handle]);
+ Ok(())
+ }
+
+ fn active_query_binding(&self, target: u32) -> Option<&Binding<WebGLQuery>> {
+ match target {
+ GL_ANY_SAMPLES_PASSED => Some(&self.any_samples_passed),
+ GL_ANY_SAMPLES_PASSED_CONSERVATIVE => Some(&self.any_samples_passed_conservative),
+ GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN => Some(&self.transform_feedback_primitives_written),
+ _ => None,
+ }
+ }
+
+ pub(crate) fn begin_query(&self, _: &mut CallContext, target: u32, query: Ref<WebGLQuery>) -> WebIdlResult<()> {
+ let Some(query_handle) = self.handle_of(query) else {
+ return Ok(());
+ };
+ if let Some(active_query_binding) = self.active_query_binding(target) {
+ active_query_binding.set(Some(query));
+ }
+ self.proxy.begin_query(target, query_handle);
+ Ok(())
+ }
+
+ pub(crate) fn end_query(&self, _: &mut CallContext, target: u32) -> WebIdlResult<()> {
+ if let Some(active_query_binding) = self.active_query_binding(target) {
+ active_query_binding.set(None);
+ }
+ self.proxy.end_query(target);
+ Ok(())
+ }
+
+ pub(crate) fn get_query(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ pname: u32,
+ ) -> WebIdlResult<Option<Ref<WebGLQuery>>> {
+ if pname != GL_CURRENT_QUERY {
+ self.set_error(GL_INVALID_ENUM);
+ return Ok(None);
+ }
+ let Some(active_query_binding) = self.active_query_binding(target) else {
+ self.set_error(GL_INVALID_ENUM);
+ return Ok(None);
+ };
+ Ok(active_query_binding.get())
+ }
+
+ pub(crate) fn get_query_parameter(
+ &self,
+ _: &mut CallContext,
+ query: Ref<WebGLQuery>,
+ pname: u32,
+ ) -> WebIdlResult<Value> {
+ let Some(query_handle) = self.handle_of(query) else {
+ return Ok(Value::NULL);
+ };
+ let mut result = [0];
+ self.proxy
+ .get_query_objectuiv_robust_angle(query_handle, pname, 1, &mut result);
+ let [result] = result;
+ Ok(match pname {
+ GL_QUERY_RESULT => Value::from_f64(f64::from(result)),
+ GL_QUERY_RESULT_AVAILABLE => Value::from_bool(result == GL_TRUE),
+ _ => Value::NULL,
+ })
+ }
+
+ pub(crate) fn create_sampler(&self, cx: &mut CallContext) -> WebIdlResult<Ref<WebGLSampler>> {
+ let mut handle = [0];
+ self.proxy.gen_samplers(&mut handle);
+ Ok(WebGLSampler::create(cx.vm(), self, handle[0]))
+ }
+
+ pub(crate) fn delete_sampler(&self, _: &mut CallContext, sampler: Option<Ref<WebGLSampler>>) -> WebIdlResult<()> {
+ let Some(sampler) = sampler else {
+ return Ok(());
+ };
+ let Some(handle) = self.handle_for_deletion_of(sampler) else {
+ return Ok(());
+ };
+ self.proxy.delete_samplers(1, &[handle]);
+ Ok(())
+ }
+
+ pub(crate) fn bind_sampler(
+ &self,
+ _: &mut CallContext,
+ unit: u32,
+ sampler: Option<Ref<WebGLSampler>>,
+ ) -> WebIdlResult<()> {
+ let mut sampler_handle = 0;
+ if let Some(sampler) = sampler {
+ let Some(handle) = self.handle_of(sampler) else {
+ return Ok(());
+ };
+ sampler_handle = handle;
+ }
+ self.proxy.bind_sampler(unit, sampler_handle);
+ Ok(())
+ }
+
+ fn is_sampler_parameter_name(&self, pname: u32) -> bool {
+ match pname {
+ GL_TEXTURE_COMPARE_FUNC
+ | GL_TEXTURE_COMPARE_MODE
+ | GL_TEXTURE_MAG_FILTER
+ | GL_TEXTURE_MAX_LOD
+ | GL_TEXTURE_MIN_FILTER
+ | GL_TEXTURE_MIN_LOD
+ | GL_TEXTURE_WRAP_R
+ | GL_TEXTURE_WRAP_S
+ | GL_TEXTURE_WRAP_T => true,
+ GL_TEXTURE_MAX_ANISOTROPY_EXT => self.extension_enabled("EXT_texture_filter_anisotropic"),
+ _ => false,
+ }
+ }
+
+ pub(crate) fn sampler_parameteri(
+ &self,
+ _: &mut CallContext,
+ sampler: Ref<WebGLSampler>,
+ pname: u32,
+ param: i32,
+ ) -> WebIdlResult<()> {
+ let Some(sampler_handle) = self.handle_of(sampler) else {
+ return Ok(());
+ };
+ if !self.is_sampler_parameter_name(pname) {
+ self.set_error(GL_INVALID_ENUM);
+ return Ok(());
+ }
+ self.proxy.sampler_parameteri(sampler_handle, pname, param);
+ Ok(())
+ }
+
+ pub(crate) fn sampler_parameterf(
+ &self,
+ _: &mut CallContext,
+ sampler: Ref<WebGLSampler>,
+ pname: u32,
+ param: f32,
+ ) -> WebIdlResult<()> {
+ let Some(sampler_handle) = self.handle_of(sampler) else {
+ return Ok(());
+ };
+ if !self.is_sampler_parameter_name(pname) {
+ self.set_error(GL_INVALID_ENUM);
+ return Ok(());
+ }
+ self.proxy.sampler_parameterf(sampler_handle, pname, param);
+ Ok(())
+ }
+
+ pub(crate) fn fence_sync(
+ &self,
+ cx: &mut CallContext,
+ condition: u32,
+ flags: u32,
+ ) -> WebIdlResult<Option<Ref<WebGLSync>>> {
+ let sync_handle = self.proxy.fence_sync(condition, flags);
+ Ok(Some(WebGLSync::create(cx.vm(), self, sync_handle)))
+ }
+
+ pub(crate) fn delete_sync(&self, _: &mut CallContext, sync: Option<Ref<WebGLSync>>) -> WebIdlResult<()> {
+ let Some(sync) = sync else {
+ return Ok(());
+ };
+ let Ok(sync_handle) = sync.sync_handle_for_deletion(self) else {
+ self.set_error(GL_INVALID_OPERATION);
+ return Ok(());
+ };
+ let Some(sync_handle) = sync_handle else {
+ return Ok(());
+ };
+ self.proxy.delete_sync(sync_handle);
+ Ok(())
+ }
+
+ pub(crate) fn client_wait_sync(
+ &self,
+ _: &mut CallContext,
+ sync: Ref<WebGLSync>,
+ flags: u32,
+ timeout: u64,
+ ) -> WebIdlResult<u32> {
+ let Ok(sync_handle) = sync.sync_handle(self) else {
+ self.set_error(GL_INVALID_OPERATION);
+ return Ok(GL_WAIT_FAILED);
+ };
+ Ok(self.proxy.client_wait_sync(sync_handle, flags, timeout))
+ }
+
+ pub(crate) fn wait_sync(
+ &self,
+ _: &mut CallContext,
+ sync: Ref<WebGLSync>,
+ flags: u32,
+ timeout: i64,
+ ) -> WebIdlResult<()> {
+ let Ok(sync_handle) = sync.sync_handle(self) else {
+ self.set_error(GL_INVALID_OPERATION);
+ return Ok(());
+ };
+ // NB: GL has an unsigned timeout, whose largest value is what TIMEOUT_IGNORED, which is -1 here, stands for.
+ self.proxy.wait_sync(sync_handle, flags, timeout.cast_unsigned());
+ Ok(())
+ }
+
+ pub(crate) fn get_sync_parameter(
+ &self,
+ _: &mut CallContext,
+ sync: Ref<WebGLSync>,
+ pname: u32,
+ ) -> WebIdlResult<Value> {
+ let Ok(sync_handle) = sync.sync_handle(self) else {
+ self.set_error(GL_INVALID_OPERATION);
+ return Ok(Value::NULL);
+ };
+ let mut result = [0];
+ self.proxy.get_synciv(sync_handle, pname, 1, &mut result);
+ let [result] = result;
+ Ok(Value::from_i32(result))
+ }
+
+ pub(crate) fn create_transform_feedback(&self, cx: &mut CallContext) -> WebIdlResult<Ref<WebGLTransformFeedback>> {
+ let mut handle = [0];
+ self.proxy.gen_transform_feedbacks(&mut handle);
+ Ok(WebGLTransformFeedback::create(cx.vm(), self, handle[0]))
+ }
+
+ pub(crate) fn delete_transform_feedback(
+ &self,
+ _: &mut CallContext,
+ tf: Option<Ref<WebGLTransformFeedback>>,
+ ) -> WebIdlResult<()> {
+ let Some(transform_feedback) = tf else {
+ return Ok(());
+ };
+ let Some(handle) = self.handle_for_deletion_of(transform_feedback) else {
+ return Ok(());
+ };
+ self.proxy.delete_transform_feedbacks(1, &[handle]);
+ Ok(())
+ }
+
+ pub(crate) fn bind_transform_feedback(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ tf: Option<Ref<WebGLTransformFeedback>>,
+ ) -> WebIdlResult<()> {
+ let mut transform_feedback_handle = 0;
+ if let Some(transform_feedback) = tf {
+ let Some(handle) = self.handle_of(transform_feedback) else {
+ return Ok(());
+ };
+ transform_feedback_handle = handle;
+ }
+ self.proxy.bind_transform_feedback(target, transform_feedback_handle);
+ Ok(())
+ }
+
+ pub(crate) fn begin_transform_feedback(&self, _: &mut CallContext, primitive_mode: u32) -> WebIdlResult<()> {
+ self.proxy.begin_transform_feedback(primitive_mode);
+ Ok(())
+ }
+
+ pub(crate) fn end_transform_feedback(&self, _: &mut CallContext) -> WebIdlResult<()> {
+ self.proxy.end_transform_feedback();
+ Ok(())
+ }
+
+ pub(crate) fn transform_feedback_varyings(
+ &self,
+ _: &mut CallContext,
+ program: Ref<WebGLProgram>,
+ varyings: Vec<Utf16String>,
+ buffer_mode: u32,
+ ) -> WebIdlResult<()> {
+ let Some(program_handle) = self.handle_of(program) else {
+ return Ok(());
+ };
+ let varyings: Vec<Vec<u8>> = varyings.iter().map(utf8_bytes).collect();
+ let varyings: Vec<&[u8]> = varyings.iter().map(Vec::as_slice).collect();
+ self.proxy
+ .transform_feedback_varyings(program_handle, &varyings, buffer_mode);
+ Ok(())
+ }
+
+ pub(crate) fn pause_transform_feedback(&self, _: &mut CallContext) -> WebIdlResult<()> {
+ self.proxy.pause_transform_feedback();
+ Ok(())
+ }
+
+ pub(crate) fn resume_transform_feedback(&self, _: &mut CallContext) -> WebIdlResult<()> {
+ self.proxy.resume_transform_feedback();
+ Ok(())
+ }
+
+ fn buffer_handle_for_indexed_binding(&self, target: u32, buffer: Option<Ref<WebGLBuffer>>) -> Option<u32> {
+ let Some(buffer) = buffer else {
+ return Some(0);
+ };
+ let buffer_handle = self.handle_of(buffer)?;
+ if !buffer.kind_allows_binding_to(target) {
+ self.set_error(GL_INVALID_OPERATION);
+ return None;
+ }
+
+ // NB: GL reports a target that these do not bind buffers to, and binds nothing to it.
+ if let Some(kind_of_buffers_at_target) = BufferKind::of_buffers_at_indexed_target(target) {
+ buffer.was_bound_as(kind_of_buffers_at_target);
+ }
+ Some(buffer_handle)
+ }
+
+ pub(crate) fn bind_buffer_base(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ index: u32,
+ buffer: Option<Ref<WebGLBuffer>>,
+ ) -> WebIdlResult<()> {
+ let Some(buffer_handle) = self.buffer_handle_for_indexed_binding(target, buffer) else {
+ return Ok(());
+ };
+ self.proxy.bind_buffer_base(target, index, buffer_handle);
+ Ok(())
+ }
+
+ pub(crate) fn bind_buffer_range(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ index: u32,
+ buffer: Option<Ref<WebGLBuffer>>,
+ offset: i64,
+ size: i64,
+ ) -> WebIdlResult<()> {
+ let Some(buffer_handle) = self.buffer_handle_for_indexed_binding(target, buffer) else {
+ return Ok(());
+ };
+ self.proxy.bind_buffer_range(target, index, buffer_handle, offset, size);
+ Ok(())
+ }
+
+ pub(crate) fn get_uniform_indices(
+ &self,
+ _: &mut CallContext,
+ program: Ref<WebGLProgram>,
+ uniform_names: Vec<Utf16String>,
+ ) -> WebIdlResult<Option<Vec<u32>>> {
+ let Some(program_handle) = self.handle_of(program) else {
+ return Ok(None);
+ };
+ let uniform_names: Vec<Vec<u8>> = uniform_names.iter().map(utf8_bytes).collect();
+ let uniform_names: Vec<&[u8]> = uniform_names.iter().map(Vec::as_slice).collect();
+ let mut uniform_indices = vec![0; uniform_names.len()];
+ self.proxy
+ .get_uniform_indices(program_handle, &uniform_names, &mut uniform_indices);
+ Ok(Some(uniform_indices))
+ }
+
+ pub(crate) fn get_active_uniforms(
+ &self,
+ cx: &mut CallContext,
+ program: Ref<WebGLProgram>,
+ uniform_indices: Vec<u32>,
+ pname: u32,
+ ) -> WebIdlResult<Value> {
+ let Some(program_handle) = self.handle_of(program) else {
+ return Ok(Value::NULL);
+ };
+ let Ok(uniform_count) = i32::try_from(uniform_indices.len()) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(Value::NULL);
+ };
+ let mut params = vec![0; uniform_indices.len()];
+ self.proxy.get_active_uniformsiv(
+ program_handle,
+ uniform_count,
+ bytes_of(&uniform_indices),
+ pname,
+ &mut params,
+ );
+
+ let mut params_as_values = Vec::with_capacity(params.len());
+ for param in params {
+ params_as_values.push(match pname {
+ GL_UNIFORM_TYPE | GL_UNIFORM_SIZE => Value::from_f64(f64::from(param.cast_unsigned())),
+ GL_UNIFORM_BLOCK_INDEX | GL_UNIFORM_OFFSET | GL_UNIFORM_ARRAY_STRIDE | GL_UNIFORM_MATRIX_STRIDE => {
+ Value::from_i32(param)
+ }
+ GL_UNIFORM_IS_ROW_MAJOR => Value::from_bool(param.cast_unsigned() == GL_TRUE),
+ _ => {
+ self.set_error(GL_INVALID_ENUM);
+ return Ok(Value::NULL);
+ }
+ });
+ }
+ Ok(Value::from_object(Array::create_from(
+ cx.vm(),
+ self.realm(),
+ &params_as_values,
+ )))
+ }
+
+ pub(crate) fn get_uniform_block_index(
+ &self,
+ _: &mut CallContext,
+ program: Ref<WebGLProgram>,
+ uniform_block_name: Utf16String,
+ ) -> WebIdlResult<u32> {
+ let Some(program_handle) = self.handle_of(program) else {
+ return Ok(GL_INVALID_INDEX);
+ };
+ Ok(self
+ .proxy
+ .get_uniform_block_index(program_handle, &utf8_bytes(&uniform_block_name)))
+ }
+
+ pub(crate) fn get_active_uniform_block_parameter(
+ &self,
+ cx: &mut CallContext,
+ program: Ref<WebGLProgram>,
+ uniform_block_index: u32,
+ pname: u32,
+ ) -> WebIdlResult<Value> {
+ let Some(program_handle) = self.handle_of(program) else {
+ return Ok(Value::NULL);
+ };
+ match pname {
+ GL_UNIFORM_BLOCK_BINDING | GL_UNIFORM_BLOCK_DATA_SIZE | GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS => {
+ let mut result = [0];
+ self.proxy.get_active_uniform_blockiv_robust_angle(
+ program_handle,
+ uniform_block_index,
+ pname,
+ 1,
+ &mut result,
+ );
+ let [result] = result;
+ Ok(Value::from_i32(result))
+ }
+ GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES => {
+ let mut num_active_uniforms = [0];
+ self.proxy.get_active_uniform_blockiv_robust_angle(
+ program_handle,
+ uniform_block_index,
+ GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS,
+ 1,
+ &mut num_active_uniforms,
+ );
+ let [num_active_uniforms] = num_active_uniforms;
+ let mut active_uniform_indices = vec![0; element_count_from_gl(num_active_uniforms)];
+ self.proxy.get_active_uniform_blockiv_robust_angle(
+ program_handle,
+ uniform_block_index,
+ GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES,
+ num_active_uniforms,
+ &mut active_uniform_indices,
+ );
+ let active_uniform_indices: Vec<u32> =
+ active_uniform_indices.into_iter().map(i32::cast_unsigned).collect();
+ Ok(self.uint32_array(cx, &active_uniform_indices))
+ }
+ GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER | GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER => {
+ let mut result = [0];
+ self.proxy.get_active_uniform_blockiv_robust_angle(
+ program_handle,
+ uniform_block_index,
+ pname,
+ 1,
+ &mut result,
+ );
+ let [result] = result;
+ Ok(Value::from_bool(result.cast_unsigned() == GL_TRUE))
+ }
+ _ => {
+ self.set_error(GL_INVALID_ENUM);
+ Ok(Value::NULL)
+ }
+ }
+ }
+
+ pub(crate) fn get_active_uniform_block_name(
+ &self,
+ _: &mut CallContext,
+ program: Ref<WebGLProgram>,
+ uniform_block_index: u32,
+ ) -> WebIdlResult<Option<Utf16String>> {
+ let Some(program_handle) = self.handle_of(program) else {
+ return Ok(None);
+ };
+ let mut uniform_block_name_length = [0];
+ self.proxy.get_active_uniform_blockiv_robust_angle(
+ program_handle,
+ uniform_block_index,
+ GL_UNIFORM_BLOCK_NAME_LENGTH,
+ 1,
+ &mut uniform_block_name_length,
+ );
+ let [uniform_block_name_length] = uniform_block_name_length;
+ let mut uniform_block_name = vec![0; element_count_from_gl(uniform_block_name_length)];
+ if uniform_block_name.is_empty() {
+ return Ok(Some(Utf16String::from_ascii(b"")));
+ }
+ self.proxy.get_active_uniform_block_name(
+ program_handle,
+ uniform_block_index,
+ uniform_block_name_length,
+ &mut uniform_block_name,
+ );
+ let length_without_nul = uniform_block_name.len() - 1;
+ Ok(Some(utf16_string_from_gl_string(
+ &uniform_block_name[..length_without_nul],
+ )))
+ }
+
+ pub(crate) fn uniform_block_binding(
+ &self,
+ _: &mut CallContext,
+ program: Ref<WebGLProgram>,
+ uniform_block_index: u32,
+ uniform_block_binding: u32,
+ ) -> WebIdlResult<()> {
+ let Some(program_handle) = self.handle_of(program) else {
+ return Ok(());
+ };
+ self.proxy
+ .uniform_block_binding(program_handle, uniform_block_index, uniform_block_binding);
+ Ok(())
+ }
+
+ pub(crate) fn create_vertex_array(&self, cx: &mut CallContext) -> WebIdlResult<Ref<WebGLVertexArrayObject>> {
+ let mut handle = [0];
+ self.proxy.gen_vertex_arrays(&mut handle);
+ Ok(WebGLVertexArrayObject::create(cx.vm(), self, handle[0]))
+ }
+
+ pub(crate) fn delete_vertex_array(
+ &self,
+ _: &mut CallContext,
+ vertex_array: Option<Ref<WebGLVertexArrayObject>>,
+ ) -> WebIdlResult<()> {
+ let Some(vertex_array) = vertex_array else {
+ return Ok(());
+ };
+ let Some(handle) = self.handle_for_deletion_of(vertex_array) else {
+ return Ok(());
+ };
+ self.proxy.delete_vertex_arrays(1, &[handle]);
+ let is_current_vertex_array = matches!(
+ self.current_vertex_array.get(),
+ Some(VertexArrayBinding::WebGL2(current_vertex_array))
+ if current_vertex_array.as_ptr() == vertex_array.as_ptr()
+ );
+ if is_current_vertex_array {
+ self.current_vertex_array.set(None);
+ }
+ Ok(())
+ }
+
+ pub(crate) fn is_vertex_array(
+ &self,
+ _: &mut CallContext,
+ vertex_array: Option<Ref<WebGLVertexArrayObject>>,
+ ) -> WebIdlResult<bool> {
+ let Some(vertex_array) = vertex_array else {
+ return Ok(false);
+ };
+ let Some(handle) = self.handle_for_query_of(vertex_array) else {
+ return Ok(false);
+ };
+ Ok(self.proxy.is_vertex_array(handle))
+ }
+
+ pub(crate) fn bind_vertex_array(
+ &self,
+ _: &mut CallContext,
+ array: Option<Ref<WebGLVertexArrayObject>>,
+ ) -> WebIdlResult<()> {
+ let mut array_handle = 0;
+ if let Some(array) = array {
+ let Some(handle) = self.handle_of(array) else {
+ return Ok(());
+ };
+ array_handle = handle;
+ }
+ self.proxy.bind_vertex_array(array_handle);
+ self.current_vertex_array.set(array.map(VertexArrayBinding::WebGL2));
+ Ok(())
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl2_rendering_context_overloads.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl2_rendering_context_overloads.rs
new file mode 100644
index 00000000000..3bf839d98e8
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl2_rendering_context_overloads.rs
@@ -0,0 +1,854 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://registry.khronos.org/webgl/specs/latest/2.0/#3.7
+//!
+//! The operations of a WebGL 2 context that it has more overloads of than a WebGL 1 context.
+
+use super::buffer_source::{destination_bytes, list_bytes, source_bytes, write_checked};
+use super::canvas::is_valid_2d_pixel_unpack_state;
+use super::constants::{GL_INVALID_ENUM, GL_INVALID_OPERATION, GL_INVALID_VALUE, GL_OUT_OF_MEMORY};
+use super::state::{RenderingContext, WebGL2};
+use super::types::Float32List;
+use super::web_gl_rendering_context_overloads::{Int32List, TexImageSource};
+use super::web_gl_uniform_location::WebGLUniformLocation;
+use crate::bindings::conversions::{ArrayBufferView, BufferSource};
+use crate::bindings::interface::Ref;
+use crate::bindings::{CallContext, WebIdlResult};
+
+#[expect(
+ clippy::too_many_arguments,
+ reason = "the operations have the arguments of the GL functions"
+)]
+impl RenderingContext<WebGL2> {
+ pub(crate) fn buffer_data_with_size(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ size: i64,
+ usage: u32,
+ ) -> WebIdlResult<()> {
+ self.proxy.buffer_data(target, size, None, usage);
+ Ok(())
+ }
+
+ pub(crate) fn buffer_data(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ src_data: Option<BufferSource>,
+ usage: u32,
+ ) -> WebIdlResult<()> {
+ // https://registry.khronos.org/webgl/specs/latest/1.0/#5.14.5
+ // If the passed data is null then an INVALID_VALUE error is generated.
+ let Some(src_data) = src_data else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Ok(bytes) = source_bytes(src_data, 0, 0) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let size = i64::from(bytes.gl_size());
+ // SAFETY: Recording the command neither runs script nor allocates a cell.
+ unsafe {
+ self.upload_through_nullable_pointer(&bytes, |bytes| {
+ self.proxy.buffer_data(target, size, bytes, usage);
+ });
+ }
+ Ok(())
+ }
+
+ pub(crate) fn buffer_data_with_offset(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ src_data: ArrayBufferView,
+ usage: u32,
+ src_offset: u64,
+ length: u32,
+ ) -> WebIdlResult<()> {
+ let Ok(bytes) = source_bytes(src_data.into(), src_offset, length) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let size = i64::from(bytes.gl_size());
+ // SAFETY: Recording the command neither runs script nor allocates a cell.
+ unsafe {
+ self.upload_through_nullable_pointer(&bytes, |bytes| {
+ self.proxy.buffer_data(target, size, bytes, usage);
+ });
+ }
+ Ok(())
+ }
+
+ pub(crate) fn buffer_sub_data(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ dst_byte_offset: i64,
+ src_data: BufferSource,
+ ) -> WebIdlResult<()> {
+ let Ok(bytes) = source_bytes(src_data, 0, 0) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let size = i64::from(bytes.gl_size());
+ // SAFETY: Recording the command neither runs script nor allocates a cell.
+ unsafe {
+ self.upload(&bytes, |bytes| {
+ self.proxy.buffer_sub_data(target, dst_byte_offset, size, bytes);
+ });
+ }
+ Ok(())
+ }
+
+ pub(crate) fn buffer_sub_data_with_offset(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ dst_byte_offset: i64,
+ src_data: ArrayBufferView,
+ src_offset: u64,
+ length: u32,
+ ) -> WebIdlResult<()> {
+ let Ok(bytes) = source_bytes(src_data.into(), src_offset, length) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let size = i64::from(bytes.gl_size());
+ // SAFETY: Recording the command neither runs script nor allocates a cell.
+ unsafe {
+ self.upload(&bytes, |bytes| {
+ self.proxy.buffer_sub_data(target, dst_byte_offset, size, bytes);
+ });
+ }
+ Ok(())
+ }
+
+ pub(crate) fn tex_image2d(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ level: i32,
+ internalformat: i32,
+ width: i32,
+ height: i32,
+ border: i32,
+ format: u32,
+ r#type: u32,
+ pixels: Option<ArrayBufferView>,
+ ) -> WebIdlResult<()> {
+ let Some(pixels) = pixels else {
+ self.proxy.tex_image2d_robust_angle(
+ target,
+ level,
+ internalformat,
+ width,
+ height,
+ border,
+ format,
+ r#type,
+ 0,
+ None,
+ );
+ return Ok(());
+ };
+
+ let Ok(texture_data) = self.texture_data_for_2d_upload(pixels, 0, width, height, format, r#type) else {
+ self.set_error(GL_INVALID_OPERATION);
+ return Ok(());
+ };
+ let buf_size = texture_data.gl_size();
+ // SAFETY: Recording the command neither runs script nor allocates a cell.
+ unsafe {
+ self.upload_through_nullable_pointer(&texture_data, |texture_data| {
+ self.proxy.tex_image2d_robust_angle(
+ target,
+ level,
+ internalformat,
+ width,
+ height,
+ border,
+ format,
+ r#type,
+ buf_size,
+ texture_data,
+ );
+ });
+ }
+ Ok(())
+ }
+
+ pub(crate) fn tex_image2d_with_source(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ level: i32,
+ internalformat: i32,
+ format: u32,
+ r#type: u32,
+ source: TexImageSource,
+ ) -> WebIdlResult<()> {
+ let Some((frame, upload)) = self.read_texture_image_source(&source, format, r#type) else {
+ return Ok(());
+ };
+ self.proxy
+ .tex_image2d_from_bitmap(target, level, internalformat, format, r#type, frame, upload);
+ Ok(())
+ }
+
+ pub(crate) fn tex_image2d_with_size_and_source(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ level: i32,
+ internalformat: i32,
+ width: i32,
+ height: i32,
+ border: i32,
+ format: u32,
+ r#type: u32,
+ source: TexImageSource,
+ ) -> WebIdlResult<()> {
+ // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
+ // border: This value must be 0.
+ if border != 0 {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ }
+
+ let Some((frame, mut upload)) = self.read_texture_image_source(&source, format, r#type) else {
+ return Ok(());
+ };
+ upload.destination_size = Some((width, height));
+ self.proxy
+ .tex_image2d_from_bitmap(target, level, internalformat, format, r#type, frame, upload);
+ Ok(())
+ }
+
+ pub(crate) fn tex_image2d_with_offset(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ level: i32,
+ internalformat: i32,
+ width: i32,
+ height: i32,
+ border: i32,
+ format: u32,
+ r#type: u32,
+ src_data: ArrayBufferView,
+ src_offset: u64,
+ ) -> WebIdlResult<()> {
+ let Ok(texture_data) = self.texture_data_for_2d_upload(src_data, src_offset, width, height, format, r#type)
+ else {
+ self.set_error(GL_INVALID_OPERATION);
+ return Ok(());
+ };
+ let buf_size = texture_data.gl_size();
+ // SAFETY: Recording the command neither runs script nor allocates a cell.
+ unsafe {
+ self.upload_through_nullable_pointer(&texture_data, |texture_data| {
+ self.proxy.tex_image2d_robust_angle(
+ target,
+ level,
+ internalformat,
+ width,
+ height,
+ border,
+ format,
+ r#type,
+ buf_size,
+ texture_data,
+ );
+ });
+ }
+ Ok(())
+ }
+
+ pub(crate) fn tex_sub_image2d(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ level: i32,
+ xoffset: i32,
+ yoffset: i32,
+ width: i32,
+ height: i32,
+ format: u32,
+ r#type: u32,
+ pixels: Option<ArrayBufferView>,
+ ) -> WebIdlResult<()> {
+ let Some(pixels) = pixels else {
+ if !is_valid_2d_pixel_unpack_state(width, &self.unpack_state.get()) {
+ self.set_error(GL_INVALID_OPERATION);
+ return Ok(());
+ }
+ self.proxy
+ .tex_sub_image2d_robust_angle(target, level, xoffset, yoffset, width, height, format, r#type, 0, None);
+ return Ok(());
+ };
+
+ let Ok(texture_data) = self.texture_data_for_2d_upload(pixels, 0, width, height, format, r#type) else {
+ self.set_error(GL_INVALID_OPERATION);
+ return Ok(());
+ };
+ let buf_size = texture_data.gl_size();
+ // SAFETY: Recording the command neither runs script nor allocates a cell.
+ unsafe {
+ self.upload_through_nullable_pointer(&texture_data, |texture_data| {
+ self.proxy.tex_sub_image2d_robust_angle(
+ target,
+ level,
+ xoffset,
+ yoffset,
+ width,
+ height,
+ format,
+ r#type,
+ buf_size,
+ texture_data,
+ );
+ });
+ }
+ Ok(())
+ }
+
+ pub(crate) fn tex_sub_image2d_with_source(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ level: i32,
+ xoffset: i32,
+ yoffset: i32,
+ format: u32,
+ r#type: u32,
+ source: TexImageSource,
+ ) -> WebIdlResult<()> {
+ let Some((frame, upload)) = self.read_texture_image_source(&source, format, r#type) else {
+ return Ok(());
+ };
+ self.proxy
+ .tex_sub_image2d_from_bitmap(target, level, xoffset, yoffset, format, r#type, frame, upload);
+ Ok(())
+ }
+
+ pub(crate) fn tex_sub_image2d_with_size_and_source(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ level: i32,
+ xoffset: i32,
+ yoffset: i32,
+ width: i32,
+ height: i32,
+ format: u32,
+ r#type: u32,
+ source: TexImageSource,
+ ) -> WebIdlResult<()> {
+ let Some((frame, mut upload)) = self.read_texture_image_source(&source, format, r#type) else {
+ return Ok(());
+ };
+ upload.destination_size = Some((width, height));
+ self.proxy
+ .tex_sub_image2d_from_bitmap(target, level, xoffset, yoffset, format, r#type, frame, upload);
+ Ok(())
+ }
+
+ pub(crate) fn tex_sub_image2d_with_offset(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ level: i32,
+ xoffset: i32,
+ yoffset: i32,
+ width: i32,
+ height: i32,
+ format: u32,
+ r#type: u32,
+ src_data: ArrayBufferView,
+ src_offset: u64,
+ ) -> WebIdlResult<()> {
+ let Ok(texture_data) = self.texture_data_for_2d_upload(src_data, src_offset, width, height, format, r#type)
+ else {
+ self.set_error(GL_INVALID_OPERATION);
+ return Ok(());
+ };
+ let buf_size = texture_data.gl_size();
+ // SAFETY: Recording the command neither runs script nor allocates a cell.
+ unsafe {
+ self.upload_through_nullable_pointer(&texture_data, |texture_data| {
+ self.proxy.tex_sub_image2d_robust_angle(
+ target,
+ level,
+ xoffset,
+ yoffset,
+ width,
+ height,
+ format,
+ r#type,
+ buf_size,
+ texture_data,
+ );
+ });
+ }
+ Ok(())
+ }
+
+ pub(crate) fn compressed_tex_image2d(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ level: i32,
+ internalformat: u32,
+ width: i32,
+ height: i32,
+ border: i32,
+ src_data: ArrayBufferView,
+ src_offset: u64,
+ src_length_override: u32,
+ ) -> WebIdlResult<()> {
+ if !self
+ .enabled_compressed_texture_formats
+ .borrow()
+ .contains(&internalformat)
+ {
+ self.set_error(GL_INVALID_ENUM);
+ return Ok(());
+ }
+ let Ok(bytes) = source_bytes(src_data.into(), src_offset, src_length_override) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let size = bytes.gl_size();
+ // SAFETY: Recording the command neither runs script nor allocates a cell.
+ unsafe {
+ self.upload(&bytes, |bytes| {
+ self.proxy.compressed_tex_image2d_robust_angle(
+ target,
+ level,
+ internalformat,
+ width,
+ height,
+ border,
+ size,
+ size,
+ bytes,
+ );
+ });
+ }
+ Ok(())
+ }
+
+ pub(crate) fn compressed_tex_sub_image2d(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ level: i32,
+ xoffset: i32,
+ yoffset: i32,
+ width: i32,
+ height: i32,
+ format: u32,
+ src_data: ArrayBufferView,
+ src_offset: u64,
+ src_length_override: u32,
+ ) -> WebIdlResult<()> {
+ if !self.enabled_compressed_texture_formats.borrow().contains(&format) {
+ self.set_error(GL_INVALID_ENUM);
+ return Ok(());
+ }
+ let Ok(bytes) = source_bytes(src_data.into(), src_offset, src_length_override) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let size = bytes.gl_size();
+ // SAFETY: Recording the command neither runs script nor allocates a cell.
+ unsafe {
+ self.upload(&bytes, |bytes| {
+ self.proxy.compressed_tex_sub_image2d_robust_angle(
+ target, level, xoffset, yoffset, width, height, format, size, size, bytes,
+ );
+ });
+ }
+ Ok(())
+ }
+
+ pub(crate) fn uniform1fv(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ v: Float32List,
+ src_offset: u64,
+ src_length: u32,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ let Ok(values) = list_bytes(&v, src_offset, src_length) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy
+ .uniform1fv(location_handle, values.gl_count(), values.as_bytes());
+ Ok(())
+ }
+
+ pub(crate) fn uniform2fv(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ v: Float32List,
+ src_offset: u64,
+ src_length: u32,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ let Ok(values) = list_bytes(&v, src_offset, src_length) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Some(count) = values.gl_count_of_whole_groups_of(2) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy.uniform2fv(location_handle, count, values.as_bytes());
+ Ok(())
+ }
+
+ pub(crate) fn uniform3fv(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ v: Float32List,
+ src_offset: u64,
+ src_length: u32,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ let Ok(values) = list_bytes(&v, src_offset, src_length) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Some(count) = values.gl_count_of_whole_groups_of(3) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy.uniform3fv(location_handle, count, values.as_bytes());
+ Ok(())
+ }
+
+ pub(crate) fn uniform4fv(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ v: Float32List,
+ src_offset: u64,
+ src_length: u32,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ let Ok(values) = list_bytes(&v, src_offset, src_length) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Some(count) = values.gl_count_of_whole_groups_of(4) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy.uniform4fv(location_handle, count, values.as_bytes());
+ Ok(())
+ }
+
+ pub(crate) fn uniform1iv(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ v: Int32List,
+ src_offset: u64,
+ src_length: u32,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ let Ok(values) = list_bytes(&v, src_offset, src_length) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy
+ .uniform1iv(location_handle, values.gl_count(), values.as_bytes());
+ Ok(())
+ }
+
+ pub(crate) fn uniform2iv(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ v: Int32List,
+ src_offset: u64,
+ src_length: u32,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ let Ok(values) = list_bytes(&v, src_offset, src_length) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Some(count) = values.gl_count_of_whole_groups_of(2) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy.uniform2iv(location_handle, count, values.as_bytes());
+ Ok(())
+ }
+
+ pub(crate) fn uniform3iv(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ v: Int32List,
+ src_offset: u64,
+ src_length: u32,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ let Ok(values) = list_bytes(&v, src_offset, src_length) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Some(count) = values.gl_count_of_whole_groups_of(3) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy.uniform3iv(location_handle, count, values.as_bytes());
+ Ok(())
+ }
+
+ pub(crate) fn uniform4iv(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ v: Int32List,
+ src_offset: u64,
+ src_length: u32,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ let Ok(values) = list_bytes(&v, src_offset, src_length) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Some(count) = values.gl_count_of_whole_groups_of(4) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy.uniform4iv(location_handle, count, values.as_bytes());
+ Ok(())
+ }
+
+ pub(crate) fn uniform_matrix2fv(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ transpose: bool,
+ data: Float32List,
+ src_offset: u64,
+ src_length: u32,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ const MATRIX_SIZE: usize = 2 * 2;
+ let Ok(values) = list_bytes(&data, src_offset, src_length) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Some(count) = values.gl_count_of_whole_groups_of(MATRIX_SIZE) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy
+ .uniform_matrix2fv(location_handle, count, transpose, values.as_bytes());
+ Ok(())
+ }
+
+ pub(crate) fn uniform_matrix3fv(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ transpose: bool,
+ data: Float32List,
+ src_offset: u64,
+ src_length: u32,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ const MATRIX_SIZE: usize = 3 * 3;
+ let Ok(values) = list_bytes(&data, src_offset, src_length) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Some(count) = values.gl_count_of_whole_groups_of(MATRIX_SIZE) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy
+ .uniform_matrix3fv(location_handle, count, transpose, values.as_bytes());
+ Ok(())
+ }
+
+ pub(crate) fn uniform_matrix4fv(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ transpose: bool,
+ data: Float32List,
+ src_offset: u64,
+ src_length: u32,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ const MATRIX_SIZE: usize = 4 * 4;
+ let Ok(values) = list_bytes(&data, src_offset, src_length) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Some(count) = values.gl_count_of_whole_groups_of(MATRIX_SIZE) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy
+ .uniform_matrix4fv(location_handle, count, transpose, values.as_bytes());
+ Ok(())
+ }
+
+ /// https://registry.khronos.org/webgl/specs/latest/1.0/index.html#5.14.12
+ pub(crate) fn read_pixels(
+ &self,
+ cx: &mut CallContext,
+ x: i32,
+ y: i32,
+ width: i32,
+ height: i32,
+ format: u32,
+ r#type: u32,
+ pixels: Option<ArrayBufferView>,
+ ) -> WebIdlResult<()> {
+ let Some(view) = pixels else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.read_pixels_with_offset(cx, x, y, width, height, format, r#type, view, 0)
+ }
+
+ /// https://registry.khronos.org/webgl/specs/latest/2.0/#4.7.10
+ pub(crate) fn read_pixels_with_offset(
+ &self,
+ _: &mut CallContext,
+ x: i32,
+ y: i32,
+ width: i32,
+ height: i32,
+ format: u32,
+ r#type: u32,
+ dst_data: ArrayBufferView,
+ dst_offset: u64,
+ ) -> WebIdlResult<()> {
+ // If a WebGLBuffer is bound to the PIXEL_PACK_BUFFER target, generates an INVALID_OPERATION error.
+ if self.pixel_pack_buffer_binding.get().is_some() {
+ self.set_error(GL_INVALID_OPERATION);
+ return Ok(());
+ }
+
+ // If pixel store parameter constraints are not met, generates an INVALID_OPERATION error.
+ // If dstData doesn't have enough space for the read operation starting at dstOffset, generate
+ // INVALID_OPERATION.
+ let Ok(destination_bytes) = destination_bytes(&dst_data, dst_offset) else {
+ self.set_error(GL_INVALID_OPERATION);
+ return Ok(());
+ };
+
+ let Ok(buf_size) = i32::try_from(destination_bytes.len()) else {
+ self.set_error(GL_OUT_OF_MEMORY);
+ return Ok(());
+ };
+ self.proxy
+ .read_pixels_robust_angle(x, y, width, height, format, r#type, buf_size, |_, pixels| {
+ if pixels.is_empty() {
+ return;
+ }
+ if write_checked(&dst_data, pixels, destination_bytes.start).is_err() {
+ self.set_error(GL_INVALID_OPERATION);
+ }
+ });
+ Ok(())
+ }
+
+ /// https://registry.khronos.org/webgl/specs/latest/2.0/#4.7.10
+ pub(crate) fn read_pixels_into_pack_buffer(
+ &self,
+ _: &mut CallContext,
+ x: i32,
+ y: i32,
+ width: i32,
+ height: i32,
+ format: u32,
+ r#type: u32,
+ offset: i64,
+ ) -> WebIdlResult<()> {
+ // If no WebGLBuffer is bound to the PIXEL_PACK_BUFFER target, generates an INVALID_OPERATION error.
+ if self.pixel_pack_buffer_binding.get().is_none() {
+ self.set_error(GL_INVALID_OPERATION);
+ return Ok(());
+ }
+
+ self.proxy
+ .read_pixels_into_pixel_pack_buffer(x, y, width, height, format, r#type, offset);
+ Ok(())
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_active_info.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_active_info.rs
new file mode 100644
index 00000000000..d5314e1737e
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_active_info.rs
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://registry.khronos.org/webgl/specs/latest/1.0/#5.11
+
+use ak::Utf16String;
+use libjs_rust::api::{Trace, Vm};
+
+use crate::bindings::interface::{Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, WebIdlResult};
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct WebGLActiveInfo {
+ #[gc(untraced)]
+ name: Utf16String,
+ #[gc(untraced)]
+ r#type: u32,
+ #[gc(untraced)]
+ size: i32,
+}
+
+impl Wrappable for WebGLActiveInfo {}
+
+impl WebGLActiveInfo {
+ pub(crate) fn create(vm: &Vm, name: Utf16String, r#type: u32, size: i32) -> Ref<Self> {
+ allocate(vm, Self { name, r#type, size })
+ }
+
+ pub(crate) fn size(&self, _: &mut CallContext) -> WebIdlResult<i32> {
+ Ok(self.size)
+ }
+
+ pub(crate) fn r#type(&self, _: &mut CallContext) -> WebIdlResult<u32> {
+ Ok(self.r#type)
+ }
+
+ pub(crate) fn name(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(self.name.clone())
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_buffer.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_buffer.rs
new file mode 100644
index 00000000000..ae92d7bdb86
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_buffer.rs
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://registry.khronos.org/webgl/specs/latest/1.0/#5.4
+
+use libjs_rust::api::{Gc, Realm, Trace, Vm};
+
+use super::buffer_kind::{BufferKind, KindOfFirstBinding};
+use super::state::ContextState;
+use super::web_gl_object::WebGLObject;
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct WebGLBuffer {
+ object: WebGLObject,
+ #[gc(untraced)]
+ kind: KindOfFirstBinding,
+}
+
+impl Wrappable for WebGLBuffer {
+ fn relevant_realm(&self, vm: &Vm) -> Option<Gc<Realm>> {
+ self.object.relevant_realm(vm)
+ }
+}
+
+impl Inherits<WebGLObject> for WebGLBuffer {
+ fn parent(&self) -> &WebGLObject {
+ &self.object
+ }
+}
+
+impl WebGLBuffer {
+ pub(crate) fn create(vm: &Vm, context: &ContextState, handle: u32) -> Ref<Self> {
+ allocate(
+ vm,
+ Self {
+ object: WebGLObject::new(context, handle),
+ kind: KindOfFirstBinding::default(),
+ },
+ )
+ }
+
+ pub(crate) fn kind_allows_binding_to(&self, target: u32) -> bool {
+ self.kind.allows_binding_to(target)
+ }
+
+ pub(crate) fn was_bound_as(&self, kind: BufferKind) {
+ self.kind.record_binding_as(kind);
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_draw_buffers.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_draw_buffers.rs
new file mode 100644
index 00000000000..bd868b7f505
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_draw_buffers.rs
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://registry.khronos.org/webgl/extensions/WEBGL_draw_buffers/
+
+use libjs_rust::api::{Gc, Realm, Trace, Vm};
+
+use super::constants::GL_INVALID_VALUE;
+use super::proxy::recorder::bytes_of;
+use super::state::{ContextRef, ContextState};
+use crate::bindings::interface::{Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, WebIdlResult};
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct WebGLDrawBuffers {
+ context: ContextRef,
+}
+
+impl Wrappable for WebGLDrawBuffers {
+ fn relevant_realm(&self, _vm: &Vm) -> Option<Gc<Realm>> {
+ self.context.state().canvas().relevant_realm()
+ }
+}
+
+impl WebGLDrawBuffers {
+ pub(crate) fn create(vm: &Vm, context: &ContextState) -> Ref<Self> {
+ allocate(
+ vm,
+ Self {
+ context: context.context_ref(),
+ },
+ )
+ }
+
+ pub(crate) fn draw_buffers_webgl(&self, _: &mut CallContext, buffers: Vec<u32>) -> WebIdlResult<()> {
+ let context = self.context.state();
+ let Ok(buffer_count) = i32::try_from(buffers.len()) else {
+ context.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ context.proxy.draw_buffers_ext(buffer_count, bytes_of(&buffers));
+ Ok(())
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_framebuffer.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_framebuffer.rs
new file mode 100644
index 00000000000..9c32092a7f1
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_framebuffer.rs
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://registry.khronos.org/webgl/specs/latest/1.0/#5.5
+
+use core::cell::RefCell;
+
+use libjs_rust::api::{Gc, Realm, Trace, Vm};
+
+use super::state::ContextState;
+use super::web_gl_object::WebGLObject;
+use super::web_gl_renderbuffer::WebGLRenderbuffer;
+use super::web_gl_texture::WebGLTexture;
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+
+#[derive(Clone, Copy, Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct Attachment {
+ #[gc(untraced)]
+ attachment: u32,
+ pub(crate) texture: Option<Ref<WebGLTexture>>,
+ pub(crate) renderbuffer: Option<Ref<WebGLRenderbuffer>>,
+ #[gc(untraced)]
+ pub(crate) texture_target: u32,
+ #[gc(untraced)]
+ pub(crate) texture_level: i32,
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct WebGLFramebuffer {
+ object: WebGLObject,
+ attachments: RefCell<Vec<Attachment>>,
+}
+
+impl Wrappable for WebGLFramebuffer {
+ fn relevant_realm(&self, vm: &Vm) -> Option<Gc<Realm>> {
+ self.object.relevant_realm(vm)
+ }
+}
+
+impl Inherits<WebGLObject> for WebGLFramebuffer {
+ fn parent(&self) -> &WebGLObject {
+ &self.object
+ }
+}
+
+impl WebGLFramebuffer {
+ pub(crate) fn create(vm: &Vm, context: &ContextState, handle: u32) -> Ref<Self> {
+ allocate(
+ vm,
+ Self {
+ object: WebGLObject::new(context, handle),
+ attachments: RefCell::new(Vec::new()),
+ },
+ )
+ }
+
+ pub(crate) fn attachment(&self, attachment: u32) -> Option<Attachment> {
+ self.attachments
+ .borrow()
+ .iter()
+ .find(|existing| existing.attachment == attachment)
+ .copied()
+ }
+
+ fn set_attachment(&self, attachment: u32, new_attachment: Option<Attachment>) {
+ let mut attachments = self.attachments.borrow_mut();
+ attachments.retain(|existing| existing.attachment != attachment);
+ attachments.extend(new_attachment);
+ }
+
+ pub(crate) fn set_renderbuffer_attachment(&self, attachment: u32, renderbuffer: Option<Ref<WebGLRenderbuffer>>) {
+ let new_attachment = renderbuffer.map(|renderbuffer| Attachment {
+ attachment,
+ texture: None,
+ renderbuffer: Some(renderbuffer),
+ texture_target: 0,
+ texture_level: 0,
+ });
+ self.set_attachment(attachment, new_attachment);
+ }
+
+ pub(crate) fn set_texture_attachment(
+ &self,
+ attachment: u32,
+ texture: Option<Ref<WebGLTexture>>,
+ texture_target: u32,
+ texture_level: i32,
+ ) {
+ let new_attachment = texture.map(|texture| Attachment {
+ attachment,
+ texture: Some(texture),
+ renderbuffer: None,
+ texture_target,
+ texture_level,
+ });
+ self.set_attachment(attachment, new_attachment);
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_object.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_object.rs
new file mode 100644
index 00000000000..23d552c1020
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_object.rs
@@ -0,0 +1,140 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://registry.khronos.org/webgl/specs/latest/1.0/#5.3
+
+use core::cell::{Cell, RefCell};
+
+use libjs_rust::api::{Gc, Realm, Trace, Vm};
+
+use super::state::{ContextRef, ContextState};
+use crate::bindings::conversions::UsvString;
+use crate::bindings::interface::Wrappable;
+use crate::bindings::{CallContext, WebIdlResult};
+
+pub(crate) struct InvalidOperation;
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct WebGLObject {
+ context: ContextRef,
+ #[gc(untraced)]
+ handle: u32,
+ /// Restoring a lost context starts a new generation, in which the objects of earlier ones are invalid.
+ #[gc(untraced)]
+ context_generation: u64,
+ #[gc(untraced)]
+ invalidated: Cell<bool>,
+ #[gc(untraced)]
+ label: RefCell<UsvString>,
+}
+
+impl Wrappable for WebGLObject {
+ fn relevant_realm(&self, _vm: &Vm) -> Option<Gc<Realm>> {
+ self.context.state().canvas().relevant_realm()
+ }
+}
+
+impl WebGLObject {
+ pub(crate) fn new(context: &ContextState, handle: u32) -> Self {
+ Self {
+ context: context.context_ref(),
+ handle,
+ context_generation: context.context_generation(),
+ invalidated: Cell::new(false),
+ label: RefCell::new(UsvString::from_ascii(b"")),
+ }
+ }
+
+ pub(crate) fn label(&self, _: &mut CallContext) -> WebIdlResult<UsvString> {
+ Ok(self.label.borrow().clone())
+ }
+
+ pub(crate) fn set_label(&self, _: &mut CallContext, value: UsvString) -> WebIdlResult<()> {
+ self.label.replace(value);
+ Ok(())
+ }
+
+ fn validate_context(&self, context: &ContextState) -> Result<(), InvalidOperation> {
+ if core::ptr::eq(self.context.state(), context) {
+ Ok(())
+ } else {
+ Err(InvalidOperation)
+ }
+ }
+
+ pub(crate) fn invalidated_for_context(&self, context: &ContextState) -> bool {
+ self.invalidated.get() || self.context_generation != context.context_generation()
+ }
+
+ pub(crate) fn invalidate(&self) {
+ self.invalidated.set(true);
+ }
+
+ pub(crate) fn handle(&self, context: &ContextState) -> Result<u32, InvalidOperation> {
+ self.handle_for_query(context)?.ok_or(InvalidOperation)
+ }
+
+ pub(crate) fn handle_for_deletion(&self, context: &ContextState) -> Result<Option<u32>, InvalidOperation> {
+ let handle = self.handle_for_query(context)?;
+ if handle.is_some() {
+ self.invalidate();
+ }
+ Ok(handle)
+ }
+
+ /// `None` for a deleted or lost object, which a question about it has an answer for without asking GL.
+ pub(crate) fn handle_for_query(&self, context: &ContextState) -> Result<Option<u32>, InvalidOperation> {
+ self.validate_context(context)?;
+ Ok((!self.invalidated_for_context(context)).then_some(self.handle))
+ }
+}
+
+macro_rules! modules_of_interfaces_that_only_inherit_from_web_gl_object {
+ ($(
+ $(#[$specification_link:meta])*
+ $module:ident :: $interface:ident
+ ),+ $(,)?) => {$(
+ $(#[$specification_link])*
+ pub(crate) mod $module {
+ use libjs_rust::api::{Gc, Realm, Trace, Vm};
+
+ use $crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+ use $crate::web_gl::state::ContextState;
+ use $crate::web_gl::web_gl_object::WebGLObject;
+
+ #[derive(Trace)]
+ #[gc(crate = libjs_rust)]
+ pub(crate) struct $interface {
+ object: WebGLObject,
+ }
+
+ impl Wrappable for $interface {
+ fn relevant_realm(&self, vm: &Vm) -> Option<Gc<Realm>> {
+ self.object.relevant_realm(vm)
+ }
+ }
+
+ impl Inherits<WebGLObject> for $interface {
+ fn parent(&self) -> &WebGLObject {
+ &self.object
+ }
+ }
+
+ impl $interface {
+ pub(crate) fn create(vm: &Vm, context: &ContextState, handle: u32) -> Ref<Self> {
+ allocate(
+ vm,
+ Self {
+ object: WebGLObject::new(context, handle),
+ },
+ )
+ }
+ }
+ }
+ )+};
+}
+pub(crate) use modules_of_interfaces_that_only_inherit_from_web_gl_object;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_program.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_program.rs
new file mode 100644
index 00000000000..c4bf4f812f5
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_program.rs
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://registry.khronos.org/webgl/specs/latest/1.0/#5.6
+
+use core::cell::Cell;
+
+use libjs_rust::api::{Gc, Realm, Trace, Vm};
+
+use super::state::ContextState;
+use super::web_gl_object::WebGLObject;
+use super::web_gl_shader::WebGLShader;
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct WebGLProgram {
+ object: WebGLObject,
+ pub(crate) attached_vertex_shader: Cell<Option<Ref<WebGLShader>>>,
+ pub(crate) attached_fragment_shader: Cell<Option<Ref<WebGLShader>>>,
+}
+
+impl Wrappable for WebGLProgram {
+ fn relevant_realm(&self, vm: &Vm) -> Option<Gc<Realm>> {
+ self.object.relevant_realm(vm)
+ }
+}
+
+impl Inherits<WebGLObject> for WebGLProgram {
+ fn parent(&self) -> &WebGLObject {
+ &self.object
+ }
+}
+
+impl WebGLProgram {
+ pub(crate) fn create(vm: &Vm, context: &ContextState, handle: u32) -> Ref<Self> {
+ allocate(
+ vm,
+ Self {
+ object: WebGLObject::new(context, handle),
+ attached_vertex_shader: Cell::new(None),
+ attached_fragment_shader: Cell::new(None),
+ },
+ )
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_rendering_context.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_rendering_context.rs
new file mode 100644
index 00000000000..9a9879fa922
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_rendering_context.rs
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://registry.khronos.org/webgl/specs/latest/1.0/#5.14
+
+use super::state::{RenderingContext, WebGL1};
+
+pub(crate) type WebGLRenderingContext = RenderingContext<WebGL1>;
+
+/// https://registry.khronos.org/webgl/specs/latest/1.0/#5.2
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum WebGLPowerPreference {
+ Default,
+ LowPower,
+ HighPerformance,
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_rendering_context_base.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_rendering_context_base.rs
new file mode 100644
index 00000000000..168b0eba7ae
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_rendering_context_base.rs
@@ -0,0 +1,1478 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://registry.khronos.org/webgl/specs/latest/1.0/#5.14
+
+use ak::Utf16String;
+use libjs_rust::api::{Gc, Object, Trace};
+
+use super::buffer_kind::BufferKind;
+use super::buffer_source::copy_of_first_numbers;
+use super::byte_ranges::gl_sizei_of_array_length;
+use super::constants::{
+ GL_ARRAY_BUFFER, GL_COLOR_ATTACHMENT0, GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, GL_DEPTH_ATTACHMENT,
+ GL_DEPTH_STENCIL, GL_DEPTH_STENCIL_ATTACHMENT, GL_DEPTH24_STENCIL8, GL_DRAW_FRAMEBUFFER, GL_ELEMENT_ARRAY_BUFFER,
+ GL_FRAGMENT_SHADER, GL_FRAMEBUFFER, GL_INFO_LOG_LENGTH, GL_INVALID_ENUM, GL_INVALID_OPERATION, GL_INVALID_VALUE,
+ GL_PIXEL_PACK_BUFFER, GL_PIXEL_UNPACK_BUFFER, GL_READ_FRAMEBUFFER, GL_RENDERBUFFER, GL_SHADER_SOURCE_LENGTH,
+ GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_3D, GL_TEXTURE_CUBE_MAP,
+ GL_TEXTURE_CUBE_MAP_NEGATIVE_X, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z,
+ GL_TEXTURE_CUBE_MAP_POSITIVE_X, GL_TEXTURE_CUBE_MAP_POSITIVE_Y, GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
+ GL_TRANSFORM_FEEDBACK_BUFFER, GL_UNIFORM_BUFFER, GL_UNPACK_ALIGNMENT, GL_UNPACK_COLORSPACE_CONVERSION_WEBGL,
+ GL_UNPACK_FLIP_Y_WEBGL, GL_UNPACK_PREMULTIPLY_ALPHA_WEBGL, GL_UNPACK_ROW_LENGTH, GL_UNPACK_SKIP_PIXELS,
+ GL_UNPACK_SKIP_ROWS, GL_VERTEX_ATTRIB_ARRAY_POINTER, GL_VERTEX_SHADER,
+};
+use super::gl_string::{utf8_bytes, utf16_string_from_gl_string};
+use super::state::{
+ Binding, ContextState, MAX_WEBGL_DRAWING_BUFFER_DIMENSION, RenderingContext, Version, WebGLVersion,
+};
+use super::types::Float32List;
+use super::web_gl_active_info::WebGLActiveInfo;
+use super::web_gl_buffer::WebGLBuffer;
+use super::web_gl_framebuffer::WebGLFramebuffer;
+use super::web_gl_program::WebGLProgram;
+use super::web_gl_renderbuffer::WebGLRenderbuffer;
+use super::web_gl_rendering_context::WebGLPowerPreference;
+use super::web_gl_shader::WebGLShader;
+use super::web_gl_shader_precision_format::WebGLShaderPrecisionFormat;
+use super::web_gl_texture::WebGLTexture;
+use super::web_gl_uniform_location::WebGLUniformLocation;
+use crate::bindings::conversions::CppInterface;
+use crate::bindings::interface::Ref;
+use crate::bindings::{CallContext, WebIdlResult};
+
+/// https://www.khronos.org/registry/webgl/specs/latest/1.0/#WEBGLCONTEXTATTRIBUTES
+#[derive(Clone, Copy, Debug)]
+pub(crate) struct WebGLContextAttributes {
+ pub(crate) alpha: bool,
+ pub(crate) depth: bool,
+ pub(crate) stencil: bool,
+ pub(crate) antialias: bool,
+ pub(crate) premultiplied_alpha: bool,
+ pub(crate) preserve_drawing_buffer: bool,
+ pub(crate) power_preference: WebGLPowerPreference,
+ pub(crate) fail_if_major_performance_caveat: bool,
+ pub(crate) desynchronized: bool,
+ /// https://immersive-web.github.io/webxr/#dom-webglcontextattributes-xrcompatible
+ pub(crate) xr_compatible: bool,
+}
+
+const ACTIVE_INFO_NAME_BUFFER_SIZE: usize = 256;
+const ACTIVE_INFO_NAME_BUFFER_GL_SIZE: i32 = gl_sizei_of_array_length(ACTIVE_INFO_NAME_BUFFER_SIZE);
+
+pub(crate) fn is_valid_framebuffer_binding_target(version: WebGLVersion, target: u32) -> bool {
+ if target == GL_FRAMEBUFFER {
+ return true;
+ }
+ version == WebGLVersion::WebGL2 && (target == GL_READ_FRAMEBUFFER || target == GL_DRAW_FRAMEBUFFER)
+}
+
+pub(crate) fn is_valid_framebuffer_attachment(
+ version: WebGLVersion,
+ draw_buffers_extension_enabled: bool,
+ attachment: u32,
+) -> bool {
+ if matches!(
+ attachment,
+ GL_COLOR_ATTACHMENT0 | GL_DEPTH_ATTACHMENT | GL_STENCIL_ATTACHMENT | GL_DEPTH_STENCIL_ATTACHMENT
+ ) {
+ return true;
+ }
+ if version == WebGLVersion::WebGL2 || draw_buffers_extension_enabled {
+ return attachment > GL_COLOR_ATTACHMENT0 && attachment <= GL_COLOR_ATTACHMENT0 + 15;
+ }
+ false
+}
+
+fn is_valid_framebuffer_texture_2d_target(target: u32) -> bool {
+ matches!(
+ target,
+ GL_TEXTURE_2D
+ | GL_TEXTURE_CUBE_MAP_POSITIVE_X
+ | GL_TEXTURE_CUBE_MAP_NEGATIVE_X
+ | GL_TEXTURE_CUBE_MAP_POSITIVE_Y
+ | GL_TEXTURE_CUBE_MAP_NEGATIVE_Y
+ | GL_TEXTURE_CUBE_MAP_POSITIVE_Z
+ | GL_TEXTURE_CUBE_MAP_NEGATIVE_Z
+ )
+}
+
+fn holds_object<T: Trace>(binding: &Binding<T>, object: Ref<T>) -> bool {
+ binding.get().is_some_and(|held| held.as_ptr() == object.as_ptr())
+}
+
+fn active_info_name(name_buffer: &[u8], length: i32) -> Utf16String {
+ let length = usize::try_from(length).expect("the length of a name that GL wrote is not negative");
+ utf16_string_from_gl_string(&name_buffer[..length])
+}
+
+fn zeroed_gl_string_buffer(size_with_terminating_nul: i32) -> Vec<u8> {
+ let size = usize::try_from(size_with_terminating_nul).expect("GL does not report a negative size for a string");
+ vec![0; size]
+}
+
+#[expect(
+ clippy::too_many_arguments,
+ reason = "the operations have the arguments of the GL functions"
+)]
+impl<V: Version> RenderingContext<V> {
+ // NB: The state has a `canvas()` and an `is_context_lost()` of its own, which a method call on a context does not
+ // reach past the operations of the same names.
+ pub(crate) fn canvas(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ Ok(ContextState::canvas(self).wrapper(cx.realm()))
+ }
+
+ pub(crate) fn drawing_buffer_width(&self, _: &mut CallContext) -> WebIdlResult<i32> {
+ let (width, _) = ContextState::canvas(self).bitmap_size();
+ Ok(width.min(MAX_WEBGL_DRAWING_BUFFER_DIMENSION))
+ }
+
+ pub(crate) fn drawing_buffer_height(&self, _: &mut CallContext) -> WebIdlResult<i32> {
+ let (_, height) = ContextState::canvas(self).bitmap_size();
+ Ok(height.min(MAX_WEBGL_DRAWING_BUFFER_DIMENSION))
+ }
+
+ pub(crate) fn get_context_attributes(&self, _: &mut CallContext) -> WebIdlResult<Option<WebGLContextAttributes>> {
+ if ContextState::is_context_lost(self) {
+ return Ok(None);
+ }
+ Ok(Some(self.actual_context_parameters))
+ }
+
+ pub(crate) fn is_context_lost(&self, _: &mut CallContext) -> WebIdlResult<bool> {
+ Ok(ContextState::is_context_lost(self))
+ }
+
+ pub(crate) fn get_supported_extensions(&self, _: &mut CallContext) -> WebIdlResult<Option<Vec<Utf16String>>> {
+ Ok(Some(self.supported_extensions()))
+ }
+
+ pub(crate) fn get_extension(&self, cx: &mut CallContext, name: Utf16String) -> WebIdlResult<Option<Gc<Object>>> {
+ Ok(self.extension(cx, &name))
+ }
+
+ pub(crate) fn active_texture(&self, _: &mut CallContext, texture: u32) -> WebIdlResult<()> {
+ self.proxy.active_texture(texture);
+ Ok(())
+ }
+
+ pub(crate) fn attach_shader(
+ &self,
+ _: &mut CallContext,
+ program: Ref<WebGLProgram>,
+ shader: Ref<WebGLShader>,
+ ) -> WebIdlResult<()> {
+ let Some(program_handle) = self.handle_of(program) else {
+ return Ok(());
+ };
+ let Some(shader_handle) = self.handle_of(shader) else {
+ return Ok(());
+ };
+
+ if holds_object(&program.attached_vertex_shader, shader)
+ || holds_object(&program.attached_fragment_shader, shader)
+ {
+ self.set_error(GL_INVALID_OPERATION);
+ return Ok(());
+ }
+
+ if shader.r#type() == GL_VERTEX_SHADER && program.attached_vertex_shader.get().is_some() {
+ self.set_error(GL_INVALID_OPERATION);
+ return Ok(());
+ }
+
+ if shader.r#type() == GL_FRAGMENT_SHADER && program.attached_fragment_shader.get().is_some() {
+ self.set_error(GL_INVALID_OPERATION);
+ return Ok(());
+ }
+
+ self.proxy.attach_shader(program_handle, shader_handle);
+
+ match shader.r#type() {
+ GL_VERTEX_SHADER => program.attached_vertex_shader.set(Some(shader)),
+ GL_FRAGMENT_SHADER => program.attached_fragment_shader.set(Some(shader)),
+ _ => unreachable!("a shader is a vertex shader or a fragment shader"),
+ }
+ Ok(())
+ }
+
+ pub(crate) fn bind_attrib_location(
+ &self,
+ _: &mut CallContext,
+ program: Ref<WebGLProgram>,
+ index: u32,
+ name: Utf16String,
+ ) -> WebIdlResult<()> {
+ let Some(program_handle) = self.handle_of(program) else {
+ return Ok(());
+ };
+ self.proxy
+ .bind_attrib_location(program_handle, index, &utf8_bytes(&name));
+ Ok(())
+ }
+
+ pub(crate) fn bind_buffer(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ buffer: Option<Ref<WebGLBuffer>>,
+ ) -> WebIdlResult<()> {
+ let mut buffer_handle = 0;
+ if let Some(buffer) = buffer {
+ let Some(handle) = self.handle_of(buffer) else {
+ return Ok(());
+ };
+ buffer_handle = handle;
+
+ if !buffer.kind_allows_binding_to(target) {
+ self.set_error(GL_INVALID_OPERATION);
+ return Ok(());
+ }
+ }
+
+ let (binding, kind_of_buffers_at_target) = match target {
+ GL_ARRAY_BUFFER => (&self.array_buffer_binding, BufferKind::OtherData),
+ GL_ELEMENT_ARRAY_BUFFER => (&self.element_array_buffer_binding, BufferKind::ElementArray),
+ // FIXME: A buffer of indices can be bound to COPY_READ_BUFFER and to COPY_WRITE_BUFFER as well.
+ GL_COPY_READ_BUFFER if self.is_webgl2() => (&self.copy_read_buffer_binding, BufferKind::OtherData),
+ GL_COPY_WRITE_BUFFER if self.is_webgl2() => (&self.copy_write_buffer_binding, BufferKind::OtherData),
+ GL_PIXEL_PACK_BUFFER if self.is_webgl2() => (&self.pixel_pack_buffer_binding, BufferKind::OtherData),
+ GL_PIXEL_UNPACK_BUFFER if self.is_webgl2() => (&self.pixel_unpack_buffer_binding, BufferKind::OtherData),
+ GL_TRANSFORM_FEEDBACK_BUFFER if self.is_webgl2() => {
+ (&self.transform_feedback_buffer_binding, BufferKind::OtherData)
+ }
+ GL_UNIFORM_BUFFER if self.is_webgl2() => (&self.uniform_buffer_binding, BufferKind::OtherData),
+ _ => {
+ self.set_error(GL_INVALID_ENUM);
+ return Ok(());
+ }
+ };
+ if let Some(buffer) = buffer {
+ buffer.was_bound_as(kind_of_buffers_at_target);
+ }
+ binding.set(buffer);
+
+ self.proxy.bind_buffer(target, buffer_handle);
+ Ok(())
+ }
+
+ pub(crate) fn bind_framebuffer(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ framebuffer: Option<Ref<WebGLFramebuffer>>,
+ ) -> WebIdlResult<()> {
+ let mut framebuffer_handle = 0;
+ if let Some(framebuffer) = framebuffer {
+ let Some(handle) = self.handle_of(framebuffer) else {
+ return Ok(());
+ };
+ framebuffer_handle = handle;
+ }
+
+ self.proxy.bind_framebuffer(target, framebuffer_handle);
+ self.framebuffer_binding.set(framebuffer);
+ Ok(())
+ }
+
+ pub(crate) fn bind_renderbuffer(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ renderbuffer: Option<Ref<WebGLRenderbuffer>>,
+ ) -> WebIdlResult<()> {
+ let mut renderbuffer_handle = 0;
+ if let Some(renderbuffer) = renderbuffer {
+ let Some(handle) = self.handle_of(renderbuffer) else {
+ return Ok(());
+ };
+ renderbuffer_handle = handle;
+ }
+
+ self.proxy.bind_renderbuffer(target, renderbuffer_handle);
+ self.renderbuffer_binding.set(renderbuffer);
+ Ok(())
+ }
+
+ pub(crate) fn bind_texture(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ texture: Option<Ref<WebGLTexture>>,
+ ) -> WebIdlResult<()> {
+ let mut texture_handle = 0;
+ if let Some(texture) = texture {
+ let Some(handle) = self.handle_of(texture) else {
+ return Ok(());
+ };
+ texture_handle = handle;
+ }
+
+ let binding = match target {
+ GL_TEXTURE_2D => &self.texture_binding_2d,
+ GL_TEXTURE_CUBE_MAP => &self.texture_binding_cube_map,
+ GL_TEXTURE_2D_ARRAY if self.is_webgl2() => &self.texture_binding_2d_array,
+ GL_TEXTURE_3D if self.is_webgl2() => &self.texture_binding_3d,
+ _ => {
+ self.set_error(GL_INVALID_ENUM);
+ return Ok(());
+ }
+ };
+ binding.set(texture);
+
+ self.proxy.bind_texture(target, texture_handle);
+ Ok(())
+ }
+
+ pub(crate) fn blend_color(
+ &self,
+ _: &mut CallContext,
+ red: f32,
+ green: f32,
+ blue: f32,
+ alpha: f32,
+ ) -> WebIdlResult<()> {
+ self.proxy.blend_color(red, green, blue, alpha);
+ Ok(())
+ }
+
+ pub(crate) fn blend_equation(&self, _: &mut CallContext, mode: u32) -> WebIdlResult<()> {
+ self.proxy.blend_equation(mode);
+ Ok(())
+ }
+
+ pub(crate) fn blend_equation_separate(
+ &self,
+ _: &mut CallContext,
+ mode_rgb: u32,
+ mode_alpha: u32,
+ ) -> WebIdlResult<()> {
+ self.proxy.blend_equation_separate(mode_rgb, mode_alpha);
+ Ok(())
+ }
+
+ pub(crate) fn blend_func(&self, _: &mut CallContext, sfactor: u32, dfactor: u32) -> WebIdlResult<()> {
+ self.proxy.blend_func(sfactor, dfactor);
+ Ok(())
+ }
+
+ pub(crate) fn blend_func_separate(
+ &self,
+ _: &mut CallContext,
+ src_rgb: u32,
+ dst_rgb: u32,
+ src_alpha: u32,
+ dst_alpha: u32,
+ ) -> WebIdlResult<()> {
+ self.proxy.blend_func_separate(src_rgb, dst_rgb, src_alpha, dst_alpha);
+ Ok(())
+ }
+
+ pub(crate) fn check_framebuffer_status(&self, _: &mut CallContext, target: u32) -> WebIdlResult<u32> {
+ Ok(self.proxy.check_framebuffer_status(target))
+ }
+
+ pub(crate) fn clear(&self, _: &mut CallContext, mask: u32) -> WebIdlResult<()> {
+ self.did_update_canvas_content();
+ self.proxy.clear(mask);
+ Ok(())
+ }
+
+ pub(crate) fn clear_color(
+ &self,
+ _: &mut CallContext,
+ red: f32,
+ green: f32,
+ blue: f32,
+ alpha: f32,
+ ) -> WebIdlResult<()> {
+ self.proxy.clear_color(red, green, blue, alpha);
+ Ok(())
+ }
+
+ pub(crate) fn clear_depth(&self, _: &mut CallContext, depth: f32) -> WebIdlResult<()> {
+ self.proxy.clear_depthf(depth);
+ Ok(())
+ }
+
+ pub(crate) fn clear_stencil(&self, _: &mut CallContext, s: i32) -> WebIdlResult<()> {
+ self.proxy.clear_stencil(s);
+ Ok(())
+ }
+
+ pub(crate) fn color_mask(
+ &self,
+ _: &mut CallContext,
+ red: bool,
+ green: bool,
+ blue: bool,
+ alpha: bool,
+ ) -> WebIdlResult<()> {
+ self.proxy.color_mask(red, green, blue, alpha);
+ Ok(())
+ }
+
+ pub(crate) fn compile_shader(&self, _: &mut CallContext, shader: Ref<WebGLShader>) -> WebIdlResult<()> {
+ let Some(shader_handle) = self.handle_of(shader) else {
+ return Ok(());
+ };
+ self.proxy.compile_shader(shader_handle);
+ Ok(())
+ }
+
+ pub(crate) fn copy_tex_image2d(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ level: i32,
+ internalformat: u32,
+ x: i32,
+ y: i32,
+ width: i32,
+ height: i32,
+ border: i32,
+ ) -> WebIdlResult<()> {
+ self.proxy
+ .copy_tex_image2d(target, level, internalformat, x, y, width, height, border);
+ Ok(())
+ }
+
+ pub(crate) fn copy_tex_sub_image2d(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ level: i32,
+ xoffset: i32,
+ yoffset: i32,
+ x: i32,
+ y: i32,
+ width: i32,
+ height: i32,
+ ) -> WebIdlResult<()> {
+ self.proxy
+ .copy_tex_sub_image2d(target, level, xoffset, yoffset, x, y, width, height);
+ Ok(())
+ }
+
+ pub(crate) fn create_buffer(&self, cx: &mut CallContext) -> WebIdlResult<Ref<WebGLBuffer>> {
+ let mut handle = [0];
+ self.proxy.gen_buffers(&mut handle);
+ Ok(WebGLBuffer::create(cx.vm(), self, handle[0]))
+ }
+
+ pub(crate) fn create_framebuffer(&self, cx: &mut CallContext) -> WebIdlResult<Ref<WebGLFramebuffer>> {
+ let mut handle = [0];
+ self.proxy.gen_framebuffers(&mut handle);
+ Ok(WebGLFramebuffer::create(cx.vm(), self, handle[0]))
+ }
+
+ pub(crate) fn create_program(&self, cx: &mut CallContext) -> WebIdlResult<Ref<WebGLProgram>> {
+ let handle = self.proxy.create_program();
+ Ok(WebGLProgram::create(cx.vm(), self, handle))
+ }
+
+ pub(crate) fn create_renderbuffer(&self, cx: &mut CallContext) -> WebIdlResult<Ref<WebGLRenderbuffer>> {
+ let mut handle = [0];
+ self.proxy.gen_renderbuffers(&mut handle);
+ Ok(WebGLRenderbuffer::create(cx.vm(), self, handle[0]))
+ }
+
+ pub(crate) fn create_shader(&self, cx: &mut CallContext, r#type: u32) -> WebIdlResult<Option<Ref<WebGLShader>>> {
+ if r#type != GL_VERTEX_SHADER && r#type != GL_FRAGMENT_SHADER {
+ self.set_error(GL_INVALID_ENUM);
+ return Ok(None);
+ }
+
+ let handle = self.proxy.create_shader(r#type);
+ Ok(Some(WebGLShader::create(cx.vm(), self, handle, r#type)))
+ }
+
+ pub(crate) fn create_texture(&self, cx: &mut CallContext) -> WebIdlResult<Ref<WebGLTexture>> {
+ let mut handle = [0];
+ self.proxy.gen_textures(&mut handle);
+ Ok(WebGLTexture::create(cx.vm(), self, handle[0]))
+ }
+
+ pub(crate) fn cull_face(&self, _: &mut CallContext, mode: u32) -> WebIdlResult<()> {
+ self.proxy.cull_face(mode);
+ Ok(())
+ }
+
+ pub(crate) fn delete_buffer(&self, _: &mut CallContext, buffer: Option<Ref<WebGLBuffer>>) -> WebIdlResult<()> {
+ let Some(buffer) = buffer else {
+ return Ok(());
+ };
+ let Some(handle) = self.handle_for_deletion_of(buffer) else {
+ return Ok(());
+ };
+ self.proxy.delete_buffers(1, &[handle]);
+ Ok(())
+ }
+
+ pub(crate) fn delete_framebuffer(
+ &self,
+ _: &mut CallContext,
+ framebuffer: Option<Ref<WebGLFramebuffer>>,
+ ) -> WebIdlResult<()> {
+ let Some(framebuffer) = framebuffer else {
+ return Ok(());
+ };
+ let Some(handle) = self.handle_for_deletion_of(framebuffer) else {
+ return Ok(());
+ };
+ self.proxy.delete_framebuffers(1, &[handle]);
+
+ if holds_object(&self.framebuffer_binding, framebuffer) {
+ self.framebuffer_binding.set(None);
+ }
+ Ok(())
+ }
+
+ pub(crate) fn delete_program(&self, _: &mut CallContext, program: Option<Ref<WebGLProgram>>) -> WebIdlResult<()> {
+ let Some(program) = program else {
+ return Ok(());
+ };
+ let Some(handle) = self.handle_for_deletion_of(program) else {
+ return Ok(());
+ };
+ self.proxy.delete_program(handle);
+
+ if holds_object(&self.current_program, program) {
+ self.current_program.set(None);
+ }
+ Ok(())
+ }
+
+ pub(crate) fn delete_renderbuffer(
+ &self,
+ _: &mut CallContext,
+ renderbuffer: Option<Ref<WebGLRenderbuffer>>,
+ ) -> WebIdlResult<()> {
+ let Some(renderbuffer) = renderbuffer else {
+ return Ok(());
+ };
+ let Some(handle) = self.handle_for_deletion_of(renderbuffer) else {
+ return Ok(());
+ };
+ self.proxy.delete_renderbuffers(1, &[handle]);
+ Ok(())
+ }
+
+ pub(crate) fn delete_shader(&self, _: &mut CallContext, shader: Option<Ref<WebGLShader>>) -> WebIdlResult<()> {
+ let Some(shader) = shader else {
+ return Ok(());
+ };
+ let Some(handle) = self.handle_for_deletion_of(shader) else {
+ return Ok(());
+ };
+ self.proxy.delete_shader(handle);
+ Ok(())
+ }
+
+ pub(crate) fn delete_texture(&self, _: &mut CallContext, texture: Option<Ref<WebGLTexture>>) -> WebIdlResult<()> {
+ let Some(texture) = texture else {
+ return Ok(());
+ };
+ let Some(handle) = self.handle_for_deletion_of(texture) else {
+ return Ok(());
+ };
+ self.proxy.delete_textures(1, &[handle]);
+
+ for binding in [
+ &self.texture_binding_2d,
+ &self.texture_binding_cube_map,
+ &self.texture_binding_2d_array,
+ &self.texture_binding_3d,
+ ] {
+ if holds_object(binding, texture) {
+ binding.set(None);
+ }
+ }
+ Ok(())
+ }
+
+ pub(crate) fn depth_func(&self, _: &mut CallContext, func: u32) -> WebIdlResult<()> {
+ self.proxy.depth_func(func);
+ Ok(())
+ }
+
+ pub(crate) fn depth_mask(&self, _: &mut CallContext, flag: bool) -> WebIdlResult<()> {
+ self.proxy.depth_mask(flag);
+ Ok(())
+ }
+
+ pub(crate) fn depth_range(&self, _: &mut CallContext, z_near: f32, z_far: f32) -> WebIdlResult<()> {
+ self.proxy.depth_rangef(z_near, z_far);
+ Ok(())
+ }
+
+ pub(crate) fn detach_shader(
+ &self,
+ _: &mut CallContext,
+ program: Ref<WebGLProgram>,
+ shader: Ref<WebGLShader>,
+ ) -> WebIdlResult<()> {
+ let Some(program_handle) = self.handle_of(program) else {
+ return Ok(());
+ };
+ let Some(shader_handle) = self.handle_of(shader) else {
+ return Ok(());
+ };
+
+ self.proxy.detach_shader(program_handle, shader_handle);
+
+ match shader.r#type() {
+ GL_VERTEX_SHADER => program.attached_vertex_shader.set(None),
+ GL_FRAGMENT_SHADER => program.attached_fragment_shader.set(None),
+ _ => {}
+ }
+ Ok(())
+ }
+
+ pub(crate) fn disable(&self, _: &mut CallContext, cap: u32) -> WebIdlResult<()> {
+ self.proxy.disable(cap);
+ Ok(())
+ }
+
+ pub(crate) fn disable_vertex_attrib_array(&self, _: &mut CallContext, index: u32) -> WebIdlResult<()> {
+ self.proxy.disable_vertex_attrib_array(index);
+ Ok(())
+ }
+
+ pub(crate) fn draw_arrays(&self, _: &mut CallContext, mode: u32, first: i32, count: i32) -> WebIdlResult<()> {
+ self.did_update_canvas_content();
+ self.proxy.draw_arrays(mode, first, count);
+ Ok(())
+ }
+
+ pub(crate) fn draw_elements(
+ &self,
+ _: &mut CallContext,
+ mode: u32,
+ count: i32,
+ r#type: u32,
+ offset: i64,
+ ) -> WebIdlResult<()> {
+ self.proxy.draw_elements(mode, count, r#type, offset);
+ self.did_update_canvas_content();
+ Ok(())
+ }
+
+ pub(crate) fn enable(&self, _: &mut CallContext, cap: u32) -> WebIdlResult<()> {
+ self.proxy.enable(cap);
+ Ok(())
+ }
+
+ pub(crate) fn enable_vertex_attrib_array(&self, _: &mut CallContext, index: u32) -> WebIdlResult<()> {
+ self.proxy.enable_vertex_attrib_array(index);
+ Ok(())
+ }
+
+ pub(crate) fn finish(&self, _: &mut CallContext) -> WebIdlResult<()> {
+ self.proxy.finish();
+ Ok(())
+ }
+
+ pub(crate) fn flush(&self, _: &mut CallContext) -> WebIdlResult<()> {
+ self.proxy.flush();
+ Ok(())
+ }
+
+ pub(crate) fn framebuffer_renderbuffer(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ attachment: u32,
+ renderbuffertarget: u32,
+ renderbuffer: Option<Ref<WebGLRenderbuffer>>,
+ ) -> WebIdlResult<()> {
+ if !is_valid_framebuffer_binding_target(self.version(), target) {
+ self.set_error(GL_INVALID_ENUM);
+ return Ok(());
+ }
+
+ if !is_valid_framebuffer_attachment(self.version(), self.extension_enabled("WEBGL_draw_buffers"), attachment) {
+ self.set_error(GL_INVALID_ENUM);
+ return Ok(());
+ }
+
+ if renderbuffertarget != GL_RENDERBUFFER {
+ self.set_error(GL_INVALID_ENUM);
+ return Ok(());
+ }
+
+ let Some(bound_framebuffer) = self.framebuffer_binding.get() else {
+ self.set_error(GL_INVALID_OPERATION);
+ return Ok(());
+ };
+
+ let mut renderbuffer_handle = 0;
+ if let Some(renderbuffer) = renderbuffer {
+ let Some(handle) = self.handle_of(renderbuffer) else {
+ return Ok(());
+ };
+ renderbuffer_handle = handle;
+ }
+ self.proxy
+ .framebuffer_renderbuffer(target, attachment, renderbuffertarget, renderbuffer_handle);
+ bound_framebuffer.set_renderbuffer_attachment(attachment, renderbuffer);
+ Ok(())
+ }
+
+ pub(crate) fn framebuffer_texture2d(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ attachment: u32,
+ textarget: u32,
+ texture: Option<Ref<WebGLTexture>>,
+ level: i32,
+ ) -> WebIdlResult<()> {
+ if !is_valid_framebuffer_binding_target(self.version(), target) {
+ self.set_error(GL_INVALID_ENUM);
+ return Ok(());
+ }
+
+ if !is_valid_framebuffer_attachment(self.version(), self.extension_enabled("WEBGL_draw_buffers"), attachment) {
+ self.set_error(GL_INVALID_ENUM);
+ return Ok(());
+ }
+
+ if !is_valid_framebuffer_texture_2d_target(textarget) {
+ self.set_error(GL_INVALID_ENUM);
+ return Ok(());
+ }
+
+ if level < 0 || (self.version() == WebGLVersion::WebGL1 && level != 0) {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ }
+
+ let Some(bound_framebuffer) = self.framebuffer_binding.get() else {
+ self.set_error(GL_INVALID_OPERATION);
+ return Ok(());
+ };
+
+ let mut texture_handle = 0;
+ if let Some(texture) = texture {
+ let Some(handle) = self.handle_of(texture) else {
+ return Ok(());
+ };
+ texture_handle = handle;
+ }
+ self.proxy
+ .framebuffer_texture2d(target, attachment, textarget, texture_handle, level);
+ bound_framebuffer.set_texture_attachment(attachment, texture, textarget, level);
+ Ok(())
+ }
+
+ pub(crate) fn front_face(&self, _: &mut CallContext, mode: u32) -> WebIdlResult<()> {
+ self.proxy.front_face(mode);
+ Ok(())
+ }
+
+ pub(crate) fn generate_mipmap(&self, _: &mut CallContext, target: u32) -> WebIdlResult<()> {
+ self.proxy.generate_mipmap(target);
+ Ok(())
+ }
+
+ pub(crate) fn get_active_attrib(
+ &self,
+ cx: &mut CallContext,
+ program: Ref<WebGLProgram>,
+ index: u32,
+ ) -> WebIdlResult<Option<Ref<WebGLActiveInfo>>> {
+ let Some(program_handle) = self.handle_of(program) else {
+ return Ok(None);
+ };
+
+ let mut name = [0; ACTIVE_INFO_NAME_BUFFER_SIZE];
+ let outputs = self
+ .proxy
+ .get_active_attrib(program_handle, index, ACTIVE_INFO_NAME_BUFFER_GL_SIZE, &mut name);
+ Ok(Some(WebGLActiveInfo::create(
+ cx.vm(),
+ active_info_name(&name, outputs.length),
+ outputs.r#type,
+ outputs.size,
+ )))
+ }
+
+ pub(crate) fn get_active_uniform(
+ &self,
+ cx: &mut CallContext,
+ program: Ref<WebGLProgram>,
+ index: u32,
+ ) -> WebIdlResult<Option<Ref<WebGLActiveInfo>>> {
+ let Some(program_handle) = self.handle_of(program) else {
+ return Ok(None);
+ };
+
+ let mut name = [0; ACTIVE_INFO_NAME_BUFFER_SIZE];
+ let outputs = self
+ .proxy
+ .get_active_uniform(program_handle, index, ACTIVE_INFO_NAME_BUFFER_GL_SIZE, &mut name);
+ Ok(Some(WebGLActiveInfo::create(
+ cx.vm(),
+ active_info_name(&name, outputs.length),
+ outputs.r#type,
+ outputs.size,
+ )))
+ }
+
+ pub(crate) fn get_attached_shaders(
+ &self,
+ _: &mut CallContext,
+ program: Ref<WebGLProgram>,
+ ) -> WebIdlResult<Option<Vec<Ref<WebGLShader>>>> {
+ if self.handle_of(program).is_none() {
+ return Ok(None);
+ }
+
+ let attached_shaders = [
+ program.attached_vertex_shader.get(),
+ program.attached_fragment_shader.get(),
+ ];
+ Ok(Some(attached_shaders.into_iter().flatten().collect()))
+ }
+
+ pub(crate) fn get_attrib_location(
+ &self,
+ _: &mut CallContext,
+ program: Ref<WebGLProgram>,
+ name: Utf16String,
+ ) -> WebIdlResult<i32> {
+ let Some(program_handle) = self.handle_of(program) else {
+ return Ok(-1);
+ };
+ Ok(self.proxy.get_attrib_location(program_handle, &utf8_bytes(&name)))
+ }
+
+ pub(crate) fn make_xr_compatible(&self, _: &mut CallContext) -> WebIdlResult<Gc<Object>> {
+ // SAFETY: The cell is that of this context.
+ Ok(unsafe { super::canvas::make_xr_compatible(self.context_ref().cell()) })
+ }
+
+ pub(crate) fn get_error(&self, _: &mut CallContext) -> WebIdlResult<u32> {
+ Ok(self.take_error())
+ }
+
+ pub(crate) fn get_program_info_log(
+ &self,
+ _: &mut CallContext,
+ program: Ref<WebGLProgram>,
+ ) -> WebIdlResult<Option<Utf16String>> {
+ let Some(program_handle) = self.handle_of(program) else {
+ return Ok(None);
+ };
+
+ let mut info_log_length = [0i32; 1];
+ self.proxy
+ .get_programiv(program_handle, GL_INFO_LOG_LENGTH, &mut info_log_length);
+ let [info_log_length] = info_log_length;
+ if info_log_length == 0 {
+ return Ok(Some(Utf16String::from_ascii(b"")));
+ }
+ let mut info_log = zeroed_gl_string_buffer(info_log_length);
+ self.proxy
+ .get_program_info_log(program_handle, info_log_length, &mut info_log);
+ Ok(Some(utf16_string_from_gl_string(&info_log[..info_log.len() - 1])))
+ }
+
+ pub(crate) fn get_shader_precision_format(
+ &self,
+ cx: &mut CallContext,
+ shadertype: u32,
+ precisiontype: u32,
+ ) -> WebIdlResult<Option<Ref<WebGLShaderPrecisionFormat>>> {
+ let mut range = [0i32; 2];
+ let mut precision = [0i32; 1];
+ self.proxy
+ .get_shader_precision_format(shadertype, precisiontype, &mut range, &mut precision);
+ let [range_min, range_max] = range;
+ let [precision] = precision;
+ Ok(Some(WebGLShaderPrecisionFormat::create(
+ cx.vm(),
+ range_min,
+ range_max,
+ precision,
+ )))
+ }
+
+ pub(crate) fn get_shader_info_log(
+ &self,
+ _: &mut CallContext,
+ shader: Ref<WebGLShader>,
+ ) -> WebIdlResult<Option<Utf16String>> {
+ let Some(shader_handle) = self.handle_of(shader) else {
+ return Ok(None);
+ };
+
+ let mut info_log_length = [0i32; 1];
+ self.proxy
+ .get_shaderiv(shader_handle, GL_INFO_LOG_LENGTH, &mut info_log_length);
+ let [info_log_length] = info_log_length;
+ if info_log_length == 0 {
+ return Ok(Some(Utf16String::from_ascii(b"")));
+ }
+ let mut info_log = zeroed_gl_string_buffer(info_log_length);
+ self.proxy
+ .get_shader_info_log(shader_handle, info_log_length, &mut info_log);
+ Ok(Some(utf16_string_from_gl_string(&info_log[..info_log.len() - 1])))
+ }
+
+ pub(crate) fn get_shader_source(
+ &self,
+ _: &mut CallContext,
+ shader: Ref<WebGLShader>,
+ ) -> WebIdlResult<Option<Utf16String>> {
+ let Some(shader_handle) = self.handle_of(shader) else {
+ return Ok(None);
+ };
+
+ let mut shader_source_length = [0i32; 1];
+ self.proxy
+ .get_shaderiv(shader_handle, GL_SHADER_SOURCE_LENGTH, &mut shader_source_length);
+ let [shader_source_length] = shader_source_length;
+ if shader_source_length == 0 {
+ return Ok(Some(Utf16String::from_ascii(b"")));
+ }
+
+ let mut shader_source = zeroed_gl_string_buffer(shader_source_length);
+ self.proxy
+ .get_shader_source(shader_handle, shader_source_length, &mut shader_source);
+ Ok(Some(utf16_string_from_gl_string(
+ &shader_source[..shader_source.len() - 1],
+ )))
+ }
+
+ pub(crate) fn get_uniform_location(
+ &self,
+ cx: &mut CallContext,
+ program: Ref<WebGLProgram>,
+ name: Utf16String,
+ ) -> WebIdlResult<Option<Ref<WebGLUniformLocation>>> {
+ let Some(program_handle) = self.handle_of(program) else {
+ return Ok(None);
+ };
+
+ // "This function returns -1 if name does not correspond to an active uniform variable in program or if name
+ // starts with the reserved prefix "gl_"."
+ // WebGL Spec: The return value is null if name does not correspond to an active uniform variable in the passed
+ // program.
+ let location = self.proxy.get_uniform_location(program_handle, &utf8_bytes(&name));
+ if location == -1 {
+ return Ok(None);
+ }
+
+ Ok(Some(WebGLUniformLocation::create(cx.vm(), location, program)))
+ }
+
+ pub(crate) fn get_vertex_attrib_offset(&self, _: &mut CallContext, index: u32, pname: u32) -> WebIdlResult<i64> {
+ if pname != GL_VERTEX_ATTRIB_ARRAY_POINTER {
+ self.set_error(GL_INVALID_ENUM);
+ return Ok(0);
+ }
+
+ Ok(self
+ .proxy
+ .get_vertex_attrib_pointerv_robust_angle(index, GL_VERTEX_ATTRIB_ARRAY_POINTER))
+ }
+
+ pub(crate) fn hint(&self, _: &mut CallContext, target: u32, mode: u32) -> WebIdlResult<()> {
+ self.proxy.hint(target, mode);
+ Ok(())
+ }
+
+ pub(crate) fn is_buffer(&self, _: &mut CallContext, buffer: Option<Ref<WebGLBuffer>>) -> WebIdlResult<bool> {
+ let Some(buffer) = buffer else {
+ return Ok(false);
+ };
+ let Some(buffer_handle) = self.handle_for_query_of(buffer) else {
+ return Ok(false);
+ };
+ Ok(self.proxy.is_buffer(buffer_handle))
+ }
+
+ pub(crate) fn is_enabled(&self, _: &mut CallContext, cap: u32) -> WebIdlResult<bool> {
+ Ok(self.proxy.is_enabled(cap))
+ }
+
+ pub(crate) fn is_framebuffer(
+ &self,
+ _: &mut CallContext,
+ framebuffer: Option<Ref<WebGLFramebuffer>>,
+ ) -> WebIdlResult<bool> {
+ let Some(framebuffer) = framebuffer else {
+ return Ok(false);
+ };
+ let Some(framebuffer_handle) = self.handle_for_query_of(framebuffer) else {
+ return Ok(false);
+ };
+ Ok(self.proxy.is_framebuffer(framebuffer_handle))
+ }
+
+ pub(crate) fn is_program(&self, _: &mut CallContext, program: Option<Ref<WebGLProgram>>) -> WebIdlResult<bool> {
+ let Some(program) = program else {
+ return Ok(false);
+ };
+ let Some(program_handle) = self.handle_for_query_of(program) else {
+ return Ok(false);
+ };
+ Ok(self.proxy.is_program(program_handle))
+ }
+
+ pub(crate) fn is_renderbuffer(
+ &self,
+ _: &mut CallContext,
+ renderbuffer: Option<Ref<WebGLRenderbuffer>>,
+ ) -> WebIdlResult<bool> {
+ let Some(renderbuffer) = renderbuffer else {
+ return Ok(false);
+ };
+ let Some(renderbuffer_handle) = self.handle_for_query_of(renderbuffer) else {
+ return Ok(false);
+ };
+ Ok(self.proxy.is_renderbuffer(renderbuffer_handle))
+ }
+
+ pub(crate) fn is_shader(&self, _: &mut CallContext, shader: Option<Ref<WebGLShader>>) -> WebIdlResult<bool> {
+ let Some(shader) = shader else {
+ return Ok(false);
+ };
+ let Some(shader_handle) = self.handle_for_query_of(shader) else {
+ return Ok(false);
+ };
+ Ok(self.proxy.is_shader(shader_handle))
+ }
+
+ pub(crate) fn is_texture(&self, _: &mut CallContext, texture: Option<Ref<WebGLTexture>>) -> WebIdlResult<bool> {
+ let Some(texture) = texture else {
+ return Ok(false);
+ };
+ let Some(texture_handle) = self.handle_for_query_of(texture) else {
+ return Ok(false);
+ };
+ Ok(self.proxy.is_texture(texture_handle))
+ }
+
+ pub(crate) fn line_width(&self, _: &mut CallContext, width: f32) -> WebIdlResult<()> {
+ self.proxy.line_width(width);
+ Ok(())
+ }
+
+ pub(crate) fn link_program(&self, _: &mut CallContext, program: Ref<WebGLProgram>) -> WebIdlResult<()> {
+ let Some(program_handle) = self.handle_of(program) else {
+ return Ok(());
+ };
+ self.proxy.link_program(program_handle);
+ Ok(())
+ }
+
+ pub(crate) fn pixel_storei(&self, _: &mut CallContext, pname: u32, param: i32) -> WebIdlResult<()> {
+ let mut unpack_state = self.unpack_state.get();
+ match pname {
+ GL_UNPACK_ALIGNMENT => {
+ let Ok(alignment @ (1 | 2 | 4 | 8)) = usize::try_from(param) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ unpack_state.alignment = alignment;
+ }
+ GL_UNPACK_ROW_LENGTH => {
+ if self.is_webgl2()
+ && let Ok(row_length) = usize::try_from(param)
+ {
+ unpack_state.row_length = row_length;
+ }
+ }
+ GL_UNPACK_SKIP_PIXELS => {
+ if self.is_webgl2()
+ && let Ok(skip_pixels) = usize::try_from(param)
+ {
+ unpack_state.skip_pixels = skip_pixels;
+ }
+ }
+ GL_UNPACK_SKIP_ROWS => {
+ if self.is_webgl2()
+ && let Ok(skip_rows) = usize::try_from(param)
+ {
+ unpack_state.skip_rows = skip_rows;
+ }
+ }
+ GL_UNPACK_FLIP_Y_WEBGL => {
+ self.unpack_flip_y.set(param != 0);
+ return Ok(());
+ }
+ GL_UNPACK_PREMULTIPLY_ALPHA_WEBGL => {
+ self.unpack_premultiply_alpha.set(param != 0);
+ return Ok(());
+ }
+ GL_UNPACK_COLORSPACE_CONVERSION_WEBGL => {
+ self.unpack_colorspace_conversion.set(param.cast_unsigned());
+ return Ok(());
+ }
+ _ => {}
+ }
+ self.unpack_state.set(unpack_state);
+
+ self.proxy.pixel_storei(pname, param);
+ Ok(())
+ }
+
+ pub(crate) fn polygon_offset(&self, _: &mut CallContext, factor: f32, units: f32) -> WebIdlResult<()> {
+ self.proxy.polygon_offset(factor, units);
+ Ok(())
+ }
+
+ pub(crate) fn renderbuffer_storage(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ internalformat: u32,
+ width: i32,
+ height: i32,
+ ) -> WebIdlResult<()> {
+ let internalformat = if internalformat == GL_DEPTH_STENCIL {
+ GL_DEPTH24_STENCIL8
+ } else {
+ internalformat
+ };
+
+ self.proxy.renderbuffer_storage(target, internalformat, width, height);
+ Ok(())
+ }
+
+ pub(crate) fn sample_coverage(&self, _: &mut CallContext, value: f32, invert: bool) -> WebIdlResult<()> {
+ self.proxy.sample_coverage(value, invert);
+ Ok(())
+ }
+
+ pub(crate) fn scissor(&self, _: &mut CallContext, x: i32, y: i32, width: i32, height: i32) -> WebIdlResult<()> {
+ self.proxy.scissor(x, y, width, height);
+ Ok(())
+ }
+
+ pub(crate) fn shader_source(
+ &self,
+ _: &mut CallContext,
+ shader: Ref<WebGLShader>,
+ source: Utf16String,
+ ) -> WebIdlResult<()> {
+ let Some(shader_handle) = self.handle_of(shader) else {
+ return Ok(());
+ };
+
+ self.proxy.shader_source(shader_handle, &utf8_bytes(&source));
+ Ok(())
+ }
+
+ pub(crate) fn stencil_func(&self, _: &mut CallContext, func: u32, r#ref: i32, mask: u32) -> WebIdlResult<()> {
+ self.proxy.stencil_func(func, r#ref, mask);
+ Ok(())
+ }
+
+ pub(crate) fn stencil_func_separate(
+ &self,
+ _: &mut CallContext,
+ face: u32,
+ func: u32,
+ r#ref: i32,
+ mask: u32,
+ ) -> WebIdlResult<()> {
+ self.proxy.stencil_func_separate(face, func, r#ref, mask);
+ Ok(())
+ }
+
+ pub(crate) fn stencil_mask(&self, _: &mut CallContext, mask: u32) -> WebIdlResult<()> {
+ self.proxy.stencil_mask(mask);
+ Ok(())
+ }
+
+ pub(crate) fn stencil_mask_separate(&self, _: &mut CallContext, face: u32, mask: u32) -> WebIdlResult<()> {
+ self.proxy.stencil_mask_separate(face, mask);
+ Ok(())
+ }
+
+ pub(crate) fn stencil_op(&self, _: &mut CallContext, fail: u32, zfail: u32, zpass: u32) -> WebIdlResult<()> {
+ self.proxy.stencil_op(fail, zfail, zpass);
+ Ok(())
+ }
+
+ pub(crate) fn stencil_op_separate(
+ &self,
+ _: &mut CallContext,
+ face: u32,
+ fail: u32,
+ zfail: u32,
+ zpass: u32,
+ ) -> WebIdlResult<()> {
+ self.proxy.stencil_op_separate(face, fail, zfail, zpass);
+ Ok(())
+ }
+
+ pub(crate) fn tex_parameterf(&self, _: &mut CallContext, target: u32, pname: u32, param: f32) -> WebIdlResult<()> {
+ self.proxy.tex_parameterf(target, pname, param);
+ Ok(())
+ }
+
+ pub(crate) fn tex_parameteri(&self, _: &mut CallContext, target: u32, pname: u32, param: i32) -> WebIdlResult<()> {
+ self.proxy.tex_parameteri(target, pname, param);
+ Ok(())
+ }
+
+ pub(crate) fn uniform1f(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ x: f32,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ self.proxy.uniform1f(location_handle, x);
+ Ok(())
+ }
+
+ pub(crate) fn uniform2f(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ x: f32,
+ y: f32,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ self.proxy.uniform2f(location_handle, x, y);
+ Ok(())
+ }
+
+ pub(crate) fn uniform3f(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ x: f32,
+ y: f32,
+ z: f32,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ self.proxy.uniform3f(location_handle, x, y, z);
+ Ok(())
+ }
+
+ pub(crate) fn uniform4f(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ x: f32,
+ y: f32,
+ z: f32,
+ w: f32,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ self.proxy.uniform4f(location_handle, x, y, z, w);
+ Ok(())
+ }
+
+ pub(crate) fn uniform1i(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ x: i32,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ self.proxy.uniform1i(location_handle, x);
+ Ok(())
+ }
+
+ pub(crate) fn uniform2i(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ x: i32,
+ y: i32,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ self.proxy.uniform2i(location_handle, x, y);
+ Ok(())
+ }
+
+ pub(crate) fn uniform3i(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ x: i32,
+ y: i32,
+ z: i32,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ self.proxy.uniform3i(location_handle, x, y, z);
+ Ok(())
+ }
+
+ pub(crate) fn uniform4i(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ x: i32,
+ y: i32,
+ z: i32,
+ w: i32,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ self.proxy.uniform4i(location_handle, x, y, z, w);
+ Ok(())
+ }
+
+ pub(crate) fn use_program(&self, _: &mut CallContext, program: Option<Ref<WebGLProgram>>) -> WebIdlResult<()> {
+ let mut program_handle = 0;
+ if let Some(program) = program {
+ let Some(handle) = self.handle_of(program) else {
+ return Ok(());
+ };
+ program_handle = handle;
+ }
+
+ self.proxy.use_program(program_handle);
+ self.current_program.set(program);
+ Ok(())
+ }
+
+ pub(crate) fn validate_program(&self, _: &mut CallContext, program: Ref<WebGLProgram>) -> WebIdlResult<()> {
+ let Some(program_handle) = self.handle_of(program) else {
+ return Ok(());
+ };
+ self.proxy.validate_program(program_handle);
+ Ok(())
+ }
+
+ pub(crate) fn vertex_attrib1f(&self, _: &mut CallContext, index: u32, x: f32) -> WebIdlResult<()> {
+ self.proxy.vertex_attrib1f(index, x);
+ Ok(())
+ }
+
+ pub(crate) fn vertex_attrib2f(&self, _: &mut CallContext, index: u32, x: f32, y: f32) -> WebIdlResult<()> {
+ self.proxy.vertex_attrib2f(index, x, y);
+ Ok(())
+ }
+
+ pub(crate) fn vertex_attrib3f(&self, _: &mut CallContext, index: u32, x: f32, y: f32, z: f32) -> WebIdlResult<()> {
+ self.proxy.vertex_attrib3f(index, x, y, z);
+ Ok(())
+ }
+
+ pub(crate) fn vertex_attrib4f(
+ &self,
+ _: &mut CallContext,
+ index: u32,
+ x: f32,
+ y: f32,
+ z: f32,
+ w: f32,
+ ) -> WebIdlResult<()> {
+ self.proxy.vertex_attrib4f(index, x, y, z, w);
+ Ok(())
+ }
+
+ pub(crate) fn vertex_attrib1fv(&self, _: &mut CallContext, index: u32, values: Float32List) -> WebIdlResult<()> {
+ let Some(values) = copy_of_first_numbers(&values, 1) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy.vertex_attrib1fv(index, &values);
+ Ok(())
+ }
+
+ pub(crate) fn vertex_attrib2fv(&self, _: &mut CallContext, index: u32, values: Float32List) -> WebIdlResult<()> {
+ let Some(values) = copy_of_first_numbers(&values, 2) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy.vertex_attrib2fv(index, &values);
+ Ok(())
+ }
+
+ pub(crate) fn vertex_attrib3fv(&self, _: &mut CallContext, index: u32, values: Float32List) -> WebIdlResult<()> {
+ let Some(values) = copy_of_first_numbers(&values, 3) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy.vertex_attrib3fv(index, &values);
+ Ok(())
+ }
+
+ pub(crate) fn vertex_attrib4fv(&self, _: &mut CallContext, index: u32, values: Float32List) -> WebIdlResult<()> {
+ let Some(values) = copy_of_first_numbers(&values, 4) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy.vertex_attrib4fv(index, &values);
+ Ok(())
+ }
+
+ pub(crate) fn vertex_attrib_pointer(
+ &self,
+ _: &mut CallContext,
+ index: u32,
+ size: i32,
+ r#type: u32,
+ normalized: bool,
+ stride: i32,
+ offset: i64,
+ ) -> WebIdlResult<()> {
+ // If no WebGLBuffer is bound to the ARRAY_BUFFER target and offset is non-zero, an INVALID_OPERATION error will
+ // be generated.
+ if self.array_buffer_binding.get().is_none() && offset != 0 {
+ self.set_error(GL_INVALID_OPERATION);
+ return Ok(());
+ }
+
+ self.proxy
+ .vertex_attrib_pointer(index, size, r#type, normalized, stride, offset);
+ Ok(())
+ }
+
+ pub(crate) fn viewport(&self, _: &mut CallContext, x: i32, y: i32, width: i32, height: i32) -> WebIdlResult<()> {
+ self.proxy.viewport(x, y, width, height);
+ Ok(())
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_rendering_context_overloads.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_rendering_context_overloads.rs
new file mode 100644
index 00000000000..473098343b5
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_rendering_context_overloads.rs
@@ -0,0 +1,637 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://registry.khronos.org/webgl/specs/latest/1.0/#5.14
+//!
+//! The operations of a WebGL 1 context that a WebGL 2 context has more overloads of.
+
+use libjs_rust::api::{Gc, TypedArrayBase};
+
+use super::buffer_source::{destination_bytes, list_bytes, source_bytes, write_checked};
+use super::byte_ranges::size_of_zero_filled_texture;
+use super::constants::{
+ GL_ALPHA, GL_INVALID_ENUM, GL_INVALID_OPERATION, GL_INVALID_VALUE, GL_LUMINANCE, GL_LUMINANCE_ALPHA,
+ GL_OUT_OF_MEMORY, GL_RGB, GL_RGBA, GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT_4_4_4_4, GL_UNSIGNED_SHORT_5_5_5_1,
+ GL_UNSIGNED_SHORT_5_6_5,
+};
+use super::state::{RenderingContext, WebGL1};
+use super::types::Float32List;
+use super::web_gl_uniform_location::WebGLUniformLocation;
+use crate::bindings::conversions::{ArrayBufferView, BufferSource, CppInterface};
+use crate::bindings::interface::Ref;
+use crate::bindings::{CallContext, WebIdlResult};
+
+/// https://registry.khronos.org/webgl/specs/latest/1.0/#5.14.8
+// FIXME: VideoFrame
+pub(crate) enum TexImageSource {
+ ImageBitmap(CppInterface),
+ ImageData(CppInterface),
+ HTMLImageElement(CppInterface),
+ HTMLCanvasElement(CppInterface),
+ HTMLVideoElement(CppInterface),
+ OffscreenCanvas(CppInterface),
+}
+
+pub(crate) enum Int32List {
+ Int32Array(Gc<TypedArrayBase>),
+ Sequence(Vec<i32>),
+}
+
+#[expect(
+ clippy::too_many_arguments,
+ reason = "the operations have the arguments of the GL functions"
+)]
+impl RenderingContext<WebGL1> {
+ pub(crate) fn buffer_data_with_size(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ size: i64,
+ usage: u32,
+ ) -> WebIdlResult<()> {
+ self.proxy.buffer_data(target, size, None, usage);
+ Ok(())
+ }
+
+ pub(crate) fn buffer_data(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ data: Option<BufferSource>,
+ usage: u32,
+ ) -> WebIdlResult<()> {
+ // https://registry.khronos.org/webgl/specs/latest/1.0/#5.14.5
+ // If the passed data is null then an INVALID_VALUE error is generated.
+ let Some(data) = data else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Ok(bytes) = source_bytes(data, 0, 0) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let size = i64::from(bytes.gl_size());
+ // SAFETY: Recording the command neither runs script nor allocates a cell.
+ unsafe {
+ self.upload_through_nullable_pointer(&bytes, |bytes| {
+ self.proxy.buffer_data(target, size, bytes, usage);
+ });
+ }
+ Ok(())
+ }
+
+ pub(crate) fn buffer_sub_data(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ offset: i64,
+ data: BufferSource,
+ ) -> WebIdlResult<()> {
+ let Ok(bytes) = source_bytes(data, 0, 0) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let size = i64::from(bytes.gl_size());
+ // SAFETY: Recording the command neither runs script nor allocates a cell.
+ unsafe {
+ self.upload(&bytes, |bytes| {
+ self.proxy.buffer_sub_data(target, offset, size, bytes);
+ });
+ }
+ Ok(())
+ }
+
+ pub(crate) fn compressed_tex_image2d(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ level: i32,
+ internalformat: u32,
+ width: i32,
+ height: i32,
+ border: i32,
+ data: ArrayBufferView,
+ ) -> WebIdlResult<()> {
+ if !self
+ .enabled_compressed_texture_formats
+ .borrow()
+ .contains(&internalformat)
+ {
+ self.set_error(GL_INVALID_ENUM);
+ return Ok(());
+ }
+ let Ok(bytes) = source_bytes(data.into(), 0, 0) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let size = bytes.gl_size();
+ // SAFETY: Recording the command neither runs script nor allocates a cell.
+ unsafe {
+ self.upload(&bytes, |bytes| {
+ self.proxy.compressed_tex_image2d_robust_angle(
+ target,
+ level,
+ internalformat,
+ width,
+ height,
+ border,
+ size,
+ size,
+ bytes,
+ );
+ });
+ }
+ Ok(())
+ }
+
+ pub(crate) fn compressed_tex_sub_image2d(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ level: i32,
+ xoffset: i32,
+ yoffset: i32,
+ width: i32,
+ height: i32,
+ format: u32,
+ data: ArrayBufferView,
+ ) -> WebIdlResult<()> {
+ if !self.enabled_compressed_texture_formats.borrow().contains(&format) {
+ self.set_error(GL_INVALID_ENUM);
+ return Ok(());
+ }
+ let Ok(bytes) = source_bytes(data.into(), 0, 0) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let size = bytes.gl_size();
+ // SAFETY: Recording the command neither runs script nor allocates a cell.
+ unsafe {
+ self.upload(&bytes, |bytes| {
+ self.proxy.compressed_tex_sub_image2d_robust_angle(
+ target, level, xoffset, yoffset, width, height, format, size, size, bytes,
+ );
+ });
+ }
+ Ok(())
+ }
+
+ pub(crate) fn read_pixels(
+ &self,
+ _: &mut CallContext,
+ x: i32,
+ y: i32,
+ width: i32,
+ height: i32,
+ format: u32,
+ r#type: u32,
+ pixels: Option<ArrayBufferView>,
+ ) -> WebIdlResult<()> {
+ let Some(view) = pixels else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Ok(destination_bytes) = destination_bytes(&view, 0) else {
+ self.set_error(GL_INVALID_OPERATION);
+ return Ok(());
+ };
+ let Ok(buf_size) = i32::try_from(destination_bytes.len()) else {
+ self.set_error(GL_OUT_OF_MEMORY);
+ return Ok(());
+ };
+ self.proxy
+ .read_pixels_robust_angle(x, y, width, height, format, r#type, buf_size, |_, pixels| {
+ if write_checked(&view, pixels, 0).is_err() {
+ self.set_error(GL_INVALID_OPERATION);
+ }
+ });
+ Ok(())
+ }
+
+ pub(crate) fn tex_image2d(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ level: i32,
+ internalformat: i32,
+ width: i32,
+ height: i32,
+ border: i32,
+ format: u32,
+ r#type: u32,
+ pixels: Option<ArrayBufferView>,
+ ) -> WebIdlResult<()> {
+ if let Some(pixels) = pixels {
+ let Ok(texture_data) = self.texture_data_for_2d_upload(pixels, 0, width, height, format, r#type) else {
+ self.set_error(GL_INVALID_OPERATION);
+ return Ok(());
+ };
+ let buf_size = texture_data.gl_size();
+ // SAFETY: Recording the command neither runs script nor allocates a cell.
+ unsafe {
+ self.upload_through_nullable_pointer(&texture_data, |texture_data| {
+ self.proxy.tex_image2d_robust_angle(
+ target,
+ level,
+ internalformat,
+ width,
+ height,
+ border,
+ format,
+ r#type,
+ buf_size,
+ texture_data,
+ );
+ });
+ }
+ return Ok(());
+ }
+
+ if r#type == GL_UNSIGNED_SHORT_5_6_5 && format != GL_RGB {
+ self.set_error(GL_INVALID_OPERATION);
+ return Ok(());
+ }
+ if (r#type == GL_UNSIGNED_SHORT_4_4_4_4 || r#type == GL_UNSIGNED_SHORT_5_5_5_1) && format != GL_RGBA {
+ self.set_error(GL_INVALID_OPERATION);
+ return Ok(());
+ }
+ let bytes_per_pixel: usize = match (format, r#type) {
+ (GL_ALPHA | GL_LUMINANCE, GL_UNSIGNED_BYTE) => 1,
+ (GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE)
+ | (GL_RGB | GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4 | GL_UNSIGNED_SHORT_5_5_5_1 | GL_UNSIGNED_SHORT_5_6_5) => 2,
+ (GL_RGB, GL_UNSIGNED_BYTE) => 3,
+ (GL_RGBA, GL_UNSIGNED_BYTE) => 4,
+ _ => {
+ self.set_error(GL_INVALID_ENUM);
+ return Ok(());
+ }
+ };
+ let Ok(size) = size_of_zero_filled_texture(bytes_per_pixel, width, height) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let zeroes = vec![0; size.get()];
+ self.proxy.tex_image2d_robust_angle(
+ target,
+ level,
+ internalformat,
+ width,
+ height,
+ border,
+ format,
+ r#type,
+ size.as_gl_sizei(),
+ Some(&zeroes),
+ );
+ Ok(())
+ }
+
+ pub(crate) fn tex_image2d_with_source(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ level: i32,
+ internalformat: i32,
+ format: u32,
+ r#type: u32,
+ source: TexImageSource,
+ ) -> WebIdlResult<()> {
+ let Some((frame, upload)) = self.read_texture_image_source(&source, format, r#type) else {
+ return Ok(());
+ };
+ self.proxy
+ .tex_image2d_from_bitmap(target, level, internalformat, format, r#type, frame, upload);
+ Ok(())
+ }
+
+ pub(crate) fn tex_sub_image2d(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ level: i32,
+ xoffset: i32,
+ yoffset: i32,
+ width: i32,
+ height: i32,
+ format: u32,
+ r#type: u32,
+ pixels: Option<ArrayBufferView>,
+ ) -> WebIdlResult<()> {
+ let Some(pixels) = pixels else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Ok(texture_data) = self.texture_data_for_2d_upload(pixels, 0, width, height, format, r#type) else {
+ self.set_error(GL_INVALID_OPERATION);
+ return Ok(());
+ };
+ let buf_size = texture_data.gl_size();
+ // SAFETY: Recording the command neither runs script nor allocates a cell.
+ unsafe {
+ self.upload_through_nullable_pointer(&texture_data, |texture_data| {
+ self.proxy.tex_sub_image2d_robust_angle(
+ target,
+ level,
+ xoffset,
+ yoffset,
+ width,
+ height,
+ format,
+ r#type,
+ buf_size,
+ texture_data,
+ );
+ });
+ }
+ Ok(())
+ }
+
+ pub(crate) fn tex_sub_image2d_with_source(
+ &self,
+ _: &mut CallContext,
+ target: u32,
+ level: i32,
+ xoffset: i32,
+ yoffset: i32,
+ format: u32,
+ r#type: u32,
+ source: TexImageSource,
+ ) -> WebIdlResult<()> {
+ let Some((frame, upload)) = self.read_texture_image_source(&source, format, r#type) else {
+ return Ok(());
+ };
+ self.proxy
+ .tex_sub_image2d_from_bitmap(target, level, xoffset, yoffset, format, r#type, frame, upload);
+ Ok(())
+ }
+
+ pub(crate) fn uniform1fv(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ v: Float32List,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ let Ok(values) = list_bytes(&v, 0, 0) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy
+ .uniform1fv(location_handle, values.gl_count(), values.as_bytes());
+ Ok(())
+ }
+
+ pub(crate) fn uniform2fv(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ v: Float32List,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ let Ok(values) = list_bytes(&v, 0, 0) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Some(count) = values.gl_count_of_whole_groups_of(2) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy.uniform2fv(location_handle, count, values.as_bytes());
+ Ok(())
+ }
+
+ pub(crate) fn uniform3fv(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ v: Float32List,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ let Ok(values) = list_bytes(&v, 0, 0) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Some(count) = values.gl_count_of_whole_groups_of(3) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy.uniform3fv(location_handle, count, values.as_bytes());
+ Ok(())
+ }
+
+ pub(crate) fn uniform4fv(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ v: Float32List,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ let Ok(values) = list_bytes(&v, 0, 0) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Some(count) = values.gl_count_of_whole_groups_of(4) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy.uniform4fv(location_handle, count, values.as_bytes());
+ Ok(())
+ }
+
+ pub(crate) fn uniform1iv(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ v: Int32List,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ let Ok(values) = list_bytes(&v, 0, 0) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy
+ .uniform1iv(location_handle, values.gl_count(), values.as_bytes());
+ Ok(())
+ }
+
+ pub(crate) fn uniform2iv(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ v: Int32List,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ let Ok(values) = list_bytes(&v, 0, 0) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Some(count) = values.gl_count_of_whole_groups_of(2) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy.uniform2iv(location_handle, count, values.as_bytes());
+ Ok(())
+ }
+
+ pub(crate) fn uniform3iv(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ v: Int32List,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ let Ok(values) = list_bytes(&v, 0, 0) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Some(count) = values.gl_count_of_whole_groups_of(3) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy.uniform3iv(location_handle, count, values.as_bytes());
+ Ok(())
+ }
+
+ pub(crate) fn uniform4iv(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ v: Int32List,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ let Ok(values) = list_bytes(&v, 0, 0) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Some(count) = values.gl_count_of_whole_groups_of(4) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy.uniform4iv(location_handle, count, values.as_bytes());
+ Ok(())
+ }
+
+ pub(crate) fn uniform_matrix2fv(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ transpose: bool,
+ value: Float32List,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ const MATRIX_SIZE: usize = 2 * 2;
+ let Ok(values) = list_bytes(&value, 0, 0) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Some(count) = values.gl_count_of_whole_groups_of(MATRIX_SIZE) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy
+ .uniform_matrix2fv(location_handle, count, transpose, values.as_bytes());
+ Ok(())
+ }
+
+ pub(crate) fn uniform_matrix3fv(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ transpose: bool,
+ value: Float32List,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ const MATRIX_SIZE: usize = 3 * 3;
+ let Ok(values) = list_bytes(&value, 0, 0) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Some(count) = values.gl_count_of_whole_groups_of(MATRIX_SIZE) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy
+ .uniform_matrix3fv(location_handle, count, transpose, values.as_bytes());
+ Ok(())
+ }
+
+ pub(crate) fn uniform_matrix4fv(
+ &self,
+ _: &mut CallContext,
+ location: Option<Ref<WebGLUniformLocation>>,
+ transpose: bool,
+ value: Float32List,
+ ) -> WebIdlResult<()> {
+ let Some(location) = location else {
+ return Ok(());
+ };
+ let Some(location_handle) = self.uniform_location_handle(location) else {
+ return Ok(());
+ };
+ const MATRIX_SIZE: usize = 4 * 4;
+ let Ok(values) = list_bytes(&value, 0, 0) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ let Some(count) = values.gl_count_of_whole_groups_of(MATRIX_SIZE) else {
+ self.set_error(GL_INVALID_VALUE);
+ return Ok(());
+ };
+ self.proxy
+ .uniform_matrix4fv(location_handle, count, transpose, values.as_bytes());
+ Ok(())
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_shader.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_shader.rs
new file mode 100644
index 00000000000..d52e4693f34
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_shader.rs
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://registry.khronos.org/webgl/specs/latest/1.0/#5.8
+
+use libjs_rust::api::{Gc, Realm, Trace, Vm};
+
+use super::state::ContextState;
+use super::web_gl_object::WebGLObject;
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct WebGLShader {
+ object: WebGLObject,
+ #[gc(untraced)]
+ r#type: u32,
+}
+
+impl Wrappable for WebGLShader {
+ fn relevant_realm(&self, vm: &Vm) -> Option<Gc<Realm>> {
+ self.object.relevant_realm(vm)
+ }
+}
+
+impl Inherits<WebGLObject> for WebGLShader {
+ fn parent(&self) -> &WebGLObject {
+ &self.object
+ }
+}
+
+impl WebGLShader {
+ pub(crate) fn create(vm: &Vm, context: &ContextState, handle: u32, r#type: u32) -> Ref<Self> {
+ allocate(
+ vm,
+ Self {
+ object: WebGLObject::new(context, handle),
+ r#type,
+ },
+ )
+ }
+
+ pub(crate) fn r#type(&self) -> u32 {
+ self.r#type
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_shader_precision_format.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_shader_precision_format.rs
new file mode 100644
index 00000000000..0945895e2fc
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_shader_precision_format.rs
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://registry.khronos.org/webgl/specs/latest/1.0/#5.12
+
+use libjs_rust::api::{Trace, Vm};
+
+use crate::bindings::interface::{Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, WebIdlResult};
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct WebGLShaderPrecisionFormat {
+ #[gc(untraced)]
+ range_min: i32,
+ #[gc(untraced)]
+ range_max: i32,
+ #[gc(untraced)]
+ precision: i32,
+}
+
+impl Wrappable for WebGLShaderPrecisionFormat {}
+
+impl WebGLShaderPrecisionFormat {
+ pub(crate) fn create(vm: &Vm, range_min: i32, range_max: i32, precision: i32) -> Ref<Self> {
+ allocate(
+ vm,
+ Self {
+ range_min,
+ range_max,
+ precision,
+ },
+ )
+ }
+
+ pub(crate) fn range_min(&self, _: &mut CallContext) -> WebIdlResult<i32> {
+ Ok(self.range_min)
+ }
+
+ pub(crate) fn range_max(&self, _: &mut CallContext) -> WebIdlResult<i32> {
+ Ok(self.range_max)
+ }
+
+ pub(crate) fn precision(&self, _: &mut CallContext) -> WebIdlResult<i32> {
+ Ok(self.precision)
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_sync.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_sync.rs
new file mode 100644
index 00000000000..08663fb7763
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_sync.rs
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://registry.khronos.org/webgl/specs/latest/2.0/#3.4
+
+use libjs_rust::api::{Gc, Realm, Trace, Vm};
+
+use super::state::ContextState;
+use super::web_gl_object::{InvalidOperation, WebGLObject};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct WebGLSync {
+ object: WebGLObject,
+ /// The name of the sync object, which is no GL name of the kind that other objects have.
+ #[gc(untraced)]
+ sync_handle: u32,
+}
+
+impl Wrappable for WebGLSync {
+ fn relevant_realm(&self, vm: &Vm) -> Option<Gc<Realm>> {
+ self.object.relevant_realm(vm)
+ }
+}
+
+impl Inherits<WebGLObject> for WebGLSync {
+ fn parent(&self) -> &WebGLObject {
+ &self.object
+ }
+}
+
+impl WebGLSync {
+ pub(crate) fn create(vm: &Vm, context: &ContextState, sync_handle: u32) -> Ref<Self> {
+ allocate(
+ vm,
+ Self {
+ object: WebGLObject::new(context, 0),
+ sync_handle,
+ },
+ )
+ }
+
+ pub(crate) fn sync_handle(&self, context: &ContextState) -> Result<u32, InvalidOperation> {
+ self.object.handle(context).map(|_| self.sync_handle)
+ }
+
+ pub(crate) fn sync_handle_for_deletion(&self, context: &ContextState) -> Result<Option<u32>, InvalidOperation> {
+ Ok(self.object.handle_for_deletion(context)?.map(|_| self.sync_handle))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_uniform_location.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_uniform_location.rs
new file mode 100644
index 00000000000..d48f8c411d4
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_uniform_location.rs
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://registry.khronos.org/webgl/specs/latest/1.0/#5.10
+
+use libjs_rust::api::{Gc, Realm, Trace, Vm};
+
+use super::web_gl_object::InvalidOperation;
+use super::web_gl_program::WebGLProgram;
+use crate::bindings::interface::{Ref, Wrappable, allocate};
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct WebGLUniformLocation {
+ #[gc(untraced)]
+ handle: i32,
+ program: Ref<WebGLProgram>,
+}
+
+impl Wrappable for WebGLUniformLocation {
+ fn relevant_realm(&self, vm: &Vm) -> Option<Gc<Realm>> {
+ self.program.relevant_realm(vm)
+ }
+}
+
+impl WebGLUniformLocation {
+ pub(crate) fn create(vm: &Vm, handle: i32, program: Ref<WebGLProgram>) -> Ref<Self> {
+ allocate(vm, Self { handle, program })
+ }
+
+ pub(crate) fn handle(&self, current_program: Option<Ref<WebGLProgram>>) -> Result<i32, InvalidOperation> {
+ match current_program {
+ Some(current_program) if current_program.as_ptr() == self.program.as_ptr() => Ok(self.handle),
+ _ => Err(InvalidOperation),
+ }
+ }
+}
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index df98f12cd41..ef7558053eb 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -1049,45 +1049,9 @@ set(SOURCES
WebDriver/UserPrompt.cpp
WebGL/EventNames.cpp
WebGL/RemoteWebGLTransportFFI.cpp
- WebGL/Extensions/ANGLEInstancedArrays.cpp
- WebGL/Extensions/EXTBlendMinMax.cpp
- WebGL/Extensions/EXTColorBufferFloat.cpp
- WebGL/Extensions/EXTRenderSnorm.cpp
- WebGL/Extensions/EXTTextureFilterAnisotropic.cpp
- WebGL/Extensions/EXTTextureNorm16.cpp
- WebGL/Extensions/OESElementIndexUint.cpp
- WebGL/Extensions/OESStandardDerivatives.cpp
- WebGL/Extensions/OESVertexArrayObject.cpp
- WebGL/Extensions/WebGLCompressedTextureS3tc.cpp
- WebGL/Extensions/WebGLCompressedTextureS3tcSrgb.cpp
- WebGL/Extensions/WebGLDebugRendererInfo.cpp
- WebGL/Extensions/WebGLDrawBuffers.cpp
- WebGL/Extensions/WebGLVertexArrayObjectOES.cpp
- WebGL/WebGL2RenderingContext.cpp
- WebGL/WebGL2RenderingContextImpl.cpp
- WebGL/WebGL2RenderingContextOverloads.cpp
- WebGL/WebGLActiveInfo.cpp
- WebGL/WebGLBuffer.cpp
WebGL/WebGLContextAttributes.cpp
WebGL/WebGLContextEvent.cpp
- WebGL/WebGLContextProxyBase.cpp
- WebGL/WebGLFramebuffer.cpp
- WebGL/WebGLObject.cpp
- WebGL/WebGLProgram.cpp
- WebGL/WebGLQuery.cpp
- WebGL/WebGLRenderbuffer.cpp
- WebGL/WebGLRenderingContext.cpp
WebGL/WebGLRenderingContextBase.cpp
- WebGL/WebGLRenderingContextImpl.cpp
- WebGL/WebGLRenderingContextOverloads.cpp
- WebGL/WebGLSampler.cpp
- WebGL/WebGLShader.cpp
- WebGL/WebGLShaderPrecisionFormat.cpp
- WebGL/WebGLSync.cpp
- WebGL/WebGLTexture.cpp
- WebGL/WebGLTransformFeedback.cpp
- WebGL/WebGLUniformLocation.cpp
- WebGL/WebGLVertexArrayObject.cpp
WebIDL/AbstractOperations.cpp
WebIDL/AsyncIterator.cpp
WebIDL/Buffers.cpp
@@ -1138,7 +1102,6 @@ generate_css_implementation()
generate_html_implementation()
-generate_webgl_implementation()
set(GENERATED_SOURCES
ARIA/AriaRoles.cpp
@@ -1161,7 +1124,6 @@ set(GENERATED_SOURCES
SVG/SVGStyleSheetSource.cpp
HTML/MediaControlsDOM.cpp
HTML/Parser/NamedCharacterReferences.cpp
- WebGL/WebGLContextProxy.cpp
)
ladybird_lib(LibWeb web EXPLICIT_SYMBOL_EXPORT)
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index 6f944df8294..254b2f23a4f 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -1265,39 +1265,10 @@ class PeriodicWave;
namespace Web::WebGL {
class RemoteWebGLTransport;
-class WebGLContextProxy;
class WebGL2RenderingContext;
-class WebGLActiveInfo;
-class WebGLBuffer;
class WebGLContextEvent;
-class WebGLFramebuffer;
-class WebGLObject;
-class WebGLProgram;
-class WebGLQuery;
-class WebGLRenderbuffer;
class WebGLRenderingContext;
class WebGLRenderingContextBase;
-class WebGLSampler;
-class WebGLShader;
-class WebGLShaderPrecisionFormat;
-class WebGLSync;
-class WebGLTexture;
-class WebGLTransformFeedback;
-class WebGLUniformLocation;
-class WebGLVertexArrayObject;
-class ANGLEInstancedArrays;
-class EXTBlendMinMax;
-class EXTColorBufferFloat;
-class EXTRenderSnorm;
-class EXTTextureFilterAnisotropic;
-class EXTTextureNorm16;
-class OESElementIndexUint;
-class OESStandardDerivatives;
-class OESVertexArrayObject;
-class WebGLCompressedTextureS3tc;
-class WebGLCompressedTextureS3tcSrgb;
-class WebGLDrawBuffers;
-class WebGLVertexArrayObjectOES;
}
diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasHost.cpp b/Libraries/LibWeb/HTML/Canvas/CanvasHost.cpp
index 9323b4b15ea..26ec79559a6 100644
--- a/Libraries/LibWeb/HTML/Canvas/CanvasHost.cpp
+++ b/Libraries/LibWeb/HTML/Canvas/CanvasHost.cpp
@@ -10,7 +10,6 @@
#include <LibGfx/Rect.h>
#include <LibWeb/HTML/Canvas/Canvas2DContextBase.h>
#include <LibWeb/HTML/Canvas/CanvasHost.h>
-#include <LibWeb/WebGL/WebGLContextProxy.h>
#include <LibWeb/WebGL/WebGLRenderingContextBase.h>
namespace Web::HTML {
@@ -51,7 +50,7 @@ RefPtr<Gfx::Bitmap> CanvasHost::get_bitmap_from_surface()
return nullptr;
if (auto* webgl_context = canvas_webgl_context())
- return webgl_context->context().read_back_drawing_buffer({ {}, size });
+ return webgl_context->read_back_drawing_buffer({ {}, size });
if (auto* context = canvas_2d_context()) {
context->ensure_backing_storage();
diff --git a/Libraries/LibWeb/HTML/HTMLCanvasElement.cpp b/Libraries/LibWeb/HTML/HTMLCanvasElement.cpp
index 0c5390050c0..b34f316111d 100644
--- a/Libraries/LibWeb/HTML/HTMLCanvasElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLCanvasElement.cpp
@@ -41,7 +41,6 @@
#include <LibWeb/Platform/EventLoopPlugin.h>
#include <LibWeb/Platform/FontPlugin.h>
#include <LibWeb/WebGL/WebGL2RenderingContext.h>
-#include <LibWeb/WebGL/WebGLContextProxy.h>
#include <LibWeb/WebGL/WebGLRenderingContext.h>
#include <LibWeb/WebIDL/AbstractOperations.h>
#include <LibWeb/WebIDL/DOMException.h>
@@ -486,7 +485,7 @@ Optional<Compositing::CanvasId> HTMLCanvasElement::canvas_id() const
if (auto context = canvas_rendering_context_2d())
return context->canvas_id();
if (auto* webgl_context = canvas_webgl_context(); webgl_context && !webgl_context->is_context_lost())
- return webgl_context->context().canvas_id();
+ return webgl_context->canvas_id();
return {};
}
diff --git a/Libraries/LibWeb/HTML/OffscreenCanvas.cpp b/Libraries/LibWeb/HTML/OffscreenCanvas.cpp
index 7d1c7048474..76dac9cd1ea 100644
--- a/Libraries/LibWeb/HTML/OffscreenCanvas.cpp
+++ b/Libraries/LibWeb/HTML/OffscreenCanvas.cpp
@@ -33,7 +33,6 @@
#include <LibWeb/Platform/EventLoopPlugin.h>
#include <LibWeb/Platform/FontPlugin.h>
#include <LibWeb/WebGL/WebGL2RenderingContext.h>
-#include <LibWeb/WebGL/WebGLContextProxy.h>
#include <LibWeb/WebGL/WebGLRenderingContext.h>
#include <LibWeb/WebIDL/DOMException.h>
#include <LibWeb/WebIDL/ExceptionOrUtils.h>
@@ -225,7 +224,7 @@ WebIDL::ExceptionOr<GC::Ref<ImageBitmap>> OffscreenCanvas::transfer_to_image_bit
if (auto* context = m_context.get_pointer<GC::Ref<OffscreenCanvasRenderingContext2D>>())
(*context)->replace_bitmap_with_cleared_bitmap();
else if (auto* webgl_context = canvas_webgl_context())
- webgl_context->context().clear_drawing_buffer();
+ webgl_context->clear_drawing_buffer();
// 5. Return image.
return image;
@@ -353,7 +352,7 @@ void OffscreenCanvas::commit_to_placeholder()
if (context->is_context_lost())
return;
context->prepare_for_compositing();
- source_canvas_id = context->context().canvas_id();
+ source_canvas_id = context->canvas_id();
},
[](Empty) {
// Do nothing.
diff --git a/Libraries/LibWeb/WebGL/BindingsGlue.h b/Libraries/LibWeb/WebGL/BindingsGlue.h
deleted file mode 100644
index a406b0b1a4b..00000000000
--- a/Libraries/LibWeb/WebGL/BindingsGlue.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Optional.h>
-#include <AK/String.h>
-#include <AK/Types.h>
-#include <AK/Vector.h>
-#include <LibGC/Forward.h>
-#include <LibJS/Forward.h>
-#include <LibJS/Runtime/Completion.h>
-#include <LibJS/Runtime/Value.h>
-#include <LibWeb/Export.h>
-#include <LibWeb/Forward.h>
-#include <LibWeb/WebGL/WebGLContextAttributes.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-#include <LibWeb/WebIDL/Promise.h>
-#include <LibWebCommon/WebIDL/Types.h>
-
-namespace Web::WebGL {
-
-class WebGL2RenderingContext;
-class WebGLExtension;
-class WebGLProgram;
-class WebGLQuery;
-class WebGLRenderingContext;
-class WebGLRenderingContextBase;
-class WebGLRenderingContextImpl;
-class WebGLShader;
-class WebGLSync;
-class WebGLUniformLocation;
-
-}
-
-namespace Web::Bindings {
-
-class Wrappable;
-
-WEB_API JS::Object* webgl_extension(JS::Realm&, GC::Ref<WebGL::WebGLExtension>);
-WEB_API JS::Value webgl_wrappable(JS::Realm&, GC::Ref<Wrappable>);
-WEB_API JS::Value webgl_buffer(JS::Realm&, GC::Ref<WebGL::WebGLRenderingContextBase>, u32 handle);
-WEB_API Optional<WebGLContextAttributes> get_context_attributes(JS::Realm&, WebGL::WebGLRenderingContext&);
-WEB_API Optional<WebGLContextAttributes> get_context_attributes(JS::Realm&, WebGL::WebGL2RenderingContext&);
-WEB_API JS::Object* get_extension(JS::Realm&, WebGL::WebGLRenderingContext&, String const& name);
-WEB_API JS::Object* get_extension(JS::Realm&, WebGL::WebGL2RenderingContext&, String const& name);
-WEB_API JS::Value get_buffer_parameter(JS::Realm&, WebGL::WebGLRenderingContextImpl&, WebIDL::UnsignedLong target, WebIDL::UnsignedLong pname);
-WEB_API JS::Value get_parameter(JS::Realm&, WebGL::WebGLRenderingContextImpl&, WebIDL::UnsignedLong pname);
-WEB_API JS::Value get_program_parameter(JS::Realm&, WebGL::WebGLRenderingContextImpl&, GC::Ref<WebGL::WebGLProgram>, WebIDL::UnsignedLong pname);
-WEB_API JS::Value get_renderbuffer_parameter(JS::Realm&, WebGL::WebGLRenderingContextImpl&, WebIDL::UnsignedLong target, WebIDL::UnsignedLong pname);
-WEB_API JS::Value get_shader_parameter(JS::Realm&, WebGL::WebGLRenderingContextImpl&, GC::Ref<WebGL::WebGLShader>, WebIDL::UnsignedLong pname);
-WEB_API JS::Value get_tex_parameter(JS::Realm&, WebGL::WebGLRenderingContextImpl&, WebIDL::UnsignedLong target, WebIDL::UnsignedLong pname);
-WEB_API JS::Value get_vertex_attrib(JS::Realm&, WebGL::WebGLRenderingContextImpl&, WebIDL::UnsignedLong index, WebIDL::UnsignedLong pname);
-WEB_API JS::Value get_uniform(JS::Realm&, WebGL::WebGLRenderingContextImpl&, GC::Ref<WebGL::WebGLProgram>, GC::Ref<WebGL::WebGLUniformLocation>);
-WEB_API JS::Value get_query_parameter(JS::Realm&, WebGL::WebGL2RenderingContext&, GC::Ref<WebGL::WebGLQuery>, WebIDL::UnsignedLong pname);
-WEB_API JS::Value get_sync_parameter(JS::Realm&, WebGL::WebGL2RenderingContext&, GC::Ref<WebGL::WebGLSync>, WebIDL::UnsignedLong pname);
-WEB_API JS::Value get_active_uniforms(JS::Realm&, WebGL::WebGL2RenderingContext&, GC::Ref<WebGL::WebGLProgram>, Vector<WebIDL::UnsignedLong> uniform_indices, WebIDL::UnsignedLong pname);
-WEB_API JS::Value get_internalformat_parameter(JS::Realm&, WebGL::WebGL2RenderingContext&, WebIDL::UnsignedLong target, WebIDL::UnsignedLong internalformat, WebIDL::UnsignedLong pname);
-WEB_API JS::Value get_active_uniform_block_parameter(JS::Realm&, WebGL::WebGL2RenderingContext&, GC::Ref<WebGL::WebGLProgram>, WebIDL::UnsignedLong uniform_block_index, WebIDL::UnsignedLong pname);
-WEB_API WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> make_xr_compatible(JS::Realm&, WebGL::WebGLRenderingContextBase&);
-
-template<typename T>
-JS::Value webgl_wrappable(JS::Realm& realm, GC::Ptr<T> wrappable)
-{
- if (!wrappable)
- return JS::js_null();
- return webgl_wrappable(realm, GC::Ref<Wrappable> { *wrappable });
-}
-
-}
diff --git a/Libraries/LibWeb/WebGL/Extensions/ANGLEInstancedArrays.cpp b/Libraries/LibWeb/WebGL/Extensions/ANGLEInstancedArrays.cpp
deleted file mode 100644
index e701349a374..00000000000
--- a/Libraries/LibWeb/WebGL/Extensions/ANGLEInstancedArrays.cpp
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (c) 2024, Aliaksandr Kalenik <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/Runtime/Realm.h>
-#include <LibWeb/Bindings/ANGLEInstancedArrays.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/WebGL/Extensions/ANGLEInstancedArrays.h>
-#include <LibWeb/WebGL/WebGLContextProxy.h>
-#include <LibWeb/WebGL/WebGLRenderingContextBase.h>
-
-#include <GLES2/gl2.h>
-#include <GLES2/gl2ext.h>
-
-namespace Web::WebGL {
-
-GC_DEFINE_ALLOCATOR(ANGLEInstancedArrays);
-
-GC::Ref<Bindings::Wrappable> ANGLEInstancedArrays::create(GC::Ref<WebGLRenderingContextBase> context)
-{
- auto& realm = context->realm();
- return realm.create<ANGLEInstancedArrays>(realm, context);
-}
-
-ANGLEInstancedArrays::ANGLEInstancedArrays(JS::Realm&, GC::Ref<WebGLRenderingContextBase> context)
- : m_context(context)
-{
-}
-
-void ANGLEInstancedArrays::vertex_attrib_divisor_angle(GLuint index, GLuint divisor)
-{
- m_context->context().make_current();
- m_context->context().vertex_attrib_divisor_angle(index, divisor);
-}
-
-void ANGLEInstancedArrays::draw_arrays_instanced_angle(GLenum mode, GLint first, GLsizei count, GLsizei primcount)
-{
- m_context->context().make_current();
- m_context->context().draw_arrays_instanced_angle(mode, first, count, primcount);
-}
-
-void ANGLEInstancedArrays::draw_elements_instanced_angle(GLenum mode, GLsizei count, GLenum type, GLintptr offset, GLsizei primcount)
-{
- m_context->context().make_current();
- m_context->context().draw_elements_instanced_angle(mode, count, type, reinterpret_cast<void*>(offset), primcount);
-}
-
-void ANGLEInstancedArrays::visit_edges(Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_context);
-}
-
-}
diff --git a/Libraries/LibWeb/WebGL/Extensions/ANGLEInstancedArrays.h b/Libraries/LibWeb/WebGL/Extensions/ANGLEInstancedArrays.h
deleted file mode 100644
index dc231571ac7..00000000000
--- a/Libraries/LibWeb/WebGL/Extensions/ANGLEInstancedArrays.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (c) 2024, Aliaksandr Kalenik <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/Forward.h>
-#include <LibWeb/WebGL/Types.h>
-
-namespace Web::WebGL {
-
-class ANGLEInstancedArrays : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(ANGLEInstancedArrays, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(ANGLEInstancedArrays);
-
-public:
- static GC::Ref<Bindings::Wrappable> create(GC::Ref<WebGLRenderingContextBase>);
-
- void draw_arrays_instanced_angle(GLenum mode, GLint first, GLsizei count, GLsizei primcount);
- void draw_elements_instanced_angle(GLenum mode, GLsizei count, GLenum type, GLintptr offset, GLsizei primcount);
- void vertex_attrib_divisor_angle(GLuint index, GLuint divisor);
-
-protected:
- void visit_edges(Visitor&) override;
-
-private:
- ANGLEInstancedArrays(JS::Realm&, GC::Ref<WebGLRenderingContextBase>);
-
- GC::Ref<WebGLRenderingContextBase> m_context;
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/Extensions/ANGLEInstancedArrays.idl b/Libraries/LibWeb/WebGL/Extensions/ANGLEInstancedArrays.idl
index da5f0415d3b..59dae09d609 100644
--- a/Libraries/LibWeb/WebGL/Extensions/ANGLEInstancedArrays.idl
+++ b/Libraries/LibWeb/WebGL/Extensions/ANGLEInstancedArrays.idl
@@ -4,7 +4,7 @@
// IDL generator to handle snake_case to TitleCase conversion.
// Having a different name is totally fine, because LegacyNoInterfaceObject
// prevents the name from being exposed to JavaScript.
-[Exposed=(Window,Worker), LegacyNoInterfaceObject]
+[Exposed=(Window,Worker), ImplementedIn=Rust, LegacyNoInterfaceObject]
interface ANGLEInstancedArrays {
const GLenum VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE = 0x88FE;
undefined drawArraysInstancedANGLE(GLenum mode, GLint first, GLsizei count, GLsizei primcount);
diff --git a/Libraries/LibWeb/WebGL/Extensions/EXTBlendMinMax.cpp b/Libraries/LibWeb/WebGL/Extensions/EXTBlendMinMax.cpp
deleted file mode 100644
index 0ff433be21a..00000000000
--- a/Libraries/LibWeb/WebGL/Extensions/EXTBlendMinMax.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (c) 2025, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/Runtime/Realm.h>
-#include <LibWeb/Bindings/EXTBlendMinMax.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/WebGL/Extensions/EXTBlendMinMax.h>
-#include <LibWeb/WebGL/WebGLContextProxy.h>
-#include <LibWeb/WebGL/WebGLRenderingContextBase.h>
-
-namespace Web::WebGL {
-
-GC_DEFINE_ALLOCATOR(EXTBlendMinMax);
-
-GC::Ref<Bindings::Wrappable> EXTBlendMinMax::create(GC::Ref<WebGLRenderingContextBase> context)
-{
- auto& realm = context->realm();
- return realm.create<EXTBlendMinMax>(realm, context);
-}
-
-EXTBlendMinMax::EXTBlendMinMax(JS::Realm&, GC::Ref<WebGLRenderingContextBase> context)
- : m_context(context)
-{
-}
-
-void EXTBlendMinMax::visit_edges(Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_context);
-}
-
-}
diff --git a/Libraries/LibWeb/WebGL/Extensions/EXTBlendMinMax.h b/Libraries/LibWeb/WebGL/Extensions/EXTBlendMinMax.h
deleted file mode 100644
index 3df6764d4d4..00000000000
--- a/Libraries/LibWeb/WebGL/Extensions/EXTBlendMinMax.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (c) 2025, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/Forward.h>
-
-namespace Web::WebGL {
-
-class EXTBlendMinMax : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(EXTBlendMinMax, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(EXTBlendMinMax);
-
-public:
- static GC::Ref<Bindings::Wrappable> create(GC::Ref<WebGLRenderingContextBase>);
-
-protected:
- void visit_edges(Visitor&) override;
-
-private:
- EXTBlendMinMax(JS::Realm&, GC::Ref<WebGLRenderingContextBase>);
-
- GC::Ref<WebGLRenderingContextBase> m_context;
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/Extensions/EXTBlendMinMax.idl b/Libraries/LibWeb/WebGL/Extensions/EXTBlendMinMax.idl
index 3e92031acc5..936dce6d9ca 100644
--- a/Libraries/LibWeb/WebGL/Extensions/EXTBlendMinMax.idl
+++ b/Libraries/LibWeb/WebGL/Extensions/EXTBlendMinMax.idl
@@ -4,7 +4,7 @@
// IDL generator to handle snake_case to TitleCase conversion.
// Having a different name is totally fine, because LegacyNoInterfaceObject
// prevents the name from being exposed to JavaScript.
-[Exposed=(Window,Worker), LegacyNoInterfaceObject]
+[Exposed=(Window,Worker), ImplementedIn=Rust, LegacyNoInterfaceObject]
interface EXTBlendMinMax {
const GLenum MIN_EXT = 0x8007;
const GLenum MAX_EXT = 0x8008;
diff --git a/Libraries/LibWeb/WebGL/Extensions/EXTColorBufferFloat.cpp b/Libraries/LibWeb/WebGL/Extensions/EXTColorBufferFloat.cpp
deleted file mode 100644
index f662ca38a6e..00000000000
--- a/Libraries/LibWeb/WebGL/Extensions/EXTColorBufferFloat.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (c) 2025, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/Runtime/Realm.h>
-#include <LibWeb/Bindings/EXTColorBufferFloat.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/WebGL/Extensions/EXTColorBufferFloat.h>
-#include <LibWeb/WebGL/WebGLContextProxy.h>
-#include <LibWeb/WebGL/WebGLRenderingContextBase.h>
-
-namespace Web::WebGL {
-
-GC_DEFINE_ALLOCATOR(EXTColorBufferFloat);
-
-GC::Ref<Bindings::Wrappable> EXTColorBufferFloat::create(GC::Ref<WebGLRenderingContextBase> context)
-{
- auto& realm = context->realm();
- return realm.create<EXTColorBufferFloat>(realm, context);
-}
-
-EXTColorBufferFloat::EXTColorBufferFloat(JS::Realm&, GC::Ref<WebGLRenderingContextBase> context)
- : m_context(context)
-{
-}
-
-void EXTColorBufferFloat::visit_edges(Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_context);
-}
-
-}
diff --git a/Libraries/LibWeb/WebGL/Extensions/EXTColorBufferFloat.h b/Libraries/LibWeb/WebGL/Extensions/EXTColorBufferFloat.h
deleted file mode 100644
index 10e4db2c8e2..00000000000
--- a/Libraries/LibWeb/WebGL/Extensions/EXTColorBufferFloat.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (c) 2025, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/Forward.h>
-
-namespace Web::WebGL {
-
-class EXTColorBufferFloat : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(EXTColorBufferFloat, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(EXTColorBufferFloat);
-
-public:
- static GC::Ref<Bindings::Wrappable> create(GC::Ref<WebGLRenderingContextBase>);
-
-protected:
- void visit_edges(Visitor&) override;
-
-private:
- EXTColorBufferFloat(JS::Realm&, GC::Ref<WebGLRenderingContextBase>);
-
- GC::Ref<WebGLRenderingContextBase> m_context;
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/Extensions/EXTColorBufferFloat.idl b/Libraries/LibWeb/WebGL/Extensions/EXTColorBufferFloat.idl
index adc9fd8a78c..865c5d628aa 100644
--- a/Libraries/LibWeb/WebGL/Extensions/EXTColorBufferFloat.idl
+++ b/Libraries/LibWeb/WebGL/Extensions/EXTColorBufferFloat.idl
@@ -4,6 +4,6 @@
// IDL generator to handle snake_case to TitleCase conversion.
// Having a different name is totally fine, because LegacyNoInterfaceObject
// prevents the name from being exposed to JavaScript.
-[Exposed=(Window,Worker), LegacyNoInterfaceObject]
+[Exposed=(Window,Worker), ImplementedIn=Rust, LegacyNoInterfaceObject]
interface EXTColorBufferFloat {
};
diff --git a/Libraries/LibWeb/WebGL/Extensions/EXTRenderSnorm.cpp b/Libraries/LibWeb/WebGL/Extensions/EXTRenderSnorm.cpp
deleted file mode 100644
index 53cbf71a6e5..00000000000
--- a/Libraries/LibWeb/WebGL/Extensions/EXTRenderSnorm.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (c) 2025, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/Runtime/Realm.h>
-#include <LibWeb/Bindings/EXTRenderSnorm.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/WebGL/Extensions/EXTRenderSnorm.h>
-#include <LibWeb/WebGL/WebGLContextProxy.h>
-#include <LibWeb/WebGL/WebGLRenderingContextBase.h>
-
-namespace Web::WebGL {
-
-GC_DEFINE_ALLOCATOR(EXTRenderSnorm);
-
-GC::Ref<Bindings::Wrappable> EXTRenderSnorm::create(GC::Ref<WebGLRenderingContextBase> context)
-{
- auto& realm = context->realm();
- return realm.create<EXTRenderSnorm>(realm, context);
-}
-
-EXTRenderSnorm::EXTRenderSnorm(JS::Realm&, GC::Ref<WebGLRenderingContextBase> context)
- : m_context(context)
-{
-}
-
-void EXTRenderSnorm::visit_edges(Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_context);
-}
-
-}
diff --git a/Libraries/LibWeb/WebGL/Extensions/EXTRenderSnorm.h b/Libraries/LibWeb/WebGL/Extensions/EXTRenderSnorm.h
deleted file mode 100644
index 4a2267e7918..00000000000
--- a/Libraries/LibWeb/WebGL/Extensions/EXTRenderSnorm.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (c) 2025, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/Forward.h>
-
-namespace Web::WebGL {
-
-class EXTRenderSnorm : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(EXTRenderSnorm, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(EXTRenderSnorm);
-
-public:
- static GC::Ref<Bindings::Wrappable> create(GC::Ref<WebGLRenderingContextBase>);
-
-protected:
- void visit_edges(Visitor&) override;
-
-private:
- EXTRenderSnorm(JS::Realm&, GC::Ref<WebGLRenderingContextBase>);
-
- GC::Ref<WebGLRenderingContextBase> m_context;
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/Extensions/EXTRenderSnorm.idl b/Libraries/LibWeb/WebGL/Extensions/EXTRenderSnorm.idl
index 692e99a2059..0109996c4a1 100644
--- a/Libraries/LibWeb/WebGL/Extensions/EXTRenderSnorm.idl
+++ b/Libraries/LibWeb/WebGL/Extensions/EXTRenderSnorm.idl
@@ -4,6 +4,6 @@
// IDL generator to handle snake_case to TitleCase conversion.
// Having a different name is totally fine, because LegacyNoInterfaceObject
// prevents the name from being exposed to JavaScript.
-[Exposed=(Window,Worker), LegacyNoInterfaceObject]
+[Exposed=(Window,Worker), ImplementedIn=Rust, LegacyNoInterfaceObject]
interface EXTRenderSnorm {
};
diff --git a/Libraries/LibWeb/WebGL/Extensions/EXTTextureFilterAnisotropic.cpp b/Libraries/LibWeb/WebGL/Extensions/EXTTextureFilterAnisotropic.cpp
deleted file mode 100644
index 3c153931d4e..00000000000
--- a/Libraries/LibWeb/WebGL/Extensions/EXTTextureFilterAnisotropic.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (c) 2025, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/Runtime/Realm.h>
-#include <LibWeb/Bindings/EXTTextureFilterAnisotropic.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/WebGL/Extensions/EXTTextureFilterAnisotropic.h>
-#include <LibWeb/WebGL/WebGLContextProxy.h>
-#include <LibWeb/WebGL/WebGLRenderingContextBase.h>
-
-namespace Web::WebGL {
-
-GC_DEFINE_ALLOCATOR(EXTTextureFilterAnisotropic);
-
-GC::Ref<Bindings::Wrappable> EXTTextureFilterAnisotropic::create(GC::Ref<WebGLRenderingContextBase> context)
-{
- auto& realm = context->realm();
- return realm.create<EXTTextureFilterAnisotropic>(realm, context);
-}
-
-EXTTextureFilterAnisotropic::EXTTextureFilterAnisotropic(JS::Realm&, GC::Ref<WebGLRenderingContextBase> context)
- : m_context(context)
-{
-}
-
-void EXTTextureFilterAnisotropic::visit_edges(Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_context);
-}
-
-}
diff --git a/Libraries/LibWeb/WebGL/Extensions/EXTTextureFilterAnisotropic.h b/Libraries/LibWeb/WebGL/Extensions/EXTTextureFilterAnisotropic.h
deleted file mode 100644
index f25b952f406..00000000000
--- a/Libraries/LibWeb/WebGL/Extensions/EXTTextureFilterAnisotropic.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (c) 2025, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/Forward.h>
-
-namespace Web::WebGL {
-
-class EXTTextureFilterAnisotropic : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(EXTTextureFilterAnisotropic, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(EXTTextureFilterAnisotropic);
-
-public:
- static GC::Ref<Bindings::Wrappable> create(GC::Ref<WebGLRenderingContextBase>);
-
-protected:
- void visit_edges(Visitor&) override;
-
-private:
- EXTTextureFilterAnisotropic(JS::Realm&, GC::Ref<WebGLRenderingContextBase>);
-
- GC::Ref<WebGLRenderingContextBase> m_context;
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/Extensions/EXTTextureFilterAnisotropic.idl b/Libraries/LibWeb/WebGL/Extensions/EXTTextureFilterAnisotropic.idl
index 7da4019ccc9..01add451f51 100644
--- a/Libraries/LibWeb/WebGL/Extensions/EXTTextureFilterAnisotropic.idl
+++ b/Libraries/LibWeb/WebGL/Extensions/EXTTextureFilterAnisotropic.idl
@@ -4,7 +4,7 @@
// IDL generator to handle snake_case to TitleCase conversion.
// Having a different name is totally fine, because LegacyNoInterfaceObject
// prevents the name from being exposed to JavaScript.
-[Exposed=(Window,Worker), LegacyNoInterfaceObject]
+[Exposed=(Window,Worker), ImplementedIn=Rust, LegacyNoInterfaceObject]
interface EXTTextureFilterAnisotropic {
const GLenum TEXTURE_MAX_ANISOTROPY_EXT = 0x84FE;
const GLenum MAX_TEXTURE_MAX_ANISOTROPY_EXT = 0x84FF;
diff --git a/Libraries/LibWeb/WebGL/Extensions/EXTTextureNorm16.cpp b/Libraries/LibWeb/WebGL/Extensions/EXTTextureNorm16.cpp
deleted file mode 100644
index 39e1cec0462..00000000000
--- a/Libraries/LibWeb/WebGL/Extensions/EXTTextureNorm16.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (c) 2025, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/Runtime/Realm.h>
-#include <LibWeb/Bindings/EXTTextureNorm16.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/WebGL/Extensions/EXTTextureNorm16.h>
-#include <LibWeb/WebGL/WebGLContextProxy.h>
-#include <LibWeb/WebGL/WebGLRenderingContextBase.h>
-
-namespace Web::WebGL {
-
-GC_DEFINE_ALLOCATOR(EXTTextureNorm16);
-
-GC::Ref<Bindings::Wrappable> EXTTextureNorm16::create(GC::Ref<WebGLRenderingContextBase> context)
-{
- auto& realm = context->realm();
- return realm.create<EXTTextureNorm16>(realm, context);
-}
-
-EXTTextureNorm16::EXTTextureNorm16(JS::Realm&, GC::Ref<WebGLRenderingContextBase> context)
- : m_context(context)
-{
-}
-
-void EXTTextureNorm16::visit_edges(Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_context);
-}
-
-}
diff --git a/Libraries/LibWeb/WebGL/Extensions/EXTTextureNorm16.h b/Libraries/LibWeb/WebGL/Extensions/EXTTextureNorm16.h
deleted file mode 100644
index 975e3d4cfe6..00000000000
--- a/Libraries/LibWeb/WebGL/Extensions/EXTTextureNorm16.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (c) 2025, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/Forward.h>
-
-namespace Web::WebGL {
-
-class EXTTextureNorm16 : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(EXTTextureNorm16, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(EXTTextureNorm16);
-
-public:
- static GC::Ref<Bindings::Wrappable> create(GC::Ref<WebGLRenderingContextBase>);
-
-protected:
- void visit_edges(Visitor&) override;
-
-private:
- EXTTextureNorm16(JS::Realm&, GC::Ref<WebGLRenderingContextBase>);
-
- GC::Ref<WebGLRenderingContextBase> m_context;
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/Extensions/EXTTextureNorm16.idl b/Libraries/LibWeb/WebGL/Extensions/EXTTextureNorm16.idl
index 006da72ce10..46ceedc6cbb 100644
--- a/Libraries/LibWeb/WebGL/Extensions/EXTTextureNorm16.idl
+++ b/Libraries/LibWeb/WebGL/Extensions/EXTTextureNorm16.idl
@@ -4,7 +4,7 @@
// IDL generator to handle snake_case to TitleCase conversion.
// Having a different name is totally fine, because LegacyNoInterfaceObject
// prevents the name from being exposed to JavaScript.
-[Exposed=(Window,Worker), LegacyNoInterfaceObject]
+[Exposed=(Window,Worker), ImplementedIn=Rust, LegacyNoInterfaceObject]
interface EXTTextureNorm16 {
const GLenum R16_EXT = 0x822A;
const GLenum RG16_EXT = 0x822C;
diff --git a/Libraries/LibWeb/WebGL/Extensions/OESElementIndexUint.cpp b/Libraries/LibWeb/WebGL/Extensions/OESElementIndexUint.cpp
deleted file mode 100644
index a877c7ac657..00000000000
--- a/Libraries/LibWeb/WebGL/Extensions/OESElementIndexUint.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (c) 2025, Undefine <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/Runtime/Realm.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/Bindings/OESElementIndexUint.h>
-#include <LibWeb/WebGL/Extensions/OESElementIndexUint.h>
-#include <LibWeb/WebGL/WebGLContextProxy.h>
-#include <LibWeb/WebGL/WebGLRenderingContextBase.h>
-
-namespace Web::WebGL {
-
-GC_DEFINE_ALLOCATOR(OESElementIndexUint);
-
-GC::Ref<Bindings::Wrappable> OESElementIndexUint::create(GC::Ref<WebGLRenderingContextBase> context)
-{
- auto& realm = context->realm();
- return realm.create<OESElementIndexUint>(realm, context);
-}
-
-OESElementIndexUint::OESElementIndexUint(JS::Realm&, GC::Ref<WebGLRenderingContextBase> context)
- : m_context(context)
-{
-}
-
-void OESElementIndexUint::visit_edges(Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_context);
-}
-
-}
diff --git a/Libraries/LibWeb/WebGL/Extensions/OESElementIndexUint.h b/Libraries/LibWeb/WebGL/Extensions/OESElementIndexUint.h
deleted file mode 100644
index 4cf8f79b139..00000000000
--- a/Libraries/LibWeb/WebGL/Extensions/OESElementIndexUint.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (c) 2025, Undefine <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/Forward.h>
-
-namespace Web::WebGL {
-
-class OESElementIndexUint : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(OESElementIndexUint, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(OESElementIndexUint);
-
-public:
- static GC::Ref<Bindings::Wrappable> create(GC::Ref<WebGLRenderingContextBase>);
-
-protected:
- void visit_edges(Visitor&) override;
-
-private:
- OESElementIndexUint(JS::Realm&, GC::Ref<WebGLRenderingContextBase>);
-
- GC::Ref<WebGLRenderingContextBase> m_context;
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/Extensions/OESElementIndexUint.idl b/Libraries/LibWeb/WebGL/Extensions/OESElementIndexUint.idl
index b34f91e3bfd..15d587c3a62 100644
--- a/Libraries/LibWeb/WebGL/Extensions/OESElementIndexUint.idl
+++ b/Libraries/LibWeb/WebGL/Extensions/OESElementIndexUint.idl
@@ -2,6 +2,6 @@
// NOTE: Original OES_element_index_uint name is changed to title case, so it matches corresponding C++ class name, and
// does not require IDL generator to handle snake_case to TitleCase conversion. Having a different name is totally
// fine, because LegacyNoInterfaceObject prevents the name from being exposed to JavaScript.
-[Exposed=(Window,Worker), LegacyNoInterfaceObject]
+[Exposed=(Window,Worker), ImplementedIn=Rust, LegacyNoInterfaceObject]
interface OESElementIndexUint {
};
diff --git a/Libraries/LibWeb/WebGL/Extensions/OESStandardDerivatives.cpp b/Libraries/LibWeb/WebGL/Extensions/OESStandardDerivatives.cpp
deleted file mode 100644
index b892c58306d..00000000000
--- a/Libraries/LibWeb/WebGL/Extensions/OESStandardDerivatives.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (c) 2025, Undefine <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/Runtime/Realm.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/Bindings/OESStandardDerivatives.h>
-#include <LibWeb/WebGL/Extensions/OESStandardDerivatives.h>
-#include <LibWeb/WebGL/WebGLContextProxy.h>
-#include <LibWeb/WebGL/WebGLRenderingContextBase.h>
-
-namespace Web::WebGL {
-
-GC_DEFINE_ALLOCATOR(OESStandardDerivatives);
-
-GC::Ref<Bindings::Wrappable> OESStandardDerivatives::create(GC::Ref<WebGLRenderingContextBase> context)
-{
- auto& realm = context->realm();
- return realm.create<OESStandardDerivatives>(realm, context);
-}
-
-OESStandardDerivatives::OESStandardDerivatives(JS::Realm&, GC::Ref<WebGLRenderingContextBase> context)
- : m_context(context)
-{
-}
-
-void OESStandardDerivatives::visit_edges(Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_context);
-}
-
-}
diff --git a/Libraries/LibWeb/WebGL/Extensions/OESStandardDerivatives.h b/Libraries/LibWeb/WebGL/Extensions/OESStandardDerivatives.h
deleted file mode 100644
index cafe006bdbe..00000000000
--- a/Libraries/LibWeb/WebGL/Extensions/OESStandardDerivatives.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (c) 2025, Undefine <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/Forward.h>
-
-namespace Web::WebGL {
-
-class OESStandardDerivatives : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(OESStandardDerivatives, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(OESStandardDerivatives);
-
-public:
- static GC::Ref<Bindings::Wrappable> create(GC::Ref<WebGLRenderingContextBase>);
-
-protected:
- void visit_edges(Visitor&) override;
-
-private:
- OESStandardDerivatives(JS::Realm&, GC::Ref<WebGLRenderingContextBase>);
-
- GC::Ref<WebGLRenderingContextBase> m_context;
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/Extensions/OESStandardDerivatives.idl b/Libraries/LibWeb/WebGL/Extensions/OESStandardDerivatives.idl
index b66ab06785e..49929bf9877 100644
--- a/Libraries/LibWeb/WebGL/Extensions/OESStandardDerivatives.idl
+++ b/Libraries/LibWeb/WebGL/Extensions/OESStandardDerivatives.idl
@@ -4,7 +4,7 @@
// IDL generator to handle snake_case to TitleCase conversion.
// Having a different name is totally fine, because LegacyNoInterfaceObject
// prevents the name from being exposed to JavaScript.
-[Exposed=(Window,Worker), LegacyNoInterfaceObject]
+[Exposed=(Window,Worker), ImplementedIn=Rust, LegacyNoInterfaceObject]
interface OESStandardDerivatives {
const GLenum FRAGMENT_SHADER_DERIVATIVE_HINT_OES = 0x8B8B;
};
diff --git a/Libraries/LibWeb/WebGL/Extensions/OESVertexArrayObject.cpp b/Libraries/LibWeb/WebGL/Extensions/OESVertexArrayObject.cpp
deleted file mode 100644
index 18b4e1dae06..00000000000
--- a/Libraries/LibWeb/WebGL/Extensions/OESVertexArrayObject.cpp
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Copyright (c) 2025, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/Runtime/Realm.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/Bindings/OESVertexArrayObject.h>
-#include <LibWeb/WebGL/Extensions/OESVertexArrayObject.h>
-#include <LibWeb/WebGL/Extensions/WebGLVertexArrayObjectOES.h>
-#include <LibWeb/WebGL/WebGLContextProxy.h>
-#include <LibWeb/WebGL/WebGLRenderingContextBase.h>
-
-#include <GLES2/gl2.h>
-#include <GLES2/gl2ext.h>
-
-namespace Web::WebGL {
-
-GC_DEFINE_ALLOCATOR(OESVertexArrayObject);
-
-GC::Ref<Bindings::Wrappable> OESVertexArrayObject::create(GC::Ref<WebGLRenderingContextBase> context)
-{
- auto& realm = context->realm();
- return realm.create<OESVertexArrayObject>(realm, context);
-}
-
-OESVertexArrayObject::OESVertexArrayObject(JS::Realm&, GC::Ref<WebGLRenderingContextBase> context)
- : m_context(context)
-{
-}
-
-GC::Ref<WebGLVertexArrayObjectOES> OESVertexArrayObject::create_vertex_array_oes()
-{
- m_context->context().make_current();
-
- GLuint handle = 0;
- m_context->context().gen_vertex_arrays_oes(1, &handle);
- return WebGLVertexArrayObjectOES::create(m_context, handle);
-}
-
-void OESVertexArrayObject::delete_vertex_array_oes(GC::Ptr<WebGLVertexArrayObjectOES> array_object)
-{
- m_context->context().make_current();
-
- if (!array_object)
- return;
-
- auto handle_or_error = array_object->handle_for_deletion(m_context.ptr());
- if (handle_or_error.is_error()) {
- // FIXME: m_context->set_error(GL_INVALID_OPERATION);
- return;
- }
- auto vertex_array_handle = handle_or_error.release_value();
- if (!vertex_array_handle.has_value())
- return;
-
- auto handle = vertex_array_handle.value();
- m_context->context().delete_vertex_arrays_oes(1, &handle);
- if (m_context->current_vertex_array_binding() == array_object)
- m_context->set_current_vertex_array_binding(nullptr);
-}
-
-bool OESVertexArrayObject::is_vertex_array_oes(GC::Ptr<WebGLVertexArrayObjectOES> array_object)
-{
- m_context->context().make_current();
-
- if (!array_object)
- return false;
-
- auto handle_or_error = array_object->handle_for_query(m_context.ptr());
- if (handle_or_error.is_error()) {
- return false;
- }
- auto vertex_array_handle = handle_or_error.release_value();
- if (!vertex_array_handle.has_value())
- return false;
-
- return m_context->context().is_vertex_array_oes(vertex_array_handle.value()) == GL_TRUE;
-}
-
-void OESVertexArrayObject::bind_vertex_array_oes(GC::Ptr<WebGLVertexArrayObjectOES> array_object)
-{
- m_context->context().make_current();
-
- GLuint vertex_array_handle = 0;
- if (array_object) {
- auto handle_or_error = array_object->handle(m_context.ptr());
- if (handle_or_error.is_error()) {
- // FIXME: m_context->set_error(GL_INVALID_OPERATION);
- return;
- }
- vertex_array_handle = handle_or_error.release_value();
- }
-
- m_context->context().bind_vertex_array_oes(vertex_array_handle);
- m_context->set_current_vertex_array_binding(array_object);
-}
-
-void OESVertexArrayObject::visit_edges(Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_context);
-}
-
-}
diff --git a/Libraries/LibWeb/WebGL/Extensions/OESVertexArrayObject.h b/Libraries/LibWeb/WebGL/Extensions/OESVertexArrayObject.h
deleted file mode 100644
index 8074cf834e2..00000000000
--- a/Libraries/LibWeb/WebGL/Extensions/OESVertexArrayObject.h
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (c) 2025, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/Forward.h>
-#include <LibWeb/WebGL/Types.h>
-
-namespace Web::WebGL {
-
-class OESVertexArrayObject : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(OESVertexArrayObject, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(OESVertexArrayObject);
-
-public:
- static GC::Ref<Bindings::Wrappable> create(GC::Ref<WebGLRenderingContextBase>);
-
- GC::Ref<WebGLVertexArrayObjectOES> create_vertex_array_oes();
- void delete_vertex_array_oes(GC::Ptr<WebGLVertexArrayObjectOES> array_object);
- bool is_vertex_array_oes(GC::Ptr<WebGLVertexArrayObjectOES> array_object);
- void bind_vertex_array_oes(GC::Ptr<WebGLVertexArrayObjectOES> array_object);
-
-protected:
- void visit_edges(Visitor&) override;
-
-private:
- OESVertexArrayObject(JS::Realm&, GC::Ref<WebGLRenderingContextBase>);
-
- GC::Ref<WebGLRenderingContextBase> m_context;
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/Extensions/OESVertexArrayObject.idl b/Libraries/LibWeb/WebGL/Extensions/OESVertexArrayObject.idl
index ac0ff4bc1f7..7e6f586f74c 100644
--- a/Libraries/LibWeb/WebGL/Extensions/OESVertexArrayObject.idl
+++ b/Libraries/LibWeb/WebGL/Extensions/OESVertexArrayObject.idl
@@ -4,7 +4,7 @@
// IDL generator to handle snake_case to TitleCase conversion.
// Having a different name is totally fine, because LegacyNoInterfaceObject
// prevents the name from being exposed to JavaScript.
-[Exposed=(Window,Worker), LegacyNoInterfaceObject]
+[Exposed=(Window,Worker), ImplementedIn=Rust, LegacyNoInterfaceObject]
interface OESVertexArrayObject {
// Same note as WebGLRenderingContextBase:
// Functions that have the [WebGLHandlesContextLoss] extended attribute in the spec do not have them here.
diff --git a/Libraries/LibWeb/WebGL/Extensions/WebGLCompressedTextureS3tc.cpp b/Libraries/LibWeb/WebGL/Extensions/WebGLCompressedTextureS3tc.cpp
deleted file mode 100644
index 8e58c1435b4..00000000000
--- a/Libraries/LibWeb/WebGL/Extensions/WebGLCompressedTextureS3tc.cpp
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (c) 2025, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <GLES2/gl2.h>
-#include <GLES2/gl2ext.h>
-
-#include <LibJS/Runtime/Realm.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/Bindings/WebGLCompressedTextureS3tc.h>
-#include <LibWeb/WebGL/Extensions/WebGLCompressedTextureS3tc.h>
-#include <LibWeb/WebGL/WebGLContextProxy.h>
-#include <LibWeb/WebGL/WebGLRenderingContextBase.h>
-
-namespace Web::WebGL {
-
-GC_DEFINE_ALLOCATOR(WebGLCompressedTextureS3tc);
-
-GC::Ref<Bindings::Wrappable> WebGLCompressedTextureS3tc::create(GC::Ref<WebGLRenderingContextBase> context)
-{
- auto& realm = context->realm();
- return realm.create<WebGLCompressedTextureS3tc>(realm, context);
-}
-
-WebGLCompressedTextureS3tc::WebGLCompressedTextureS3tc(JS::Realm&, GC::Ref<WebGLRenderingContextBase> context)
- : m_context(context)
-{
- m_context->enable_compressed_texture_format(GL_COMPRESSED_RGB_S3TC_DXT1_EXT);
- m_context->enable_compressed_texture_format(GL_COMPRESSED_RGBA_S3TC_DXT1_EXT);
- m_context->enable_compressed_texture_format(GL_COMPRESSED_RGBA_S3TC_DXT3_EXT);
- m_context->enable_compressed_texture_format(GL_COMPRESSED_RGBA_S3TC_DXT5_EXT);
-}
-
-void WebGLCompressedTextureS3tc::visit_edges(Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_context);
-}
-
-}
diff --git a/Libraries/LibWeb/WebGL/Extensions/WebGLCompressedTextureS3tc.h b/Libraries/LibWeb/WebGL/Extensions/WebGLCompressedTextureS3tc.h
deleted file mode 100644
index 9bbfe1148f5..00000000000
--- a/Libraries/LibWeb/WebGL/Extensions/WebGLCompressedTextureS3tc.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (c) 2025, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/Forward.h>
-
-namespace Web::WebGL {
-
-class WebGLCompressedTextureS3tc : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(WebGLCompressedTextureS3tc, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(WebGLCompressedTextureS3tc);
-
-public:
- static GC::Ref<Bindings::Wrappable> create(GC::Ref<WebGLRenderingContextBase>);
-
-protected:
- void visit_edges(Visitor&) override;
-
-private:
- WebGLCompressedTextureS3tc(JS::Realm&, GC::Ref<WebGLRenderingContextBase>);
-
- GC::Ref<WebGLRenderingContextBase> m_context;
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/Extensions/WebGLCompressedTextureS3tc.idl b/Libraries/LibWeb/WebGL/Extensions/WebGLCompressedTextureS3tc.idl
index a9c34308642..7f17442fcf4 100644
--- a/Libraries/LibWeb/WebGL/Extensions/WebGLCompressedTextureS3tc.idl
+++ b/Libraries/LibWeb/WebGL/Extensions/WebGLCompressedTextureS3tc.idl
@@ -4,7 +4,7 @@
// IDL generator to handle snake_case to TitleCase conversion.
// Having a different name is totally fine, because LegacyNoInterfaceObject
// prevents the name from being exposed to JavaScript.
-[Exposed=(Window,Worker), LegacyNoInterfaceObject]
+[Exposed=(Window,Worker), ImplementedIn=Rust, LegacyNoInterfaceObject]
interface WebGLCompressedTextureS3tc {
// Compressed Texture Formats
const GLenum COMPRESSED_RGB_S3TC_DXT1_EXT = 0x83F0;
diff --git a/Libraries/LibWeb/WebGL/Extensions/WebGLCompressedTextureS3tcSrgb.cpp b/Libraries/LibWeb/WebGL/Extensions/WebGLCompressedTextureS3tcSrgb.cpp
deleted file mode 100644
index 8851854a2bd..00000000000
--- a/Libraries/LibWeb/WebGL/Extensions/WebGLCompressedTextureS3tcSrgb.cpp
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (c) 2025, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <GLES2/gl2.h>
-#include <GLES2/gl2ext.h>
-
-#include <LibJS/Runtime/Realm.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/Bindings/WebGLCompressedTextureS3tcSrgb.h>
-#include <LibWeb/WebGL/Extensions/WebGLCompressedTextureS3tcSrgb.h>
-#include <LibWeb/WebGL/WebGLContextProxy.h>
-#include <LibWeb/WebGL/WebGLRenderingContextBase.h>
-
-namespace Web::WebGL {
-
-GC_DEFINE_ALLOCATOR(WebGLCompressedTextureS3tcSrgb);
-
-GC::Ref<Bindings::Wrappable> WebGLCompressedTextureS3tcSrgb::create(GC::Ref<WebGLRenderingContextBase> context)
-{
- auto& realm = context->realm();
- return realm.create<WebGLCompressedTextureS3tcSrgb>(realm, context);
-}
-
-WebGLCompressedTextureS3tcSrgb::WebGLCompressedTextureS3tcSrgb(JS::Realm&, GC::Ref<WebGLRenderingContextBase> context)
- : m_context(context)
-{
- m_context->enable_compressed_texture_format(GL_COMPRESSED_SRGB_S3TC_DXT1_EXT);
- m_context->enable_compressed_texture_format(GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT);
- m_context->enable_compressed_texture_format(GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT);
- m_context->enable_compressed_texture_format(GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT);
-}
-
-void WebGLCompressedTextureS3tcSrgb::visit_edges(Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_context);
-}
-
-}
diff --git a/Libraries/LibWeb/WebGL/Extensions/WebGLCompressedTextureS3tcSrgb.h b/Libraries/LibWeb/WebGL/Extensions/WebGLCompressedTextureS3tcSrgb.h
deleted file mode 100644
index a7c312fd174..00000000000
--- a/Libraries/LibWeb/WebGL/Extensions/WebGLCompressedTextureS3tcSrgb.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (c) 2025, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/Forward.h>
-
-namespace Web::WebGL {
-
-class WebGLCompressedTextureS3tcSrgb : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(WebGLCompressedTextureS3tcSrgb, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(WebGLCompressedTextureS3tcSrgb);
-
-public:
- static GC::Ref<Bindings::Wrappable> create(GC::Ref<WebGLRenderingContextBase>);
-
-protected:
- void visit_edges(Visitor&) override;
-
-private:
- WebGLCompressedTextureS3tcSrgb(JS::Realm&, GC::Ref<WebGLRenderingContextBase>);
-
- GC::Ref<WebGLRenderingContextBase> m_context;
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/Extensions/WebGLCompressedTextureS3tcSrgb.idl b/Libraries/LibWeb/WebGL/Extensions/WebGLCompressedTextureS3tcSrgb.idl
index 278c2cd2bb6..005a72a31ae 100644
--- a/Libraries/LibWeb/WebGL/Extensions/WebGLCompressedTextureS3tcSrgb.idl
+++ b/Libraries/LibWeb/WebGL/Extensions/WebGLCompressedTextureS3tcSrgb.idl
@@ -4,7 +4,7 @@
// IDL generator to handle snake_case to TitleCase conversion.
// Having a different name is totally fine, because LegacyNoInterfaceObject
// prevents the name from being exposed to JavaScript.
-[Exposed=(Window,Worker), LegacyNoInterfaceObject]
+[Exposed=(Window,Worker), ImplementedIn=Rust, LegacyNoInterfaceObject]
interface WebGLCompressedTextureS3tcSrgb {
// Compressed Texture Formats
const GLenum COMPRESSED_SRGB_S3TC_DXT1_EXT = 0x8C4C;
diff --git a/Libraries/LibWeb/WebGL/Extensions/WebGLDebugRendererInfo.cpp b/Libraries/LibWeb/WebGL/Extensions/WebGLDebugRendererInfo.cpp
deleted file mode 100644
index 9c948752b3f..00000000000
--- a/Libraries/LibWeb/WebGL/Extensions/WebGLDebugRendererInfo.cpp
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (c) 2026, Aliaksandr Kalenik <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/Runtime/Realm.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/Bindings/WebGLDebugRendererInfo.h>
-#include <LibWeb/WebGL/Extensions/WebGLDebugRendererInfo.h>
-#include <LibWeb/WebGL/WebGLRenderingContextBase.h>
-
-namespace Web::WebGL {
-
-GC_DEFINE_ALLOCATOR(WebGLDebugRendererInfo);
-
-GC::Ref<Bindings::Wrappable> WebGLDebugRendererInfo::create(GC::Ref<WebGLRenderingContextBase> context)
-{
- auto& realm = context->realm();
- return realm.create<WebGLDebugRendererInfo>(realm, context);
-}
-
-WebGLDebugRendererInfo::WebGLDebugRendererInfo(JS::Realm&, GC::Ref<WebGLRenderingContextBase> context)
- : m_context(context)
-{
-}
-
-void WebGLDebugRendererInfo::visit_edges(Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_context);
-}
-
-}
diff --git a/Libraries/LibWeb/WebGL/Extensions/WebGLDebugRendererInfo.h b/Libraries/LibWeb/WebGL/Extensions/WebGLDebugRendererInfo.h
deleted file mode 100644
index 4f496eaa45a..00000000000
--- a/Libraries/LibWeb/WebGL/Extensions/WebGLDebugRendererInfo.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (c) 2026, Aliaksandr Kalenik <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/Forward.h>
-
-namespace Web::WebGL {
-
-class WebGLDebugRendererInfo : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(WebGLDebugRendererInfo, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(WebGLDebugRendererInfo);
-
-public:
- static GC::Ref<Bindings::Wrappable> create(GC::Ref<WebGLRenderingContextBase>);
-
-protected:
- void visit_edges(Visitor&) override;
-
-private:
- WebGLDebugRendererInfo(JS::Realm&, GC::Ref<WebGLRenderingContextBase>);
-
- GC::Ref<WebGLRenderingContextBase> m_context;
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/Extensions/WebGLDebugRendererInfo.idl b/Libraries/LibWeb/WebGL/Extensions/WebGLDebugRendererInfo.idl
index e2dce084672..44562274a88 100644
--- a/Libraries/LibWeb/WebGL/Extensions/WebGLDebugRendererInfo.idl
+++ b/Libraries/LibWeb/WebGL/Extensions/WebGLDebugRendererInfo.idl
@@ -4,7 +4,7 @@
// IDL generator to handle snake_case to TitleCase conversion.
// Having a different name is totally fine, because LegacyNoInterfaceObject
// prevents the name from being exposed to JavaScript.
-[Exposed=(Window,Worker), LegacyNoInterfaceObject]
+[Exposed=(Window,Worker), ImplementedIn=Rust, LegacyNoInterfaceObject]
interface WebGLDebugRendererInfo {
const GLenum UNMASKED_VENDOR_WEBGL = 0x9245;
const GLenum UNMASKED_RENDERER_WEBGL = 0x9246;
diff --git a/Libraries/LibWeb/WebGL/Extensions/WebGLDrawBuffers.cpp b/Libraries/LibWeb/WebGL/Extensions/WebGLDrawBuffers.cpp
deleted file mode 100644
index 28376a500fc..00000000000
--- a/Libraries/LibWeb/WebGL/Extensions/WebGLDrawBuffers.cpp
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (c) 2025, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/Runtime/Realm.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/Bindings/WebGLDrawBuffers.h>
-#include <LibWeb/WebGL/Extensions/WebGLDrawBuffers.h>
-#include <LibWeb/WebGL/WebGLContextProxy.h>
-#include <LibWeb/WebGL/WebGLRenderingContextBase.h>
-
-#include <GLES2/gl2.h>
-#include <GLES2/gl2ext.h>
-
-namespace Web::WebGL {
-
-GC_DEFINE_ALLOCATOR(WebGLDrawBuffers);
-
-GC::Ref<Bindings::Wrappable> WebGLDrawBuffers::create(GC::Ref<WebGLRenderingContextBase> context)
-{
- auto& realm = context->realm();
- return realm.create<WebGLDrawBuffers>(realm, context);
-}
-
-WebGLDrawBuffers::WebGLDrawBuffers(JS::Realm&, GC::Ref<WebGLRenderingContextBase> context)
- : m_context(context)
-{
-}
-
-void WebGLDrawBuffers::draw_buffers_webgl(Vector<GLenum> buffers)
-{
- m_context->context().make_current();
- m_context->context().draw_buffers_ext(buffers.size(), buffers.data());
-}
-
-void WebGLDrawBuffers::visit_edges(Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_context);
-}
-
-}
diff --git a/Libraries/LibWeb/WebGL/Extensions/WebGLDrawBuffers.h b/Libraries/LibWeb/WebGL/Extensions/WebGLDrawBuffers.h
deleted file mode 100644
index a37acd87b40..00000000000
--- a/Libraries/LibWeb/WebGL/Extensions/WebGLDrawBuffers.h
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (c) 2025, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/Forward.h>
-#include <LibWeb/WebGL/Types.h>
-
-namespace Web::WebGL {
-
-class WebGLDrawBuffers : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(WebGLDrawBuffers, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(WebGLDrawBuffers);
-
-public:
- static GC::Ref<Bindings::Wrappable> create(GC::Ref<WebGLRenderingContextBase>);
-
- void draw_buffers_webgl(Vector<GLenum> buffers);
-
-protected:
- void visit_edges(Visitor&) override;
-
-private:
- WebGLDrawBuffers(JS::Realm&, GC::Ref<WebGLRenderingContextBase>);
-
- GC::Ref<WebGLRenderingContextBase> m_context;
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/Extensions/WebGLDrawBuffers.idl b/Libraries/LibWeb/WebGL/Extensions/WebGLDrawBuffers.idl
index ae09505a1a5..0e6b384bfa2 100644
--- a/Libraries/LibWeb/WebGL/Extensions/WebGLDrawBuffers.idl
+++ b/Libraries/LibWeb/WebGL/Extensions/WebGLDrawBuffers.idl
@@ -4,7 +4,7 @@
// IDL generator to handle snake_case to TitleCase conversion.
// Having a different name is totally fine, because LegacyNoInterfaceObject
// prevents the name from being exposed to JavaScript.
-[Exposed=(Window,Worker), LegacyNoInterfaceObject]
+[Exposed=(Window,Worker), ImplementedIn=Rust, LegacyNoInterfaceObject]
interface WebGLDrawBuffers {
const GLenum COLOR_ATTACHMENT0_WEBGL = 0x8CE0;
const GLenum COLOR_ATTACHMENT1_WEBGL = 0x8CE1;
diff --git a/Libraries/LibWeb/WebGL/Extensions/WebGLVertexArrayObjectOES.cpp b/Libraries/LibWeb/WebGL/Extensions/WebGLVertexArrayObjectOES.cpp
deleted file mode 100644
index c7641dc410f..00000000000
--- a/Libraries/LibWeb/WebGL/Extensions/WebGLVertexArrayObjectOES.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (c) 2024, Andrew Kaster <[email protected]>
- * Copyright (c) 2025, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/Runtime/Realm.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/Bindings/WebGLVertexArrayObjectOES.h>
-#include <LibWeb/WebGL/Extensions/WebGLVertexArrayObjectOES.h>
-
-namespace Web::WebGL {
-
-GC_DEFINE_ALLOCATOR(WebGLVertexArrayObjectOES);
-
-GC::Ref<WebGLVertexArrayObjectOES> WebGLVertexArrayObjectOES::create(WebGLRenderingContextBase& context, GLuint handle)
-{
- auto& realm = context.realm();
- return realm.create<WebGLVertexArrayObjectOES>(realm, context, handle);
-}
-
-WebGLVertexArrayObjectOES::WebGLVertexArrayObjectOES(JS::Realm& realm, WebGLRenderingContextBase& context, GLuint handle)
- : WebGLObject(realm, context, handle)
-{
-}
-
-WebGLVertexArrayObjectOES::~WebGLVertexArrayObjectOES() = default;
-
-}
diff --git a/Libraries/LibWeb/WebGL/Extensions/WebGLVertexArrayObjectOES.h b/Libraries/LibWeb/WebGL/Extensions/WebGLVertexArrayObjectOES.h
deleted file mode 100644
index cf140779219..00000000000
--- a/Libraries/LibWeb/WebGL/Extensions/WebGLVertexArrayObjectOES.h
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright (c) 2024, Andrew Kaster <[email protected]>
- * Copyright (c) 2025, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/WebGL/Types.h>
-#include <LibWeb/WebGL/WebGLObject.h>
-
-namespace Web::WebGL {
-
-class WebGLVertexArrayObjectOES : public WebGLObject {
- WEB_WRAPPABLE(WebGLVertexArrayObjectOES, WebGLObject);
- GC_DECLARE_ALLOCATOR(WebGLVertexArrayObjectOES);
-
-public:
- static GC::Ref<WebGLVertexArrayObjectOES> create(WebGLRenderingContextBase&, GLuint handle);
-
- virtual ~WebGLVertexArrayObjectOES() override;
-
-protected:
- explicit WebGLVertexArrayObjectOES(JS::Realm&, WebGLRenderingContextBase&, GLuint handle);
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/Extensions/WebGLVertexArrayObjectOES.idl b/Libraries/LibWeb/WebGL/Extensions/WebGLVertexArrayObjectOES.idl
index 8ea8597304a..bdf567e3852 100644
--- a/Libraries/LibWeb/WebGL/Extensions/WebGLVertexArrayObjectOES.idl
+++ b/Libraries/LibWeb/WebGL/Extensions/WebGLVertexArrayObjectOES.idl
@@ -1,4 +1,4 @@
// https://registry.khronos.org/webgl/extensions/OES_vertex_array_object/
-[Exposed=(Window,Worker), LegacyNoInterfaceObject]
+[Exposed=(Window,Worker), ImplementedIn=Rust, LegacyNoInterfaceObject]
interface WebGLVertexArrayObjectOES : WebGLObject {
};
diff --git a/Libraries/LibWeb/WebGL/RemoteWebGLTransportFFI.cpp b/Libraries/LibWeb/WebGL/RemoteWebGLTransportFFI.cpp
index 61a808cbddd..580fa48d120 100644
--- a/Libraries/LibWeb/WebGL/RemoteWebGLTransportFFI.cpp
+++ b/Libraries/LibWeb/WebGL/RemoteWebGLTransportFFI.cpp
@@ -31,14 +31,17 @@ static_assert(offsetof(ReadPixelsResult, columns) == sizeof(i32));
static_assert(offsetof(ReadPixelsResult, rows) == 2 * sizeof(i32));
static_assert(sizeof(Compositing::CanvasId) == sizeof(u64));
-// What the recorder and the replayer of the command stream have to agree on besides the command structs. The
-// recorder has constants of its own for these, and compares them with this before it records (fingerprint.rs).
+// What the WebGL implementation in Rust states for itself besides the command structs: the framing and the shared
+// data region that the recorder and the replayer of the command stream have to agree on, and the largest drawing
+// buffer that the compositor allocates. Rust compares its own constants with these before the first context records
+// (fingerprint.rs).
struct ConstantsRestatedInRust {
size_t record_alignment { 0 };
size_t header_size { 0 };
size_t header_payload_size_offset { 0 };
size_t shared_data_region_offset { 0 };
size_t shared_data_region_capacity { 0 };
+ size_t max_drawing_buffer_dimension { 0 };
};
// NB: The recorder writes the header of a command and that of a synchronous call the same way.
@@ -194,6 +197,7 @@ void web_webgl_constants_restated_in_rust(ConstantsRestatedInRust* out_constants
.header_payload_size_offset = offsetof(Compositing::WebGL::WebGLCommandHeader, payload_size),
.shared_data_region_offset = Compositing::WebGL::WebGLSharedCommandBuffer::data_region_offset,
.shared_data_region_capacity = Compositing::WebGL::WebGLSharedCommandBuffer::default_data_region_capacity,
+ .max_drawing_buffer_dimension = Compositing::WebGL::max_webgl_drawing_buffer_dimension,
};
}
diff --git a/Libraries/LibWeb/WebGL/WebGL2RenderingContext.cpp b/Libraries/LibWeb/WebGL/WebGL2RenderingContext.cpp
deleted file mode 100644
index 17fa136fa4f..00000000000
--- a/Libraries/LibWeb/WebGL/WebGL2RenderingContext.cpp
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * Copyright (c) 2022, Luke Wilde <[email protected]>
- * Copyright (c) 2024, Andrew Kaster <[email protected]>
- * Copyright (c) 2023, Aliaksandr Kalenik <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/Runtime/ArrayBuffer.h>
-#include <LibJS/Runtime/TypedArray.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/Bindings/WebGL2RenderingContext.h>
-#include <LibWeb/HTML/HTMLCanvasElement.h>
-#include <LibWeb/HTML/OffscreenCanvas.h>
-#include <LibWeb/Layout/Node.h>
-#include <LibWeb/WebGL/EventNames.h>
-#include <LibWeb/WebGL/WebGL2RenderingContext.h>
-#include <LibWeb/WebGL/WebGLContextEvent.h>
-#include <LibWeb/WebGL/WebGLContextProxy.h>
-#include <LibWeb/WebGL/WebGLRenderingContext.h>
-#include <LibWeb/WebGL/WebGLShader.h>
-#include <LibWeb/WebIDL/Buffers.h>
-#include <LibWebCommon/Infra/Strings.h>
-
-#include <GLES2/gl2.h>
-#include <GLES2/gl2ext.h>
-
-namespace Web::WebGL {
-
-GC_DEFINE_ALLOCATOR(WebGL2RenderingContext);
-
-JS::ThrowCompletionOr<GC::Ptr<WebGL2RenderingContext>> WebGL2RenderingContext::create(JS::Realm& realm, CanvasOwner canvas, JS::Value options)
-{
- // We should be coming here from getContext being called on a wrapped <canvas> element or OffscreenCanvas.
- auto context_attributes = TRY(convert_value_to_context_attributes_dictionary(realm.vm(), options));
-
- auto context = create_webgl_context_proxy(canvas_host_for(canvas), WebGLVersion::WebGL2, context_attributes);
- if (!context) {
- fire_webgl_context_creation_error(canvas_host_for(canvas));
- return GC::Ptr<WebGL2RenderingContext> { nullptr };
- }
-
- return realm.create<WebGL2RenderingContext>(realm, canvas, context.release_nonnull(), context_attributes, context_attributes);
-}
-
-WebGL2RenderingContext::WebGL2RenderingContext(JS::Realm& realm, CanvasOwner canvas, NonnullOwnPtr<WebGLContextProxy> context, WebGLContextAttributes context_creation_parameters, WebGLContextAttributes actual_context_parameters)
- : WebGL2RenderingContextOverloads(realm, move(context))
- , m_canvas(canvas)
- , m_context_creation_parameters(context_creation_parameters)
- , m_actual_context_parameters(actual_context_parameters)
-{
-}
-
-WebGL2RenderingContext::~WebGL2RenderingContext() = default;
-
-void WebGL2RenderingContext::visit_edges(Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- WebGL2RenderingContextImpl::visit_edges(visitor);
- m_canvas.visit([&](auto const& canvas) { visitor.visit(canvas); });
-}
-
-void WebGL2RenderingContext::prepare_for_compositing()
-{
- context().present_canvas_for_compositing(m_context_creation_parameters.preserve_drawing_buffer);
-}
-
-bool WebGL2RenderingContext::reestablish_remote_context()
-{
- return restore_webgl_context_proxy(context(), canvas_host(), WebGLVersion::WebGL2, m_actual_context_parameters);
-}
-
-CanvasOwner WebGL2RenderingContext::canvas_for_binding() const
-{
- return m_canvas;
-}
-
-void WebGL2RenderingContext::did_update_canvas_content()
-{
- canvas_host().did_change_canvas_content();
-}
-
-Optional<WebGLContextAttributes> WebGL2RenderingContext::get_context_attributes()
-{
- if (is_context_lost())
- return {};
- return m_actual_context_parameters;
-}
-
-void WebGL2RenderingContext::set_size(Gfx::IntSize const& size)
-{
- Gfx::IntSize final_size;
- final_size.set_width(clamp(size.width(), 1, max_webgl_drawing_buffer_dimension));
- final_size.set_height(clamp(size.height(), 1, max_webgl_drawing_buffer_dimension));
- context().set_size(final_size);
-}
-
-void WebGL2RenderingContext::reset_to_default_state()
-{
-}
-
-WebIDL::Long WebGL2RenderingContext::drawing_buffer_width() const
-{
- auto size = canvas_host().bitmap_size_for_canvas();
- return min(size.width(), max_webgl_drawing_buffer_dimension);
-}
-
-WebIDL::Long WebGL2RenderingContext::drawing_buffer_height() const
-{
- auto size = canvas_host().bitmap_size_for_canvas();
- return min(size.height(), max_webgl_drawing_buffer_dimension);
-}
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGL2RenderingContext.h b/Libraries/LibWeb/WebGL/WebGL2RenderingContext.h
index 9a3541cdd6d..edf94ebb112 100644
--- a/Libraries/LibWeb/WebGL/WebGL2RenderingContext.h
+++ b/Libraries/LibWeb/WebGL/WebGL2RenderingContext.h
@@ -8,52 +8,17 @@
#pragma once
-#include <LibGC/Ptr.h>
-#include <LibWeb/Bindings/PlatformObject.h>
-#include <LibWeb/Forward.h>
-#include <LibWeb/WebGL/Types.h>
-#include <LibWeb/WebGL/WebGL2RenderingContextOverloads.h>
-#include <LibWeb/WebGL/WebGLContextAttributes.h>
+#include <LibWeb/Bindings/WebGL2RenderingContext.h>
+#include <LibWeb/WebGL/WebGLRenderingContextBase.h>
namespace Web::WebGL {
-class WebGL2RenderingContext final : public WebGL2RenderingContextOverloads {
- WEB_WRAPPABLE(WebGL2RenderingContext, WebGL2RenderingContextOverloads);
- GC_DECLARE_ALLOCATOR(WebGL2RenderingContext);
+// https://registry.khronos.org/webgl/specs/latest/2.0/#3.7
+class WEB_API WebGL2RenderingContext final : public WebGLRenderingContextBase {
+ WEB_RUST_INTERFACE(WebGL2RenderingContext, web_gl2_rendering_context)
public:
static JS::ThrowCompletionOr<GC::Ptr<WebGL2RenderingContext>> create(JS::Realm&, CanvasOwner, JS::Value options);
-
- virtual ~WebGL2RenderingContext() override;
-
- void prepare_for_compositing() override;
- void did_update_canvas_content() override;
-
- virtual CanvasOwner canvas_for_binding() const override;
-
- Optional<WebGLContextAttributes> get_context_attributes();
-
- void set_size(Gfx::IntSize const&);
- void reset_to_default_state();
-
- WebIDL::Long drawing_buffer_width() const;
- WebIDL::Long drawing_buffer_height() const;
-
-private:
- WebGL2RenderingContext(JS::Realm&, CanvasOwner, NonnullOwnPtr<WebGLContextProxy> context, WebGLContextAttributes context_creation_parameters, WebGLContextAttributes actual_context_parameters);
-
- virtual void visit_edges(Cell::Visitor&) override;
- virtual bool reestablish_remote_context() override;
-
- CanvasOwner m_canvas;
-
- // https://www.khronos.org/registry/webgl/specs/latest/1.0/#context-creation-parameters
- // Each WebGLRenderingContext has context creation parameters, set upon creation, in a WebGLContextAttributes object.
- WebGLContextAttributes m_context_creation_parameters {};
-
- // https://www.khronos.org/registry/webgl/specs/latest/1.0/#actual-context-parameters
- // Each WebGLRenderingContext has actual context parameters, set each time the drawing buffer is created, in a WebGLContextAttributes object.
- WebGLContextAttributes m_actual_context_parameters {};
};
}
diff --git a/Libraries/LibWeb/WebGL/WebGL2RenderingContext.idl b/Libraries/LibWeb/WebGL/WebGL2RenderingContext.idl
index fd8292adfcf..b21a61b21da 100644
--- a/Libraries/LibWeb/WebGL/WebGL2RenderingContext.idl
+++ b/Libraries/LibWeb/WebGL/WebGL2RenderingContext.idl
@@ -1,5 +1,5 @@
// https://registry.khronos.org/webgl/specs/latest/2.0/#3.7
-[Exposed=(Window,Worker)]
+[Exposed=(Window,Worker), ImplementedIn=Rust]
interface WebGL2RenderingContext {
};
diff --git a/Libraries/LibWeb/WebGL/WebGL2RenderingContextBase.idl b/Libraries/LibWeb/WebGL/WebGL2RenderingContextBase.idl
index 0511bdfc3ce..92185734c9d 100644
--- a/Libraries/LibWeb/WebGL/WebGL2RenderingContextBase.idl
+++ b/Libraries/LibWeb/WebGL/WebGL2RenderingContextBase.idl
@@ -296,17 +296,17 @@ interface mixin WebGL2RenderingContextBase {
[FIXME] undefined texImage3D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, GLintptr pboOffset);
// May throw DOMException
- undefined texImage3D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, TexImageSource source);
+ [ImplementedAs=tex_image3d_with_source] undefined texImage3D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, TexImageSource source);
- undefined texImage3D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, [AllowShared] ArrayBufferView? srcData);
- undefined texImage3D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, [AllowShared] ArrayBufferView srcData, unsigned long long srcOffset);
+ [ImplementedAs=tex_image3d] undefined texImage3D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, [AllowShared] ArrayBufferView? srcData);
+ [ImplementedAs=tex_image3d_with_offset] undefined texImage3D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, [AllowShared] ArrayBufferView srcData, unsigned long long srcOffset);
[FIXME] undefined texSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, GLintptr pboOffset);
// May throw DOMException
- undefined texSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, TexImageSource source);
+ [ImplementedAs=tex_sub_image3d_with_source] undefined texSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, TexImageSource source);
- undefined texSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, [AllowShared] ArrayBufferView? srcData, optional unsigned long long srcOffset = 0);
+ [ImplementedAs=tex_sub_image3d] undefined texSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, [AllowShared] ArrayBufferView? srcData, optional unsigned long long srcOffset = 0);
[FIXME] undefined copyTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
diff --git a/Libraries/LibWeb/WebGL/WebGL2RenderingContextImpl.cpp b/Libraries/LibWeb/WebGL/WebGL2RenderingContextImpl.cpp
deleted file mode 100644
index 12f64a83b36..00000000000
--- a/Libraries/LibWeb/WebGL/WebGL2RenderingContextImpl.cpp
+++ /dev/null
@@ -1,1386 +0,0 @@
-/*
- * Copyright (c) 2024-2025, Aliaksandr Kalenik <[email protected]>
- * Copyright (c) 2024-2025, Luke Wilde <[email protected]>
- * Copyright (c) 2025, Jelle Raaijmakers <[email protected]>
- * Copyright (c) 2025, Undefine <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/ByteBuffer.h>
-#include <AK/Checked.h>
-#include <GLES3/gl3.h>
-extern "C" {
-#include <GLES2/gl2ext.h>
-#include <GLES2/gl2ext_angle.h>
-}
-
-#include <LibJS/Runtime/Array.h>
-#include <LibJS/Runtime/ArrayBuffer.h>
-#include <LibJS/Runtime/TypedArray.h>
-#include <LibWeb/WebGL/WebGL2RenderingContextImpl.h>
-#include <LibWeb/WebGL/WebGLActiveInfo.h>
-#include <LibWeb/WebGL/WebGLBuffer.h>
-#include <LibWeb/WebGL/WebGLContextProxy.h>
-#include <LibWeb/WebGL/WebGLFramebuffer.h>
-#include <LibWeb/WebGL/WebGLProgram.h>
-#include <LibWeb/WebGL/WebGLQuery.h>
-#include <LibWeb/WebGL/WebGLRenderbuffer.h>
-#include <LibWeb/WebGL/WebGLSampler.h>
-#include <LibWeb/WebGL/WebGLShader.h>
-#include <LibWeb/WebGL/WebGLShaderPrecisionFormat.h>
-#include <LibWeb/WebGL/WebGLSync.h>
-#include <LibWeb/WebGL/WebGLTexture.h>
-#include <LibWeb/WebGL/WebGLTransformFeedback.h>
-#include <LibWeb/WebGL/WebGLUniformLocation.h>
-#include <LibWeb/WebGL/WebGLVertexArrayObject.h>
-#include <LibWeb/WebIDL/Buffers.h>
-
-namespace Web::WebGL {
-
-WebGL2RenderingContextImpl::WebGL2RenderingContextImpl(JS::Realm& realm, NonnullOwnPtr<WebGLContextProxy> context)
- : WebGLRenderingContextImpl(realm, move(context))
-{
-}
-
-void WebGL2RenderingContextImpl::copy_buffer_sub_data(WebIDL::UnsignedLong read_target, WebIDL::UnsignedLong write_target, WebIDL::LongLong read_offset, WebIDL::LongLong write_offset, WebIDL::LongLong size)
-{
- m_context->make_current();
- m_context->copy_buffer_sub_data(read_target, write_target, read_offset, write_offset, size);
-}
-
-// https://registry.khronos.org/webgl/specs/latest/2.0/#3.7.3
-void WebGL2RenderingContextImpl::get_buffer_sub_data(WebIDL::UnsignedLong target, WebIDL::LongLong src_byte_offset,
- WebIDL::ArrayBufferView dst_buffer, WebIDL::UnsignedLongLong dst_offset, WebIDL::UnsignedLong length)
-{
- // If dstBuffer is a DataView, let elementSize be 1; otherwise, let elementSize be dstBuffer.BYTES_PER_ELEMENT.
- size_t element_size = dst_buffer.element_size();
-
- // If length is 0:
- size_t copy_length;
- if (length == 0) {
- // If dstBuffer is a DataView, let copyLength be dstBuffer.byteLength - dstOffset; the typed elements in the
- // text below are bytes. Otherwise, let copyLength be dstBuffer.length - dstOffset.
- auto destination_element_count = dst_buffer.byte_length() / element_size;
- if (dst_offset > destination_element_count) {
- set_error(GL_INVALID_VALUE);
- return;
- }
- copy_length = destination_element_count - dst_offset;
- }
-
- // Otherwise, let copyLength be length.
- else {
- copy_length = length;
- }
-
- // If copyLength is 0, no data is written to dstBuffer, but this does not cause a GL error to be generated.
- if (copy_length == 0)
- return;
-
- // If dstOffset is greater than dstBuffer.length (or dstBuffer.byteLength in the case of DataView), generates an
- // INVALID_VALUE error.
- Checked<size_t> dst_offset_in_bytes_checked = dst_offset;
- dst_offset_in_bytes_checked *= element_size;
- if (dst_offset_in_bytes_checked.has_overflow() || dst_offset_in_bytes_checked.value() > dst_buffer.byte_length()) {
- set_error(GL_INVALID_VALUE);
- return;
- }
- auto dst_offset_in_bytes = dst_offset_in_bytes_checked.value();
-
- // If dstOffset + copyLength is greater than dstBuffer.length (or dstBuffer.byteLength in the case of DataView),
- // generates an INVALID_VALUE error.
- Checked<size_t> copy_bytes_checked = copy_length;
- copy_bytes_checked *= element_size;
- if (copy_bytes_checked.has_overflow()) {
- set_error(GL_INVALID_VALUE);
- return;
- }
- Checked<size_t> end_offset_checked = dst_offset_in_bytes;
- end_offset_checked += copy_bytes_checked.value();
- if (end_offset_checked.has_overflow() || end_offset_checked.value() > dst_buffer.byte_length()) {
- set_error(GL_INVALID_VALUE);
- return;
- }
- auto copy_bytes = copy_bytes_checked.value();
-
- // If copyLength is greater than zero, copy copyLength typed elements (each of size elementSize) from buf into
- // dstBuffer, reading buf starting at byte index srcByteOffset and writing into dstBuffer starting at element
- // index dstOffset.
- auto temporary_buffer = ByteBuffer::create_uninitialized(copy_bytes);
- if (temporary_buffer.is_error()) {
- set_error(GL_OUT_OF_MEMORY);
- return;
- }
-
- auto bytes = temporary_buffer.release_value();
- if (!m_context->read_buffer_sub_data(target, src_byte_offset, bytes))
- return;
- if (dst_buffer.write_checked(bytes, dst_offset_in_bytes).is_error()) [[unlikely]]
- set_error(GL_INVALID_VALUE);
-}
-
-void WebGL2RenderingContextImpl::blit_framebuffer(WebIDL::Long src_x0, WebIDL::Long src_y0, WebIDL::Long src_x1, WebIDL::Long src_y1, WebIDL::Long dst_x0, WebIDL::Long dst_y0, WebIDL::Long dst_x1, WebIDL::Long dst_y1, WebIDL::UnsignedLong mask, WebIDL::UnsignedLong filter)
-{
- m_context->make_current();
- m_context->notify_content_will_change();
- did_update_canvas_content();
- m_context->blit_framebuffer(src_x0, src_y0, src_x1, src_y1, dst_x0, dst_y0, dst_x1, dst_y1, mask, filter);
-}
-
-void WebGL2RenderingContextImpl::framebuffer_texture_layer(WebIDL::UnsignedLong target, WebIDL::UnsignedLong attachment, GC::Ptr<WebGLTexture> texture, WebIDL::Long level, WebIDL::Long layer)
-{
- m_context->make_current();
-
- GLuint texture_handle = 0;
- if (texture) {
- auto handle_or_error = texture->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- texture_handle = handle_or_error.release_value();
- }
-
- m_context->framebuffer_texture_layer(target, attachment, texture_handle, level, layer);
-}
-
-void WebGL2RenderingContextImpl::invalidate_framebuffer(WebIDL::UnsignedLong target, Vector<WebIDL::UnsignedLong> attachments)
-{
- m_context->make_current();
- m_context->notify_content_will_change();
-
- m_context->invalidate_framebuffer(target, attachments.size(), attachments.data());
- did_update_canvas_content();
-}
-
-void WebGL2RenderingContextImpl::invalidate_sub_framebuffer(WebIDL::UnsignedLong target, Vector<WebIDL::UnsignedLong> attachments, WebIDL::Long x, WebIDL::Long y, WebIDL::Long width, WebIDL::Long height)
-{
- m_context->make_current();
- m_context->notify_content_will_change();
-
- m_context->invalidate_sub_framebuffer(target, attachments.size(), attachments.data(), x, y, width, height);
- did_update_canvas_content();
-}
-
-void WebGL2RenderingContextImpl::read_buffer(WebIDL::UnsignedLong src)
-{
- m_context->make_current();
- m_context->read_buffer(src);
-}
-
-JS::Value WebGL2RenderingContextImpl::get_internalformat_parameter(WebIDL::UnsignedLong target, WebIDL::UnsignedLong internalformat, WebIDL::UnsignedLong pname)
-{
- m_context->make_current();
-
- switch (pname) {
- case GL_SAMPLES: {
- GLint num_sample_counts { 0 };
- m_context->get_internalformativ_robust_angle(target, internalformat, GL_NUM_SAMPLE_COUNTS, 1, nullptr, &num_sample_counts);
- auto samples_buffer = MUST(ByteBuffer::create_zeroed(num_sample_counts * sizeof(GLint)));
- m_context->get_internalformativ_robust_angle(target, internalformat, GL_SAMPLES, num_sample_counts, nullptr, reinterpret_cast<GLint*>(samples_buffer.data()));
- auto array_buffer = JS::ArrayBuffer::create(realm(), move(samples_buffer));
- return JS::Int32Array::create(realm(), num_sample_counts, array_buffer);
- }
- default:
- dbgln("Unknown WebGL internal format parameter name: {:x}", pname);
- set_error(GL_INVALID_ENUM);
- return JS::js_null();
- }
-}
-
-void WebGL2RenderingContextImpl::renderbuffer_storage_multisample(WebIDL::UnsignedLong target, WebIDL::Long samples, WebIDL::UnsignedLong internalformat, WebIDL::Long width, WebIDL::Long height)
-{
- m_context->make_current();
- m_context->renderbuffer_storage_multisample(target, samples, internalformat, width, height);
-}
-
-void WebGL2RenderingContextImpl::tex_storage2d(WebIDL::UnsignedLong target, WebIDL::Long levels, WebIDL::UnsignedLong internalformat, WebIDL::Long width, WebIDL::Long height)
-{
- m_context->make_current();
-
- m_context->tex_storage2d(target, levels, internalformat, width, height);
-}
-
-void WebGL2RenderingContextImpl::tex_storage3d(WebIDL::UnsignedLong target, WebIDL::Long levels, WebIDL::UnsignedLong internalformat, WebIDL::Long width, WebIDL::Long height, WebIDL::Long depth)
-{
- m_context->make_current();
- m_context->tex_storage3d(target, levels, internalformat, width, height, depth);
-}
-
-void WebGL2RenderingContextImpl::tex_image3d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long internalformat, WebIDL::Long width, WebIDL::Long height, WebIDL::Long depth, WebIDL::Long border, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, WebIDL::NullableArrayBufferViewVariant src_data)
-{
- m_context->make_current();
-
- if (src_data.has<Empty>()) {
- m_context->tex_image3d_robust_angle(target, level, internalformat, width, height, depth, border, format, type, 0, nullptr);
- return;
- }
-
- SET_ERROR_VALUE_IF_ERROR(with_buffer_source_bytes(WebIDL::BufferSource { src_data.downcast<WebIDL::ArrayBufferViewVariant>() }, /* src_offset= */ 0, /* src_length_override= */ 0, [&](ReadonlyBytes src_data_bytes) {
- m_context->tex_image3d_robust_angle(target, level, internalformat, width, height, depth, border, format, type, src_data_bytes.size(), src_data_bytes.data());
- }),
- GL_INVALID_OPERATION);
-}
-
-void WebGL2RenderingContextImpl::tex_image3d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long internalformat, WebIDL::Long width, WebIDL::Long height, WebIDL::Long depth, WebIDL::Long border, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, TexImageSource source)
-{
- m_context->make_current();
-
- // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage3D.xhtml
- // border: This value must be 0.
- if (border != 0) {
- set_error(GL_INVALID_VALUE);
- return;
- }
-
- auto maybe_source_frame = read_texture_image_source(source, format, type);
- if (!maybe_source_frame.has_value())
- return;
- auto source_frame = maybe_source_frame.release_value();
- m_context->tex_image3d_from_bitmap(target, level, internalformat, depth, format, type, move(source_frame.frame), Gfx::IntSize { width, height }, source_frame.flip_y, source_frame.premultiply_alpha);
-}
-
-void WebGL2RenderingContextImpl::tex_image3d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long internalformat, WebIDL::Long width, WebIDL::Long height, WebIDL::Long depth, WebIDL::Long border, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, WebIDL::ArrayBufferView src_data, WebIDL::UnsignedLongLong src_offset)
-{
- m_context->make_current();
-
- SET_ERROR_VALUE_IF_ERROR(with_buffer_source_bytes(WebIDL::BufferSource { src_data }, src_offset, /* src_length_override= */ 0, [&](ReadonlyBytes src_data_bytes) {
- m_context->tex_image3d_robust_angle(target, level, internalformat, width, height, depth, border, format, type, src_data_bytes.size(), src_data_bytes.data());
- }),
- GL_INVALID_OPERATION);
-}
-
-void WebGL2RenderingContextImpl::tex_sub_image3d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long xoffset, WebIDL::Long yoffset, WebIDL::Long zoffset, WebIDL::Long width, WebIDL::Long height, WebIDL::Long depth, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, TexImageSource source)
-{
- m_context->make_current();
-
- auto maybe_source_frame = read_texture_image_source(source, format, type);
- if (!maybe_source_frame.has_value())
- return;
- auto source_frame = maybe_source_frame.release_value();
- m_context->tex_sub_image3d_from_bitmap(target, level, xoffset, yoffset, zoffset, depth, format, type, move(source_frame.frame), Gfx::IntSize { width, height }, source_frame.flip_y, source_frame.premultiply_alpha);
-}
-
-void WebGL2RenderingContextImpl::tex_sub_image3d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long xoffset, WebIDL::Long yoffset, WebIDL::Long zoffset, WebIDL::Long width, WebIDL::Long height, WebIDL::Long depth, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, WebIDL::NullableArrayBufferViewVariant src_data, WebIDL::UnsignedLongLong src_offset)
-{
- m_context->make_current();
-
- if (src_data.has<Empty>()) {
- m_context->tex_sub_image3d_robust_angle(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, 0, nullptr);
- return;
- }
-
- SET_ERROR_VALUE_IF_ERROR(with_buffer_source_bytes(WebIDL::BufferSource { src_data.downcast<WebIDL::ArrayBufferViewVariant>() }, src_offset, /* src_length_override= */ 0, [&](ReadonlyBytes src_data_bytes) {
- m_context->tex_sub_image3d_robust_angle(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, src_data_bytes.size(), src_data_bytes.data());
- }),
- GL_INVALID_OPERATION);
-}
-
-void WebGL2RenderingContextImpl::uniform1ui(GC::Ptr<WebGLUniformLocation> location, WebIDL::UnsignedLong v0)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- m_context->uniform1ui(location_handle, v0);
-}
-
-void WebGL2RenderingContextImpl::uniform2ui(GC::Ptr<WebGLUniformLocation> location, WebIDL::UnsignedLong v0, WebIDL::UnsignedLong v1)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- m_context->uniform2ui(location_handle, v0, v1);
-}
-
-void WebGL2RenderingContextImpl::uniform3ui(GC::Ptr<WebGLUniformLocation> location, WebIDL::UnsignedLong v0, WebIDL::UnsignedLong v1, WebIDL::UnsignedLong v2)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- m_context->uniform3ui(location_handle, v0, v1, v2);
-}
-
-void WebGL2RenderingContextImpl::uniform4ui(GC::Ptr<WebGLUniformLocation> location, WebIDL::UnsignedLong v0, WebIDL::UnsignedLong v1, WebIDL::UnsignedLong v2, WebIDL::UnsignedLong v3)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- m_context->uniform4ui(location_handle, v0, v1, v2, v3);
-}
-
-void WebGL2RenderingContextImpl::uniform1uiv(GC::Ptr<WebGLUniformLocation> location, Uint32List values, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- auto span = SET_ERROR_VALUE_IF_ERROR(span_from_uint32_list(values, src_offset, src_length), GL_INVALID_VALUE);
- m_context->uniform1uiv(location_handle, span.size(), span.data());
-}
-
-void WebGL2RenderingContextImpl::uniform2uiv(GC::Ptr<WebGLUniformLocation> location, Uint32List values, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- auto span = SET_ERROR_VALUE_IF_ERROR(span_from_uint32_list(values, src_offset, src_length), GL_INVALID_VALUE);
- if (span.size() % 2 != 0) [[unlikely]] {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_context->uniform2uiv(location_handle, span.size() / 2, span.data());
-}
-
-void WebGL2RenderingContextImpl::uniform3uiv(GC::Ptr<WebGLUniformLocation> location, Uint32List values, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- auto span = SET_ERROR_VALUE_IF_ERROR(span_from_uint32_list(values, src_offset, src_length), GL_INVALID_VALUE);
- if (span.size() % 3 != 0) [[unlikely]] {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_context->uniform3uiv(location_handle, span.size() / 3, span.data());
-}
-
-void WebGL2RenderingContextImpl::uniform4uiv(GC::Ptr<WebGLUniformLocation> location, Uint32List values, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- auto span = SET_ERROR_VALUE_IF_ERROR(span_from_uint32_list(values, src_offset, src_length), GL_INVALID_VALUE);
- if (span.size() % 4 != 0) [[unlikely]] {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_context->uniform4uiv(location_handle, span.size() / 4, span.data());
-}
-
-void WebGL2RenderingContextImpl::uniform_matrix3x2fv(GC::Ptr<WebGLUniformLocation> location, bool transpose, Float32List data, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- constexpr auto matrix_size = 3 * 2;
- auto span = SET_ERROR_VALUE_IF_ERROR(span_from_float32_list(data, src_offset, src_length), GL_INVALID_VALUE);
- if (span.size() % matrix_size != 0) [[unlikely]] {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_context->uniform_matrix3x2fv(location_handle, span.size() / matrix_size, transpose, span.data());
-}
-
-void WebGL2RenderingContextImpl::uniform_matrix4x2fv(GC::Ptr<WebGLUniformLocation> location, bool transpose, Float32List data, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- constexpr auto matrix_size = 4 * 2;
- auto span = SET_ERROR_VALUE_IF_ERROR(span_from_float32_list(data, src_offset, src_length), GL_INVALID_VALUE);
- if (span.size() % matrix_size != 0) [[unlikely]] {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_context->uniform_matrix4x2fv(location_handle, span.size() / matrix_size, transpose, span.data());
-}
-
-void WebGL2RenderingContextImpl::uniform_matrix2x3fv(GC::Ptr<WebGLUniformLocation> location, bool transpose, Float32List data, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- constexpr auto matrix_size = 2 * 3;
- auto span = SET_ERROR_VALUE_IF_ERROR(span_from_float32_list(data, src_offset, src_length), GL_INVALID_VALUE);
- if (span.size() % matrix_size != 0) [[unlikely]] {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_context->uniform_matrix2x3fv(location_handle, span.size() / matrix_size, transpose, span.data());
-}
-
-void WebGL2RenderingContextImpl::uniform_matrix4x3fv(GC::Ptr<WebGLUniformLocation> location, bool transpose, Float32List data, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- constexpr auto matrix_size = 4 * 3;
- auto span = SET_ERROR_VALUE_IF_ERROR(span_from_float32_list(data, src_offset, src_length), GL_INVALID_VALUE);
- if (span.size() % matrix_size != 0) [[unlikely]] {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_context->uniform_matrix4x3fv(location_handle, span.size() / matrix_size, transpose, span.data());
-}
-
-void WebGL2RenderingContextImpl::uniform_matrix2x4fv(GC::Ptr<WebGLUniformLocation> location, bool transpose, Float32List data, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- constexpr auto matrix_size = 2 * 4;
- auto span = SET_ERROR_VALUE_IF_ERROR(span_from_float32_list(data, src_offset, src_length), GL_INVALID_VALUE);
- if (span.size() % matrix_size != 0) [[unlikely]] {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_context->uniform_matrix2x4fv(location_handle, span.size() / matrix_size, transpose, span.data());
-}
-
-void WebGL2RenderingContextImpl::uniform_matrix3x4fv(GC::Ptr<WebGLUniformLocation> location, bool transpose, Float32List data, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- constexpr auto matrix_size = 3 * 4;
- auto span = SET_ERROR_VALUE_IF_ERROR(span_from_float32_list(data, src_offset, src_length), GL_INVALID_VALUE);
- if (span.size() % matrix_size != 0) [[unlikely]] {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_context->uniform_matrix3x4fv(location_handle, span.size() / matrix_size, transpose, span.data());
-}
-
-void WebGL2RenderingContextImpl::vertex_attrib_i4i(WebIDL::UnsignedLong index, WebIDL::Long x, WebIDL::Long y, WebIDL::Long z, WebIDL::Long w)
-{
- m_context->make_current();
- m_context->vertex_attrib_i4i(index, x, y, z, w);
-}
-
-void WebGL2RenderingContextImpl::vertex_attrib_i4iv(WebIDL::UnsignedLong index, Int32List values)
-{
- m_context->make_current();
- auto span = MUST(span_from_int32_list(values, /* src_offset= */ 0));
- if (span.size() < 4) [[unlikely]] {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_context->vertex_attrib_i4iv(index, span.data());
-}
-
-void WebGL2RenderingContextImpl::vertex_attrib_i4ui(WebIDL::UnsignedLong index, WebIDL::UnsignedLong x, WebIDL::UnsignedLong y, WebIDL::UnsignedLong z, WebIDL::UnsignedLong w)
-{
- m_context->make_current();
- m_context->vertex_attrib_i4ui(index, x, y, z, w);
-}
-
-void WebGL2RenderingContextImpl::vertex_attrib_i4uiv(WebIDL::UnsignedLong index, Uint32List values)
-{
- m_context->make_current();
- auto span = MUST(span_from_uint32_list(values, /* src_offset= */ 0));
- if (span.size() < 4) [[unlikely]] {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_context->vertex_attrib_i4uiv(index, span.data());
-}
-
-void WebGL2RenderingContextImpl::vertex_attrib_i_pointer(WebIDL::UnsignedLong index, WebIDL::Long size, WebIDL::UnsignedLong type, WebIDL::Long stride, WebIDL::LongLong offset)
-{
- m_context->make_current();
-
- m_context->vertex_attrib_i_pointer(index, size, type, stride, reinterpret_cast<void*>(offset));
-}
-
-void WebGL2RenderingContextImpl::vertex_attrib_divisor(WebIDL::UnsignedLong index, WebIDL::UnsignedLong divisor)
-{
- m_context->make_current();
- m_context->vertex_attrib_divisor(index, divisor);
-}
-
-void WebGL2RenderingContextImpl::draw_arrays_instanced(WebIDL::UnsignedLong mode, WebIDL::Long first, WebIDL::Long count, WebIDL::Long instance_count)
-{
- m_context->make_current();
- m_context->notify_content_will_change();
- did_update_canvas_content();
- m_context->draw_arrays_instanced(mode, first, count, instance_count);
-}
-
-void WebGL2RenderingContextImpl::draw_elements_instanced(WebIDL::UnsignedLong mode, WebIDL::Long count, WebIDL::UnsignedLong type, WebIDL::LongLong offset, WebIDL::Long instance_count)
-{
- m_context->make_current();
- m_context->notify_content_will_change();
-
- m_context->draw_elements_instanced(mode, count, type, reinterpret_cast<void*>(offset), instance_count);
- did_update_canvas_content();
-}
-
-void WebGL2RenderingContextImpl::draw_range_elements(WebIDL::UnsignedLong mode, WebIDL::UnsignedLong start, WebIDL::UnsignedLong end, WebIDL::Long count, WebIDL::UnsignedLong type, WebIDL::LongLong offset)
-{
- m_context->make_current();
- m_context->notify_content_will_change();
- did_update_canvas_content();
- m_context->draw_range_elements(mode, start, end, count, type, reinterpret_cast<void*>(offset));
-}
-
-void WebGL2RenderingContextImpl::draw_buffers(Vector<WebIDL::UnsignedLong> buffers)
-{
- m_context->make_current();
-
- m_context->draw_buffers(buffers.size(), buffers.data());
-}
-
-void WebGL2RenderingContextImpl::clear_bufferfv(WebIDL::UnsignedLong buffer, WebIDL::Long drawbuffer, Float32List values, WebIDL::UnsignedLongLong src_offset)
-{
- m_context->make_current();
- m_context->notify_content_will_change();
-
- auto span = SET_ERROR_VALUE_IF_ERROR(span_from_float32_list(values, src_offset), GL_INVALID_VALUE);
-
- switch (buffer) {
- case GL_COLOR:
- if (span.size() < 4) {
- set_error(GL_INVALID_VALUE);
- return;
- }
- break;
- case GL_DEPTH:
- case GL_STENCIL:
- if (span.size() < 1) {
- set_error(GL_INVALID_VALUE);
- return;
- }
- break;
- default:
- dbgln("Unknown WebGL buffer target for buffer clearing: 0x{:04x}", buffer);
- set_error(GL_INVALID_ENUM);
- return;
- }
-
- m_context->clear_bufferfv(buffer, drawbuffer, span.data());
- did_update_canvas_content();
-}
-
-void WebGL2RenderingContextImpl::clear_bufferiv(WebIDL::UnsignedLong buffer, WebIDL::Long drawbuffer, Int32List values, WebIDL::UnsignedLongLong src_offset)
-{
- m_context->make_current();
- m_context->notify_content_will_change();
-
- auto span = SET_ERROR_VALUE_IF_ERROR(span_from_int32_list(values, src_offset), GL_INVALID_VALUE);
-
- switch (buffer) {
- case GL_COLOR:
- if (span.size() < 4) {
- set_error(GL_INVALID_VALUE);
- return;
- }
- break;
- case GL_DEPTH:
- case GL_STENCIL:
- if (span.size() < 1) {
- set_error(GL_INVALID_VALUE);
- return;
- }
- break;
- default:
- dbgln("Unknown WebGL buffer target for buffer clearing: 0x{:04x}", buffer);
- set_error(GL_INVALID_ENUM);
- return;
- }
-
- m_context->clear_bufferiv(buffer, drawbuffer, span.data());
- did_update_canvas_content();
-}
-
-void WebGL2RenderingContextImpl::clear_bufferuiv(WebIDL::UnsignedLong buffer, WebIDL::Long drawbuffer, Uint32List values, WebIDL::UnsignedLongLong src_offset)
-{
- m_context->make_current();
- m_context->notify_content_will_change();
-
- auto span = SET_ERROR_VALUE_IF_ERROR(span_from_uint32_list(values, src_offset), GL_INVALID_VALUE);
- switch (buffer) {
- case GL_COLOR:
- if (span.size() < 4) {
- set_error(GL_INVALID_VALUE);
- return;
- }
- break;
- case GL_DEPTH:
- case GL_STENCIL:
- if (span.size() < 1) {
- set_error(GL_INVALID_VALUE);
- return;
- }
- break;
- default:
- dbgln("Unknown WebGL buffer target for buffer clearing: 0x{:04x}", buffer);
- set_error(GL_INVALID_ENUM);
- return;
- }
-
- m_context->clear_bufferuiv(buffer, drawbuffer, span.data());
- did_update_canvas_content();
-}
-
-void WebGL2RenderingContextImpl::clear_bufferfi(WebIDL::UnsignedLong buffer, WebIDL::Long drawbuffer, float depth, WebIDL::Long stencil)
-{
- m_context->make_current();
- m_context->notify_content_will_change();
- did_update_canvas_content();
- m_context->clear_bufferfi(buffer, drawbuffer, depth, stencil);
-}
-
-GC::Ref<WebGLQuery> WebGL2RenderingContextImpl::create_query()
-{
- m_context->make_current();
-
- GLuint handle = 0;
- m_context->gen_queries(1, &handle);
- return WebGLQuery::create(*this, handle);
-}
-
-void WebGL2RenderingContextImpl::delete_query(GC::Ptr<WebGLQuery> query)
-{
- m_context->make_current();
-
- if (!query)
- return;
-
- auto handle_or_error = query->handle_for_deletion(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- auto query_handle = handle_or_error.release_value();
- if (!query_handle.has_value())
- return;
-
- auto handle = query_handle.value();
- m_context->delete_queries(1, &handle);
-}
-
-void WebGL2RenderingContextImpl::begin_query(WebIDL::UnsignedLong target, GC::Ref<WebGLQuery> query)
-{
- m_context->make_current();
-
- auto handle_or_error = query->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- auto query_handle = handle_or_error.release_value();
-
- switch (target) {
- case GL_ANY_SAMPLES_PASSED:
- m_any_samples_passed = query;
- break;
- case GL_ANY_SAMPLES_PASSED_CONSERVATIVE:
- m_any_samples_passed_conservative = query;
- break;
- case GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN:
- m_transform_feedback_primitives_written = query;
- break;
- }
-
- m_context->begin_query(target, query_handle);
-}
-
-void WebGL2RenderingContextImpl::end_query(WebIDL::UnsignedLong target)
-{
- m_context->make_current();
-
- switch (target) {
- case GL_ANY_SAMPLES_PASSED:
- m_any_samples_passed = nullptr;
- break;
- case GL_ANY_SAMPLES_PASSED_CONSERVATIVE:
- m_any_samples_passed_conservative = nullptr;
- break;
- case GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN:
- m_transform_feedback_primitives_written = nullptr;
- break;
- }
-
- m_context->end_query(target);
-}
-
-GC::Ptr<WebGLQuery> WebGL2RenderingContextImpl::get_query(WebIDL::UnsignedLong target, WebIDL::UnsignedLong pname)
-{
- if (pname != GL_CURRENT_QUERY) {
- set_error(GL_INVALID_ENUM);
- return nullptr;
- }
-
- switch (target) {
- case GL_ANY_SAMPLES_PASSED:
- return m_any_samples_passed;
- case GL_ANY_SAMPLES_PASSED_CONSERVATIVE:
- return m_any_samples_passed_conservative;
- case GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN:
- return m_transform_feedback_primitives_written;
- }
-
- set_error(GL_INVALID_ENUM);
- return nullptr;
-}
-
-JS::Value WebGL2RenderingContextImpl::get_query_parameter(GC::Ref<WebGLQuery> query, WebIDL::UnsignedLong pname)
-{
- m_context->make_current();
-
- auto handle_or_error = query->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return JS::js_null();
- }
- auto query_handle = handle_or_error.release_value();
-
- GLuint result { 0 };
- m_context->get_query_objectuiv_robust_angle(query_handle, pname, 1, nullptr, &result);
-
- switch (pname) {
- case GL_QUERY_RESULT:
- return JS::Value(result);
- case GL_QUERY_RESULT_AVAILABLE:
- return JS::Value(result == GL_TRUE);
- default:
- return JS::js_null();
- }
-}
-
-GC::Ref<WebGLSampler> WebGL2RenderingContextImpl::create_sampler()
-{
- m_context->make_current();
-
- GLuint handle = 0;
- m_context->gen_samplers(1, &handle);
- return WebGLSampler::create(*this, handle);
-}
-
-void WebGL2RenderingContextImpl::delete_sampler(GC::Ptr<WebGLSampler> sampler)
-{
- m_context->make_current();
-
- if (!sampler)
- return;
-
- auto handle_or_error = sampler->handle_for_deletion(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- auto sampler_handle = handle_or_error.release_value();
- if (!sampler_handle.has_value())
- return;
-
- auto handle = sampler_handle.value();
- m_context->delete_samplers(1, &handle);
-}
-
-void WebGL2RenderingContextImpl::bind_sampler(WebIDL::UnsignedLong unit, GC::Ptr<WebGLSampler> sampler)
-{
- m_context->make_current();
-
- auto sampler_handle = 0;
- if (sampler) {
- auto handle_or_error = sampler->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- sampler_handle = handle_or_error.release_value();
- }
- m_context->bind_sampler(unit, sampler_handle);
-}
-
-void WebGL2RenderingContextImpl::sampler_parameteri(GC::Ref<WebGLSampler> sampler, WebIDL::UnsignedLong pname, WebIDL::Long param)
-{
- m_context->make_current();
-
- auto handle_or_error = sampler->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- auto sampler_handle = handle_or_error.release_value();
-
- switch (pname) {
- case GL_TEXTURE_COMPARE_FUNC:
- case GL_TEXTURE_COMPARE_MODE:
- case GL_TEXTURE_MAG_FILTER:
- case GL_TEXTURE_MAX_LOD:
- case GL_TEXTURE_MIN_FILTER:
- case GL_TEXTURE_MIN_LOD:
- case GL_TEXTURE_WRAP_R:
- case GL_TEXTURE_WRAP_S:
- case GL_TEXTURE_WRAP_T:
- break;
- case GL_TEXTURE_MAX_ANISOTROPY_EXT: {
- if (extension_enabled("EXT_texture_filter_anisotropic"sv))
- break;
-
- set_error(GL_INVALID_ENUM);
- return;
- }
- default:
- dbgln("Unknown WebGL sampler parameter name: 0x{:04x}", pname);
- set_error(GL_INVALID_ENUM);
- return;
- }
- m_context->sampler_parameteri(sampler_handle, pname, param);
-}
-
-void WebGL2RenderingContextImpl::sampler_parameterf(GC::Ref<WebGLSampler> sampler, WebIDL::UnsignedLong pname, float param)
-{
- m_context->make_current();
-
- auto handle_or_error = sampler->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- auto sampler_handle = handle_or_error.release_value();
-
- switch (pname) {
- case GL_TEXTURE_COMPARE_FUNC:
- case GL_TEXTURE_COMPARE_MODE:
- case GL_TEXTURE_MAG_FILTER:
- case GL_TEXTURE_MAX_LOD:
- case GL_TEXTURE_MIN_FILTER:
- case GL_TEXTURE_MIN_LOD:
- case GL_TEXTURE_WRAP_R:
- case GL_TEXTURE_WRAP_S:
- case GL_TEXTURE_WRAP_T:
- break;
- case GL_TEXTURE_MAX_ANISOTROPY_EXT: {
- if (extension_enabled("EXT_texture_filter_anisotropic"sv))
- break;
-
- set_error(GL_INVALID_ENUM);
- return;
- }
- default:
- dbgln("Unknown WebGL sampler parameter name: 0x{:04x}", pname);
- set_error(GL_INVALID_ENUM);
- return;
- }
- m_context->sampler_parameterf(sampler_handle, pname, param);
-}
-
-GC::Ptr<WebGLSync> WebGL2RenderingContextImpl::fence_sync(WebIDL::UnsignedLong condition, WebIDL::UnsignedLong flags)
-{
- m_context->make_current();
-
- GLsync handle = m_context->fence_sync(condition, flags);
- return WebGLSync::create(*this, handle);
-}
-
-void WebGL2RenderingContextImpl::delete_sync(GC::Ptr<WebGLSync> sync)
-{
- m_context->make_current();
-
- if (!sync)
- return;
-
- auto handle_or_error = sync->sync_handle_for_deletion(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- auto sync_handle = handle_or_error.release_value();
- if (!sync_handle.has_value())
- return;
-
- m_context->delete_sync(static_cast<GLsync>(sync_handle.value()));
-}
-
-WebIDL::UnsignedLong WebGL2RenderingContextImpl::client_wait_sync(GC::Ref<WebGLSync> sync, WebIDL::UnsignedLong flags, WebIDL::UnsignedLongLong timeout)
-{
- m_context->make_current();
-
- auto handle_or_error = sync->sync_handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return GL_WAIT_FAILED;
- }
- auto sync_handle = static_cast<GLsync>(handle_or_error.release_value());
-
- return m_context->client_wait_sync(sync_handle, flags, timeout);
-}
-
-void WebGL2RenderingContextImpl::wait_sync(GC::Ref<WebGLSync> sync, WebIDL::UnsignedLong flags, WebIDL::UnsignedLongLong timeout)
-{
- m_context->make_current();
-
- auto handle_or_error = sync->sync_handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- auto sync_handle = static_cast<GLsync>(handle_or_error.release_value());
-
- m_context->wait_sync(sync_handle, flags, timeout);
-}
-
-JS::Value WebGL2RenderingContextImpl::get_sync_parameter(GC::Ref<WebGLSync> sync, WebIDL::UnsignedLong pname)
-{
- m_context->make_current();
-
- auto handle_or_error = sync->sync_handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return JS::js_null();
- }
- auto sync_handle = static_cast<GLsync>(handle_or_error.release_value());
-
- GLint result = 0;
- m_context->get_synciv(sync_handle, pname, 1, nullptr, &result);
- return JS::Value(result);
-}
-
-GC::Ref<WebGLTransformFeedback> WebGL2RenderingContextImpl::create_transform_feedback()
-{
- m_context->make_current();
-
- GLuint handle = 0;
- m_context->gen_transform_feedbacks(1, &handle);
- return WebGLTransformFeedback::create(*this, handle);
-}
-
-void WebGL2RenderingContextImpl::delete_transform_feedback(GC::Ptr<WebGLTransformFeedback> transform_feedback)
-{
- m_context->make_current();
-
- if (!transform_feedback)
- return;
-
- auto handle_or_error = transform_feedback->handle_for_deletion(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- auto transform_feedback_handle = handle_or_error.release_value();
- if (!transform_feedback_handle.has_value())
- return;
-
- auto handle = transform_feedback_handle.value();
- m_context->delete_transform_feedbacks(1, &handle);
-}
-
-void WebGL2RenderingContextImpl::bind_transform_feedback(WebIDL::UnsignedLong target, GC::Ptr<WebGLTransformFeedback> transform_feedback)
-{
- m_context->make_current();
-
- GLuint transform_feedback_handle = 0;
- if (transform_feedback) {
- auto handle_or_error = transform_feedback->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- transform_feedback_handle = handle_or_error.release_value();
- }
-
- m_context->bind_transform_feedback(target, transform_feedback_handle);
-}
-
-void WebGL2RenderingContextImpl::begin_transform_feedback(WebIDL::UnsignedLong primitive_mode)
-{
- m_context->make_current();
- m_context->begin_transform_feedback(primitive_mode);
-}
-
-void WebGL2RenderingContextImpl::end_transform_feedback()
-{
- m_context->make_current();
- m_context->end_transform_feedback();
-}
-
-void WebGL2RenderingContextImpl::transform_feedback_varyings(GC::Ref<WebGLProgram> program, Vector<Utf16String> const& varyings, WebIDL::UnsignedLong buffer_mode)
-{
- m_context->make_current();
-
- auto handle_or_error = program->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- auto program_handle = handle_or_error.release_value();
-
- Vector<Vector<GLchar>> varying_strings;
- varying_strings.ensure_capacity(varyings.size());
- for (auto const& varying : varyings) {
- varying_strings.unchecked_append(null_terminated_utf8_string(varying.utf16_view()));
- }
-
- Vector<GLchar const*> varying_strings_characters;
- varying_strings.ensure_capacity(varying_strings.size());
- for (auto const& varying_string : varying_strings) {
- varying_strings_characters.append(varying_string.data());
- }
-
- m_context->transform_feedback_varyings(program_handle, varying_strings_characters.size(), varying_strings_characters.data(), buffer_mode);
-}
-
-void WebGL2RenderingContextImpl::pause_transform_feedback()
-{
- m_context->make_current();
- m_context->pause_transform_feedback();
-}
-
-void WebGL2RenderingContextImpl::resume_transform_feedback()
-{
- m_context->make_current();
- m_context->resume_transform_feedback();
-}
-
-void WebGL2RenderingContextImpl::bind_buffer_base(WebIDL::UnsignedLong target, WebIDL::UnsignedLong index, GC::Ptr<WebGLBuffer> buffer)
-{
- m_context->make_current();
-
- auto buffer_handle = 0;
- if (buffer) {
- auto handle_or_error = buffer->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- buffer_handle = handle_or_error.release_value();
-
- if (!buffer->is_compatible_with(target)) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- }
- m_context->bind_buffer_base(target, index, buffer_handle);
-}
-
-void WebGL2RenderingContextImpl::bind_buffer_range(WebIDL::UnsignedLong target, WebIDL::UnsignedLong index, GC::Ptr<WebGLBuffer> buffer, WebIDL::LongLong offset, WebIDL::LongLong size)
-{
- m_context->make_current();
-
- auto buffer_handle = 0;
- if (buffer) {
- auto handle_or_error = buffer->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- buffer_handle = handle_or_error.release_value();
-
- if (!buffer->is_compatible_with(target)) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- }
- m_context->bind_buffer_range(target, index, buffer_handle, offset, size);
-}
-
-Optional<Vector<WebIDL::UnsignedLong>> WebGL2RenderingContextImpl::get_uniform_indices(GC::Ref<WebGLProgram> program, Vector<Utf16String> const& uniform_names)
-{
- m_context->make_current();
-
- auto handle_or_error = program->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return OptionalNone {};
- }
-
- auto program_handle = handle_or_error.release_value();
-
- Vector<Vector<GLchar>> uniform_names_strings;
- uniform_names_strings.ensure_capacity(uniform_names.size());
- for (auto const& uniform_name : uniform_names) {
- uniform_names_strings.unchecked_append(null_terminated_utf8_string(uniform_name.utf16_view()));
- }
-
- Vector<GLchar const*> uniform_names_characters;
- uniform_names_characters.ensure_capacity(uniform_names_strings.size());
- for (auto const& uniform_name_string : uniform_names_strings) {
- uniform_names_characters.unchecked_append(uniform_name_string.data());
- }
-
- auto result_buffer = MUST(ByteBuffer::create_zeroed(uniform_names_characters.size() * sizeof(WebIDL::UnsignedLong)));
- auto result_span = result_buffer.bytes().reinterpret<WebIDL::UnsignedLong>();
- m_context->get_uniform_indices(program_handle, uniform_names_characters.size(), uniform_names_characters.data(), result_span.data());
- return Vector<WebIDL::UnsignedLong> { result_span };
-}
-
-JS::Value WebGL2RenderingContextImpl::get_active_uniforms(GC::Ref<WebGLProgram> program, Vector<WebIDL::UnsignedLong> uniform_indices, WebIDL::UnsignedLong pname)
-{
- m_context->make_current();
-
- auto handle_or_error = program->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return {};
- }
- auto program_handle = handle_or_error.release_value();
-
- auto params = MUST(ByteBuffer::create_zeroed(uniform_indices.size() * sizeof(GLint)));
- Span<GLint> params_span(reinterpret_cast<GLint*>(params.data()), uniform_indices.size());
- m_context->get_active_uniformsiv(program_handle, uniform_indices.size(), uniform_indices.data(), pname, params_span.data());
-
- Vector<JS::Value> params_as_values;
- params_as_values.ensure_capacity(params.size());
- for (GLint param : params_span) {
- switch (pname) {
- case GL_UNIFORM_TYPE:
- params_as_values.unchecked_append(JS::Value(static_cast<GLenum>(param)));
- break;
- case GL_UNIFORM_SIZE:
- params_as_values.unchecked_append(JS::Value(static_cast<GLuint>(param)));
- break;
- case GL_UNIFORM_BLOCK_INDEX:
- case GL_UNIFORM_OFFSET:
- case GL_UNIFORM_ARRAY_STRIDE:
- case GL_UNIFORM_MATRIX_STRIDE:
- params_as_values.unchecked_append(JS::Value(param));
- break;
- case GL_UNIFORM_IS_ROW_MAJOR:
- params_as_values.unchecked_append(JS::Value(param == GL_TRUE));
- break;
- default:
- dbgln("Unknown WebGL uniform parameter name in getActiveUniforms: 0x{:04x}", pname);
- set_error(GL_INVALID_ENUM);
- return JS::js_null();
- }
- }
-
- return JS::Array::create_from(realm(), params_as_values);
-}
-
-WebIDL::UnsignedLong WebGL2RenderingContextImpl::get_uniform_block_index(GC::Ref<WebGLProgram> program, Utf16String uniform_block_name)
-{
- m_context->make_current();
-
- auto handle_or_error = program->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return -1;
- }
- auto program_handle = handle_or_error.release_value();
-
- auto uniform_block_name_null_terminated = null_terminated_utf8_string(uniform_block_name.utf16_view());
- return m_context->get_uniform_block_index(program_handle, uniform_block_name_null_terminated.data());
-}
-
-JS::Value WebGL2RenderingContextImpl::get_active_uniform_block_parameter(GC::Ref<WebGLProgram> program, WebIDL::UnsignedLong uniform_block_index, WebIDL::UnsignedLong pname)
-{
- m_context->make_current();
-
- auto handle_or_error = program->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return JS::js_null();
- }
- auto program_handle = handle_or_error.release_value();
-
- switch (pname) {
- case GL_UNIFORM_BLOCK_BINDING:
- case GL_UNIFORM_BLOCK_DATA_SIZE:
- case GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS: {
- GLint result = 0;
- m_context->get_active_uniform_blockiv_robust_angle(program_handle, uniform_block_index, pname, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES: {
- GLint num_active_uniforms = 0;
- m_context->get_active_uniform_blockiv_robust_angle(program_handle, uniform_block_index, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, 1, nullptr, &num_active_uniforms);
- size_t buffer_size = num_active_uniforms * sizeof(GLint);
- auto active_uniform_indices_buffer = MUST(ByteBuffer::create_zeroed(buffer_size));
- m_context->get_active_uniform_blockiv_robust_angle(program_handle, uniform_block_index, GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, num_active_uniforms, nullptr, reinterpret_cast<GLint*>(active_uniform_indices_buffer.data()));
- auto array_buffer = JS::ArrayBuffer::create(realm(), move(active_uniform_indices_buffer));
- return JS::Uint32Array::create(realm(), num_active_uniforms, array_buffer);
- }
- case GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER:
- case GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER: {
- GLint result = 0;
- m_context->get_active_uniform_blockiv_robust_angle(program_handle, uniform_block_index, pname, 1, nullptr, &result);
- return JS::Value(result == GL_TRUE);
- }
- default:
- dbgln("Unknown WebGL active uniform block parameter name: {:x}", pname);
- set_error(GL_INVALID_ENUM);
- return JS::js_null();
- }
-}
-
-Optional<Utf16String> WebGL2RenderingContextImpl::get_active_uniform_block_name(GC::Ref<WebGLProgram> program, WebIDL::UnsignedLong uniform_block_index)
-{
- m_context->make_current();
-
- auto handle_or_error = program->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return OptionalNone {};
- }
- auto program_handle = handle_or_error.release_value();
-
- GLint uniform_block_name_length = 0;
- m_context->get_active_uniform_blockiv_robust_angle(program_handle, uniform_block_index, GL_UNIFORM_BLOCK_NAME_LENGTH, 1, nullptr, &uniform_block_name_length);
- Vector<GLchar> uniform_block_name;
- uniform_block_name.resize(uniform_block_name_length);
- if (!uniform_block_name_length)
- return Utf16String {};
- m_context->get_active_uniform_block_name(program_handle, uniform_block_index, uniform_block_name_length, nullptr, uniform_block_name.data());
- return utf16_string_from_gl_string(uniform_block_name.data(), static_cast<size_t>(uniform_block_name_length - 1));
-}
-
-void WebGL2RenderingContextImpl::uniform_block_binding(GC::Ref<WebGLProgram> program, WebIDL::UnsignedLong uniform_block_index, WebIDL::UnsignedLong uniform_block_binding)
-{
- m_context->make_current();
-
- auto handle_or_error = program->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- auto program_handle = handle_or_error.release_value();
- m_context->uniform_block_binding(program_handle, uniform_block_index, uniform_block_binding);
-}
-
-GC::Ref<WebGLVertexArrayObject> WebGL2RenderingContextImpl::create_vertex_array()
-{
- m_context->make_current();
-
- GLuint handle = 0;
- m_context->gen_vertex_arrays(1, &handle);
- return WebGLVertexArrayObject::create(*this, handle);
-}
-
-void WebGL2RenderingContextImpl::delete_vertex_array(GC::Ptr<WebGLVertexArrayObject> vertex_array)
-{
- m_context->make_current();
-
- if (!vertex_array)
- return;
-
- auto handle_or_error = vertex_array->handle_for_deletion(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- auto vertex_array_handle = handle_or_error.release_value();
- if (!vertex_array_handle.has_value())
- return;
-
- auto handle = vertex_array_handle.value();
- m_context->delete_vertex_arrays(1, &handle);
- if (m_current_vertex_array == vertex_array)
- m_current_vertex_array = nullptr;
-}
-
-bool WebGL2RenderingContextImpl::is_vertex_array(GC::Ptr<WebGLVertexArrayObject> vertex_array)
-{
- m_context->make_current();
-
- if (!vertex_array)
- return false;
-
- auto handle_or_error = vertex_array->handle_for_query(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return false;
- }
- auto vertex_array_handle = handle_or_error.release_value();
- if (!vertex_array_handle.has_value())
- return false;
- return m_context->is_vertex_array(vertex_array_handle.value());
-}
-
-void WebGL2RenderingContextImpl::bind_vertex_array(GC::Ptr<WebGLVertexArrayObject> array)
-{
- m_context->make_current();
-
- auto array_handle = 0;
- if (array) {
- auto handle_or_error = array->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- array_handle = handle_or_error.release_value();
- }
-
- m_context->bind_vertex_array(array_handle);
- m_current_vertex_array = array;
-}
-
-void WebGL2RenderingContextImpl::compressed_tex_image3d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::UnsignedLong internalformat, WebIDL::Long width, WebIDL::Long height, WebIDL::Long depth, WebIDL::Long border, WebIDL::ArrayBufferView src_data, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length_override)
-{
- m_context->make_current();
-
- if (!enabled_compressed_texture_formats().contains_slow(internalformat)) {
- set_error(GL_INVALID_ENUM);
- return;
- }
-
- SET_ERROR_VALUE_IF_ERROR(with_buffer_source_bytes(WebIDL::BufferSource { src_data }, src_offset, src_length_override, [&](ReadonlyBytes pixels_bytes) {
- m_context->compressed_tex_image3d_robust_angle(target, level, internalformat, width, height, depth, border, pixels_bytes.size(), pixels_bytes.size(), pixels_bytes.data());
- }),
- GL_INVALID_VALUE);
-}
-
-void WebGL2RenderingContextImpl::compressed_tex_sub_image3d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long xoffset, WebIDL::Long yoffset, WebIDL::Long zoffset, WebIDL::Long width, WebIDL::Long height, WebIDL::Long depth, WebIDL::UnsignedLong format, WebIDL::ArrayBufferView src_data, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length_override)
-{
- m_context->make_current();
-
- if (!enabled_compressed_texture_formats().contains_slow(format)) {
- set_error(GL_INVALID_ENUM);
- return;
- }
-
- SET_ERROR_VALUE_IF_ERROR(with_buffer_source_bytes(WebIDL::BufferSource { src_data }, src_offset, src_length_override, [&](ReadonlyBytes pixels_bytes) {
- m_context->compressed_tex_sub_image3d_robust_angle(target, level, xoffset, yoffset, zoffset, width, height, depth, format, pixels_bytes.size(), pixels_bytes.size(), pixels_bytes.data());
- }),
- GL_INVALID_VALUE);
-}
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGL2RenderingContextImpl.h b/Libraries/LibWeb/WebGL/WebGL2RenderingContextImpl.h
deleted file mode 100644
index 380e0b69632..00000000000
--- a/Libraries/LibWeb/WebGL/WebGL2RenderingContextImpl.h
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * Copyright (c) 2024, Aliaksandr Kalenik <[email protected]>
- * Copyright (c) 2024-2025, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/NonnullOwnPtr.h>
-#include <AK/Utf16String.h>
-#include <LibGC/Ptr.h>
-#include <LibWeb/Bindings/PlatformObject.h>
-#include <LibWeb/Forward.h>
-#include <LibWeb/WebGL/Types.h>
-#include <LibWeb/WebGL/WebGLRenderingContextImpl.h>
-#include <LibWeb/WebIDL/Buffers.h>
-#include <LibWebCommon/WebIDL/Types.h>
-
-namespace Web::WebGL {
-
-using namespace Web::HTML;
-
-class WebGL2RenderingContextImpl : public WebGLRenderingContextImpl {
- WEB_NON_IDL_WRAPPABLE(WebGL2RenderingContextImpl, WebGLRenderingContextImpl);
-
-public:
- WebGL2RenderingContextImpl(JS::Realm&, NonnullOwnPtr<WebGLContextProxy>);
-
- void copy_buffer_sub_data(WebIDL::UnsignedLong read_target, WebIDL::UnsignedLong write_target, WebIDL::LongLong read_offset, WebIDL::LongLong write_offset, WebIDL::LongLong size);
- void get_buffer_sub_data(WebIDL::UnsignedLong target, WebIDL::LongLong src_byte_offset, WebIDL::ArrayBufferView dst_buffer, WebIDL::UnsignedLongLong dst_offset, WebIDL::UnsignedLong length);
- void blit_framebuffer(WebIDL::Long src_x0, WebIDL::Long src_y0, WebIDL::Long src_x1, WebIDL::Long src_y1, WebIDL::Long dst_x0, WebIDL::Long dst_y0, WebIDL::Long dst_x1, WebIDL::Long dst_y1, WebIDL::UnsignedLong mask, WebIDL::UnsignedLong filter);
- void framebuffer_texture_layer(WebIDL::UnsignedLong target, WebIDL::UnsignedLong attachment, GC::Ptr<WebGLTexture> texture, WebIDL::Long level, WebIDL::Long layer);
- void invalidate_framebuffer(WebIDL::UnsignedLong target, Vector<WebIDL::UnsignedLong> attachments);
- void invalidate_sub_framebuffer(WebIDL::UnsignedLong target, Vector<WebIDL::UnsignedLong> attachments, WebIDL::Long x, WebIDL::Long y, WebIDL::Long width, WebIDL::Long height);
- void read_buffer(WebIDL::UnsignedLong src);
- JS::Value get_internalformat_parameter(WebIDL::UnsignedLong target, WebIDL::UnsignedLong internalformat, WebIDL::UnsignedLong pname);
- void renderbuffer_storage_multisample(WebIDL::UnsignedLong target, WebIDL::Long samples, WebIDL::UnsignedLong internalformat, WebIDL::Long width, WebIDL::Long height);
- void tex_storage2d(WebIDL::UnsignedLong target, WebIDL::Long levels, WebIDL::UnsignedLong internalformat, WebIDL::Long width, WebIDL::Long height);
- void tex_storage3d(WebIDL::UnsignedLong target, WebIDL::Long levels, WebIDL::UnsignedLong internalformat, WebIDL::Long width, WebIDL::Long height, WebIDL::Long depth);
- void tex_image3d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long internalformat, WebIDL::Long width, WebIDL::Long height, WebIDL::Long depth, WebIDL::Long border, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, WebIDL::NullableArrayBufferViewVariant src_data);
- void tex_image3d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long internalformat, WebIDL::Long width, WebIDL::Long height, WebIDL::Long depth, WebIDL::Long border, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, TexImageSource source);
- void tex_image3d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long internalformat, WebIDL::Long width, WebIDL::Long height, WebIDL::Long depth, WebIDL::Long border, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, WebIDL::ArrayBufferView src_data, WebIDL::UnsignedLongLong src_offset);
- void tex_sub_image3d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long xoffset, WebIDL::Long yoffset, WebIDL::Long zoffset, WebIDL::Long width, WebIDL::Long height, WebIDL::Long depth, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, TexImageSource source);
- void tex_sub_image3d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long xoffset, WebIDL::Long yoffset, WebIDL::Long zoffset, WebIDL::Long width, WebIDL::Long height, WebIDL::Long depth, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, WebIDL::NullableArrayBufferViewVariant src_data, WebIDL::UnsignedLongLong src_offset);
- void uniform1ui(GC::Ptr<WebGLUniformLocation> location, WebIDL::UnsignedLong v0);
- void uniform2ui(GC::Ptr<WebGLUniformLocation> location, WebIDL::UnsignedLong v0, WebIDL::UnsignedLong v1);
- void uniform3ui(GC::Ptr<WebGLUniformLocation> location, WebIDL::UnsignedLong v0, WebIDL::UnsignedLong v1, WebIDL::UnsignedLong v2);
- void uniform4ui(GC::Ptr<WebGLUniformLocation> location, WebIDL::UnsignedLong v0, WebIDL::UnsignedLong v1, WebIDL::UnsignedLong v2, WebIDL::UnsignedLong v3);
- void uniform1uiv(GC::Ptr<WebGLUniformLocation> location, Uint32List v, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length);
- void uniform2uiv(GC::Ptr<WebGLUniformLocation> location, Uint32List v, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length);
- void uniform3uiv(GC::Ptr<WebGLUniformLocation> location, Uint32List v, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length);
- void uniform4uiv(GC::Ptr<WebGLUniformLocation> location, Uint32List v, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length);
- void uniform_matrix3x2fv(GC::Ptr<WebGLUniformLocation> location, bool transpose, Float32List data, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length);
- void uniform_matrix4x2fv(GC::Ptr<WebGLUniformLocation> location, bool transpose, Float32List data, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length);
- void uniform_matrix2x3fv(GC::Ptr<WebGLUniformLocation> location, bool transpose, Float32List data, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length);
- void uniform_matrix4x3fv(GC::Ptr<WebGLUniformLocation> location, bool transpose, Float32List data, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length);
- void uniform_matrix2x4fv(GC::Ptr<WebGLUniformLocation> location, bool transpose, Float32List data, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length);
- void uniform_matrix3x4fv(GC::Ptr<WebGLUniformLocation> location, bool transpose, Float32List data, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length);
- void vertex_attrib_i4i(WebIDL::UnsignedLong index, WebIDL::Long x, WebIDL::Long y, WebIDL::Long z, WebIDL::Long w);
- void vertex_attrib_i4iv(WebIDL::UnsignedLong index, Int32List values);
- void vertex_attrib_i4ui(WebIDL::UnsignedLong index, WebIDL::UnsignedLong x, WebIDL::UnsignedLong y, WebIDL::UnsignedLong z, WebIDL::UnsignedLong w);
- void vertex_attrib_i4uiv(WebIDL::UnsignedLong index, Uint32List values);
- void vertex_attrib_i_pointer(WebIDL::UnsignedLong index, WebIDL::Long size, WebIDL::UnsignedLong type, WebIDL::Long stride, WebIDL::LongLong offset);
- void vertex_attrib_divisor(WebIDL::UnsignedLong index, WebIDL::UnsignedLong divisor);
- void draw_arrays_instanced(WebIDL::UnsignedLong mode, WebIDL::Long first, WebIDL::Long count, WebIDL::Long instance_count);
- void draw_elements_instanced(WebIDL::UnsignedLong mode, WebIDL::Long count, WebIDL::UnsignedLong type, WebIDL::LongLong offset, WebIDL::Long instance_count);
- void draw_range_elements(WebIDL::UnsignedLong mode, WebIDL::UnsignedLong start, WebIDL::UnsignedLong end, WebIDL::Long count, WebIDL::UnsignedLong type, WebIDL::LongLong offset);
- void draw_buffers(Vector<WebIDL::UnsignedLong> buffers);
- void clear_bufferfv(WebIDL::UnsignedLong buffer, WebIDL::Long drawbuffer, Float32List values, WebIDL::UnsignedLongLong src_offset);
- void clear_bufferiv(WebIDL::UnsignedLong buffer, WebIDL::Long drawbuffer, Int32List values, WebIDL::UnsignedLongLong src_offset);
- void clear_bufferuiv(WebIDL::UnsignedLong buffer, WebIDL::Long drawbuffer, Uint32List values, WebIDL::UnsignedLongLong src_offset);
- void clear_bufferfi(WebIDL::UnsignedLong buffer, WebIDL::Long drawbuffer, float depth, WebIDL::Long stencil);
- GC::Ref<WebGLQuery> create_query();
- void delete_query(GC::Ptr<WebGLQuery> query);
- void begin_query(WebIDL::UnsignedLong target, GC::Ref<WebGLQuery> query);
- void end_query(WebIDL::UnsignedLong target);
- GC::Ptr<WebGLQuery> get_query(WebIDL::UnsignedLong target, WebIDL::UnsignedLong pname);
- JS::Value get_query_parameter(GC::Ref<WebGLQuery> query, WebIDL::UnsignedLong pname);
- GC::Ref<WebGLSampler> create_sampler();
- void delete_sampler(GC::Ptr<WebGLSampler> sampler);
- void bind_sampler(WebIDL::UnsignedLong unit, GC::Ptr<WebGLSampler> sampler);
- void sampler_parameteri(GC::Ref<WebGLSampler> sampler, WebIDL::UnsignedLong pname, WebIDL::Long param);
- void sampler_parameterf(GC::Ref<WebGLSampler> sampler, WebIDL::UnsignedLong pname, float param);
- GC::Ptr<WebGLSync> fence_sync(WebIDL::UnsignedLong condition, WebIDL::UnsignedLong flags);
- void delete_sync(GC::Ptr<WebGLSync> sync);
- WebIDL::UnsignedLong client_wait_sync(GC::Ref<WebGLSync> sync, WebIDL::UnsignedLong flags, WebIDL::UnsignedLongLong timeout);
- void wait_sync(GC::Ref<WebGLSync> sync, WebIDL::UnsignedLong flags, WebIDL::UnsignedLongLong timeout);
- JS::Value get_sync_parameter(GC::Ref<WebGLSync> sync, WebIDL::UnsignedLong pname);
- GC::Ref<WebGLTransformFeedback> create_transform_feedback();
- void delete_transform_feedback(GC::Ptr<WebGLTransformFeedback> transform_feedback);
- void bind_transform_feedback(WebIDL::UnsignedLong target, GC::Ptr<WebGLTransformFeedback>);
- void begin_transform_feedback(WebIDL::UnsignedLong primitive_mode);
- void end_transform_feedback();
- void transform_feedback_varyings(GC::Ref<WebGLProgram> program, Vector<Utf16String> const& varyings, WebIDL::UnsignedLong buffer_mode);
- void pause_transform_feedback();
- void resume_transform_feedback();
- void bind_buffer_base(WebIDL::UnsignedLong target, WebIDL::UnsignedLong index, GC::Ptr<WebGLBuffer> buffer);
- void bind_buffer_range(WebIDL::UnsignedLong target, WebIDL::UnsignedLong index, GC::Ptr<WebGLBuffer> buffer, WebIDL::LongLong offset, WebIDL::LongLong size);
- Optional<Vector<WebIDL::UnsignedLong>> get_uniform_indices(GC::Ref<WebGLProgram> program, Vector<Utf16String> const& uniform_names);
- JS::Value get_active_uniforms(GC::Ref<WebGLProgram> program, Vector<WebIDL::UnsignedLong> uniform_indices, WebIDL::UnsignedLong pname);
- WebIDL::UnsignedLong get_uniform_block_index(GC::Ref<WebGLProgram> program, Utf16String uniform_block_name);
- JS::Value get_active_uniform_block_parameter(GC::Ref<WebGLProgram> program, WebIDL::UnsignedLong uniform_block_index, WebIDL::UnsignedLong pname);
- Optional<Utf16String> get_active_uniform_block_name(GC::Ref<WebGLProgram> program, WebIDL::UnsignedLong uniform_block_index);
- void uniform_block_binding(GC::Ref<WebGLProgram> program, WebIDL::UnsignedLong uniform_block_index, WebIDL::UnsignedLong uniform_block_binding);
- GC::Ref<WebGLVertexArrayObject> create_vertex_array();
- void delete_vertex_array(GC::Ptr<WebGLVertexArrayObject> vertex_array);
- bool is_vertex_array(GC::Ptr<WebGLVertexArrayObject> vertex_array);
- void bind_vertex_array(GC::Ptr<WebGLVertexArrayObject> array);
- void compressed_tex_image3d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::UnsignedLong internalformat, WebIDL::Long width, WebIDL::Long height, WebIDL::Long depth, WebIDL::Long border, WebIDL::ArrayBufferView src_data, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length_override);
- void compressed_tex_sub_image3d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long xoffset, WebIDL::Long yoffset, WebIDL::Long zoffset, WebIDL::Long width, WebIDL::Long height, WebIDL::Long depth, WebIDL::UnsignedLong format, WebIDL::ArrayBufferView src_data, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length_override);
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGL2RenderingContextOverloads.cpp b/Libraries/LibWeb/WebGL/WebGL2RenderingContextOverloads.cpp
deleted file mode 100644
index 87324818610..00000000000
--- a/Libraries/LibWeb/WebGL/WebGL2RenderingContextOverloads.cpp
+++ /dev/null
@@ -1,484 +0,0 @@
-/*
- * Copyright (c) 2024-2025, Aliaksandr Kalenik <[email protected]>
- * Copyright (c) 2024-2025, Luke Wilde <[email protected]>
- * Copyright (c) 2025, Jelle Raaijmakers <[email protected]>
- * Copyright (c) 2025, Undefine <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <GLES3/gl3.h>
-extern "C" {
-#include <GLES2/gl2ext.h>
-#include <GLES2/gl2ext_angle.h>
-}
-
-#include <AK/Checked.h>
-#include <LibCompositing/WebGL/TextureUpload.h>
-#include <LibJS/Runtime/Array.h>
-#include <LibJS/Runtime/ArrayBuffer.h>
-#include <LibJS/Runtime/TypedArray.h>
-#include <LibWeb/WebGL/WebGL2RenderingContextOverloads.h>
-#include <LibWeb/WebGL/WebGLContextProxy.h>
-#include <LibWeb/WebGL/WebGLUniformLocation.h>
-#include <LibWeb/WebIDL/Buffers.h>
-
-namespace Web::WebGL {
-
-WebGL2RenderingContextOverloads::WebGL2RenderingContextOverloads(JS::Realm& realm, NonnullOwnPtr<WebGLContextProxy> context)
- : WebGL2RenderingContextImpl(realm, move(context))
-{
-}
-
-void WebGL2RenderingContextOverloads::buffer_data(WebIDL::UnsignedLong target, WebIDL::LongLong size, WebIDL::UnsignedLong usage)
-{
- m_context->make_current();
-
- m_context->buffer_data(target, size, 0, usage);
-}
-
-void WebGL2RenderingContextOverloads::buffer_data(WebIDL::UnsignedLong target, WebIDL::NullableBufferSourceVariant src_data, WebIDL::UnsignedLong usage)
-{
- m_context->make_current();
-
- // https://registry.khronos.org/webgl/specs/latest/1.0/#5.14.5
- // If the passed data is null then an INVALID_VALUE error is generated.
- if (src_data.has<Empty>()) {
- set_error(GL_INVALID_VALUE);
- return;
- }
-
- SET_ERROR_VALUE_IF_ERROR(with_buffer_source_bytes(WebIDL::BufferSource { src_data.downcast<WebIDL::BufferSourceVariant>() }, /* src_offset= */ 0, /* src_length_override= */ 0, [&](ReadonlyBytes data) {
- m_context->buffer_data(target, static_cast<GLsizeiptr>(data.size()), data.data(), usage);
- }),
- GL_INVALID_VALUE);
-}
-
-void WebGL2RenderingContextOverloads::buffer_sub_data(WebIDL::UnsignedLong target, WebIDL::LongLong dst_byte_offset, WebIDL::BufferSource src_data)
-{
- m_context->make_current();
-
- SET_ERROR_VALUE_IF_ERROR(with_buffer_source_bytes(src_data, /* src_offset= */ 0, /* src_length_override= */ 0, [&](ReadonlyBytes data) {
- m_context->buffer_sub_data(target, dst_byte_offset, data.size(), data.data());
- }),
- GL_INVALID_VALUE);
-}
-
-void WebGL2RenderingContextOverloads::buffer_data(WebIDL::UnsignedLong target, WebIDL::ArrayBufferView src_data, WebIDL::UnsignedLong usage, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong length)
-{
- m_context->make_current();
-
- SET_ERROR_VALUE_IF_ERROR(with_buffer_source_bytes(WebIDL::BufferSource { src_data }, src_offset, length, [&](ReadonlyBytes data) {
- m_context->buffer_data(target, data.size(), data.data(), usage);
- }),
- GL_INVALID_VALUE);
-}
-
-void WebGL2RenderingContextOverloads::buffer_sub_data(WebIDL::UnsignedLong target, WebIDL::LongLong dst_byte_offset, WebIDL::ArrayBufferView src_data, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong length)
-{
- m_context->make_current();
-
- SET_ERROR_VALUE_IF_ERROR(with_buffer_source_bytes(WebIDL::BufferSource { src_data }, src_offset, length, [&](ReadonlyBytes data) {
- m_context->buffer_sub_data(target, dst_byte_offset, data.size(), data.data());
- }),
- GL_INVALID_VALUE);
-}
-
-void WebGL2RenderingContextOverloads::tex_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long internalformat, WebIDL::Long width, WebIDL::Long height, WebIDL::Long border, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, WebIDL::NullableArrayBufferViewVariant pixels)
-{
- m_context->make_current();
-
- if (pixels.has<Empty>()) {
- m_context->tex_image2d_robust_angle(target, level, internalformat, width, height, border, format, type, 0, nullptr);
- return;
- }
-
- SET_ERROR_VALUE_IF_ERROR(with_buffer_source_bytes(WebIDL::BufferSource { pixels.downcast<WebIDL::ArrayBufferViewVariant>() }, /* src_offset= */ 0, /* src_length_override= */ 0, [&](ReadonlyBytes pixels_bytes) -> ErrorOr<void> {
- auto texture_data = TRY(texture_data_for_2d_upload(pixels_bytes, width, height, format, type));
- m_context->tex_image2d_robust_angle(target, level, internalformat, width, height, border, format, type, texture_data.size(), texture_data.data());
- return {};
- }),
- GL_INVALID_OPERATION);
-}
-
-void WebGL2RenderingContextOverloads::tex_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long internalformat, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, TexImageSource source)
-{
- m_context->make_current();
-
- auto maybe_source_frame = read_texture_image_source(source, format, type);
- if (!maybe_source_frame.has_value())
- return;
- auto source_frame = maybe_source_frame.release_value();
- m_context->tex_image2d_from_bitmap(target, level, internalformat, format, type, move(source_frame.frame), OptionalNone {}, source_frame.flip_y, source_frame.premultiply_alpha);
-}
-
-void WebGL2RenderingContextOverloads::tex_sub_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long xoffset, WebIDL::Long yoffset, WebIDL::Long width, WebIDL::Long height, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, WebIDL::NullableArrayBufferViewVariant pixels)
-{
- m_context->make_current();
-
- if (pixels.has<Empty>()) {
- if (!is_valid_2d_pixel_unpack_state(width, m_unpack_state)) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- m_context->tex_sub_image2d_robust_angle(target, level, xoffset, yoffset, width, height, format, type, 0, nullptr);
- return;
- }
-
- SET_ERROR_VALUE_IF_ERROR(with_buffer_source_bytes(WebIDL::BufferSource { pixels.downcast<WebIDL::ArrayBufferViewVariant>() }, /* src_offset= */ 0, /* src_length_override= */ 0, [&](ReadonlyBytes pixels_bytes) -> ErrorOr<void> {
- auto texture_data = TRY(texture_data_for_2d_upload(pixels_bytes, width, height, format, type));
- m_context->tex_sub_image2d_robust_angle(target, level, xoffset, yoffset, width, height, format, type, texture_data.size(), texture_data.data());
- return {};
- }),
- GL_INVALID_OPERATION);
-}
-
-void WebGL2RenderingContextOverloads::tex_sub_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long xoffset, WebIDL::Long yoffset, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, TexImageSource source)
-{
- m_context->make_current();
-
- auto maybe_source_frame = read_texture_image_source(source, format, type);
- if (!maybe_source_frame.has_value())
- return;
- auto source_frame = maybe_source_frame.release_value();
- m_context->tex_sub_image2d_from_bitmap(target, level, xoffset, yoffset, format, type, move(source_frame.frame), OptionalNone {}, source_frame.flip_y, source_frame.premultiply_alpha);
-}
-
-void WebGL2RenderingContextOverloads::tex_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long internalformat, WebIDL::Long width, WebIDL::Long height, WebIDL::Long border, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, TexImageSource source)
-{
- m_context->make_current();
-
- // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
- // border: This value must be 0.
- if (border != 0) {
- set_error(GL_INVALID_VALUE);
- return;
- }
-
- auto maybe_source_frame = read_texture_image_source(source, format, type);
- if (!maybe_source_frame.has_value())
- return;
- auto source_frame = maybe_source_frame.release_value();
- m_context->tex_image2d_from_bitmap(target, level, internalformat, format, type, move(source_frame.frame), Gfx::IntSize { width, height }, source_frame.flip_y, source_frame.premultiply_alpha);
-}
-
-void WebGL2RenderingContextOverloads::tex_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long internalformat, WebIDL::Long width, WebIDL::Long height, WebIDL::Long border, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, WebIDL::ArrayBufferView src_data, WebIDL::UnsignedLongLong src_offset)
-{
- m_context->make_current();
-
- SET_ERROR_VALUE_IF_ERROR(with_buffer_source_bytes(WebIDL::BufferSource { src_data }, src_offset, /* src_length_override= */ 0, [&](ReadonlyBytes pixels_bytes) -> ErrorOr<void> {
- auto texture_data = TRY(texture_data_for_2d_upload(pixels_bytes, width, height, format, type));
- m_context->tex_image2d_robust_angle(target, level, internalformat, width, height, border, format, type, texture_data.size(), texture_data.data());
- return {};
- }),
- GL_INVALID_OPERATION);
-}
-
-void WebGL2RenderingContextOverloads::tex_sub_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long xoffset, WebIDL::Long yoffset, WebIDL::Long width, WebIDL::Long height, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, TexImageSource source)
-{
- m_context->make_current();
-
- auto maybe_source_frame = read_texture_image_source(source, format, type);
- if (!maybe_source_frame.has_value())
- return;
- auto source_frame = maybe_source_frame.release_value();
- m_context->tex_sub_image2d_from_bitmap(target, level, xoffset, yoffset, format, type, move(source_frame.frame), Gfx::IntSize { width, height }, source_frame.flip_y, source_frame.premultiply_alpha);
-}
-
-void WebGL2RenderingContextOverloads::tex_sub_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long xoffset, WebIDL::Long yoffset, WebIDL::Long width, WebIDL::Long height, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, WebIDL::ArrayBufferView src_data, WebIDL::UnsignedLongLong src_offset)
-{
- m_context->make_current();
-
- SET_ERROR_VALUE_IF_ERROR(with_buffer_source_bytes(WebIDL::BufferSource { src_data }, src_offset, /* src_length_override= */ 0, [&](ReadonlyBytes pixels_bytes) -> ErrorOr<void> {
- auto texture_data = TRY(texture_data_for_2d_upload(pixels_bytes, width, height, format, type));
- m_context->tex_sub_image2d_robust_angle(target, level, xoffset, yoffset, width, height, format, type, texture_data.size(), texture_data.data());
- return {};
- }),
- GL_INVALID_OPERATION);
-}
-
-void WebGL2RenderingContextOverloads::compressed_tex_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::UnsignedLong internalformat, WebIDL::Long width, WebIDL::Long height, WebIDL::Long border, WebIDL::ArrayBufferView src_data, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length_override)
-{
- m_context->make_current();
-
- if (!enabled_compressed_texture_formats().contains_slow(internalformat)) {
- set_error(GL_INVALID_ENUM);
- return;
- }
-
- SET_ERROR_VALUE_IF_ERROR(with_buffer_source_bytes(WebIDL::BufferSource { src_data }, src_offset, src_length_override, [&](ReadonlyBytes pixels_bytes) {
- m_context->compressed_tex_image2d_robust_angle(target, level, internalformat, width, height, border, pixels_bytes.size(), pixels_bytes.size(), pixels_bytes.data());
- }),
- GL_INVALID_VALUE);
-}
-
-void WebGL2RenderingContextOverloads::compressed_tex_sub_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long xoffset, WebIDL::Long yoffset, WebIDL::Long width, WebIDL::Long height, WebIDL::UnsignedLong format, WebIDL::ArrayBufferView src_data, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length_override)
-{
- m_context->make_current();
-
- if (!enabled_compressed_texture_formats().contains_slow(format)) {
- set_error(GL_INVALID_ENUM);
- return;
- }
-
- SET_ERROR_VALUE_IF_ERROR(with_buffer_source_bytes(WebIDL::BufferSource { src_data }, src_offset, src_length_override, [&](ReadonlyBytes pixels_bytes) {
- m_context->compressed_tex_sub_image2d_robust_angle(target, level, xoffset, yoffset, width, height, format, pixels_bytes.size(), pixels_bytes.size(), pixels_bytes.data());
- }),
- GL_INVALID_VALUE);
-}
-
-void WebGL2RenderingContextOverloads::uniform1fv(GC::Ptr<WebGLUniformLocation> location, Float32List values, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- auto span = SET_ERROR_VALUE_IF_ERROR(span_from_float32_list(values, src_offset, src_length), GL_INVALID_VALUE);
- m_context->uniform1fv(location_handle, span.size(), span.data());
-}
-
-void WebGL2RenderingContextOverloads::uniform2fv(GC::Ptr<WebGLUniformLocation> location, Float32List values, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- auto span = SET_ERROR_VALUE_IF_ERROR(span_from_float32_list(values, src_offset, src_length), GL_INVALID_VALUE);
- if (span.size() % 2 != 0) [[unlikely]] {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_context->uniform2fv(location_handle, span.size() / 2, span.data());
-}
-
-void WebGL2RenderingContextOverloads::uniform3fv(GC::Ptr<WebGLUniformLocation> location, Float32List values, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- auto span = SET_ERROR_VALUE_IF_ERROR(span_from_float32_list(values, src_offset, src_length), GL_INVALID_VALUE);
- if (span.size() % 3 != 0) [[unlikely]] {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_context->uniform3fv(location_handle, span.size() / 3, span.data());
-}
-
-void WebGL2RenderingContextOverloads::uniform4fv(GC::Ptr<WebGLUniformLocation> location, Float32List values, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- auto span = SET_ERROR_VALUE_IF_ERROR(span_from_float32_list(values, src_offset, src_length), GL_INVALID_VALUE);
- if (span.size() % 4 != 0) [[unlikely]] {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_context->uniform4fv(location_handle, span.size() / 4, span.data());
-}
-
-void WebGL2RenderingContextOverloads::uniform1iv(GC::Ptr<WebGLUniformLocation> location, Int32List values, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- auto span = SET_ERROR_VALUE_IF_ERROR(span_from_int32_list(values, src_offset, src_length), GL_INVALID_VALUE);
- m_context->uniform1iv(location_handle, span.size(), span.data());
-}
-
-void WebGL2RenderingContextOverloads::uniform2iv(GC::Ptr<WebGLUniformLocation> location, Int32List values, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- auto span = SET_ERROR_VALUE_IF_ERROR(span_from_int32_list(values, src_offset, src_length), GL_INVALID_VALUE);
- if (span.size() % 2 != 0) [[unlikely]] {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_context->uniform2iv(location_handle, span.size() / 2, span.data());
-}
-
-void WebGL2RenderingContextOverloads::uniform3iv(GC::Ptr<WebGLUniformLocation> location, Int32List values, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- auto span = SET_ERROR_VALUE_IF_ERROR(span_from_int32_list(values, src_offset, src_length), GL_INVALID_VALUE);
- if (span.size() % 3 != 0) [[unlikely]] {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_context->uniform3iv(location_handle, span.size() / 3, span.data());
-}
-
-void WebGL2RenderingContextOverloads::uniform4iv(GC::Ptr<WebGLUniformLocation> location, Int32List values, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- auto span = SET_ERROR_VALUE_IF_ERROR(span_from_int32_list(values, src_offset, src_length), GL_INVALID_VALUE);
- if (span.size() % 4 != 0) [[unlikely]] {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_context->uniform4iv(location_handle, span.size() / 4, span.data());
-}
-
-void WebGL2RenderingContextOverloads::uniform_matrix2fv(GC::Ptr<WebGLUniformLocation> location, bool transpose, Float32List data, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- constexpr auto matrix_size = 2 * 2;
- auto span = SET_ERROR_VALUE_IF_ERROR(span_from_float32_list(data, src_offset, src_length), GL_INVALID_VALUE);
- if (span.size() % matrix_size != 0) [[unlikely]] {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_context->uniform_matrix2fv(location_handle, span.size() / matrix_size, transpose, span.data());
-}
-
-void WebGL2RenderingContextOverloads::uniform_matrix3fv(GC::Ptr<WebGLUniformLocation> location, bool transpose, Float32List data, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- constexpr auto matrix_size = 3 * 3;
- auto span = SET_ERROR_VALUE_IF_ERROR(span_from_float32_list(data, src_offset, src_length), GL_INVALID_VALUE);
- if (span.size() % matrix_size != 0) [[unlikely]] {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_context->uniform_matrix3fv(location_handle, span.size() / matrix_size, transpose, span.data());
-}
-
-void WebGL2RenderingContextOverloads::uniform_matrix4fv(GC::Ptr<WebGLUniformLocation> location, bool transpose, Float32List data, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- constexpr auto matrix_size = 4 * 4;
- auto span = SET_ERROR_VALUE_IF_ERROR(span_from_float32_list(data, src_offset, src_length), GL_INVALID_VALUE);
- if (span.size() % matrix_size != 0) [[unlikely]] {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_context->uniform_matrix4fv(location_handle, span.size() / matrix_size, transpose, span.data());
-}
-
-// https://registry.khronos.org/webgl/specs/latest/1.0/index.html#5.14.12
-void WebGL2RenderingContextOverloads::read_pixels(WebIDL::Long x, WebIDL::Long y, WebIDL::Long width, WebIDL::Long height,
- WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, WebIDL::NullableArrayBufferViewVariant pixels)
-{
- if (pixels.has<Empty>()) {
- set_error(GL_INVALID_VALUE);
- return;
- }
-
- WebIDL::ArrayBufferView view { pixels.downcast<WebIDL::ArrayBufferViewVariant>() };
- read_pixels(x, y, width, height, format, type, view, 0);
-}
-
-// https://registry.khronos.org/webgl/specs/latest/2.0/#4.7.10
-void WebGL2RenderingContextOverloads::read_pixels(WebIDL::Long x, WebIDL::Long y, WebIDL::Long width, WebIDL::Long height,
- WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, WebIDL::ArrayBufferView dst_data, WebIDL::UnsignedLongLong dst_offset)
-{
- m_context->make_current();
-
- // If a WebGLBuffer is bound to the PIXEL_PACK_BUFFER target, generates an INVALID_OPERATION error.
- if (m_pixel_pack_buffer_binding) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
-
- // If pixel store parameter constraints are not met, generates an INVALID_OPERATION error.
- auto validated_view_or_error = WebIDL::validate_array_buffer_view(dst_data);
- if (validated_view_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- auto validated_view = validated_view_or_error.release_value();
-
- // If dstData doesn't have enough space for the read operation starting at dstOffset, generate INVALID_OPERATION.
- Checked<size_t> dst_byte_offset = dst_offset;
- dst_byte_offset *= validated_view.element_size;
- if (dst_byte_offset.has_overflow() || dst_byte_offset.value() > validated_view.byte_length) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
-
- auto bytes_or_error = ByteBuffer::create_uninitialized(validated_view.byte_length - dst_byte_offset.value());
- if (bytes_or_error.is_error()) {
- set_error(GL_OUT_OF_MEMORY);
- return;
- }
- auto bytes = bytes_or_error.release_value();
- GLsizei bytes_read = 0;
- m_context->read_pixels_robust_angle(x, y, width, height, format, type, bytes.size(), &bytes_read, nullptr, nullptr, bytes.data());
- if (bytes_read == 0)
- return;
- VERIFY(bytes_read > 0);
-
- if (dst_data.write_checked({ bytes.data(), static_cast<size_t>(bytes_read) }, dst_byte_offset.value()).is_error()) [[unlikely]]
- set_error(GL_INVALID_OPERATION);
-}
-
-// https://registry.khronos.org/webgl/specs/latest/2.0/#4.7.10
-void WebGL2RenderingContextOverloads::read_pixels(WebIDL::Long x, WebIDL::Long y, WebIDL::Long width, WebIDL::Long height,
- WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, WebIDL::LongLong offset)
-{
- m_context->make_current();
-
- // If no WebGLBuffer is bound to the PIXEL_PACK_BUFFER target, generates an INVALID_OPERATION error.
- if (!m_pixel_pack_buffer_binding) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
-
- m_context->read_pixels_into_pixel_pack_buffer(x, y, width, height, format, type, offset);
-}
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGL2RenderingContextOverloads.h b/Libraries/LibWeb/WebGL/WebGL2RenderingContextOverloads.h
deleted file mode 100644
index 9101713d869..00000000000
--- a/Libraries/LibWeb/WebGL/WebGL2RenderingContextOverloads.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (c) 2024, Aliaksandr Kalenik <[email protected]>
- * Copyright (c) 2024-2025, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/NonnullOwnPtr.h>
-#include <AK/Optional.h>
-#include <LibGC/Ptr.h>
-#include <LibWeb/Forward.h>
-#include <LibWeb/WebGL/WebGL2RenderingContextImpl.h>
-#include <LibWeb/WebIDL/Buffers.h>
-#include <LibWebCommon/WebIDL/Types.h>
-
-namespace Web::WebGL {
-
-using namespace Web::HTML;
-
-class WebGL2RenderingContextOverloads : public WebGL2RenderingContextImpl {
- WEB_NON_IDL_WRAPPABLE(WebGL2RenderingContextOverloads, WebGL2RenderingContextImpl);
-
-public:
- WebGL2RenderingContextOverloads(JS::Realm&, NonnullOwnPtr<WebGLContextProxy>);
-
- void buffer_data(WebIDL::UnsignedLong target, WebIDL::LongLong size, WebIDL::UnsignedLong usage);
- void buffer_data(WebIDL::UnsignedLong target, WebIDL::NullableBufferSourceVariant src_data, WebIDL::UnsignedLong usage);
- void buffer_sub_data(WebIDL::UnsignedLong target, WebIDL::LongLong dst_byte_offset, WebIDL::BufferSource src_data);
- void buffer_data(WebIDL::UnsignedLong target, WebIDL::ArrayBufferView src_data, WebIDL::UnsignedLong usage, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong length);
- void buffer_sub_data(WebIDL::UnsignedLong target, WebIDL::LongLong dst_byte_offset, WebIDL::ArrayBufferView src_data, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong length);
- void tex_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long internalformat, WebIDL::Long width, WebIDL::Long height, WebIDL::Long border, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, WebIDL::NullableArrayBufferViewVariant pixels);
- void tex_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long internalformat, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, TexImageSource source);
- void tex_sub_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long xoffset, WebIDL::Long yoffset, WebIDL::Long width, WebIDL::Long height, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, WebIDL::NullableArrayBufferViewVariant pixels);
- void tex_sub_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long xoffset, WebIDL::Long yoffset, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, TexImageSource source);
- void tex_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long internalformat, WebIDL::Long width, WebIDL::Long height, WebIDL::Long border, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, TexImageSource source);
- void tex_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long internalformat, WebIDL::Long width, WebIDL::Long height, WebIDL::Long border, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, WebIDL::ArrayBufferView src_data, WebIDL::UnsignedLongLong src_offset);
- void tex_sub_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long xoffset, WebIDL::Long yoffset, WebIDL::Long width, WebIDL::Long height, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, TexImageSource source);
- void tex_sub_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long xoffset, WebIDL::Long yoffset, WebIDL::Long width, WebIDL::Long height, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, WebIDL::ArrayBufferView src_data, WebIDL::UnsignedLongLong src_offset);
- void compressed_tex_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::UnsignedLong internalformat, WebIDL::Long width, WebIDL::Long height, WebIDL::Long border, WebIDL::ArrayBufferView src_data, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length_override);
- void compressed_tex_sub_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long xoffset, WebIDL::Long yoffset, WebIDL::Long width, WebIDL::Long height, WebIDL::UnsignedLong format, WebIDL::ArrayBufferView src_data, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length_override);
- void uniform1fv(GC::Ptr<WebGLUniformLocation> location, Float32List v, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length);
- void uniform2fv(GC::Ptr<WebGLUniformLocation> location, Float32List v, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length);
- void uniform3fv(GC::Ptr<WebGLUniformLocation> location, Float32List v, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length);
- void uniform4fv(GC::Ptr<WebGLUniformLocation> location, Float32List v, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length);
- void uniform1iv(GC::Ptr<WebGLUniformLocation> location, Int32List v, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length);
- void uniform2iv(GC::Ptr<WebGLUniformLocation> location, Int32List v, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length);
- void uniform3iv(GC::Ptr<WebGLUniformLocation> location, Int32List v, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length);
- void uniform4iv(GC::Ptr<WebGLUniformLocation> location, Int32List v, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length);
- void uniform_matrix2fv(GC::Ptr<WebGLUniformLocation> location, bool transpose, Float32List data, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length);
- void uniform_matrix3fv(GC::Ptr<WebGLUniformLocation> location, bool transpose, Float32List data, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length);
- void uniform_matrix4fv(GC::Ptr<WebGLUniformLocation> location, bool transpose, Float32List data, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length);
- void read_pixels(WebIDL::Long x, WebIDL::Long y, WebIDL::Long width, WebIDL::Long height, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, WebIDL::NullableArrayBufferViewVariant pixels);
- void read_pixels(WebIDL::Long x, WebIDL::Long y, WebIDL::Long width, WebIDL::Long height, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, WebIDL::ArrayBufferView dst_data, WebIDL::UnsignedLongLong dst_offset);
- void read_pixels(WebIDL::Long x, WebIDL::Long y, WebIDL::Long width, WebIDL::Long height, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, WebIDL::LongLong offset);
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGL2RenderingContextOverloads.idl b/Libraries/LibWeb/WebGL/WebGL2RenderingContextOverloads.idl
index f3bb10080e0..9ca71bc67ba 100644
--- a/Libraries/LibWeb/WebGL/WebGL2RenderingContextOverloads.idl
+++ b/Libraries/LibWeb/WebGL/WebGL2RenderingContextOverloads.idl
@@ -2,37 +2,37 @@
interface mixin WebGL2RenderingContextOverloads {
// WebGL1:
// FIXME: BufferSource is really a AllowSharedBufferSource
- undefined bufferData(GLenum target, GLsizeiptr size, GLenum usage);
- undefined bufferData(GLenum target, BufferSource? srcData, GLenum usage);
- undefined bufferSubData(GLenum target, GLintptr dstByteOffset, BufferSource srcData);
+ [ImplementedAs=buffer_data_with_size] undefined bufferData(GLenum target, GLsizeiptr size, GLenum usage);
+ [ImplementedAs=buffer_data] undefined bufferData(GLenum target, BufferSource? srcData, GLenum usage);
+ [ImplementedAs=buffer_sub_data] undefined bufferSubData(GLenum target, GLintptr dstByteOffset, BufferSource srcData);
// WebGL2:
- undefined bufferData(GLenum target, [AllowShared] ArrayBufferView srcData, GLenum usage, unsigned long long srcOffset, optional GLuint length = 0);
- undefined bufferSubData(GLenum target, GLintptr dstByteOffset, [AllowShared] ArrayBufferView srcData, unsigned long long srcOffset, optional GLuint length = 0);
+ [ImplementedAs=buffer_data_with_offset] undefined bufferData(GLenum target, [AllowShared] ArrayBufferView srcData, GLenum usage, unsigned long long srcOffset, optional GLuint length = 0);
+ [ImplementedAs=buffer_sub_data_with_offset] undefined bufferSubData(GLenum target, GLintptr dstByteOffset, [AllowShared] ArrayBufferView srcData, unsigned long long srcOffset, optional GLuint length = 0);
// WebGL1 legacy entrypoints:
- undefined texImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, [AllowShared] ArrayBufferView? pixels);
+ [ImplementedAs=tex_image2d] undefined texImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, [AllowShared] ArrayBufferView? pixels);
// May throw DOMException
- undefined texImage2D(GLenum target, GLint level, GLint internalformat, GLenum format, GLenum type, TexImageSource source);
+ [ImplementedAs=tex_image2d_with_source] undefined texImage2D(GLenum target, GLint level, GLint internalformat, GLenum format, GLenum type, TexImageSource source);
- undefined texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, [AllowShared] ArrayBufferView? pixels);
+ [ImplementedAs=tex_sub_image2d] undefined texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, [AllowShared] ArrayBufferView? pixels);
// May throw DOMException
- undefined texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLenum format, GLenum type, TexImageSource source);
+ [ImplementedAs=tex_sub_image2d_with_source] undefined texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLenum format, GLenum type, TexImageSource source);
// WebGL2 entrypoints:
[FIXME] undefined texImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, GLintptr pboOffset);
// May throw DOMException
- undefined texImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, TexImageSource source);
+ [ImplementedAs=tex_image2d_with_size_and_source] undefined texImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, TexImageSource source);
- undefined texImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, [AllowShared] ArrayBufferView srcData, unsigned long long srcOffset);
+ [ImplementedAs=tex_image2d_with_offset] undefined texImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, [AllowShared] ArrayBufferView srcData, unsigned long long srcOffset);
[FIXME] undefined texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, GLintptr pboOffset);
// May throw DOMException
- undefined texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, TexImageSource source);
- undefined texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, [AllowShared] ArrayBufferView srcData, unsigned long long srcOffset);
+ [ImplementedAs=tex_sub_image2d_with_size_and_source] undefined texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, TexImageSource source);
+ [ImplementedAs=tex_sub_image2d_with_offset] undefined texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, [AllowShared] ArrayBufferView srcData, unsigned long long srcOffset);
[FIXME] undefined compressedTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, GLintptr offset);
undefined compressedTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, [AllowShared] ArrayBufferView srcData, optional unsigned long long srcOffset = 0, optional GLuint srcLengthOverride = 0);
@@ -56,8 +56,8 @@ interface mixin WebGL2RenderingContextOverloads {
// Reading back pixels
// WebGL1:
- undefined readPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, [AllowShared] ArrayBufferView? pixels);
+ [ImplementedAs=read_pixels] undefined readPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, [AllowShared] ArrayBufferView? pixels);
// WebGL2:
- undefined readPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, [AllowShared] ArrayBufferView dstData, unsigned long long dstOffset);
- undefined readPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLintptr offset);
+ [ImplementedAs=read_pixels_with_offset] undefined readPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, [AllowShared] ArrayBufferView dstData, unsigned long long dstOffset);
+ [ImplementedAs=read_pixels_into_pack_buffer] undefined readPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLintptr offset);
};
diff --git a/Libraries/LibWeb/WebGL/WebGLActiveInfo.cpp b/Libraries/LibWeb/WebGL/WebGLActiveInfo.cpp
deleted file mode 100644
index 34d4f4734f6..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLActiveInfo.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/Runtime/Realm.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/Bindings/WebGLActiveInfo.h>
-#include <LibWeb/WebGL/WebGLActiveInfo.h>
-
-namespace Web::WebGL {
-
-GC_DEFINE_ALLOCATOR(WebGLActiveInfo);
-
-GC::Ptr<WebGLActiveInfo> WebGLActiveInfo::create(JS::Realm& realm, Utf16String name, GLenum type, GLsizei size)
-{
- return realm.create<WebGLActiveInfo>(realm, move(name), type, size);
-}
-
-WebGLActiveInfo::WebGLActiveInfo(JS::Realm&, Utf16String name, GLenum type, GLsizei size)
- : m_name(move(name))
- , m_type(type)
- , m_size(size)
-{
-}
-
-WebGLActiveInfo::~WebGLActiveInfo() = default;
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLActiveInfo.h b/Libraries/LibWeb/WebGL/WebGLActiveInfo.h
deleted file mode 100644
index 39c5a4e89dc..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLActiveInfo.h
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Utf16String.h>
-#include <LibWeb/Bindings/Wrappable.h>
-
-typedef unsigned int GLenum;
-typedef int GLsizei;
-
-namespace Web::WebGL {
-
-class WebGLActiveInfo : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(WebGLActiveInfo, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(WebGLActiveInfo);
-
-public:
- static GC::Ptr<WebGLActiveInfo> create(JS::Realm&, Utf16String name, GLenum type, GLsizei size);
- virtual ~WebGLActiveInfo();
-
- GLsizei size() const { return m_size; }
- GLenum type() const { return m_type; }
- Utf16String const& name() const { return m_name; }
-
-protected:
- explicit WebGLActiveInfo(JS::Realm&, Utf16String name, GLenum type, GLsizei size);
-
-private:
- Utf16String m_name;
- GLenum m_type { 0 };
- GLsizei m_size { 0 };
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLActiveInfo.idl b/Libraries/LibWeb/WebGL/WebGLActiveInfo.idl
index 826c0e8c887..9a033cd7629 100644
--- a/Libraries/LibWeb/WebGL/WebGLActiveInfo.idl
+++ b/Libraries/LibWeb/WebGL/WebGLActiveInfo.idl
@@ -1,5 +1,5 @@
// https://registry.khronos.org/webgl/specs/latest/1.0/#5.11
-[Exposed=(Window,Worker)]
+[Exposed=(Window,Worker), ImplementedIn=Rust]
interface WebGLActiveInfo {
readonly attribute GLint size;
readonly attribute GLenum type;
diff --git a/Libraries/LibWeb/WebGL/WebGLBuffer.cpp b/Libraries/LibWeb/WebGL/WebGLBuffer.cpp
deleted file mode 100644
index 6cb44ad8792..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLBuffer.cpp
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
- * Copyright (c) 2024, Aliaksandr Kalenik <[email protected]>
- * Copyright (c) 2024, Luke Wilde <[email protected]>
- * Copyright (c) 2025, Undefine <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <GLES2/gl2.h>
-#include <LibJS/Runtime/Realm.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/Bindings/WebGLBuffer.h>
-#include <LibWeb/WebGL/WebGLBuffer.h>
-
-namespace Web::WebGL {
-
-GC_DEFINE_ALLOCATOR(WebGLBuffer);
-
-GC::Ref<WebGLBuffer> WebGLBuffer::create(GC::Ref<WebGLRenderingContextBase> context, GLuint handle)
-{
- auto& realm = context->realm();
- return realm.create<WebGLBuffer>(realm, context, handle);
-}
-
-WebGLBuffer::WebGLBuffer(JS::Realm& realm, GC::Ref<WebGLRenderingContextBase> context, GLuint handle)
- : WebGLObject(realm, context, handle)
-{
-}
-
-WebGLBuffer::~WebGLBuffer() = default;
-
-bool WebGLBuffer::is_compatible_with(GLenum target)
-{
- // https://registry.khronos.org/webgl/specs/latest/2.0/#5.1
- if (!m_target.has_value()) {
- m_target = target;
- return true;
- }
-
- if (target == GL_ELEMENT_ARRAY_BUFFER)
- return m_target.value() == GL_ELEMENT_ARRAY_BUFFER;
-
- return m_target.value() != GL_ELEMENT_ARRAY_BUFFER;
-}
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLBuffer.h b/Libraries/LibWeb/WebGL/WebGLBuffer.h
deleted file mode 100644
index 2255f6c4664..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLBuffer.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
- * Copyright (c) 2024, Aliaksandr Kalenik <[email protected]>
- * Copyright (c) 2024, Luke Wilde <[email protected]>
- * Copyright (c) 2025, Undefine <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/WebGL/Types.h>
-#include <LibWeb/WebGL/WebGLObject.h>
-
-namespace Web::WebGL {
-
-class WebGLBuffer final : public WebGLObject {
- WEB_WRAPPABLE(WebGLBuffer, WebGLObject);
- GC_DECLARE_ALLOCATOR(WebGLBuffer);
-
-public:
- static GC::Ref<WebGLBuffer> create(GC::Ref<WebGLRenderingContextBase> context, GLuint handle);
-
- virtual ~WebGLBuffer();
-
- bool is_compatible_with(GLenum target);
-
-protected:
- explicit WebGLBuffer(JS::Realm&, GC::Ref<WebGLRenderingContextBase>, GLuint handle);
-
-private:
- Optional<GLenum> m_target;
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLBuffer.idl b/Libraries/LibWeb/WebGL/WebGLBuffer.idl
index cb4971ff696..e1846d52a19 100644
--- a/Libraries/LibWeb/WebGL/WebGLBuffer.idl
+++ b/Libraries/LibWeb/WebGL/WebGLBuffer.idl
@@ -1,4 +1,4 @@
// https://registry.khronos.org/webgl/specs/latest/1.0/#5.4
-[Exposed=(Window,Worker)]
+[Exposed=(Window,Worker), ImplementedIn=Rust]
interface WebGLBuffer : WebGLObject {
};
diff --git a/Libraries/LibWeb/WebGL/WebGLContextProxyBase.cpp b/Libraries/LibWeb/WebGL/WebGLContextProxyBase.cpp
deleted file mode 100644
index f0091197638..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLContextProxyBase.cpp
+++ /dev/null
@@ -1,455 +0,0 @@
-/*
- * Copyright (c) 2026, Aliaksandr Kalenik <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/StringBuilder.h>
-#include <GLES2/gl2.h>
-#include <LibCore/AnonymousBuffer.h>
-#include <LibGfx/Bitmap.h>
-#include <LibIPC/Limits.h>
-#include <LibWeb/WebGL/WebGLContextProxy.h>
-#include <LibWeb/WebGL/WebGLContextProxyBase.h>
-
-namespace Web::WebGL {
-
-WebGLContextProxyBase::WebGLContextProxyBase(NonnullRefPtr<RemoteWebGLTransport> transport, WebGLVersion webgl_version, Vector<String> supported_extensions)
- : m_transport(move(transport))
- , m_webgl_version(webgl_version)
- , m_supported_extensions(move(supported_extensions))
-{
- initialize_shared_command_buffer();
-}
-
-WebGLContextProxyBase::~WebGLContextProxyBase()
-{
- m_transport->destroy_context();
-}
-
-void WebGLContextProxyBase::restore(NonnullRefPtr<RemoteWebGLTransport> transport, Vector<String> supported_extensions)
-{
- m_transport = move(transport);
- m_supported_extensions = move(supported_extensions);
- m_lost = false;
- m_out_of_line_commands.clear_with_capacity();
- m_pending_bitmaps.clear_with_capacity();
- m_string_cache.clear();
- initialize_shared_command_buffer();
-}
-
-void WebGLContextProxyBase::initialize_shared_command_buffer()
-{
- m_shared_data_cursor = 0;
- m_shared_data_flush_base = 0;
- m_last_published_flush_sequence_number = 0;
-
- auto shared_command_buffer_or_error = WebGLSharedCommandBuffer::create();
- if (shared_command_buffer_or_error.is_error()) {
- m_shared_command_buffer = {};
- return;
- }
- m_shared_command_buffer = shared_command_buffer_or_error.release_value();
- m_transport->set_shared_command_buffer(m_shared_command_buffer.buffer());
-}
-
-void WebGLContextProxyBase::record_bytes(WebGLCommandType type, ReadonlyBytes payload, ReadonlyBytes inline_data)
-{
- if (m_lost)
- return;
-
- if (!m_shared_command_buffer.is_valid()) {
- m_out_of_line_commands.append_bytes(type, payload, inline_data);
- if (m_out_of_line_commands.size_in_bytes() >= max_pending_command_bytes)
- flush_commands();
- return;
- }
-
- auto data_region = m_shared_command_buffer.data_region();
- auto record_size = WebGLCommandList::padded_record_size(payload, inline_data);
-
- if (record_size > data_region.size()) {
- flush_commands();
- WebGLCommandList oversized_command_list;
- oversized_command_list.append_bytes(type, payload, inline_data);
- m_transport->send_commands(oversized_command_list.bytes(), {});
- return;
- }
-
- rewind_shared_data_cursor_if_all_published_commands_executed();
- ensure_shared_data_capacity(record_size);
- if (m_lost)
- return;
-
- WebGLCommandList::write_record(data_region.slice(m_shared_data_cursor, record_size), type, payload, inline_data);
- m_shared_data_cursor += record_size;
- if (m_shared_data_cursor - m_shared_data_flush_base >= max_pending_command_bytes)
- flush_commands();
-}
-
-void WebGLContextProxyBase::rewind_shared_data_cursor_if_all_published_commands_executed()
-{
- if (m_shared_data_cursor == 0 || m_shared_data_cursor != m_shared_data_flush_base)
- return;
- if (m_shared_command_buffer.executed_flush_sequence_number() >= m_last_published_flush_sequence_number) {
- m_shared_data_cursor = 0;
- m_shared_data_flush_base = 0;
- }
-}
-
-void WebGLContextProxyBase::ensure_shared_data_capacity(size_t record_size)
-{
- auto data_region_capacity = m_shared_command_buffer.data_region().size();
- VERIFY(record_size <= data_region_capacity);
- if (record_size <= data_region_capacity - m_shared_data_cursor)
- return;
-
- flush_commands();
- VERIFY(m_shared_data_cursor == m_shared_data_flush_base);
- if (m_shared_command_buffer.executed_flush_sequence_number() < m_last_published_flush_sequence_number) {
- if (!m_transport->wait_until_published_commands_executed()) {
- set_lost();
- return;
- }
- VERIFY(m_shared_command_buffer.executed_flush_sequence_number() >= m_last_published_flush_sequence_number);
- }
- m_shared_data_cursor = 0;
- m_shared_data_flush_base = 0;
-}
-
-void WebGLContextProxyBase::flush_commands()
-{
- if (m_shared_command_buffer.is_valid()) {
- if (m_shared_data_cursor == m_shared_data_flush_base)
- return;
- m_last_published_flush_sequence_number++;
- m_transport->send_commands_from_shared_buffer(
- m_shared_data_flush_base,
- m_shared_data_cursor - m_shared_data_flush_base,
- m_last_published_flush_sequence_number,
- m_pending_bitmaps);
- m_shared_data_flush_base = m_shared_data_cursor;
- m_pending_bitmaps.clear_with_capacity();
- return;
- }
-
- if (m_out_of_line_commands.is_empty())
- return;
- m_transport->send_commands(m_out_of_line_commands.bytes(), m_pending_bitmaps);
- m_out_of_line_commands.clear_with_capacity();
- m_pending_bitmaps.clear_with_capacity();
-}
-
-u32 WebGLContextProxyBase::append_pending_bitmap(Gfx::DecodedImageFrame frame)
-{
- static_assert(IPC::MAX_MESSAGE_FD_COUNT > 1);
- // WebGL command bytes are transferred in one anonymous buffer attachment.
- static constexpr size_t max_bitmap_attachments_per_message = IPC::MAX_MESSAGE_FD_COUNT - 1;
-
- if (m_pending_bitmaps.size() >= max_bitmap_attachments_per_message)
- flush_commands();
-
- // Reserve space for the upcoming bitmap-referencing command now: a capacity flush
- // between this append and its record would publish the bitmap with the wrong batch.
- static constexpr size_t reserved_record_size_for_bitmap_command = 256;
- static_assert(sizeof(WebGLCommandHeader) + sizeof(Commands::TexImage2DFromBitmap) <= reserved_record_size_for_bitmap_command);
- static_assert(sizeof(WebGLCommandHeader) + sizeof(Commands::TexSubImage2DFromBitmap) <= reserved_record_size_for_bitmap_command);
- static_assert(sizeof(WebGLCommandHeader) + sizeof(Commands::TexImage3DFromBitmap) <= reserved_record_size_for_bitmap_command);
- static_assert(sizeof(WebGLCommandHeader) + sizeof(Commands::TexSubImage3DFromBitmap) <= reserved_record_size_for_bitmap_command);
- if (m_shared_command_buffer.is_valid())
- ensure_shared_data_capacity(reserved_record_size_for_bitmap_command);
-
- auto bitmap_index = static_cast<u32>(m_pending_bitmaps.size());
- m_pending_bitmaps.append(move(frame));
- return bitmap_index;
-}
-
-ByteBuffer WebGLContextProxyBase::send_sync_call(ByteBuffer request)
-{
- if (m_lost)
- return {};
- flush_commands();
- auto reply = m_transport->sync_call(move(request));
- if (reply.is_empty())
- set_lost();
- return reply;
-}
-
-ReadPixelsResult WebGLContextProxyBase::read_pixels_robust_angle_into_shared_buffer(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei buf_size, Core::AnonymousBuffer const& pixels)
-{
- flush_commands();
- return m_transport->read_pixels_robust_angle(x, y, width, height, format, type, buf_size, pixels);
-}
-
-void WebGLContextProxyBase::set_size(Gfx::IntSize const& size)
-{
- record(Commands::SetDrawingBufferSize { .width = size.width(), .height = size.height() });
-}
-
-void WebGLContextProxyBase::present_canvas_for_compositing(bool preserve_drawing_buffer)
-{
- flush_commands();
- m_transport->present_canvas(preserve_drawing_buffer);
-}
-
-void WebGLContextProxyBase::clear_drawing_buffer()
-{
- if (m_lost)
- return;
- flush_commands();
- m_transport->clear_drawing_buffer();
-}
-
-RefPtr<Gfx::Bitmap> WebGLContextProxyBase::read_back_drawing_buffer(Gfx::IntRect const& rect)
-{
- if (m_lost)
- return nullptr;
- flush_commands();
- auto bitmap = m_transport->read_back_drawing_buffer(rect);
- if (!bitmap.is_valid())
- return nullptr;
- return bitmap.bitmap();
-}
-
-void WebGLContextProxyBase::read_pixels_into_pixel_pack_buffer(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, long long offset)
-{
- record(Commands::ReadPixelsIntoPixelPackBuffer {
- .x = x,
- .y = y,
- .width = width,
- .height = height,
- .format = format,
- .type = type,
- .offset = static_cast<GLintptr>(offset),
- });
-}
-
-void WebGLContextProxyBase::tex_image2d_from_bitmap(GLenum target, GLint level, GLint internalformat, GLenum format, GLenum type, Gfx::DecodedImageFrame frame, Optional<Gfx::IntSize> destination_size, bool flip_y, bool premultiply_alpha)
-{
- if (m_lost)
- return;
- auto bitmap_index = append_pending_bitmap(move(frame));
- auto has_explicit_destination_size = destination_size.has_value();
- record(Commands::TexImage2DFromBitmap {
- .target = target,
- .level = level,
- .internalformat = internalformat,
- .format = format,
- .type = type,
- .bitmap_index = bitmap_index,
- .has_explicit_destination_size = has_explicit_destination_size,
- .destination_width = has_explicit_destination_size ? destination_size->width() : 0,
- .destination_height = has_explicit_destination_size ? destination_size->height() : 0,
- .flip_y = flip_y,
- .premultiply_alpha = premultiply_alpha,
- });
-}
-
-void WebGLContextProxyBase::tex_sub_image2d_from_bitmap(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLenum format, GLenum type, Gfx::DecodedImageFrame frame, Optional<Gfx::IntSize> destination_size, bool flip_y, bool premultiply_alpha)
-{
- if (m_lost)
- return;
- auto bitmap_index = append_pending_bitmap(move(frame));
- auto has_explicit_destination_size = destination_size.has_value();
- record(Commands::TexSubImage2DFromBitmap {
- .target = target,
- .level = level,
- .xoffset = xoffset,
- .yoffset = yoffset,
- .format = format,
- .type = type,
- .bitmap_index = bitmap_index,
- .has_explicit_destination_size = has_explicit_destination_size,
- .destination_width = has_explicit_destination_size ? destination_size->width() : 0,
- .destination_height = has_explicit_destination_size ? destination_size->height() : 0,
- .flip_y = flip_y,
- .premultiply_alpha = premultiply_alpha,
- });
-}
-
-void WebGLContextProxyBase::tex_image3d_from_bitmap(GLenum target, GLint level, GLint internalformat, GLsizei depth, GLenum format, GLenum type, Gfx::DecodedImageFrame frame, Optional<Gfx::IntSize> destination_size, bool flip_y, bool premultiply_alpha)
-{
- if (m_lost)
- return;
- auto bitmap_index = append_pending_bitmap(move(frame));
- auto has_explicit_destination_size = destination_size.has_value();
- record(Commands::TexImage3DFromBitmap {
- .target = target,
- .level = level,
- .internalformat = internalformat,
- .depth = depth,
- .format = format,
- .type = type,
- .bitmap_index = bitmap_index,
- .has_explicit_destination_size = has_explicit_destination_size,
- .destination_width = has_explicit_destination_size ? destination_size->width() : 0,
- .destination_height = has_explicit_destination_size ? destination_size->height() : 0,
- .flip_y = flip_y,
- .premultiply_alpha = premultiply_alpha,
- });
-}
-
-void WebGLContextProxyBase::tex_sub_image3d_from_bitmap(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei depth, GLenum format, GLenum type, Gfx::DecodedImageFrame frame, Optional<Gfx::IntSize> destination_size, bool flip_y, bool premultiply_alpha)
-{
- if (m_lost)
- return;
- auto bitmap_index = append_pending_bitmap(move(frame));
- auto has_explicit_destination_size = destination_size.has_value();
- record(Commands::TexSubImage3DFromBitmap {
- .target = target,
- .level = level,
- .xoffset = xoffset,
- .yoffset = yoffset,
- .zoffset = zoffset,
- .depth = depth,
- .format = format,
- .type = type,
- .bitmap_index = bitmap_index,
- .has_explicit_destination_size = has_explicit_destination_size,
- .destination_width = has_explicit_destination_size ? destination_size->width() : 0,
- .destination_height = has_explicit_destination_size ? destination_size->height() : 0,
- .flip_y = flip_y,
- .premultiply_alpha = premultiply_alpha,
- });
-}
-
-bool WebGLContextProxyBase::read_buffer_sub_data(GLenum target, long long offset, Bytes destination)
-{
- if (m_lost)
- return false;
- if (destination.is_empty())
- return true;
-
- auto shared_data_or_error = Core::AnonymousBuffer::create_with_size(destination.size());
- if (shared_data_or_error.is_error()) {
- set_pending_local_error(GL_OUT_OF_MEMORY);
- return false;
- }
-
- auto shared_data = shared_data_or_error.release_value();
- flush_commands();
- if (!m_transport->read_buffer_sub_data(target, static_cast<GLintptr>(offset), static_cast<GLintptr>(destination.size()), shared_data))
- return false;
- if (m_lost)
- return false;
- __builtin_memcpy(destination.data(), shared_data.data<void>(), destination.size());
- return true;
-}
-
-void WebGLContextProxy::shader_source(GLuint shader, GLsizei count, GLchar const* const* string, GLint const* length)
-{
- VERIFY(count == 1);
- auto source_length = length ? static_cast<size_t>(length[0]) : __builtin_strlen(string[0]);
- ByteBuffer source_bytes = MUST(ByteBuffer::create_uninitialized(source_length + 1));
- __builtin_memcpy(source_bytes.data(), string[0], source_length);
- source_bytes[source_length] = 0;
-
- Commands::ShaderSource command { .shader = shader, .source = {} };
- command.source = { WebGLCommandList::first_inline_data_offset(sizeof(command)), static_cast<u32>(source_bytes.size()) };
- record(command, source_bytes);
-}
-
-static ByteBuffer pack_strings(GLsizei count, GLchar const* const* strings)
-{
- StringBuilder builder;
- for (GLsizei i = 0; i < count; ++i) {
- builder.append({ strings[i], __builtin_strlen(strings[i]) });
- builder.append('\0');
- }
- return MUST(builder.to_byte_buffer());
-}
-
-void WebGLContextProxy::transform_feedback_varyings(GLuint program, GLsizei count, GLchar const* const* varyings, GLenum bufferMode)
-{
- auto varyings_bytes = pack_strings(count, varyings);
- Commands::TransformFeedbackVaryings command { .program = program, .count = count, .varyings = {}, .buffer_mode = bufferMode };
- command.varyings = { WebGLCommandList::first_inline_data_offset(sizeof(command)), static_cast<u32>(varyings_bytes.size()) };
- record(command, varyings_bytes);
-}
-
-void WebGLContextProxy::read_pixels_robust_angle(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, GLsizei* length, GLsizei* columns, GLsizei* rows, void* pixels)
-{
- if (is_lost())
- return;
-
- Core::AnonymousBuffer shared_pixels;
- if (bufSize > 0) {
- auto shared_pixels_or_error = Core::AnonymousBuffer::create_with_size(static_cast<size_t>(bufSize));
- if (shared_pixels_or_error.is_error()) {
- set_pending_local_error(GL_OUT_OF_MEMORY);
- return;
- }
- shared_pixels = shared_pixels_or_error.release_value();
- }
-
- auto result = read_pixels_robust_angle_into_shared_buffer(x, y, width, height, format, type, bufSize, shared_pixels);
- if (is_lost())
- return;
- if (length)
- *length = result.length;
- if (columns)
- *columns = result.columns;
- if (rows)
- *rows = result.rows;
- if (pixels && result.length > 0) {
- VERIFY(result.length <= bufSize);
- __builtin_memcpy(pixels, shared_pixels.data<void>(), static_cast<size_t>(result.length));
- }
-}
-
-GLubyte const* WebGLContextProxy::get_string(GLenum name)
-{
- if (auto cached = m_string_cache.get(name); cached.has_value())
- return cached.value()->data();
-
- SyncCalls::GetString::Request request { .name = name };
- auto reply_bytes = send_sync_call(WebGLSyncCall::encode_request<SyncCalls::GetString>(request));
- if (is_lost())
- return reinterpret_cast<GLubyte const*>("");
- auto reply = WebGLSyncCall::decode_reply<SyncCalls::GetString::Reply>(reply_bytes);
- auto resolved = WebGLCommandList::resolve_string_span(reply_bytes, reply.value);
- auto value = make<ByteBuffer>(MUST(ByteBuffer::copy(resolved)));
- auto const* data = value->data();
- m_string_cache.set(name, move(value));
- return data;
-}
-
-void WebGLContextProxy::get_vertex_attrib_pointerv_robust_angle(GLuint index, GLenum pname, GLsizei bufSize, GLsizei* length, void** pointer)
-{
- (void)bufSize;
- SyncCalls::GetVertexAttribPointervRobustANGLE::Request request { .index = index, .pname = pname };
- auto reply_bytes = send_sync_call(WebGLSyncCall::encode_request<SyncCalls::GetVertexAttribPointervRobustANGLE>(request));
- if (is_lost())
- return;
- auto reply = WebGLSyncCall::decode_reply<SyncCalls::GetVertexAttribPointervRobustANGLE::Reply>(reply_bytes);
- if (length)
- *length = 1;
- if (pointer)
- *pointer = reinterpret_cast<void*>(static_cast<uintptr_t>(reply.pointer));
-}
-
-void WebGLContextProxy::get_uniform_indices(GLuint program, GLsizei uniformCount, GLchar const* const* uniformNames, GLuint* uniformIndices)
-{
- auto names_bytes = pack_strings(uniformCount, uniformNames);
- SyncCalls::GetUniformIndices::Request request { .program = program, .uniform_count = uniformCount, .uniform_names = {} };
- request.uniform_names = { WebGLCommandList::first_inline_data_offset(sizeof(request)), static_cast<u32>(names_bytes.size()) };
- auto reply_bytes = send_sync_call(WebGLSyncCall::encode_request<SyncCalls::GetUniformIndices>(request, names_bytes));
- if (is_lost())
- return;
- auto reply = WebGLSyncCall::decode_reply<SyncCalls::GetUniformIndices::Reply>(reply_bytes);
- if (uniformIndices)
- WebGLCommandList::copy_data_span(reply_bytes, reply.uniform_indices, { uniformIndices, static_cast<size_t>(uniformCount) * sizeof(GLuint) });
-}
-
-void* WebGLContextProxy::map_buffer_range(GLenum, GLintptr, GLsizeiptr, GLbitfield)
-{
- // getBufferSubData() goes through read_buffer_sub_data() instead; nothing else maps.
- VERIFY_NOT_REACHED();
-}
-
-GLboolean WebGLContextProxy::unmap_buffer(GLenum)
-{
- VERIFY_NOT_REACHED();
-}
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLContextProxyBase.h b/Libraries/LibWeb/WebGL/WebGLContextProxyBase.h
deleted file mode 100644
index 0245a4b2374..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLContextProxyBase.h
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * Copyright (c) 2026, Aliaksandr Kalenik <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/ByteBuffer.h>
-#include <AK/HashMap.h>
-#include <AK/Noncopyable.h>
-#include <AK/NonnullOwnPtr.h>
-#include <AK/NonnullRefPtr.h>
-#include <AK/Optional.h>
-#include <AK/String.h>
-#include <AK/Vector.h>
-#include <LibCompositing/DisplayList/DisplayListResourceIds.h>
-#include <LibCompositing/Types.h>
-#include <LibCompositing/WebGL/WebGLCommandList.h>
-#include <LibCompositing/WebGL/WebGLSharedCommandBuffer.h>
-#include <LibCore/AnonymousBuffer.h>
-#include <LibGfx/DecodedImageFrame.h>
-#include <LibGfx/Forward.h>
-#include <LibGfx/Size.h>
-#include <LibWeb/Export.h>
-#include <LibWeb/WebGL/RemoteWebGLTransport.h>
-
-namespace Web::WebGL {
-
-class WEB_API WebGLContextProxyBase {
- AK_MAKE_NONCOPYABLE(WebGLContextProxyBase);
- AK_MAKE_NONMOVABLE(WebGLContextProxyBase);
-
-public:
- AK_ALLOC_WITH_KMALLOC;
-
- WebGLContextProxyBase(NonnullRefPtr<RemoteWebGLTransport>, WebGLVersion, Vector<String> supported_extensions);
- ~WebGLContextProxyBase();
-
- void flush_commands();
- void set_lost() { m_lost = true; }
- Optional<Compositing::CanvasId> canvas_id() const { return m_transport->canvas_id(); }
-
- void restore(NonnullRefPtr<RemoteWebGLTransport>, Vector<String> supported_extensions);
-
- void make_current() { }
- void notify_content_will_change() { }
- u32 default_framebuffer() const { return 0; }
- u32 default_renderbuffer() const { return 0; }
- WebGLVersion webgl_version() const { return m_webgl_version; }
- Vector<String> const& get_supported_opengl_extensions() const { return m_supported_extensions; }
- void set_size(Gfx::IntSize const&);
-
- void present_canvas_for_compositing(bool preserve_drawing_buffer);
- void clear_drawing_buffer();
-
- RefPtr<Gfx::Bitmap> read_back_drawing_buffer(Gfx::IntRect const&);
-
- void read_pixels_into_pixel_pack_buffer(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, long long offset);
- bool read_buffer_sub_data(GLenum target, long long offset, Bytes destination);
-
- void tex_image2d_from_bitmap(GLenum target, GLint level, GLint internalformat, GLenum format, GLenum type, Gfx::DecodedImageFrame, Optional<Gfx::IntSize> destination_size, bool flip_y, bool premultiply_alpha);
- void tex_sub_image2d_from_bitmap(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLenum format, GLenum type, Gfx::DecodedImageFrame, Optional<Gfx::IntSize> destination_size, bool flip_y, bool premultiply_alpha);
- void tex_image3d_from_bitmap(GLenum target, GLint level, GLint internalformat, GLsizei depth, GLenum format, GLenum type, Gfx::DecodedImageFrame, Optional<Gfx::IntSize> destination_size, bool flip_y, bool premultiply_alpha);
- void tex_sub_image3d_from_bitmap(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei depth, GLenum format, GLenum type, Gfx::DecodedImageFrame, Optional<Gfx::IntSize> destination_size, bool flip_y, bool premultiply_alpha);
-
- GLenum take_pending_local_error()
- {
- auto error = m_pending_local_error;
- m_pending_local_error = 0;
- return error;
- }
-
-protected:
- static constexpr size_t max_pending_command_bytes = 4 * MiB;
-
- WebGLObjectId allocate_object_id() { return m_next_object_id++; }
-
- void set_pending_local_error(GLenum error)
- {
- if (m_pending_local_error == 0)
- m_pending_local_error = error;
- }
- ReadPixelsResult read_pixels_robust_angle_into_shared_buffer(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei buf_size, Core::AnonymousBuffer const& pixels);
-
- template<typename Command>
- void record(Command const& command, ReadonlyBytes inline_data = {})
- {
- record_bytes(Command::command_type, { &command, sizeof(command) }, inline_data);
- }
-
- void record_bytes(WebGLCommandType, ReadonlyBytes payload, ReadonlyBytes inline_data);
-
- ByteBuffer send_sync_call(ByteBuffer request);
- bool is_lost() const { return m_lost; }
-
- HashMap<GLenum, NonnullOwnPtr<ByteBuffer>> m_string_cache;
-
-private:
- u32 append_pending_bitmap(Gfx::DecodedImageFrame);
- void initialize_shared_command_buffer();
- void rewind_shared_data_cursor_if_all_published_commands_executed();
- void ensure_shared_data_capacity(size_t record_size);
-
- NonnullRefPtr<RemoteWebGLTransport> m_transport;
- WebGLVersion m_webgl_version { WebGLVersion::WebGL1 };
- Vector<String> m_supported_extensions;
- WebGLSharedCommandBuffer m_shared_command_buffer;
- size_t m_shared_data_cursor { 0 };
- size_t m_shared_data_flush_base { 0 };
- u64 m_last_published_flush_sequence_number { 0 };
- WebGLCommandList m_out_of_line_commands;
- Vector<Gfx::DecodedImageFrame> m_pending_bitmaps;
- u32 m_next_object_id { 1 };
- bool m_lost { false };
- GLenum m_pending_local_error { 0 };
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLFramebuffer.cpp b/Libraries/LibWeb/WebGL/WebGLFramebuffer.cpp
deleted file mode 100644
index 46cfd10a4b6..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLFramebuffer.cpp
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
- * Copyright (c) 2024, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/Runtime/Realm.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/Bindings/WebGLFramebuffer.h>
-#include <LibWeb/WebGL/WebGLFramebuffer.h>
-#include <LibWeb/WebGL/WebGLRenderbuffer.h>
-#include <LibWeb/WebGL/WebGLTexture.h>
-
-namespace Web::WebGL {
-
-GC_DEFINE_ALLOCATOR(WebGLFramebuffer);
-
-GC::Ref<WebGLFramebuffer> WebGLFramebuffer::create(GC::Ref<WebGLRenderingContextBase> context, GLuint handle)
-{
- auto& realm = context->realm();
- return realm.create<WebGLFramebuffer>(realm, context, handle);
-}
-
-WebGLFramebuffer::WebGLFramebuffer(JS::Realm& realm, GC::Ref<WebGLRenderingContextBase> context, GLuint handle)
- : WebGLObject(realm, context, handle)
-{
-}
-
-WebGLFramebuffer::~WebGLFramebuffer() = default;
-
-void WebGLFramebuffer::visit_edges(Visitor& visitor)
-{
- Base::visit_edges(visitor);
- for (auto& attachment : m_attachments) {
- visitor.visit(attachment.value.texture);
- visitor.visit(attachment.value.renderbuffer);
- }
-}
-
-WebGLFramebuffer::Attachment const* WebGLFramebuffer::attachment(GLenum attachment) const
-{
- auto it = m_attachments.find(attachment);
- if (it == m_attachments.end())
- return nullptr;
- return &it->value;
-}
-
-void WebGLFramebuffer::set_renderbuffer_attachment(GLenum attachment, GC::Ptr<WebGLRenderbuffer> renderbuffer)
-{
- if (!renderbuffer) {
- m_attachments.remove(attachment);
- return;
- }
-
- Attachment framebuffer_attachment;
- framebuffer_attachment.renderbuffer = renderbuffer;
- m_attachments.set(attachment, framebuffer_attachment);
-}
-
-void WebGLFramebuffer::set_texture_attachment(GLenum attachment, GC::Ptr<WebGLTexture> texture, GLenum texture_target, GLint level)
-{
- if (!texture) {
- m_attachments.remove(attachment);
- return;
- }
-
- Attachment framebuffer_attachment;
- framebuffer_attachment.texture = texture;
- framebuffer_attachment.texture_target = texture_target;
- framebuffer_attachment.texture_level = level;
- m_attachments.set(attachment, framebuffer_attachment);
-}
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLFramebuffer.h b/Libraries/LibWeb/WebGL/WebGLFramebuffer.h
deleted file mode 100644
index 6cc7da38e0c..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLFramebuffer.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
- * Copyright (c) 2024, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/HashMap.h>
-#include <LibWeb/WebGL/WebGLObject.h>
-
-namespace Web::WebGL {
-
-class WebGLFramebuffer final : public WebGLObject {
- WEB_WRAPPABLE(WebGLFramebuffer, WebGLObject);
- GC_DECLARE_ALLOCATOR(WebGLFramebuffer);
-
-public:
- struct Attachment {
- GC::Ptr<WebGLTexture> texture;
- GC::Ptr<WebGLRenderbuffer> renderbuffer;
- GLenum texture_target { 0 };
- GLint texture_level { 0 };
- };
-
- static GC::Ref<WebGLFramebuffer> create(GC::Ref<WebGLRenderingContextBase>, GLuint handle);
-
- virtual ~WebGLFramebuffer();
-
- Attachment const* attachment(GLenum attachment) const;
- void set_renderbuffer_attachment(GLenum attachment, GC::Ptr<WebGLRenderbuffer>);
- void set_texture_attachment(GLenum attachment, GC::Ptr<WebGLTexture>, GLenum texture_target, GLint level);
-
-protected:
- explicit WebGLFramebuffer(JS::Realm&, GC::Ref<WebGLRenderingContextBase>, GLuint handle);
-
- virtual void visit_edges(Visitor&) override;
-
-private:
- HashMap<GLenum, Attachment> m_attachments;
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLFramebuffer.idl b/Libraries/LibWeb/WebGL/WebGLFramebuffer.idl
index ee9ffdb7876..34377e60321 100644
--- a/Libraries/LibWeb/WebGL/WebGLFramebuffer.idl
+++ b/Libraries/LibWeb/WebGL/WebGLFramebuffer.idl
@@ -1,4 +1,4 @@
// https://registry.khronos.org/webgl/specs/latest/1.0/#5.5
-[Exposed=(Window,Worker)]
+[Exposed=(Window,Worker), ImplementedIn=Rust]
interface WebGLFramebuffer : WebGLObject {
};
diff --git a/Libraries/LibWeb/WebGL/WebGLObject.cpp b/Libraries/LibWeb/WebGL/WebGLObject.cpp
deleted file mode 100644
index 6bd67e56029..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLObject.cpp
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
- * Copyright (c) 2024, Aliaksandr Kalenik <[email protected]>
- * Copyright (c) 2024, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/Bindings/WebGLObject.h>
-#include <LibWeb/WebGL/WebGLObject.h>
-
-#include <GLES2/gl2.h>
-
-namespace Web::WebGL {
-
-WebGLObject::WebGLObject(JS::Realm&, GC::Ref<WebGLRenderingContextBase> context, GLuint handle)
- : m_context(context)
- , m_handle(handle)
- , m_context_generation(context->context_generation())
-{
-}
-
-GC::Ptr<Bindings::Wrappable> WebGLObject::relevant_global_impl() const
-{
- return static_cast<Bindings::Wrappable&>(*m_context).relevant_global_impl();
-}
-
-WebGLObject::~WebGLObject() = default;
-
-void WebGLObject::visit_edges(Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_context);
-}
-
-ErrorOr<GLuint> WebGLObject::handle(WebGLRenderingContextBase const* context) const
-{
- TRY(validate_context(context));
- if (invalidated_for_context(context))
- return Error::from_errno(GL_INVALID_OPERATION);
- return m_handle;
-}
-
-ErrorOr<Optional<GLuint>> WebGLObject::handle_for_deletion(WebGLRenderingContextBase const* context)
-{
- TRY(validate_context(context));
- if (invalidated_for_context(context))
- return Optional<GLuint> {};
- m_invalidated = true;
- return Optional<GLuint> { m_handle };
-}
-
-ErrorOr<Optional<GLuint>> WebGLObject::handle_for_query(WebGLRenderingContextBase const* context) const
-{
- TRY(validate_context(context));
- if (invalidated_for_context(context))
- return Optional<GLuint> {};
- return Optional<GLuint> { m_handle };
-}
-
-bool WebGLObject::invalidated_for_context(WebGLRenderingContextBase const* context) const
-{
- return m_invalidated || m_context_generation != context->context_generation();
-}
-
-ErrorOr<void> WebGLObject::validate_context(WebGLRenderingContextBase const* context) const
-{
- if (GC::Ptr { context } == m_context)
- return {};
- return Error::from_errno(GL_INVALID_OPERATION);
-}
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLObject.h b/Libraries/LibWeb/WebGL/WebGLObject.h
deleted file mode 100644
index b16c08959cb..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLObject.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
- * Copyright (c) 2024, Aliaksandr Kalenik <[email protected]>
- * Copyright (c) 2024, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Optional.h>
-#include <AK/Utf16String.h>
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/Export.h>
-#include <LibWeb/WebGL/Types.h>
-#include <LibWeb/WebGL/WebGLRenderingContextBase.h>
-
-namespace Web::WebGL {
-
-class WEB_API WebGLObject : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(WebGLObject, Bindings::GCAllocatedWrappable);
-
-public:
- virtual ~WebGLObject();
-
- Utf16String const& label() const { return m_label; }
- void set_label(Utf16String const& label) { m_label = label; }
-
- ErrorOr<GLuint> handle(WebGLRenderingContextBase const* context) const;
- ErrorOr<Optional<GLuint>> handle_for_deletion(WebGLRenderingContextBase const* context);
- ErrorOr<Optional<GLuint>> handle_for_query(WebGLRenderingContextBase const* context) const;
-
-protected:
- explicit WebGLObject(JS::Realm&, GC::Ref<WebGLRenderingContextBase>, GLuint handle);
-
- void visit_edges(Visitor&) override;
- virtual GC::Ptr<Bindings::Wrappable> relevant_global_impl() const override;
-
- bool invalidated() const { return m_invalidated; }
- bool invalidated_for_context(WebGLRenderingContextBase const*) const;
- void invalidate() { m_invalidated = true; }
- ErrorOr<void> validate_context(WebGLRenderingContextBase const* context) const;
-
- GC::Ref<WebGLRenderingContextBase> m_context;
-
-private:
- GLuint m_handle { 0 };
- u64 m_context_generation { 0 };
-
- bool m_invalidated { false };
- Utf16String m_label;
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLObject.idl b/Libraries/LibWeb/WebGL/WebGLObject.idl
index 6b3139c9d8d..e8215b3cb6d 100644
--- a/Libraries/LibWeb/WebGL/WebGLObject.idl
+++ b/Libraries/LibWeb/WebGL/WebGLObject.idl
@@ -1,5 +1,5 @@
// https://registry.khronos.org/webgl/specs/latest/1.0/#5.3
-[Exposed=(Window,Worker)]
+[Exposed=(Window,Worker), ImplementedIn=Rust]
interface WebGLObject {
attribute USVString label;
};
diff --git a/Libraries/LibWeb/WebGL/WebGLProgram.cpp b/Libraries/LibWeb/WebGL/WebGLProgram.cpp
deleted file mode 100644
index abbcd12205c..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLProgram.cpp
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
- * Copyright (c) 2024, Aliaksandr Kalenik <[email protected]>
- * Copyright (c) 2024-2025, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/Runtime/Realm.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/Bindings/WebGLProgram.h>
-#include <LibWeb/WebGL/WebGLProgram.h>
-#include <LibWeb/WebGL/WebGLShader.h>
-
-namespace Web::WebGL {
-
-GC_DEFINE_ALLOCATOR(WebGLProgram);
-
-GC::Ref<WebGLProgram> WebGLProgram::create(GC::Ref<WebGLRenderingContextBase> context, GLuint handle)
-{
- auto& realm = context->realm();
- return realm.create<WebGLProgram>(realm, context, handle);
-}
-
-WebGLProgram::WebGLProgram(JS::Realm& realm, GC::Ref<WebGLRenderingContextBase> context, GLuint handle)
- : WebGLObject(realm, context, handle)
-{
-}
-
-WebGLProgram::~WebGLProgram() = default;
-
-void WebGLProgram::visit_edges(Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_attached_vertex_shader);
- visitor.visit(m_attached_fragment_shader);
-}
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLProgram.h b/Libraries/LibWeb/WebGL/WebGLProgram.h
deleted file mode 100644
index 8e74c30e869..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLProgram.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
- * Copyright (c) 2024, Aliaksandr Kalenik <[email protected]>
- * Copyright (c) 2024-2025, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/WebGL/Types.h>
-#include <LibWeb/WebGL/WebGLObject.h>
-
-namespace Web::WebGL {
-
-class WebGLProgram final : public WebGLObject {
- WEB_WRAPPABLE(WebGLProgram, WebGLObject);
- GC_DECLARE_ALLOCATOR(WebGLProgram);
-
-public:
- static GC::Ref<WebGLProgram> create(GC::Ref<WebGLRenderingContextBase>, GLuint handle);
-
- virtual ~WebGLProgram();
-
- GC::Ptr<WebGLShader> attached_vertex_shader() const { return m_attached_vertex_shader; }
- void set_attached_vertex_shader(GC::Ptr<WebGLShader> shader) { m_attached_vertex_shader = shader; }
-
- GC::Ptr<WebGLShader> attached_fragment_shader() const { return m_attached_fragment_shader; }
- void set_attached_fragment_shader(GC::Ptr<WebGLShader> shader) { m_attached_fragment_shader = shader; }
-
-protected:
- explicit WebGLProgram(JS::Realm&, GC::Ref<WebGLRenderingContextBase>, GLuint handle);
-
- virtual void visit_edges(JS::Cell::Visitor&) override;
-
-private:
- GC::Ptr<WebGLShader> m_attached_vertex_shader;
- GC::Ptr<WebGLShader> m_attached_fragment_shader;
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLProgram.idl b/Libraries/LibWeb/WebGL/WebGLProgram.idl
index 5081c067945..07543e4d843 100644
--- a/Libraries/LibWeb/WebGL/WebGLProgram.idl
+++ b/Libraries/LibWeb/WebGL/WebGLProgram.idl
@@ -1,4 +1,4 @@
// https://registry.khronos.org/webgl/specs/latest/1.0/#5.6
-[Exposed=(Window,Worker)]
+[Exposed=(Window,Worker), ImplementedIn=Rust]
interface WebGLProgram : WebGLObject {
};
diff --git a/Libraries/LibWeb/WebGL/WebGLQuery.cpp b/Libraries/LibWeb/WebGL/WebGLQuery.cpp
deleted file mode 100644
index a8e8184c5fa..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLQuery.cpp
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (c) 2024, Andrew Kaster <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/Runtime/Realm.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/Bindings/WebGLQuery.h>
-#include <LibWeb/WebGL/WebGLQuery.h>
-
-namespace Web::WebGL {
-
-GC_DEFINE_ALLOCATOR(WebGLQuery);
-
-GC::Ref<WebGLQuery> WebGLQuery::create(GC::Ref<WebGLRenderingContextBase> context, GLuint handle)
-{
- auto& realm = context->realm();
- return realm.create<WebGLQuery>(realm, context, handle);
-}
-
-WebGLQuery::WebGLQuery(JS::Realm& realm, GC::Ref<WebGLRenderingContextBase> context, GLuint handle)
- : WebGLObject(realm, context, handle)
-{
-}
-
-WebGLQuery::~WebGLQuery() = default;
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLQuery.h b/Libraries/LibWeb/WebGL/WebGLQuery.h
deleted file mode 100644
index 43cf11c04f1..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLQuery.h
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (c) 2024, Andrew Kaster <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/WebGL/Types.h>
-#include <LibWeb/WebGL/WebGLObject.h>
-
-namespace Web::WebGL {
-
-class WebGLQuery : public WebGLObject {
- WEB_WRAPPABLE(WebGLQuery, WebGLObject);
- GC_DECLARE_ALLOCATOR(WebGLQuery);
-
-public:
- static GC::Ref<WebGLQuery> create(GC::Ref<WebGLRenderingContextBase>, GLuint handle);
-
- virtual ~WebGLQuery() override;
-
-protected:
- explicit WebGLQuery(JS::Realm&, GC::Ref<WebGLRenderingContextBase>, GLuint handle);
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLQuery.idl b/Libraries/LibWeb/WebGL/WebGLQuery.idl
index 8df4fcfb48d..f7f8d8afc65 100644
--- a/Libraries/LibWeb/WebGL/WebGLQuery.idl
+++ b/Libraries/LibWeb/WebGL/WebGLQuery.idl
@@ -1,4 +1,4 @@
// https://registry.khronos.org/webgl/specs/latest/2.0/#3.2
-[Exposed=(Window,Worker)]
+[Exposed=(Window,Worker), ImplementedIn=Rust]
interface WebGLQuery : WebGLObject {
};
diff --git a/Libraries/LibWeb/WebGL/WebGLRenderbuffer.cpp b/Libraries/LibWeb/WebGL/WebGLRenderbuffer.cpp
deleted file mode 100644
index af31683fe16..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLRenderbuffer.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
- * Copyright (c) 2024, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/Runtime/Realm.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/Bindings/WebGLRenderbuffer.h>
-#include <LibWeb/WebGL/WebGLRenderbuffer.h>
-
-namespace Web::WebGL {
-
-GC_DEFINE_ALLOCATOR(WebGLRenderbuffer);
-
-GC::Ref<WebGLRenderbuffer> WebGLRenderbuffer::create(GC::Ref<WebGLRenderingContextBase> context, GLuint handle)
-{
- auto& realm = context->realm();
- return realm.create<WebGLRenderbuffer>(realm, context, handle);
-}
-
-WebGLRenderbuffer::WebGLRenderbuffer(JS::Realm& realm, GC::Ref<WebGLRenderingContextBase> context, GLuint handle)
- : WebGLObject(realm, context, handle)
-{
-}
-
-WebGLRenderbuffer::~WebGLRenderbuffer() = default;
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLRenderbuffer.h b/Libraries/LibWeb/WebGL/WebGLRenderbuffer.h
deleted file mode 100644
index 1730b03a621..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLRenderbuffer.h
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
- * Copyright (c) 2024, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/WebGL/WebGLObject.h>
-
-namespace Web::WebGL {
-
-class WebGLRenderbuffer final : public WebGLObject {
- WEB_WRAPPABLE(WebGLRenderbuffer, WebGLObject);
- GC_DECLARE_ALLOCATOR(WebGLRenderbuffer);
-
-public:
- static GC::Ref<WebGLRenderbuffer> create(GC::Ref<WebGLRenderingContextBase>, GLuint handle);
-
- virtual ~WebGLRenderbuffer();
-
-protected:
- explicit WebGLRenderbuffer(JS::Realm&, GC::Ref<WebGLRenderingContextBase>, GLuint handle);
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLRenderbuffer.idl b/Libraries/LibWeb/WebGL/WebGLRenderbuffer.idl
index 354c249f756..197062f8727 100644
--- a/Libraries/LibWeb/WebGL/WebGLRenderbuffer.idl
+++ b/Libraries/LibWeb/WebGL/WebGLRenderbuffer.idl
@@ -1,4 +1,4 @@
// https://registry.khronos.org/webgl/specs/latest/1.0/#5.7
-[Exposed=(Window,Worker)]
+[Exposed=(Window,Worker), ImplementedIn=Rust]
interface WebGLRenderbuffer : WebGLObject {
};
diff --git a/Libraries/LibWeb/WebGL/WebGLRenderingContext.cpp b/Libraries/LibWeb/WebGL/WebGLRenderingContext.cpp
deleted file mode 100644
index 257bb6be35a..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLRenderingContext.cpp
+++ /dev/null
@@ -1,202 +0,0 @@
-/*
- * Copyright (c) 2022, Luke Wilde <[email protected]>
- * Copyright (c) 2023, Aliaksandr Kalenik <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/Runtime/ArrayBuffer.h>
-#include <LibJS/Runtime/TypedArray.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/Bindings/WebGLContextEvent.h>
-#include <LibWeb/Bindings/WebGLRenderingContext.h>
-#include <LibWeb/Compositor/CompositorHost.h>
-#include <LibWeb/DOM/Document.h>
-#include <LibWeb/HTML/HTMLCanvasElement.h>
-#include <LibWeb/HTML/LocalNavigable.h>
-#include <LibWeb/HTML/OffscreenCanvas.h>
-#include <LibWeb/Layout/Node.h>
-#include <LibWeb/Page/Page.h>
-#include <LibWeb/WebGL/EventNames.h>
-#include <LibWeb/WebGL/RemoteWebGLTransport.h>
-#include <LibWeb/WebGL/WebGLContextEvent.h>
-#include <LibWeb/WebGL/WebGLContextProxy.h>
-#include <LibWeb/WebGL/WebGLRenderingContext.h>
-#include <LibWeb/WebGL/WebGLShader.h>
-#include <LibWeb/WebIDL/Buffers.h>
-#include <LibWebCommon/Infra/Strings.h>
-
-#include <GLES2/gl2.h>
-#include <GLES2/gl2ext.h>
-
-namespace Web::WebGL {
-
-GC_DEFINE_ALLOCATOR(WebGLRenderingContext);
-
-// https://www.khronos.org/registry/webgl/specs/latest/1.0/#fire-a-webgl-context-event
-// Returns false if the event was canceled (the page called preventDefault), which is how
-// webglcontextlost signals that the page wants the context restored.
-bool fire_webgl_context_event(HTML::CanvasHost& canvas, Utf16FlyString const& type)
-{
- // To fire a WebGL context event named e means that an event using the WebGLContextEvent interface, with its type attribute [DOM4] initialized to e, its cancelable attribute initialized to true, and its isTrusted attribute [DOM4] initialized to true, is to be dispatched at the given object.
- // FIXME: Consider setting a status message.
- auto event = WebGLContextEvent::create(type, Bindings::WebGLContextEventInit {}, HighResolutionTime::current_high_resolution_time(canvas.canvas_relevant_global_object()));
- event->set_is_trusted(true);
- event->set_cancelable(true);
- return canvas.canvas_event_target().dispatch_event(*event);
-}
-
-// https://www.khronos.org/registry/webgl/specs/latest/1.0/#fire-a-webgl-context-creation-error
-void fire_webgl_context_creation_error(HTML::CanvasHost& canvas)
-{
- // 1. Fire a WebGL context event named "webglcontextcreationerror" at canvas, optionally with its statusMessage attribute set to a platform dependent string about the nature of the failure.
- fire_webgl_context_event(canvas, EventNames::webglcontextcreationerror);
-}
-
-// The drawing buffer's creation-time size, clamped like set_size() clamps resizes;
-// later resizes travel as SetDrawingBufferSize commands.
-static Gfx::IntSize initial_drawing_buffer_size(HTML::CanvasHost& canvas)
-{
- auto size = canvas.bitmap_size_for_canvas();
- return {
- clamp(size.width(), 1, max_webgl_drawing_buffer_dimension),
- clamp(size.height(), 1, max_webgl_drawing_buffer_dimension),
- };
-}
-
-namespace {
-
-struct RemoteWebGLContext {
- NonnullRefPtr<RemoteWebGLTransport> transport;
- RemoteWebGLTransport::CreateResult result;
-};
-
-Optional<RemoteWebGLContext> create_remote_webgl_context(HTML::CanvasHost& canvas, WebGLVersion webgl_version, WebGLContextAttributes const& context_attributes)
-{
- auto& page = canvas.canvas_page();
- if (!page.has_compositor_host())
- return {};
- auto transport = page.compositor_host().create_webgl_transport();
- if (!transport)
- return {};
-
- auto result = transport->create_context(
- webgl_version,
- initial_drawing_buffer_size(canvas),
- context_attributes.depth,
- context_attributes.stencil,
- context_attributes.antialias);
- if (!result.success)
- return {};
-
- // NB: The display list must be re-recorded so its DrawCanvas command refers to the new remote context's
- // canvas id. Content updates alone don't invalidate the display list, so do it here.
- canvas.did_create_canvas_backing_storage();
-
- return RemoteWebGLContext { transport.release_nonnull(), move(result) };
-}
-
-}
-
-OwnPtr<WebGLContextProxy> create_webgl_context_proxy(HTML::CanvasHost& canvas, WebGLVersion webgl_version, WebGLContextAttributes const& context_attributes)
-{
- auto remote = create_remote_webgl_context(canvas, webgl_version, context_attributes);
- if (!remote.has_value())
- return {};
-
- return make<WebGLContextProxy>(move(remote->transport), webgl_version, move(remote->result.supported_extensions));
-}
-
-bool restore_webgl_context_proxy(WebGLContextProxy& context, HTML::CanvasHost& canvas, WebGLVersion webgl_version, WebGLContextAttributes const& context_attributes)
-{
- auto remote = create_remote_webgl_context(canvas, webgl_version, context_attributes);
- if (!remote.has_value())
- return false;
-
- context.restore(move(remote->transport), move(remote->result.supported_extensions));
- return true;
-}
-
-JS::ThrowCompletionOr<GC::Ptr<WebGLRenderingContext>> WebGLRenderingContext::create(JS::Realm& realm, CanvasOwner canvas, JS::Value options)
-{
- // We should be coming here from getContext being called on a wrapped <canvas> element or OffscreenCanvas.
- auto context_attributes = TRY(convert_value_to_context_attributes_dictionary(realm.vm(), options));
-
- auto context = create_webgl_context_proxy(canvas_host_for(canvas), WebGLVersion::WebGL1, context_attributes);
- if (!context) {
- fire_webgl_context_creation_error(canvas_host_for(canvas));
- return GC::Ptr<WebGLRenderingContext> { nullptr };
- }
-
- return realm.create<WebGLRenderingContext>(realm, canvas, context.release_nonnull(), context_attributes, context_attributes);
-}
-
-WebGLRenderingContext::WebGLRenderingContext(JS::Realm& realm, CanvasOwner canvas, NonnullOwnPtr<WebGLContextProxy> context, WebGLContextAttributes context_creation_parameters, WebGLContextAttributes actual_context_parameters)
- : WebGLRenderingContextOverloads(realm, move(context))
- , m_canvas(canvas)
- , m_context_creation_parameters(context_creation_parameters)
- , m_actual_context_parameters(actual_context_parameters)
-{
-}
-
-WebGLRenderingContext::~WebGLRenderingContext() = default;
-
-void WebGLRenderingContext::visit_edges(Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- WebGLRenderingContextImpl::visit_edges(visitor);
- m_canvas.visit([&](auto const& canvas) { visitor.visit(canvas); });
-}
-
-void WebGLRenderingContext::prepare_for_compositing()
-{
- context().present_canvas_for_compositing(m_context_creation_parameters.preserve_drawing_buffer);
-}
-
-bool WebGLRenderingContext::reestablish_remote_context()
-{
- return restore_webgl_context_proxy(context(), canvas_host(), WebGLVersion::WebGL1, m_actual_context_parameters);
-}
-
-CanvasOwner WebGLRenderingContext::canvas_for_binding() const
-{
- return m_canvas;
-}
-
-void WebGLRenderingContext::did_update_canvas_content()
-{
- canvas_host().did_change_canvas_content();
-}
-
-Optional<WebGLContextAttributes> WebGLRenderingContext::get_context_attributes()
-{
- if (is_context_lost())
- return {};
- return m_actual_context_parameters;
-}
-
-void WebGLRenderingContext::set_size(Gfx::IntSize const& size)
-{
- Gfx::IntSize final_size;
- final_size.set_width(clamp(size.width(), 1, max_webgl_drawing_buffer_dimension));
- final_size.set_height(clamp(size.height(), 1, max_webgl_drawing_buffer_dimension));
- context().set_size(final_size);
-}
-
-void WebGLRenderingContext::reset_to_default_state()
-{
-}
-
-WebIDL::Long WebGLRenderingContext::drawing_buffer_width() const
-{
- auto size = canvas_host().bitmap_size_for_canvas();
- return min(size.width(), max_webgl_drawing_buffer_dimension);
-}
-
-WebIDL::Long WebGLRenderingContext::drawing_buffer_height() const
-{
- auto size = canvas_host().bitmap_size_for_canvas();
- return min(size.height(), max_webgl_drawing_buffer_dimension);
-}
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLRenderingContext.h b/Libraries/LibWeb/WebGL/WebGLRenderingContext.h
index f34cc3e0a39..18b28e9ac66 100644
--- a/Libraries/LibWeb/WebGL/WebGLRenderingContext.h
+++ b/Libraries/LibWeb/WebGL/WebGLRenderingContext.h
@@ -7,59 +7,17 @@
#pragma once
-#include <AK/Utf16FlyString.h>
-#include <LibGC/Ptr.h>
-#include <LibWeb/Bindings/PlatformObject.h>
-#include <LibWeb/Forward.h>
-#include <LibWeb/WebGL/Types.h>
-#include <LibWeb/WebGL/WebGLContextAttributes.h>
-#include <LibWeb/WebGL/WebGLRenderingContextOverloads.h>
+#include <LibWeb/Bindings/WebGLRenderingContext.h>
+#include <LibWeb/WebGL/WebGLRenderingContextBase.h>
namespace Web::WebGL {
-class WebGLRenderingContext final : public WebGLRenderingContextOverloads {
- WEB_WRAPPABLE(WebGLRenderingContext, WebGLRenderingContextOverloads);
- GC_DECLARE_ALLOCATOR(WebGLRenderingContext);
+// https://registry.khronos.org/webgl/specs/latest/1.0/#5.14
+class WEB_API WebGLRenderingContext final : public WebGLRenderingContextBase {
+ WEB_RUST_INTERFACE(WebGLRenderingContext, web_gl_rendering_context)
public:
static JS::ThrowCompletionOr<GC::Ptr<WebGLRenderingContext>> create(JS::Realm&, CanvasOwner, JS::Value options);
-
- virtual ~WebGLRenderingContext() override;
-
- void prepare_for_compositing() override;
- void did_update_canvas_content() override;
-
- virtual CanvasOwner canvas_for_binding() const override;
-
- Optional<WebGLContextAttributes> get_context_attributes();
-
- void set_size(Gfx::IntSize const&);
- void reset_to_default_state();
-
- WebIDL::Long drawing_buffer_width() const;
- WebIDL::Long drawing_buffer_height() const;
-
-private:
- WebGLRenderingContext(JS::Realm&, CanvasOwner, NonnullOwnPtr<WebGLContextProxy> context, WebGLContextAttributes context_creation_parameters, WebGLContextAttributes actual_context_parameters);
-
- virtual void visit_edges(Cell::Visitor&) override;
- virtual bool reestablish_remote_context() override;
-
- CanvasOwner m_canvas;
-
- // https://www.khronos.org/registry/webgl/specs/latest/1.0/#context-creation-parameters
- // Each WebGLRenderingContext has context creation parameters, set upon creation, in a WebGLContextAttributes object.
- WebGLContextAttributes m_context_creation_parameters {};
-
- // https://www.khronos.org/registry/webgl/specs/latest/1.0/#actual-context-parameters
- // Each WebGLRenderingContext has actual context parameters, set each time the drawing buffer is created, in a WebGLContextAttributes object.
- WebGLContextAttributes m_actual_context_parameters {};
};
-bool fire_webgl_context_event(HTML::CanvasHost&, Utf16FlyString const& type);
-void fire_webgl_context_creation_error(HTML::CanvasHost&);
-
-OwnPtr<WebGLContextProxy> create_webgl_context_proxy(HTML::CanvasHost&, WebGLVersion, WebGLContextAttributes const&);
-bool restore_webgl_context_proxy(WebGLContextProxy&, HTML::CanvasHost&, WebGLVersion, WebGLContextAttributes const&);
-
}
diff --git a/Libraries/LibWeb/WebGL/WebGLRenderingContext.idl b/Libraries/LibWeb/WebGL/WebGLRenderingContext.idl
index 4707366536b..564b1dd7fee 100644
--- a/Libraries/LibWeb/WebGL/WebGLRenderingContext.idl
+++ b/Libraries/LibWeb/WebGL/WebGLRenderingContext.idl
@@ -1,5 +1,5 @@
// https://registry.khronos.org/webgl/specs/latest/1.0/#5.14
-[Exposed=(Window,Worker)]
+[Exposed=(Window,Worker), ImplementedIn=Rust]
interface WebGLRenderingContext {
};
diff --git a/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp b/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp
index a8ccaa56b70..04c87d70216 100644
--- a/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp
+++ b/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp
@@ -1,21 +1,26 @@
/*
- * Copyright (c) 2024-2025, Aliaksandr Kalenik <[email protected]>
+ * Copyright (c) 2022, Luke Wilde <[email protected]>
+ * Copyright (c) 2023-2025, Aliaksandr Kalenik <[email protected]>
+ * Copyright (c) 2024, Andrew Kaster <[email protected]>
* Copyright (c) 2024-2025, Luke Wilde <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <GLES2/gl2.h>
-#include <GLES2/gl2ext.h>
-extern "C" {
-#include <GLES2/gl2ext_angle.h>
-}
-
+#include <AK/Utf16FlyString.h>
+#include <AK/Vector.h>
#include <LibCompositing/WebGL/TextureUpload.h>
+#include <LibGfx/Bitmap.h>
#include <LibGfx/DecodedImageFrame.h>
+#include <LibJS/HostClassBuilder.h>
#include <LibJS/Runtime/Object.h>
+#include <LibJS/Runtime/Realm.h>
+#include <LibJS/Runtime/TypedArray.h>
+#include <LibWeb/Bindings/WebGLContextEvent.h>
#include <LibWeb/Bindings/WrapperWorld.h>
-#include <LibWeb/HTML/DecodedImageData.h>
+#include <LibWeb/Compositor/CompositorHost.h>
+#include <LibWeb/DOM/EventTarget.h>
+#include <LibWeb/HTML/Canvas/CanvasHost.h>
#include <LibWeb/HTML/EventLoop/Task.h>
#include <LibWeb/HTML/HTMLCanvasElement.h>
#include <LibWeb/HTML/HTMLImageElement.h>
@@ -24,377 +29,345 @@ extern "C" {
#include <LibWeb/HTML/ImageData.h>
#include <LibWeb/HTML/OffscreenCanvas.h>
#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
-#include <LibWeb/HTML/Window.h>
#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>
+#include <LibWeb/HighResolutionTime/TimeOrigin.h>
+#include <LibWeb/Page/Page.h>
#include <LibWeb/Platform/EventLoopPlugin.h>
#include <LibWeb/WebGL/EventNames.h>
-#include <LibWeb/WebGL/Extensions/ANGLEInstancedArrays.h>
-#include <LibWeb/WebGL/Extensions/EXTBlendMinMax.h>
-#include <LibWeb/WebGL/Extensions/EXTColorBufferFloat.h>
-#include <LibWeb/WebGL/Extensions/EXTRenderSnorm.h>
-#include <LibWeb/WebGL/Extensions/EXTTextureFilterAnisotropic.h>
-#include <LibWeb/WebGL/Extensions/EXTTextureNorm16.h>
-#include <LibWeb/WebGL/Extensions/OESElementIndexUint.h>
-#include <LibWeb/WebGL/Extensions/OESStandardDerivatives.h>
-#include <LibWeb/WebGL/Extensions/OESVertexArrayObject.h>
-#include <LibWeb/WebGL/Extensions/WebGLCompressedTextureS3tc.h>
-#include <LibWeb/WebGL/Extensions/WebGLCompressedTextureS3tcSrgb.h>
-#include <LibWeb/WebGL/Extensions/WebGLDebugRendererInfo.h>
-#include <LibWeb/WebGL/Extensions/WebGLDrawBuffers.h>
-#include <LibWeb/WebGL/WebGLContextProxy.h>
-#include <LibWeb/WebGL/WebGLObject.h>
+#include <LibWeb/WebGL/RemoteWebGLTransport.h>
+#include <LibWeb/WebGL/WebGL2RenderingContext.h>
+#include <LibWeb/WebGL/WebGLContextAttributes.h>
+#include <LibWeb/WebGL/WebGLContextEvent.h>
#include <LibWeb/WebGL/WebGLRenderingContext.h>
#include <LibWeb/WebGL/WebGLRenderingContextBase.h>
+#include <LibWeb/WebIDL/Promise.h>
namespace Web::WebGL {
-WebGLRenderingContextBase::WebGLRenderingContextBase(JS::Realm& realm)
- : m_realm(realm)
-{
+namespace {
+
+// `ContextAttributes` of Bindings/Rust/src/web_gl/exports.rs.
+struct RustContextAttributes {
+ bool alpha { true };
+ bool depth { true };
+ bool stencil { false };
+ bool antialias { true };
+ bool premultiplied_alpha { true };
+ bool preserve_drawing_buffer { false };
+ // 0 is "default", 1 is "low-power" and 2 is "high-performance".
+ u8 power_preference { 0 };
+ bool fail_if_major_performance_caveat { false };
+ bool desynchronized { false };
+ bool xr_compatible { false };
+};
+
+struct ByteSpan {
+ u8 const* data { nullptr };
+ size_t size { 0 };
+};
+
+// `ContextCreationArguments` of Bindings/Rust/src/web_gl/exports.rs.
+struct ContextCreationArguments {
+ void* transport { nullptr };
+ bool is_webgl2 { false };
+ void* realm { nullptr };
+ void* canvas { nullptr };
+ void* canvas_host { nullptr };
+ bool canvas_is_offscreen { false };
+ RustContextAttributes context_attributes;
+ ByteSpan const* supported_extensions { nullptr };
+ size_t supported_extension_count { 0 };
+};
+
+// `TexImageSourceKind` and `TexImageSourceResult` of Bindings/Rust/src/web_gl/canvas.rs.
+enum class TexImageSourceKind : u8 {
+ ImageBitmap,
+ ImageData,
+ HTMLImageElement,
+ HTMLCanvasElement,
+ HTMLVideoElement,
+ OffscreenCanvas,
+};
+
+enum class TexImageSourceResult : u8 {
+ Frame,
+ NoFrame,
+ InvalidValue,
+};
+
+// NB: `PixelUnpackState` of Bindings/Rust/src/web_gl/canvas.rs is four `usize`s in this order, with these defaults.
+static_assert(sizeof(PixelUnpackState) == 4 * sizeof(size_t));
+static_assert(offsetof(PixelUnpackState, alignment) == 0);
+static_assert(offsetof(PixelUnpackState, row_length) == sizeof(size_t));
+static_assert(offsetof(PixelUnpackState, skip_pixels) == 2 * sizeof(size_t));
+static_assert(offsetof(PixelUnpackState, skip_rows) == 3 * sizeof(size_t));
+static_assert(PixelUnpackState {}.alignment == 4);
+static_assert(PixelUnpackState {}.row_length == 0);
+static_assert(PixelUnpackState {}.skip_pixels == 0);
+static_assert(PixelUnpackState {}.skip_rows == 0);
+
}
-HTML::CanvasHost& canvas_host_for(CanvasOwner const& canvas)
-{
- return canvas.visit([](auto const& canvas) -> HTML::CanvasHost& { return *canvas; });
+extern "C" {
+
+// Defined in Bindings/Rust/src/web_gl/exports.rs. A context is the cell of a context of either kind.
+void* web_webgl_context_create(JSVM*, ContextCreationArguments const*);
+void* web_webgl_context_canvas_host(void* context);
+void* web_webgl_context_realm(void* context);
+bool web_webgl_context_is_webgl2(void* context);
+bool web_webgl_context_is_lost(void* context);
+bool web_webgl_context_canvas_id(void* context, u64* out_canvas_id);
+void web_webgl_context_set_size(void* context, i32 width, i32 height);
+void web_webgl_context_present_for_compositing(void* context);
+void web_webgl_context_clear_drawing_buffer(void* context);
+void* web_webgl_context_read_back_drawing_buffer(void* context, i32 x, i32 y, i32 width, i32 height);
+bool web_webgl_context_mark_lost(void* context);
+void web_webgl_context_set_restore_requested(void* context, bool requested);
+bool web_webgl_context_wants_restoring(void* context);
+void web_webgl_context_actual_context_parameters(void* context, RustContextAttributes* out_context_attributes);
+void web_webgl_context_restore(void* context, void* transport, ByteSpan const* supported_extensions, size_t supported_extension_count);
+bool web_webgl_context_xr_compatible(void* context);
+void web_webgl_context_set_xr_compatible(void* context, bool xr_compatible);
+
+// What the Rust implementation asks of LibWeb, declared in Bindings/Rust/src/web_gl/canvas.rs.
+void web_webgl_canvas_did_change_content(void* canvas_host);
+void web_webgl_canvas_bitmap_size(void* canvas_host, i32* out_width, i32* out_height);
+void* web_webgl_canvas_wrapper(void* canvas, bool canvas_is_offscreen, void* realm);
+void* web_webgl_canvas_relevant_realm(void* canvas_host);
+bool web_webgl_expose_experimental_interfaces();
+bool web_webgl_is_valid_2d_pixel_unpack_state(i32 width, PixelUnpackState const* unpack_state);
+bool web_webgl_required_2d_texture_data_size(i32 width, i32 height, u32 format, u32 type, PixelUnpackState const* unpack_state, size_t* out_size);
+TexImageSourceResult web_webgl_read_tex_image_source(void* source_wrapper, TexImageSourceKind, u32 format, u32 type, void** out_frame);
+void* web_webgl_make_xr_compatible(void* context);
}
-GC::Ptr<Bindings::Wrappable> WebGLRenderingContextBase::relevant_global_impl() const
+static void* cell_of(WebGLRenderingContextBase const& context)
{
- return canvas_host().canvas_relevant_global_impl();
+ return const_cast<WebGLRenderingContextBase*>(&context);
}
-struct Extension {
- Vector<StringView> required_angle_extensions;
- GC::Ref<Bindings::Wrappable> (*factory)(GC::Ref<WebGLRenderingContextBase>) { nullptr };
- Optional<WebGLVersion> only_for_webgl_version { OptionalNone {} };
- bool creates_empty_object { false };
-};
-
-static HashMap<String, Extension, AK::ASCIICaseInsensitiveStringTraits> const& available_webgl_extensions()
+static RustContextAttributes to_rust_context_attributes(WebGLContextAttributes const& context_attributes)
{
- static auto const& extensions = *new HashMap<String, Extension, AK::ASCIICaseInsensitiveStringTraits> {
- // Khronos ratified WebGL Extensions
- { "ANGLE_instanced_arrays"_string, { { "GL_ANGLE_instanced_arrays"sv }, ANGLEInstancedArrays::create, WebGLVersion::WebGL1 } },
- { "EXT_blend_minmax"_string, { { "GL_EXT_blend_minmax"sv }, EXTBlendMinMax::create, WebGLVersion::WebGL1 } },
- { "EXT_frag_depth"_string, { { "GL_EXT_frag_depth"sv }, nullptr, WebGLVersion::WebGL1 } },
- { "EXT_shader_texture_lod"_string, { { "GL_EXT_shader_texture_lod"sv }, nullptr, WebGLVersion::WebGL1 } },
- { "EXT_texture_filter_anisotropic"_string, { { "GL_EXT_texture_filter_anisotropic"sv }, EXTTextureFilterAnisotropic::create } },
- { "OES_element_index_uint"_string, { { "GL_OES_element_index_uint"sv }, OESElementIndexUint::create, WebGLVersion::WebGL1 } },
- { "OES_standard_derivatives"_string, { { "GL_OES_standard_derivatives"sv }, OESStandardDerivatives::create, WebGLVersion::WebGL1 } },
- { "OES_texture_float"_string, { { "GL_OES_texture_float"sv }, nullptr, WebGLVersion::WebGL1 } },
- { "OES_texture_float_linear"_string, { { "GL_OES_texture_float_linear"sv }, nullptr, OptionalNone {}, true } },
- { "OES_texture_half_float"_string, { { "GL_OES_texture_half_float"sv }, nullptr, WebGLVersion::WebGL1 } },
- { "OES_texture_half_float_linear"_string, { { "GL_OES_texture_half_float_linear"sv }, nullptr, WebGLVersion::WebGL1 } },
- { "OES_vertex_array_object"_string, { { "GL_OES_vertex_array_object"sv }, OESVertexArrayObject::create, WebGLVersion::WebGL1 } },
- { "WEBGL_compressed_texture_s3tc"_string, { { "GL_EXT_texture_compression_dxt1"sv, "GL_ANGLE_texture_compression_dxt3"sv, "GL_ANGLE_texture_compression_dxt5"sv }, WebGLCompressedTextureS3tc::create } },
- { "WEBGL_debug_renderer_info"_string, { {}, WebGLDebugRendererInfo::create } },
- { "WEBGL_debug_shaders"_string, { {}, nullptr } },
- { "WEBGL_depth_texture"_string, { { "GL_ANGLE_depth_texture"sv }, nullptr, WebGLVersion::WebGL1 } },
- { "WEBGL_draw_buffers"_string, { { "GL_EXT_draw_buffers"sv }, WebGLDrawBuffers::create, WebGLVersion::WebGL1 } },
- { "WEBGL_lose_context"_string, { {}, nullptr } },
-
- // Community approved WebGL Extensions
- { "EXT_clip_control"_string, { { "GL_EXT_clip_control"sv }, nullptr } },
- { "EXT_color_buffer_float"_string, { { "GL_EXT_color_buffer_float"sv }, EXTColorBufferFloat::create, WebGLVersion::WebGL2 } },
- { "EXT_color_buffer_half_float"_string, { { "GL_EXT_color_buffer_half_float"sv }, nullptr } },
- { "EXT_conservative_depth"_string, { { "GL_EXT_conservative_depth"sv }, nullptr, WebGLVersion::WebGL2 } },
- { "EXT_depth_clamp"_string, { { "GL_EXT_depth_clamp"sv }, nullptr } },
- { "EXT_disjoint_timer_query"_string, { { "GL_EXT_disjoint_timer_query"sv }, nullptr, WebGLVersion::WebGL1 } },
- { "EXT_disjoint_timer_query_webgl2"_string, { { "GL_EXT_disjoint_timer_query"sv }, nullptr, WebGLVersion::WebGL2 } },
- { "EXT_float_blend"_string, { { "GL_EXT_float_blend"sv }, nullptr, OptionalNone {}, true } },
- { "EXT_polygon_offset_clamp"_string, { { "GL_EXT_polygon_offset_clamp"sv }, nullptr } },
- { "EXT_render_snorm"_string, { { "GL_EXT_render_snorm"sv }, EXTRenderSnorm::create, WebGLVersion::WebGL2 } },
- { "EXT_sRGB"_string, { { "GL_EXT_sRGB"sv }, nullptr, WebGLVersion::WebGL1 } },
- { "EXT_texture_compression_bptc"_string, { { "GL_EXT_texture_compression_bptc"sv }, nullptr } },
- { "EXT_texture_compression_rgtc"_string, { { "GL_EXT_texture_compression_rgtc"sv }, nullptr } },
- { "EXT_texture_mirror_clamp_to_edge"_string, { { "GL_EXT_texture_mirror_clamp_to_edge"sv }, nullptr } },
- { "EXT_texture_norm16"_string, { { "GL_EXT_texture_norm16"sv }, EXTTextureNorm16::create, WebGLVersion::WebGL2 } },
- { "KHR_parallel_shader_compile"_string, { { "GL_KHR_parallel_shader_compile"sv }, nullptr } },
- { "NV_shader_noperspective_interpolation"_string, { { "GL_NV_shader_noperspective_interpolation"sv }, nullptr, WebGLVersion::WebGL2 } },
- { "OES_draw_buffers_indexed"_string, { { "GL_OES_draw_buffers_indexed"sv }, nullptr } },
- { "OES_fbo_render_mipmap"_string, { { "GL_OES_fbo_render_mipmap"sv }, nullptr, WebGLVersion::WebGL1 } },
- { "OES_sample_variables"_string, { { "GL_OES_sample_variables"sv }, nullptr, WebGLVersion::WebGL2 } },
- { "OES_shader_multisample_interpolation"_string, { { "GL_OES_shader_multisample_interpolation"sv }, nullptr, WebGLVersion::WebGL2 } },
- { "OVR_multiview2"_string, { { "GL_OVR_multiview2"sv }, nullptr, WebGLVersion::WebGL2 } },
- { "WEBGL_blend_func_extended"_string, { { "GL_EXT_blend_func_extended"sv }, nullptr } },
- { "WEBGL_clip_cull_distance"_string, { { "GL_EXT_clip_cull_distance"sv }, nullptr, WebGLVersion::WebGL2 } },
- { "WEBGL_color_buffer_float"_string, { { "EXT_color_buffer_half_float"sv, "OES_texture_float"sv }, nullptr, WebGLVersion::WebGL1 } },
- { "WEBGL_compressed_texture_astc"_string, { { "KHR_texture_compression_astc_hdr"sv, "KHR_texture_compression_astc_ldr"sv }, nullptr } },
- { "WEBGL_compressed_texture_etc"_string, { { "GL_ANGLE_compressed_texture_etc"sv }, nullptr } },
- { "WEBGL_compressed_texture_etc1"_string, { { "GL_OES_compressed_ETC1_RGB8_texture"sv }, nullptr } },
- { "WEBGL_compressed_texture_pvrtc"_string, { { "GL_IMG_texture_compression_pvrtc"sv }, nullptr } },
- { "WEBGL_compressed_texture_s3tc_srgb"_string, { { "GL_EXT_texture_compression_s3tc_srgb"sv }, WebGLCompressedTextureS3tcSrgb::create } },
- { "WEBGL_multi_draw"_string, { { "GL_ANGLE_multi_draw"sv }, nullptr } },
- { "WEBGL_polygon_mode"_string, { { "GL_ANGLE_polygon_mode"sv }, nullptr } },
- { "WEBGL_provoking_vertex"_string, { { "GL_ANGLE_provoking_vertex"sv }, nullptr, WebGLVersion::WebGL2 } },
- { "WEBGL_render_shared_exponent"_string, { { "GL_QCOM_render_shared_exponent"sv }, nullptr, WebGLVersion::WebGL2 } },
- { "WEBGL_stencil_texturing"_string, { { "GL_ANGLE_stencil_texturing"sv }, nullptr, WebGLVersion::WebGL2 } },
+ u8 power_preference = 0;
+ switch (context_attributes.power_preference) {
+ case Bindings::WebGLPowerPreference::Default:
+ power_preference = 0;
+ break;
+ case Bindings::WebGLPowerPreference::LowPower:
+ power_preference = 1;
+ break;
+ case Bindings::WebGLPowerPreference::HighPerformance:
+ power_preference = 2;
+ break;
+ }
+ return {
+ .alpha = context_attributes.alpha,
+ .depth = context_attributes.depth,
+ .stencil = context_attributes.stencil,
+ .antialias = context_attributes.antialias,
+ .premultiplied_alpha = context_attributes.premultiplied_alpha,
+ .preserve_drawing_buffer = context_attributes.preserve_drawing_buffer,
+ .power_preference = power_preference,
+ .fail_if_major_performance_caveat = context_attributes.fail_if_major_performance_caveat,
+ .desynchronized = context_attributes.desynchronized,
+ .xr_compatible = context_attributes.xr_compatible,
};
- return extensions;
}
-Optional<Vector<Utf16String>> WebGLRenderingContextBase::get_supported_extensions()
+HTML::CanvasHost& canvas_host_for(CanvasOwner const& canvas)
{
- auto const& opengl_extensions = context().get_supported_opengl_extensions();
- Vector<Utf16String> webgl_extensions;
-
- for (auto const& [available_extension_name, available_extension_info] : available_webgl_extensions()) {
- bool supported = !available_extension_info.only_for_webgl_version.has_value()
- || context().webgl_version() == available_extension_info.only_for_webgl_version;
-
- if (!available_extension_info.factory && !available_extension_info.creates_empty_object && !HTML::WindowOrWorkerGlobalScopeMixin::expose_experimental_interfaces()) {
- supported = false;
- }
-
- if (supported) {
- for (auto const& required_extension : available_extension_info.required_angle_extensions) {
- if (!opengl_extensions.contains_slow(required_extension)) {
- supported = false;
- break;
- }
- }
- }
+ return canvas.visit([](auto const& canvas) -> HTML::CanvasHost& { return *canvas; });
+}
- if (supported)
- webgl_extensions.append(Utf16String::from_ascii_without_validation(available_extension_name.bytes_as_string_view().bytes()));
- }
+// https://www.khronos.org/registry/webgl/specs/latest/1.0/#fire-a-webgl-context-event
+// Returns false if the event was canceled (the page called preventDefault), which is how
+// webglcontextlost signals that the page wants the context restored.
+static bool fire_webgl_context_event(HTML::CanvasHost& canvas, Utf16FlyString const& type)
+{
+ // To fire a WebGL context event named e means that an event using the WebGLContextEvent interface, with its type attribute [DOM4] initialized to e, its cancelable attribute initialized to true, and its isTrusted attribute [DOM4] initialized to true, is to be dispatched at the given object.
+ // FIXME: Consider setting a status message.
+ auto event = WebGLContextEvent::create(type, Bindings::WebGLContextEventInit {}, HighResolutionTime::current_high_resolution_time(canvas.canvas_relevant_global_object()));
+ event->set_is_trusted(true);
+ event->set_cancelable(true);
+ return canvas.canvas_event_target().dispatch_event(*event);
+}
- return webgl_extensions;
+// https://www.khronos.org/registry/webgl/specs/latest/1.0/#fire-a-webgl-context-creation-error
+static void fire_webgl_context_creation_error(HTML::CanvasHost& canvas)
+{
+ // 1. Fire a WebGL context event named "webglcontextcreationerror" at canvas, optionally with its statusMessage attribute set to a platform dependent string about the nature of the failure.
+ fire_webgl_context_event(canvas, EventNames::webglcontextcreationerror);
}
-GC::Ptr<JS::Object> WebGLRenderingContextBase::get_extension(JS::Realm& caller_realm, Utf16String const& name)
+// The drawing buffer's creation-time size, clamped like set_size() clamps resizes;
+// later resizes travel as SetDrawingBufferSize commands.
+static Gfx::IntSize initial_drawing_buffer_size(HTML::CanvasHost& canvas)
{
- // Returns an object if, and only if, name is an ASCII case-insensitive match [HTML] for one of the names returned
- // from getSupportedExtensions; otherwise, returns null. The object returned from getExtension contains any constants
- // or functions provided by the extension. A returned object may have no constants or functions if the extension does
- // not define any, but a unique object must still be returned. That object is used to indicate that the extension has
- // been enabled.
- if (!name.is_ascii())
- return nullptr;
+ auto size = canvas.bitmap_size_for_canvas();
+ return {
+ clamp(size.width(), 1, max_webgl_drawing_buffer_dimension),
+ clamp(size.height(), 1, max_webgl_drawing_buffer_dimension),
+ };
+}
- auto name_string = MUST(String::from_byte_string(name.to_byte_string()));
- auto supported_extensions = get_supported_extensions();
- auto supported_extension_iterator = supported_extensions->find_if([&name](Utf16String const& supported_extension) {
- return supported_extension.equals_ignoring_ascii_case(name);
- });
- if (supported_extension_iterator == supported_extensions->end())
- return nullptr;
+namespace {
- auto maybe_extension = m_enabled_extensions.get(name_string);
- if (maybe_extension.has_value())
- return Bindings::wrap(Bindings::host_defined_wrapper_world(caller_realm), caller_realm, maybe_extension.release_value()).ptr();
+struct RemoteWebGLContext {
+ NonnullRefPtr<RemoteWebGLTransport> transport;
+ Vector<String> supported_extensions;
- auto& wrapper_world = Bindings::host_defined_wrapper_world(caller_realm);
- if (auto maybe_empty_extension_cache = m_enabled_empty_extensions.get(name_string); maybe_empty_extension_cache.has_value()) {
- if (auto extension = maybe_empty_extension_cache.value()->get(wrapper_world))
- return extension;
+ Vector<ByteSpan> supported_extension_spans() const
+ {
+ Vector<ByteSpan> spans;
+ spans.ensure_capacity(supported_extensions.size());
+ for (auto const& extension : supported_extensions)
+ spans.unchecked_append({ extension.bytes().data(), extension.bytes().size() });
+ return spans;
}
+};
- // If we pass the check above this will always return a value
- auto const& extension_info = available_webgl_extensions().get(name_string).release_value();
+Optional<RemoteWebGLContext> create_remote_webgl_context(HTML::CanvasHost& canvas, WebGLVersion webgl_version, bool depth, bool stencil, bool antialias)
+{
+ auto& page = canvas.canvas_page();
+ if (!page.has_compositor_host())
+ return {};
+ auto transport = page.compositor_host().create_webgl_transport();
+ if (!transport)
+ return {};
+
+ auto result = transport->create_context(webgl_version, initial_drawing_buffer_size(canvas), depth, stencil, antialias);
+ if (!result.success)
+ return {};
+
+ // NB: The display list must be re-recorded so its DrawCanvas command refers to the new remote context's
+ // canvas id. Content updates alone don't invalidate the display list, so do it here.
+ canvas.did_create_canvas_backing_storage();
+
+ return RemoteWebGLContext { transport.release_nonnull(), move(result.supported_extensions) };
+}
- if (!extension_info.factory && !extension_info.creates_empty_object)
- return nullptr;
+}
- for (auto const& required_extension : extension_info.required_angle_extensions) {
- context().request_extension_angle(null_terminated_string(required_extension).data());
- }
+JS::ThrowCompletionOr<WebGLRenderingContextBase*> WebGLRenderingContextBase::create(JS::Realm& realm, CanvasOwner canvas, JS::Value options, WebGLVersion webgl_version)
+{
+ // We should be coming here from getContext being called on a wrapped <canvas> element or OffscreenCanvas.
+ auto context_attributes = TRY(convert_value_to_context_attributes_dictionary(realm.vm(), options));
- if (extension_info.creates_empty_object) {
- auto extension = JS::Object::create(caller_realm, caller_realm.intrinsics().object_prototype());
- auto& cache = m_enabled_empty_extensions.ensure(move(name_string), [] {
- return make<Bindings::WrapperWorldWeakValueCache<JS::Object>>();
- });
- cache->set(wrapper_world, extension);
- return extension;
+ auto& canvas_host = canvas_host_for(canvas);
+ auto remote = create_remote_webgl_context(canvas_host, webgl_version, context_attributes.depth, context_attributes.stencil, context_attributes.antialias);
+ if (!remote.has_value()) {
+ fire_webgl_context_creation_error(canvas_host);
+ return nullptr;
}
- auto extension = extension_info.factory(*this);
- m_enabled_extensions.set(move(name_string), extension);
- return Bindings::wrap(Bindings::host_defined_wrapper_world(caller_realm), caller_realm, extension);
+ auto supported_extensions = remote->supported_extension_spans();
+ ContextCreationArguments arguments {
+ .transport = &remote->transport.leak_ref(),
+ .is_webgl2 = webgl_version == WebGLVersion::WebGL2,
+ .realm = &realm,
+ .canvas = canvas.visit([](auto const& canvas) -> void* { return static_cast<GC::Cell*>(canvas.ptr()); }),
+ .canvas_host = &canvas_host,
+ .canvas_is_offscreen = canvas.has<GC::Ref<HTML::OffscreenCanvas>>(),
+ .context_attributes = to_rust_context_attributes(context_attributes),
+ .supported_extensions = supported_extensions.data(),
+ .supported_extension_count = supported_extensions.size(),
+ };
+ return static_cast<WebGLRenderingContextBase*>(web_webgl_context_create(JS::HostABI::vm_to_abi(realm.vm()), &arguments));
}
-void WebGLRenderingContextBase::enable_compressed_texture_format(WebIDL::UnsignedLong format)
+JS::ThrowCompletionOr<GC::Ptr<WebGLRenderingContext>> WebGLRenderingContext::create(JS::Realm& realm, CanvasOwner canvas, JS::Value options)
{
- m_enabled_compressed_texture_formats.append(format);
+ return static_cast<WebGLRenderingContext*>(TRY(WebGLRenderingContextBase::create(realm, canvas, options, WebGLVersion::WebGL1)));
}
-void WebGLRenderingContextBase::visit_edges(Cell::Visitor& visitor)
+JS::ThrowCompletionOr<GC::Ptr<WebGL2RenderingContext>> WebGL2RenderingContext::create(JS::Realm& realm, CanvasOwner canvas, JS::Value options)
{
- Base::visit_edges(visitor);
- visitor.visit(m_realm);
- visitor.visit(m_current_vertex_array);
- visitor.visit(m_enabled_extensions);
+ return static_cast<WebGL2RenderingContext*>(TRY(WebGLRenderingContextBase::create(realm, canvas, options, WebGLVersion::WebGL2)));
}
-bool WebGLRenderingContextBase::extension_enabled(StringView extension) const
+HTML::CanvasHost& WebGLRenderingContextBase::canvas_host() const
{
- auto extension_name = MUST(String::from_utf8(extension));
- return m_enabled_extensions.contains(extension_name) || m_enabled_empty_extensions.contains(extension_name);
+ return *static_cast<HTML::CanvasHost*>(web_webgl_context_canvas_host(cell_of(*this)));
}
-ReadonlySpan<WebIDL::UnsignedLong> WebGLRenderingContextBase::enabled_compressed_texture_formats() const
+bool WebGLRenderingContextBase::is_context_lost() const
{
- return m_enabled_compressed_texture_formats;
+ return web_webgl_context_is_lost(cell_of(*this));
}
-ErrorOr<ReadonlyBytes> WebGLRenderingContextBase::texture_data_for_2d_upload(ReadonlyBytes bytes, GLsizei width, GLsizei height, GLenum format, GLenum type) const
+Optional<Compositing::CanvasId> WebGLRenderingContextBase::canvas_id() const
{
- if (!is_valid_2d_pixel_unpack_state(width, m_unpack_state))
- return Error::from_errno(EINVAL);
- if (auto size = required_2d_texture_data_size(width, height, format, type, m_unpack_state); size.has_value() && *size <= bytes.size())
- return bytes.slice(0, *size);
- return bytes;
+ u64 canvas_id = 0;
+ if (!web_webgl_context_canvas_id(cell_of(*this), &canvas_id))
+ return {};
+ return Compositing::CanvasId { canvas_id };
}
-Optional<WebGLRenderingContextBase::TexImageSourceFrame> WebGLRenderingContextBase::read_texture_image_source(TexImageSource const& source, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type)
+void WebGLRenderingContextBase::set_size(Gfx::IntSize const& size)
{
- // FIXME: If this function is called with an ImageData whose data attribute has been neutered,
- // an INVALID_VALUE error is generated.
- // FIXME: If this function is called with an ImageBitmap that has been neutered, an INVALID_VALUE
- // error is generated.
- // FIXME: If this function is called with an HTMLImageElement or HTMLVideoElement whose origin
- // differs from the origin of the containing Document, or with an HTMLCanvasElement,
- // ImageBitmap or OffscreenCanvas whose bitmap's origin-clean flag is set to false,
- // a SECURITY_ERR exception must be thrown. See Origin Restrictions.
- // FIXME: If source is null then an INVALID_VALUE error is generated.
- auto frame = source.visit(
- [](GC::Ref<HTML::HTMLImageElement> source) -> Optional<Gfx::DecodedImageFrame> {
- return source->current_image_frame();
- },
- [](OneOf<GC::Ref<HTML::HTMLCanvasElement>, GC::Ref<HTML::OffscreenCanvas>> auto source) -> Optional<Gfx::DecodedImageFrame> {
- auto bitmap = source->get_bitmap_from_surface();
- if (!bitmap)
- return {};
- return Gfx::DecodedImageFrame { *bitmap };
- },
- [](GC::Ref<HTML::HTMLVideoElement> source) -> Optional<Gfx::DecodedImageFrame> {
- return source->current_decoded_image_frame();
- },
- [](GC::Ref<HTML::ImageBitmap> source) -> Optional<Gfx::DecodedImageFrame> {
- return Gfx::DecodedImageFrame { *source->bitmap() };
- },
- [this](GC::Ref<HTML::ImageData> source) -> Optional<Gfx::DecodedImageFrame> {
- // ImageData keeps a cached bitmap for ordinary use, but its data
- // attribute can be detached independently. WebGL must reject that
- // source instead of uploading the stale cached pixels.
- auto data = source->data();
- if (!data)
- return OptionalNone {};
- auto data_record = JS::make_typed_array_with_buffer_witness_record(*data, JS::ArrayBuffer::Order::SeqCst);
- if (JS::is_typed_array_out_of_bounds(data_record)) {
- set_error(GL_INVALID_VALUE);
- return OptionalNone {};
- }
- auto bitmap = source->bitmap();
- if (bitmap.is_error()) {
- set_error(GL_INVALID_VALUE);
- return OptionalNone {};
- }
- NonnullRefPtr<Gfx::Bitmap const> bitmap_ref = bitmap.release_value();
- return Gfx::DecodedImageFrame { move(bitmap_ref) };
- });
- if (!frame.has_value())
- return OptionalNone {};
-
- // Validate the combination before recording; the pixels travel to the host as shared
- // memory and the host performs the conversion next to GL.
- if (!texture_export_format(format, type).has_value())
- return OptionalNone {};
-
- // FIXME: Respect unpackColorSpace
- return TexImageSourceFrame {
- .frame = frame.release_value(),
- // The first pixel transferred from the source to the WebGL implementation corresponds to the upper left corner of
- // the source. This behavior is modified by the UNPACK_FLIP_Y_WEBGL pixel storage parameter, except for ImageBitmap
- // arguments, as described in the abovementioned section.
- .flip_y = m_unpack_flip_y && !source.has<GC::Ref<HTML::ImageBitmap>>(),
- .premultiply_alpha = m_unpack_premultiply_alpha,
- };
+ web_webgl_context_set_size(this, size.width(), size.height());
}
-// https://registry.khronos.org/webgl/specs/latest/1.0/#CONTEXT_LOST_WEBGL
-static constexpr GLenum CONTEXT_LOST_WEBGL = 0x9242;
-
-// TODO: The glGetError spec allows for queueing errors which is something we should probably do, for now
-// this just keeps track of one error which is also fine by the spec
-GLenum WebGLRenderingContextBase::get_error_value()
+void WebGLRenderingContextBase::prepare_for_compositing()
{
- if (m_context_lost) {
- auto error = m_error;
- m_error = GL_NO_ERROR;
- return error;
- }
-
- if (auto local_error = context().take_pending_local_error(); local_error != GL_NO_ERROR)
- return local_error;
-
- auto context_error = context().get_error();
- if (context_error != GL_NO_ERROR)
- return context_error;
-
- auto error = m_error;
- m_error = GL_NO_ERROR;
- return error;
+ web_webgl_context_present_for_compositing(this);
}
-void WebGLRenderingContextBase::set_error(GLenum error)
+void WebGLRenderingContextBase::clear_drawing_buffer()
{
- if (m_error == GL_NO_ERROR)
- m_error = error;
+ web_webgl_context_clear_drawing_buffer(this);
}
-bool WebGLRenderingContextBase::is_context_lost() const
+RefPtr<Gfx::Bitmap> WebGLRenderingContextBase::read_back_drawing_buffer(Gfx::IntRect const& rect)
{
- dbgln_if(WEBGL_CONTEXT_DEBUG, "WebGLRenderingContext::is_context_lost()");
- return m_context_lost;
+ auto* bitmap = static_cast<Gfx::Bitmap*>(web_webgl_context_read_back_drawing_buffer(this, rect.x(), rect.y(), rect.width(), rect.height()));
+ if (!bitmap)
+ return nullptr;
+ return adopt_ref(*bitmap);
}
void WebGLRenderingContextBase::lose_context_from_compositor_loss()
{
- if (m_context_lost)
+ if (!web_webgl_context_mark_lost(this))
return;
- m_context_lost = true;
- context().set_lost();
- // The next getError() must report CONTEXT_LOST_WEBGL (one-shot) per the spec.
- m_error = CONTEXT_LOST_WEBGL;
-
- HTML::queue_a_task(HTML::Task::Source::WebGL, nullptr, nullptr, GC::create_function(heap(), [this] {
+ HTML::queue_a_task(HTML::Task::Source::WebGL, nullptr, nullptr, GC::create_function(GC::Heap::the(), [this] {
// webglcontextlost is cancelable; preventDefault() means the page wants the context
// restored once a compositor is available again.
- m_context_restore_requested = !fire_webgl_context_event(canvas_host(), EventNames::webglcontextlost);
+ web_webgl_context_set_restore_requested(this, !fire_webgl_context_event(canvas_host(), EventNames::webglcontextlost));
}));
}
void WebGLRenderingContextBase::restore_context_after_compositor_reconnect()
{
- if (!m_context_lost || !m_context_restore_requested)
+ if (!web_webgl_context_wants_restoring(this))
return;
// A fresh host context starts with no GL objects; per the spec the page re-creates them
// in its webglcontextrestored handler.
- if (!reestablish_remote_context())
+ RustContextAttributes actual_context_parameters;
+ web_webgl_context_actual_context_parameters(this, &actual_context_parameters);
+ auto webgl_version = web_webgl_context_is_webgl2(this) ? WebGLVersion::WebGL2 : WebGLVersion::WebGL1;
+ auto remote = create_remote_webgl_context(canvas_host(), webgl_version, actual_context_parameters.depth, actual_context_parameters.stencil, actual_context_parameters.antialias);
+ if (!remote.has_value())
return;
- reset_context_state_after_loss();
- m_context_lost = false;
- m_context_restore_requested = false;
- m_error = GL_NO_ERROR;
+ auto supported_extensions = remote->supported_extension_spans();
+ web_webgl_context_restore(this, &remote->transport.leak_ref(), supported_extensions.data(), supported_extensions.size());
- HTML::queue_a_task(HTML::Task::Source::WebGL, nullptr, nullptr, GC::create_function(heap(), [this] {
+ HTML::queue_a_task(HTML::Task::Source::WebGL, nullptr, nullptr, GC::create_function(GC::Heap::the(), [this] {
fire_webgl_context_event(canvas_host(), EventNames::webglcontextrestored);
}));
}
-void WebGLRenderingContextBase::reset_context_state_after_loss()
+bool WebGLRenderingContextBase::xr_compatible() const
+{
+ return web_webgl_context_xr_compatible(cell_of(*this));
+}
+
+void WebGLRenderingContextBase::set_xr_compatible(bool xr_compatible)
{
- ++m_context_generation;
- m_unpack_state = {};
- m_unpack_flip_y = false;
- m_unpack_premultiply_alpha = false;
- m_unpack_colorspace_conversion = BROWSER_DEFAULT_WEBGL;
- reset_client_side_webgl_state();
+ web_webgl_context_set_xr_compatible(this, xr_compatible);
}
// https://immersive-web.github.io/webxr/#dom-webglrenderingcontextbase-makexrcompatible
@@ -405,7 +378,7 @@ GC::Ref<WebIDL::Promise> WebGLRenderingContextBase::make_xr_compatible()
// FIXME: Implement this.
// 2. Let promise be a new Promise created in the Realm of this WebGLRenderingContextBase.
- auto& realm = this->realm();
+ auto& realm = *static_cast<JS::Realm*>(web_webgl_context_realm(this));
auto promise = WebIDL::create_promise_for(canvas_host().canvas_relevant_global_object());
// 3. Let context be this.
@@ -470,4 +443,118 @@ GC::Ref<WebIDL::Promise> WebGLRenderingContextBase::make_xr_compatible()
return promise;
}
+void web_webgl_canvas_did_change_content(void* canvas_host)
+{
+ static_cast<HTML::CanvasHost*>(canvas_host)->did_change_canvas_content();
+}
+
+void web_webgl_canvas_bitmap_size(void* canvas_host, i32* out_width, i32* out_height)
+{
+ auto size = static_cast<HTML::CanvasHost*>(canvas_host)->bitmap_size_for_canvas();
+ *out_width = size.width();
+ *out_height = size.height();
+}
+
+void* web_webgl_canvas_wrapper(void* canvas, bool canvas_is_offscreen, void* realm_pointer)
+{
+ auto& realm = *static_cast<JS::Realm*>(realm_pointer);
+ auto& wrapper_world = Bindings::host_defined_wrapper_world(realm);
+ auto* cell = static_cast<GC::Cell*>(canvas);
+ if (canvas_is_offscreen)
+ return Bindings::wrap(wrapper_world, realm, GC::Ref { *static_cast<HTML::OffscreenCanvas*>(cell) }).ptr();
+ return Bindings::wrap(wrapper_world, realm, GC::Ref { *static_cast<HTML::HTMLCanvasElement*>(cell) }).ptr();
+}
+
+void* web_webgl_canvas_relevant_realm(void* canvas_host)
+{
+ return &static_cast<HTML::CanvasHost*>(canvas_host)->canvas_relevant_global_object().shape().realm();
+}
+
+bool web_webgl_expose_experimental_interfaces()
+{
+ return HTML::WindowOrWorkerGlobalScopeMixin::expose_experimental_interfaces();
+}
+
+bool web_webgl_is_valid_2d_pixel_unpack_state(i32 width, PixelUnpackState const* unpack_state)
+{
+ return is_valid_2d_pixel_unpack_state(width, *unpack_state);
+}
+
+bool web_webgl_required_2d_texture_data_size(i32 width, i32 height, u32 format, u32 type, PixelUnpackState const* unpack_state, size_t* out_size)
+{
+ auto size = required_2d_texture_data_size(width, height, format, type, *unpack_state);
+ if (!size.has_value())
+ return false;
+ *out_size = *size;
+ return true;
+}
+
+TexImageSourceResult web_webgl_read_tex_image_source(void* source_wrapper, TexImageSourceKind source_kind, u32 format, u32 type, void** out_frame)
+{
+ // FIXME: If this function is called with an ImageData whose data attribute has been neutered,
+ // an INVALID_VALUE error is generated.
+ // FIXME: If this function is called with an ImageBitmap that has been neutered, an INVALID_VALUE
+ // error is generated.
+ // FIXME: If this function is called with an HTMLImageElement or HTMLVideoElement whose origin
+ // differs from the origin of the containing Document, or with an HTMLCanvasElement,
+ // ImageBitmap or OffscreenCanvas whose bitmap's origin-clean flag is set to false,
+ // a SECURITY_ERR exception must be thrown. See Origin Restrictions.
+ // FIXME: If source is null then an INVALID_VALUE error is generated.
+ auto& wrapper = *static_cast<JS::Object*>(source_wrapper);
+ Optional<Gfx::DecodedImageFrame> frame;
+ switch (source_kind) {
+ case TexImageSourceKind::HTMLImageElement:
+ frame = Bindings::impl_from<HTML::HTMLImageElement>(wrapper).current_image_frame();
+ break;
+ case TexImageSourceKind::HTMLCanvasElement:
+ if (auto bitmap = Bindings::impl_from<HTML::HTMLCanvasElement>(wrapper).get_bitmap_from_surface())
+ frame = Gfx::DecodedImageFrame { *bitmap };
+ break;
+ case TexImageSourceKind::OffscreenCanvas:
+ if (auto bitmap = Bindings::impl_from<HTML::OffscreenCanvas>(wrapper).get_bitmap_from_surface())
+ frame = Gfx::DecodedImageFrame { *bitmap };
+ break;
+ case TexImageSourceKind::HTMLVideoElement:
+ frame = Bindings::impl_from<HTML::HTMLVideoElement>(wrapper).current_decoded_image_frame();
+ break;
+ case TexImageSourceKind::ImageBitmap:
+ frame = Gfx::DecodedImageFrame { *Bindings::impl_from<HTML::ImageBitmap>(wrapper).bitmap() };
+ break;
+ case TexImageSourceKind::ImageData: {
+ // ImageData keeps a cached bitmap for ordinary use, but its data
+ // attribute can be detached independently. WebGL must reject that
+ // source instead of uploading the stale cached pixels.
+ auto& source = Bindings::impl_from<HTML::ImageData>(wrapper);
+ auto data = source.data();
+ if (!data)
+ return TexImageSourceResult::NoFrame;
+ auto data_record = JS::make_typed_array_with_buffer_witness_record(*data, JS::ArrayBuffer::Order::SeqCst);
+ if (JS::is_typed_array_out_of_bounds(data_record))
+ return TexImageSourceResult::InvalidValue;
+ auto bitmap = source.bitmap();
+ if (bitmap.is_error())
+ return TexImageSourceResult::InvalidValue;
+ NonnullRefPtr<Gfx::Bitmap const> bitmap_ref = bitmap.release_value();
+ frame = Gfx::DecodedImageFrame { move(bitmap_ref) };
+ break;
+ }
+ }
+ if (!frame.has_value())
+ return TexImageSourceResult::NoFrame;
+
+ // Validate the combination before recording; the pixels travel to the host as shared
+ // memory and the host performs the conversion next to GL.
+ if (!texture_export_format(format, type).has_value())
+ return TexImageSourceResult::NoFrame;
+
+ // FIXME: Respect unpackColorSpace
+ *out_frame = new Gfx::DecodedImageFrame(frame.release_value());
+ return TexImageSourceResult::Frame;
+}
+
+void* web_webgl_make_xr_compatible(void* context)
+{
+ return static_cast<WebGLRenderingContextBase*>(context)->make_xr_compatible()->promise().ptr();
+}
+
}
diff --git a/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.h b/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.h
index 4eccb1de74c..42bfc55f7f0 100644
--- a/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.h
+++ b/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.h
@@ -6,61 +6,40 @@
#pragma once
-#include <AK/ByteBuffer.h>
-#include <AK/Checked.h>
-#include <AK/Utf16String.h>
-#include <AK/Utf16View.h>
-#include <LibGfx/DecodedImageFrame.h>
-#include <LibJS/Runtime/DataView.h>
-#include <LibJS/Runtime/TypedArray.h>
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/Bindings/WrapperWorld.h>
+#include <AK/Optional.h>
+#include <AK/RefPtr.h>
+#include <AK/Variant.h>
+#include <LibCompositing/DisplayList/DisplayListResourceIds.h>
+#include <LibGC/Ptr.h>
+#include <LibGfx/Forward.h>
+#include <LibGfx/Rect.h>
+#include <LibGfx/Size.h>
+#include <LibJS/Forward.h>
+#include <LibJS/Runtime/Completion.h>
+#include <LibWeb/Bindings/RustInterface.h>
+#include <LibWeb/Export.h>
#include <LibWeb/Forward.h>
#include <LibWeb/WebGL/Types.h>
-#include <LibWeb/WebIDL/Buffers.h>
-#include <LibWebCommon/WebIDL/Types.h>
-
-#define SET_ERROR_VALUE_IF_ERROR(expression, error_value) \
- ({ \
- auto maybe_error = expression; \
- if (maybe_error.is_error()) [[unlikely]] { \
- set_error(error_value); \
- return; \
- } \
- maybe_error.release_value(); \
- })
namespace Web::WebGL {
-static constexpr int COMPRESSED_TEXTURE_FORMATS = 0x86A3;
-static constexpr int UNPACK_FLIP_Y_WEBGL = 0x9240;
-static constexpr int UNPACK_PREMULTIPLY_ALPHA_WEBGL = 0x9241;
-static constexpr int UNPACK_COLORSPACE_CONVERSION_WEBGL = 0x9243;
-static constexpr int BROWSER_DEFAULT_WEBGL = 0x9244;
-static constexpr int MAX_CLIENT_WAIT_TIMEOUT_WEBGL = 0x9247;
-
-// NOTE: This is the Variant created by the IDL wrapper generator, and needs to be updated accordingly.
-using TexImageSource = Variant<GC::Ref<HTML::ImageBitmap>, GC::Ref<HTML::ImageData>, GC::Ref<HTML::HTMLImageElement>, GC::Ref<HTML::HTMLCanvasElement>, GC::Ref<HTML::OffscreenCanvas>, GC::Ref<HTML::HTMLVideoElement>>;
-
using CanvasOwner = Variant<GC::Ref<HTML::HTMLCanvasElement>, GC::Ref<HTML::OffscreenCanvas>>;
HTML::CanvasHost& canvas_host_for(CanvasOwner const&);
-class WebGLRenderingContextBase : public Bindings::GCAllocatedWrappable {
- WEB_NON_IDL_WRAPPABLE(WebGLRenderingContextBase, Bindings::GCAllocatedWrappable);
-
+// The C++ side of a WebGLRenderingContext or a WebGL2RenderingContext, which are implemented in Rust
+// (Libraries/LibWeb/Bindings/Rust/src/web_gl): what the rest of LibWeb calls, and what the Rust code calls back.
+class WEB_API WebGLRenderingContextBase : public Bindings::RustInterfaceCell {
public:
- using Float32List = Variant<GC::Ref<JS::Float32Array>, Vector<float>>;
- using Int32List = Variant<GC::Ref<JS::Int32Array>, Vector<WebIDL::Long>>;
- using Uint32List = Variant<GC::Ref<JS::Uint32Array>, Vector<WebIDL::UnsignedLong>>;
-
- virtual WebGLContextProxy& context() = 0;
- virtual CanvasOwner canvas_for_binding() const = 0;
- HTML::CanvasHost& canvas_host() const { return canvas_host_for(canvas_for_binding()); }
-
- u64 context_generation() const { return m_context_generation; }
- JS::Realm& realm() const { return *m_realm; }
+ HTML::CanvasHost& canvas_host() const;
bool is_context_lost() const;
+ Optional<Compositing::CanvasId> canvas_id() const;
+
+ void set_size(Gfx::IntSize const&);
+ void reset_to_default_state() { }
+ void prepare_for_compositing();
+ void clear_drawing_buffer();
+ RefPtr<Gfx::Bitmap> read_back_drawing_buffer(Gfx::IntRect const&);
// https://registry.khronos.org/webgl/specs/latest/1.0/#CONTEXT_LOST
// The compositor process (and with it the GL state) went away: set the context lost
@@ -72,287 +51,14 @@ public:
// page can re-create its now-lost GL resources.
void restore_context_after_compositor_reconnect();
- bool xr_compatible() const { return m_xr_compatible; }
- void set_xr_compatible(bool xr_compatible) { m_xr_compatible = xr_compatible; }
+ bool xr_compatible() const;
+ void set_xr_compatible(bool);
// https://immersive-web.github.io/webxr/#dom-webglrenderingcontextbase-makexrcompatible
GC::Ref<WebIDL::Promise> make_xr_compatible();
- Optional<Vector<Utf16String>> get_supported_extensions();
- GC::Ptr<JS::Object> get_extension(JS::Realm&, Utf16String const& name);
-
- void enable_compressed_texture_format(WebIDL::UnsignedLong format);
-
- // Holds a WebGLVertexArrayObject for WebGL2 contexts, or a WebGLVertexArrayObjectOES for WebGL1 contexts with the
- // OES_vertex_array_object extension enabled.
- GC::Ptr<WebGLObject> current_vertex_array_binding() const { return m_current_vertex_array; }
- void set_current_vertex_array_binding(GC::Ptr<WebGLObject> vertex_array) { m_current_vertex_array = vertex_array; }
-
protected:
- WebGLRenderingContextBase(JS::Realm&);
-
- virtual void visit_edges(Cell::Visitor&) override;
- virtual GC::Ptr<Bindings::Wrappable> relevant_global_impl() const override;
-
- // Builds a fresh transport and host context against the reconnected compositor and
- // rebinds the proxy to it. Returns false if no compositor is available. WebGL1/2
- // implement it because they own the version and the actual context parameters.
- virtual bool reestablish_remote_context() = 0;
- virtual void reset_client_side_webgl_state() = 0;
-
- // FIXME: Make this and any another instance of extension names a FlyString, similarly to HTML::TagNames
- bool extension_enabled(StringView extension) const;
- ReadonlySpan<WebIDL::UnsignedLong> enabled_compressed_texture_formats() const;
-
- ErrorOr<ReadonlyBytes> texture_data_for_2d_upload(ReadonlyBytes, GLsizei width, GLsizei height, GLenum format, GLenum type) const;
-
- template<typename T>
- static ErrorOr<Span<T>> get_offset_span(Span<T> src_span, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length_override = 0)
- {
- Checked<WebIDL::UnsignedLongLong> length = src_offset;
- length += src_length_override;
- if (length.has_overflow() || length.value_unchecked() > src_span.size()) [[unlikely]]
- return Error::from_errno(EINVAL);
-
- if (src_length_override == 0)
- return src_span.slice(src_offset, src_span.size() - src_offset);
-
- return src_span.slice(src_offset, src_length_override);
- }
-
- // The callback's view may point straight into the JS heap: it must not escape the
- // callback, run script, or allocate on the JS heap while held.
- template<typename Callback>
- static ErrorOr<void> with_buffer_source_bytes(WebIDL::BufferSource src_data, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length_override, Callback&& callback)
- {
- auto invoke_callback = [&](ReadonlyBytes bytes) -> ErrorOr<void> {
- if constexpr (IsSame<decltype(callback(bytes)), void>) {
- callback(bytes);
- return {};
- } else {
- return callback(bytes);
- }
- };
-
- auto array_buffer = src_data.viewed_array_buffer();
- if (!array_buffer || array_buffer->is_detached()) [[unlikely]]
- return Error::from_errno(EINVAL);
-
- if (src_data.is_out_of_bounds()) {
- if (src_offset != 0 || src_length_override != 0) [[unlikely]]
- return Error::from_errno(EINVAL);
- return invoke_callback({});
- }
-
- auto element_size = src_data.element_size();
- Checked<size_t> byte_offset_in_view = static_cast<size_t>(src_offset);
- byte_offset_in_view *= element_size;
- if (byte_offset_in_view.has_overflow() || byte_offset_in_view.value() > src_data.byte_length()) [[unlikely]]
- return Error::from_errno(EINVAL);
-
- auto byte_length = src_data.byte_length() - byte_offset_in_view.value();
- if (src_length_override != 0) {
- Checked<size_t> requested_byte_length = static_cast<size_t>(src_length_override);
- requested_byte_length *= element_size;
- if (requested_byte_length.has_overflow() || requested_byte_length.value() > byte_length) [[unlikely]]
- return Error::from_errno(EINVAL);
- byte_length = requested_byte_length.value();
- }
-
- Checked<size_t> byte_offset_in_buffer = src_data.byte_offset();
- byte_offset_in_buffer += byte_offset_in_view.value();
- if (byte_offset_in_buffer.has_overflow()) [[unlikely]]
- return Error::from_errno(EINVAL);
-
- if (byte_offset_in_buffer.value() > array_buffer->byte_length()) [[unlikely]]
- return Error::from_errno(EINVAL);
- if (byte_length > array_buffer->byte_length() - byte_offset_in_buffer.value()) [[unlikely]]
- return Error::from_errno(EINVAL);
-
- return array_buffer->with_readonly_bytes(byte_offset_in_buffer.value(), byte_length, invoke_callback);
- }
-
- template<typename T>
- class SpanWithStorage {
- public:
- explicit SpanWithStorage(Span<T> span)
- : m_span(span)
- {
- }
-
- explicit SpanWithStorage(ByteBuffer storage)
- : m_storage(move(storage))
- , m_has_storage(true)
- , m_span(m_storage.bytes().template reinterpret<T>())
- {
- }
-
- SpanWithStorage(SpanWithStorage const&) = delete;
- SpanWithStorage& operator=(SpanWithStorage const&) = delete;
-
- SpanWithStorage(SpanWithStorage&& other)
- : m_storage(move(other.m_storage))
- , m_has_storage(exchange(other.m_has_storage, false))
- , m_span(m_has_storage ? m_storage.bytes().template reinterpret<T>() : other.m_span)
- {
- }
-
- SpanWithStorage& operator=(SpanWithStorage&& other)
- {
- if (this != &other) {
- m_storage = move(other.m_storage);
- m_has_storage = exchange(other.m_has_storage, false);
- m_span = m_has_storage ? m_storage.bytes().template reinterpret<T>() : other.m_span;
- }
- return *this;
- }
-
- size_t size() const { return m_span.size(); }
- T* data() { return m_span.data(); }
- T const* data() const { return m_span.data(); }
-
- private:
- ByteBuffer m_storage;
- bool m_has_storage { false };
- Span<T> m_span;
- };
-
- template<typename T>
- static ErrorOr<SpanWithStorage<T>> span_from_typed_array(JS::TypedArrayBase& typed_array, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length_override = 0)
- {
- auto record = JS::make_typed_array_with_buffer_witness_record(typed_array, JS::ArrayBuffer::Order::SeqCst);
- if (JS::is_typed_array_out_of_bounds(record)) [[unlikely]] {
- if (src_offset == 0 && src_length_override == 0)
- return SpanWithStorage<T> { Span<T> {} };
- return Error::from_errno(EINVAL);
- }
-
- auto length = JS::typed_array_length(record);
- Checked<size_t> end = static_cast<size_t>(src_offset);
- end += src_length_override;
- if (end.has_overflow() || end.value() > length) [[unlikely]]
- return Error::from_errno(EINVAL);
-
- auto elements_to_copy = src_length_override == 0 ? length - static_cast<size_t>(src_offset) : static_cast<size_t>(src_length_override);
- Checked<size_t> byte_offset = static_cast<size_t>(src_offset);
- byte_offset *= sizeof(T);
- byte_offset += typed_array.byte_offset();
-
- Checked<size_t> byte_length = elements_to_copy;
- byte_length *= sizeof(T);
- if (byte_offset.has_overflow() || byte_length.has_overflow()) [[unlikely]]
- return Error::from_errno(EINVAL);
-
- auto bytes = TRY(typed_array.viewed_array_buffer()->copy_to_byte_buffer(byte_offset.value(), byte_length.value()));
- return SpanWithStorage<T> { move(bytes) };
- }
-
- static ErrorOr<SpanWithStorage<float>> span_from_float32_list(Float32List& float32_list, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length_override = 0)
- {
- if (float32_list.has<Vector<float>>()) {
- auto& vector = float32_list.get<Vector<float>>();
- return SpanWithStorage<float> { TRY(get_offset_span(vector.span(), src_offset, src_length_override)) };
- }
- auto& buffer = float32_list.get<GC::Ref<JS::Float32Array>>();
- return span_from_typed_array<float>(*buffer, src_offset, src_length_override);
- }
-
- static ErrorOr<SpanWithStorage<int>> span_from_int32_list(Int32List& int32_list, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length_override = 0)
- {
- if (int32_list.has<Vector<int>>()) {
- auto& vector = int32_list.get<Vector<int>>();
- return SpanWithStorage<int> { TRY(get_offset_span(vector.span(), src_offset, src_length_override)) };
- }
- auto& buffer = int32_list.get<GC::Ref<JS::Int32Array>>();
- return span_from_typed_array<int>(*buffer, src_offset, src_length_override);
- }
-
- static ErrorOr<SpanWithStorage<u32>> span_from_uint32_list(Uint32List& uint32_list, WebIDL::UnsignedLongLong src_offset, WebIDL::UnsignedLong src_length_override = 0)
- {
- if (uint32_list.has<Vector<u32>>()) {
- auto& vector = uint32_list.get<Vector<u32>>();
- return SpanWithStorage<u32> { TRY(get_offset_span(vector.span(), src_offset, src_length_override)) };
- }
- auto& buffer = uint32_list.get<GC::Ref<JS::Uint32Array>>();
- return span_from_typed_array<u32>(*buffer, src_offset, src_length_override);
- }
-
- struct TexImageSourceFrame {
- Gfx::DecodedImageFrame frame;
- bool flip_y { false };
- bool premultiply_alpha { false };
- };
- Optional<TexImageSourceFrame> read_texture_image_source(TexImageSource const& source, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type);
-
- static Vector<GLchar> null_terminated_string(StringView string)
- {
- Vector<GLchar> result;
- result.ensure_capacity(string.length() + 1);
- for (auto c : string.bytes())
- result.append(c);
- result.append('\0');
- return result;
- }
-
- static Vector<GLchar> null_terminated_utf8_string(Utf16View string)
- {
- auto utf8_string = MUST(string.to_utf8());
- return null_terminated_string(utf8_string.bytes_as_string_view());
- }
-
- static Utf16String utf16_string_from_gl_string(void const* data, size_t length)
- {
- return Utf16String::from_utf8_without_validation({ reinterpret_cast<char const*>(data), length });
- }
-
- GLenum get_error_value();
- void set_error(GLenum error);
- void reset_context_state_after_loss();
-
- PixelUnpackState m_unpack_state;
-
- // UNPACK_FLIP_Y_WEBGL of type boolean
- // If set, then during any subsequent calls to texImage2D or texSubImage2D, the source data is flipped along
- // the vertical axis, so that conceptually the last row is the first one transferred. The initial value is false.
- // Any non-zero value is interpreted as true.
- bool m_unpack_flip_y { false };
-
- // UNPACK_PREMULTIPLY_ALPHA_WEBGL of type boolean
- // If set, then during any subsequent calls to texImage2D or texSubImage2D, the alpha channel of the source data,
- // if present, is multiplied into the color channels during the data transfer. The initial value is false.
- // Any non-zero value is interpreted as true.
- bool m_unpack_premultiply_alpha { false };
-
- // UNPACK_COLORSPACE_CONVERSION_WEBGL of type unsigned long
- // If set to BROWSER_DEFAULT_WEBGL, then the browser's default colorspace conversion (e.g. converting a display-p3
- // image to srgb) is applied during subsequent texture data upload calls (e.g. texImage2D and texSubImage2D) that
- // take an argument of TexImageSource. The precise conversions may be specific to both the browser and file type.
- // If set to NONE, no colorspace conversion is applied, other than conversion to RGBA. (For example, a rec709 YUV
- // video is still converted to rec709 RGB data, but not then converted to e.g. srgb RGB data) The initial value is
- // BROWSER_DEFAULT_WEBGL.
- GLenum m_unpack_colorspace_conversion { BROWSER_DEFAULT_WEBGL };
-
- GC::Ptr<WebGLObject> m_current_vertex_array;
-
-private:
- GLenum m_error { 0 };
-
- // https://registry.khronos.org/webgl/specs/latest/2.0/#webgl-context-lost-flag
- // Each WebGLRenderingContext and WebGL2RenderingContext has a webgl context lost flag, which is initially unset.
- bool m_context_lost { false };
- bool m_context_restore_requested { false };
-
- // https://immersive-web.github.io/webxr/#xr-compatible
- bool m_xr_compatible { false };
- u64 m_context_generation { 0 };
-
- Vector<WebIDL::UnsignedLong> m_enabled_compressed_texture_formats;
- GC::Ref<JS::Realm> m_realm;
-
- // Extensions
- // "Multiple calls to getExtension with the same extension string, taking into account case-insensitive comparison, must return the same object as long as the extension is enabled."
- HashMap<String, GC::Ref<Bindings::Wrappable>, AK::ASCIICaseInsensitiveStringTraits> m_enabled_extensions;
- HashMap<String, OwnPtr<Bindings::WrapperWorldWeakValueCache<JS::Object>>, AK::ASCIICaseInsensitiveStringTraits> m_enabled_empty_extensions;
+ static JS::ThrowCompletionOr<WebGLRenderingContextBase*> create(JS::Realm&, CanvasOwner, JS::Value options, WebGLVersion);
};
}
diff --git a/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.idl b/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.idl
index b8b9dd90b53..ff34cf7e2c8 100644
--- a/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.idl
+++ b/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.idl
@@ -20,7 +20,7 @@ interface mixin WebGLRenderingContextBase {
// IDL code generator. This also allows us to handle the return type ourselves instead of adding the complexity of the
// code generator working out the return type and returning the appropriate value to return on context loss.
- [ImplementedAs=canvas_for_binding] readonly attribute (HTMLCanvasElement or OffscreenCanvas) canvas;
+ readonly attribute (HTMLCanvasElement or OffscreenCanvas) canvas;
readonly attribute GLsizei drawingBufferWidth;
readonly attribute GLsizei drawingBufferHeight;
[FIXME] readonly attribute GLenum drawingBufferFormat;
diff --git a/Libraries/LibWeb/WebGL/WebGLRenderingContextImpl.cpp b/Libraries/LibWeb/WebGL/WebGLRenderingContextImpl.cpp
deleted file mode 100644
index c41305fa6c8..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLRenderingContextImpl.cpp
+++ /dev/null
@@ -1,2624 +0,0 @@
-/*
- * Copyright (c) 2024-2025, Aliaksandr Kalenik <[email protected]>
- * Copyright (c) 2024-2025, Luke Wilde <[email protected]>
- * Copyright (c) 2025, Undefine <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <GLES3/gl3.h>
-extern "C" {
-#include <GLES2/gl2ext.h>
-#include <GLES2/gl2ext_angle.h>
-}
-
-#include <AK/StringView.h>
-#include <AK/Utf16String.h>
-#include <LibJS/Runtime/Array.h>
-#include <LibJS/Runtime/ArrayBuffer.h>
-#include <LibJS/Runtime/DataView.h>
-#include <LibJS/Runtime/TypedArray.h>
-#include <LibWeb/Bindings/WrapperWorld.h>
-#include <LibWeb/WebGL/WebGLActiveInfo.h>
-#include <LibWeb/WebGL/WebGLBuffer.h>
-#include <LibWeb/WebGL/WebGLContextProxy.h>
-#include <LibWeb/WebGL/WebGLFramebuffer.h>
-#include <LibWeb/WebGL/WebGLProgram.h>
-#include <LibWeb/WebGL/WebGLQuery.h>
-#include <LibWeb/WebGL/WebGLRenderbuffer.h>
-#include <LibWeb/WebGL/WebGLRenderingContextImpl.h>
-#include <LibWeb/WebGL/WebGLSampler.h>
-#include <LibWeb/WebGL/WebGLShader.h>
-#include <LibWeb/WebGL/WebGLShaderPrecisionFormat.h>
-#include <LibWeb/WebGL/WebGLSync.h>
-#include <LibWeb/WebGL/WebGLTexture.h>
-#include <LibWeb/WebGL/WebGLTransformFeedback.h>
-#include <LibWeb/WebGL/WebGLUniformLocation.h>
-#include <LibWeb/WebGL/WebGLVertexArrayObject.h>
-#include <LibWeb/WebIDL/Buffers.h>
-
-namespace Web::WebGL {
-
-// https://registry.khronos.org/webgl/extensions/WEBGL_debug_renderer_info/
-static constexpr GLenum UNMASKED_VENDOR_WEBGL = 0x9245;
-static constexpr GLenum UNMASKED_RENDERER_WEBGL = 0x9246;
-
-static bool is_valid_framebuffer_binding_target(WebGLVersion version, GLenum target)
-{
- if (target == GL_FRAMEBUFFER)
- return true;
- if (version == WebGLVersion::WebGL2 && (target == GL_READ_FRAMEBUFFER || target == GL_DRAW_FRAMEBUFFER))
- return true;
- return false;
-}
-
-static bool is_valid_framebuffer_attachment(WebGLVersion version, bool draw_buffers_extension_enabled, GLenum attachment)
-{
- switch (attachment) {
- case GL_COLOR_ATTACHMENT0:
- case GL_DEPTH_ATTACHMENT:
- case GL_STENCIL_ATTACHMENT:
- case GL_DEPTH_STENCIL_ATTACHMENT:
- return true;
- default:
- break;
- }
-
- if (version == WebGLVersion::WebGL2 || draw_buffers_extension_enabled)
- return attachment > GL_COLOR_ATTACHMENT0 && attachment <= GL_COLOR_ATTACHMENT0 + 15;
- return false;
-}
-
-static bool is_valid_framebuffer_texture_2d_target(GLenum target)
-{
- switch (target) {
- case GL_TEXTURE_2D:
- case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
- case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
- case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
- case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
- case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
- case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
- return true;
- default:
- return false;
- }
-}
-
-static bool is_cube_map_face(GLenum target)
-{
- return target >= GL_TEXTURE_CUBE_MAP_POSITIVE_X && target <= GL_TEXTURE_CUBE_MAP_NEGATIVE_Z;
-}
-
-WebGLRenderingContextImpl::WebGLRenderingContextImpl(JS::Realm& realm, NonnullOwnPtr<WebGLContextProxy> context)
- : WebGLRenderingContextBase(realm)
- , m_context(move(context))
-{
-}
-
-void WebGLRenderingContextImpl::reset_client_side_webgl_state()
-{
- m_array_buffer_binding = nullptr;
- m_element_array_buffer_binding = nullptr;
- m_current_program = nullptr;
- m_framebuffer_binding = nullptr;
- m_renderbuffer_binding = nullptr;
- m_texture_binding_2d = nullptr;
- m_texture_binding_cube_map = nullptr;
- m_uniform_buffer_binding = nullptr;
- m_copy_read_buffer_binding = nullptr;
- m_copy_write_buffer_binding = nullptr;
- m_transform_feedback_buffer_binding = nullptr;
- m_pixel_pack_buffer_binding = nullptr;
- m_pixel_unpack_buffer_binding = nullptr;
- m_texture_binding_2d_array = nullptr;
- m_texture_binding_3d = nullptr;
- m_transform_feedback_binding = nullptr;
- m_current_vertex_array = nullptr;
- m_any_samples_passed = nullptr;
- m_any_samples_passed_conservative = nullptr;
- m_transform_feedback_primitives_written = nullptr;
-}
-
-void WebGLRenderingContextImpl::active_texture(WebIDL::UnsignedLong texture)
-{
- m_context->make_current();
- m_context->active_texture(texture);
-}
-
-void WebGLRenderingContextImpl::attach_shader(GC::Ref<WebGLProgram> program, GC::Ref<WebGLShader> shader)
-{
- m_context->make_current();
-
- GLuint program_handle = 0;
- auto handle_or_error = program->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- program_handle = handle_or_error.release_value();
-
- handle_or_error = shader->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- GLuint shader_handle = handle_or_error.release_value();
-
- if (program->attached_vertex_shader() == shader || program->attached_fragment_shader() == shader) {
- dbgln("WebGL: Shader is already attached to program");
- set_error(GL_INVALID_OPERATION);
- return;
- }
-
- if (shader->type() == GL_VERTEX_SHADER && program->attached_vertex_shader()) {
- dbgln("WebGL: Not attaching vertex shader to program as it already has a vertex shader attached");
- set_error(GL_INVALID_OPERATION);
- return;
- }
-
- if (shader->type() == GL_FRAGMENT_SHADER && program->attached_fragment_shader()) {
- dbgln("WebGL: Not attaching fragment shader to program as it already has a fragment shader attached");
- set_error(GL_INVALID_OPERATION);
- return;
- }
-
- m_context->attach_shader(program_handle, shader_handle);
-
- switch (shader->type()) {
- case GL_VERTEX_SHADER:
- program->set_attached_vertex_shader(shader.ptr());
- break;
- case GL_FRAGMENT_SHADER:
- program->set_attached_fragment_shader(shader.ptr());
- break;
- default:
- VERIFY_NOT_REACHED();
- }
-}
-
-void WebGLRenderingContextImpl::bind_attrib_location(GC::Ref<WebGLProgram> program, WebIDL::UnsignedLong index, Utf16String name)
-{
- m_context->make_current();
-
- auto handle_or_error = program->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- auto program_handle = handle_or_error.release_value();
-
- auto name_null_terminated = null_terminated_utf8_string(name.utf16_view());
- m_context->bind_attrib_location(program_handle, index, name_null_terminated.data());
-}
-
-void WebGLRenderingContextImpl::bind_buffer(WebIDL::UnsignedLong target, GC::Ptr<WebGLBuffer> buffer)
-{
- m_context->make_current();
-
- GLuint buffer_handle = 0;
- if (buffer) {
- auto handle_or_error = buffer->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- buffer_handle = handle_or_error.release_value();
-
- if (!buffer->is_compatible_with(target)) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- }
-
- if (m_context->webgl_version() == WebGLVersion::WebGL2) {
- switch (target) {
- case GL_ARRAY_BUFFER:
- m_array_buffer_binding = buffer;
- break;
- case GL_COPY_READ_BUFFER:
- m_copy_read_buffer_binding = buffer;
- break;
- case GL_COPY_WRITE_BUFFER:
- m_copy_write_buffer_binding = buffer;
- break;
- case GL_ELEMENT_ARRAY_BUFFER:
- m_element_array_buffer_binding = buffer;
- break;
- case GL_PIXEL_PACK_BUFFER:
- m_pixel_pack_buffer_binding = buffer;
- break;
- case GL_PIXEL_UNPACK_BUFFER:
- m_pixel_unpack_buffer_binding = buffer;
- break;
- case GL_TRANSFORM_FEEDBACK_BUFFER:
- m_transform_feedback_buffer_binding = buffer;
- break;
- case GL_UNIFORM_BUFFER:
- m_uniform_buffer_binding = buffer;
- break;
- default:
- dbgln("Unknown WebGL buffer object binding target for storing current binding: 0x{:04x}", target);
- set_error(GL_INVALID_ENUM);
- return;
- }
- } else {
- switch (target) {
- case GL_ELEMENT_ARRAY_BUFFER:
- m_element_array_buffer_binding = buffer;
- break;
- case GL_ARRAY_BUFFER:
- m_array_buffer_binding = buffer;
- break;
- default:
- dbgln("Unknown WebGL buffer object binding target for storing current binding: 0x{:04x}", target);
- set_error(GL_INVALID_ENUM);
- return;
- }
- }
-
- m_context->bind_buffer(target, buffer_handle);
-}
-
-void WebGLRenderingContextImpl::bind_framebuffer(WebIDL::UnsignedLong target, GC::Ptr<WebGLFramebuffer> framebuffer)
-{
- m_context->make_current();
-
- GLuint framebuffer_handle = 0;
- if (framebuffer) {
- auto handle_or_error = framebuffer->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- framebuffer_handle = handle_or_error.release_value();
- }
-
- m_context->bind_framebuffer(target, framebuffer ? framebuffer_handle : m_context->default_framebuffer());
- m_framebuffer_binding = framebuffer;
-}
-
-void WebGLRenderingContextImpl::bind_renderbuffer(WebIDL::UnsignedLong target, GC::Ptr<WebGLRenderbuffer> renderbuffer)
-{
- m_context->make_current();
-
- GLuint renderbuffer_handle = 0;
- if (renderbuffer) {
- auto handle_or_error = renderbuffer->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- renderbuffer_handle = handle_or_error.release_value();
- }
-
- m_context->bind_renderbuffer(target, renderbuffer ? renderbuffer_handle : m_context->default_renderbuffer());
- m_renderbuffer_binding = renderbuffer;
-}
-
-void WebGLRenderingContextImpl::bind_texture(WebIDL::UnsignedLong target, GC::Ptr<WebGLTexture> texture)
-{
- m_context->make_current();
-
- GLuint texture_handle = 0;
- if (texture) {
- auto handle_or_error = texture->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- texture_handle = handle_or_error.release_value();
- }
-
- switch (target) {
- case GL_TEXTURE_2D:
- m_texture_binding_2d = texture;
- break;
- case GL_TEXTURE_CUBE_MAP:
- m_texture_binding_cube_map = texture;
- break;
-
- case GL_TEXTURE_2D_ARRAY:
- if (m_context->webgl_version() == WebGLVersion::WebGL2) {
- m_texture_binding_2d_array = texture;
- break;
- }
-
- set_error(GL_INVALID_ENUM);
- return;
- case GL_TEXTURE_3D:
- if (m_context->webgl_version() == WebGLVersion::WebGL2) {
- m_texture_binding_3d = texture;
- break;
- }
-
- set_error(GL_INVALID_ENUM);
- return;
-
- default:
- dbgln("Unknown WebGL texture target for storing current binding: 0x{:04x}", target);
- set_error(GL_INVALID_ENUM);
- return;
- }
- m_context->bind_texture(target, texture_handle);
-}
-
-void WebGLRenderingContextImpl::blend_color(float red, float green, float blue, float alpha)
-{
- m_context->make_current();
- m_context->blend_color(red, green, blue, alpha);
-}
-
-void WebGLRenderingContextImpl::blend_equation(WebIDL::UnsignedLong mode)
-{
- m_context->make_current();
- m_context->blend_equation(mode);
-}
-
-void WebGLRenderingContextImpl::blend_equation_separate(WebIDL::UnsignedLong mode_rgb, WebIDL::UnsignedLong mode_alpha)
-{
- m_context->make_current();
- m_context->blend_equation_separate(mode_rgb, mode_alpha);
-}
-
-void WebGLRenderingContextImpl::blend_func(WebIDL::UnsignedLong sfactor, WebIDL::UnsignedLong dfactor)
-{
- m_context->make_current();
- m_context->blend_func(sfactor, dfactor);
-}
-
-void WebGLRenderingContextImpl::blend_func_separate(WebIDL::UnsignedLong src_rgb, WebIDL::UnsignedLong dst_rgb, WebIDL::UnsignedLong src_alpha, WebIDL::UnsignedLong dst_alpha)
-{
- m_context->make_current();
- m_context->blend_func_separate(src_rgb, dst_rgb, src_alpha, dst_alpha);
-}
-
-WebIDL::UnsignedLong WebGLRenderingContextImpl::check_framebuffer_status(WebIDL::UnsignedLong target)
-{
- m_context->make_current();
- return m_context->check_framebuffer_status(target);
-}
-
-void WebGLRenderingContextImpl::clear(WebIDL::UnsignedLong mask)
-{
- m_context->make_current();
- m_context->notify_content_will_change();
- did_update_canvas_content();
- m_context->clear(mask);
-}
-
-void WebGLRenderingContextImpl::clear_color(float red, float green, float blue, float alpha)
-{
- m_context->make_current();
- m_context->clear_color(red, green, blue, alpha);
-}
-
-void WebGLRenderingContextImpl::clear_depth(float depth)
-{
- m_context->make_current();
- m_context->clear_depthf(depth);
-}
-
-void WebGLRenderingContextImpl::clear_stencil(WebIDL::Long s)
-{
- m_context->make_current();
- m_context->clear_stencil(s);
-}
-
-void WebGLRenderingContextImpl::color_mask(bool red, bool green, bool blue, bool alpha)
-{
- m_context->make_current();
- m_context->color_mask(red, green, blue, alpha);
-}
-
-void WebGLRenderingContextImpl::compile_shader(GC::Ref<WebGLShader> shader)
-{
- m_context->make_current();
-
- auto handle_or_error = shader->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- auto shader_handle = handle_or_error.release_value();
- m_context->compile_shader(shader_handle);
-}
-
-void WebGLRenderingContextImpl::copy_tex_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::UnsignedLong internalformat, WebIDL::Long x, WebIDL::Long y, WebIDL::Long width, WebIDL::Long height, WebIDL::Long border)
-{
- m_context->make_current();
- m_context->copy_tex_image2d(target, level, internalformat, x, y, width, height, border);
-}
-
-void WebGLRenderingContextImpl::copy_tex_sub_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long xoffset, WebIDL::Long yoffset, WebIDL::Long x, WebIDL::Long y, WebIDL::Long width, WebIDL::Long height)
-{
- m_context->make_current();
- m_context->copy_tex_sub_image2d(target, level, xoffset, yoffset, x, y, width, height);
-}
-
-GC::Ref<WebGLBuffer> WebGLRenderingContextImpl::create_buffer()
-{
- m_context->make_current();
-
- GLuint handle = 0;
- m_context->gen_buffers(1, &handle);
- return WebGLBuffer::create(*this, handle);
-}
-
-GC::Ref<WebGLFramebuffer> WebGLRenderingContextImpl::create_framebuffer()
-{
- m_context->make_current();
-
- GLuint handle = 0;
- m_context->gen_framebuffers(1, &handle);
- return WebGLFramebuffer::create(*this, handle);
-}
-
-GC::Ref<WebGLProgram> WebGLRenderingContextImpl::create_program()
-{
- m_context->make_current();
- return WebGLProgram::create(*this, m_context->create_program());
-}
-
-GC::Ref<WebGLRenderbuffer> WebGLRenderingContextImpl::create_renderbuffer()
-{
- m_context->make_current();
-
- GLuint handle = 0;
- m_context->gen_renderbuffers(1, &handle);
- return WebGLRenderbuffer::create(*this, handle);
-}
-
-GC::Ptr<WebGLShader> WebGLRenderingContextImpl::create_shader(WebIDL::UnsignedLong type)
-{
- m_context->make_current();
-
- if (type != GL_VERTEX_SHADER && type != GL_FRAGMENT_SHADER) {
- dbgln("Unknown WebGL shader type: 0x{:04x}", type);
- set_error(GL_INVALID_ENUM);
- return nullptr;
- }
-
- GLuint handle = m_context->create_shader(type);
- return WebGLShader::create(*this, handle, type);
-}
-
-GC::Ref<WebGLTexture> WebGLRenderingContextImpl::create_texture()
-{
- m_context->make_current();
-
- GLuint handle = 0;
- m_context->gen_textures(1, &handle);
- return WebGLTexture::create(*this, handle);
-}
-
-void WebGLRenderingContextImpl::cull_face(WebIDL::UnsignedLong mode)
-{
- m_context->make_current();
- m_context->cull_face(mode);
-}
-
-void WebGLRenderingContextImpl::delete_buffer(GC::Ptr<WebGLBuffer> buffer)
-{
- m_context->make_current();
-
- if (!buffer)
- return;
-
- auto handle_or_error = buffer->handle_for_deletion(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- auto buffer_handle = handle_or_error.release_value();
- if (!buffer_handle.has_value())
- return;
-
- auto handle = buffer_handle.value();
- m_context->delete_buffers(1, &handle);
-}
-
-void WebGLRenderingContextImpl::delete_framebuffer(GC::Ptr<WebGLFramebuffer> framebuffer)
-{
- m_context->make_current();
-
- if (!framebuffer)
- return;
-
- auto handle_or_error = framebuffer->handle_for_deletion(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- auto framebuffer_handle = handle_or_error.release_value();
- if (!framebuffer_handle.has_value())
- return;
-
- auto handle = framebuffer_handle.value();
- m_context->delete_framebuffers(1, &handle);
-
- if (m_framebuffer_binding == framebuffer)
- m_framebuffer_binding = nullptr;
-}
-
-void WebGLRenderingContextImpl::delete_program(GC::Ptr<WebGLProgram> program)
-{
- m_context->make_current();
-
- if (!program)
- return;
-
- auto handle_or_error = program->handle_for_deletion(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- auto program_handle = handle_or_error.release_value();
- if (!program_handle.has_value())
- return;
-
- m_context->delete_program(program_handle.value());
- if (m_current_program == program)
- m_current_program = nullptr;
-}
-
-void WebGLRenderingContextImpl::delete_renderbuffer(GC::Ptr<WebGLRenderbuffer> renderbuffer)
-{
- m_context->make_current();
-
- if (!renderbuffer)
- return;
-
- auto handle_or_error = renderbuffer->handle_for_deletion(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- auto renderbuffer_handle = handle_or_error.release_value();
- if (!renderbuffer_handle.has_value())
- return;
-
- auto handle = renderbuffer_handle.value();
- m_context->delete_renderbuffers(1, &handle);
-}
-
-void WebGLRenderingContextImpl::delete_shader(GC::Ptr<WebGLShader> shader)
-{
- m_context->make_current();
-
- if (!shader)
- return;
-
- auto handle_or_error = shader->handle_for_deletion(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- auto shader_handle = handle_or_error.release_value();
- if (!shader_handle.has_value())
- return;
-
- m_context->delete_shader(shader_handle.value());
-}
-
-void WebGLRenderingContextImpl::delete_texture(GC::Ptr<WebGLTexture> texture)
-{
- m_context->make_current();
-
- if (!texture)
- return;
-
- auto handle_or_error = texture->handle_for_deletion(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- auto texture_handle = handle_or_error.release_value();
- if (!texture_handle.has_value())
- return;
-
- auto handle = texture_handle.value();
- m_context->delete_textures(1, &handle);
-
- if (m_texture_binding_2d == texture)
- m_texture_binding_2d = nullptr;
- if (m_texture_binding_cube_map == texture)
- m_texture_binding_cube_map = nullptr;
- if (m_texture_binding_2d_array == texture)
- m_texture_binding_2d_array = nullptr;
- if (m_texture_binding_3d == texture)
- m_texture_binding_3d = nullptr;
-}
-
-void WebGLRenderingContextImpl::depth_func(WebIDL::UnsignedLong func)
-{
- m_context->make_current();
- m_context->depth_func(func);
-}
-
-void WebGLRenderingContextImpl::depth_mask(bool flag)
-{
- m_context->make_current();
- m_context->depth_mask(flag);
-}
-
-void WebGLRenderingContextImpl::depth_range(float z_near, float z_far)
-{
- m_context->make_current();
- m_context->depth_rangef(z_near, z_far);
-}
-
-void WebGLRenderingContextImpl::detach_shader(GC::Ref<WebGLProgram> program, GC::Ref<WebGLShader> shader)
-{
- m_context->make_current();
-
- auto handle_or_error = program->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- auto program_handle = handle_or_error.release_value();
-
- handle_or_error = shader->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- auto shader_handle = handle_or_error.release_value();
-
- m_context->detach_shader(program_handle, shader_handle);
-
- switch (shader->type()) {
- case GL_VERTEX_SHADER:
- program->set_attached_vertex_shader(nullptr);
- break;
- case GL_FRAGMENT_SHADER:
- program->set_attached_fragment_shader(nullptr);
- break;
- }
-}
-
-void WebGLRenderingContextImpl::disable(WebIDL::UnsignedLong cap)
-{
- m_context->make_current();
- m_context->disable(cap);
-}
-
-void WebGLRenderingContextImpl::disable_vertex_attrib_array(WebIDL::UnsignedLong index)
-{
- m_context->make_current();
- m_context->disable_vertex_attrib_array(index);
-}
-
-void WebGLRenderingContextImpl::draw_arrays(WebIDL::UnsignedLong mode, WebIDL::Long first, WebIDL::Long count)
-{
- m_context->make_current();
- m_context->notify_content_will_change();
- did_update_canvas_content();
- m_context->draw_arrays(mode, first, count);
-}
-
-void WebGLRenderingContextImpl::draw_elements(WebIDL::UnsignedLong mode, WebIDL::Long count, WebIDL::UnsignedLong type, WebIDL::LongLong offset)
-{
- m_context->make_current();
- m_context->notify_content_will_change();
-
- m_context->draw_elements(mode, count, type, reinterpret_cast<void*>(offset));
- did_update_canvas_content();
-}
-
-void WebGLRenderingContextImpl::enable(WebIDL::UnsignedLong cap)
-{
- m_context->make_current();
- m_context->enable(cap);
-}
-
-void WebGLRenderingContextImpl::enable_vertex_attrib_array(WebIDL::UnsignedLong index)
-{
- m_context->make_current();
- m_context->enable_vertex_attrib_array(index);
-}
-
-void WebGLRenderingContextImpl::finish()
-{
- m_context->make_current();
- m_context->finish();
-}
-
-void WebGLRenderingContextImpl::flush()
-{
- m_context->make_current();
- m_context->flush();
-}
-
-void WebGLRenderingContextImpl::framebuffer_renderbuffer(WebIDL::UnsignedLong target, WebIDL::UnsignedLong attachment, WebIDL::UnsignedLong renderbuffertarget, GC::Ptr<WebGLRenderbuffer> renderbuffer)
-{
- m_context->make_current();
-
- if (!is_valid_framebuffer_binding_target(m_context->webgl_version(), target)) {
- set_error(GL_INVALID_ENUM);
- return;
- }
-
- if (!is_valid_framebuffer_attachment(m_context->webgl_version(), extension_enabled("WEBGL_draw_buffers"sv), attachment)) {
- set_error(GL_INVALID_ENUM);
- return;
- }
-
- if (renderbuffertarget != GL_RENDERBUFFER) {
- set_error(GL_INVALID_ENUM);
- return;
- }
-
- if (!m_framebuffer_binding) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
-
- auto renderbuffer_handle = 0;
- if (renderbuffer) {
- auto handle_or_error = renderbuffer->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- renderbuffer_handle = handle_or_error.release_value();
- }
- m_context->framebuffer_renderbuffer(target, attachment, renderbuffertarget, renderbuffer_handle);
- m_framebuffer_binding->set_renderbuffer_attachment(attachment, renderbuffer);
-}
-
-void WebGLRenderingContextImpl::framebuffer_texture2d(WebIDL::UnsignedLong target, WebIDL::UnsignedLong attachment, WebIDL::UnsignedLong textarget, GC::Ptr<WebGLTexture> texture, WebIDL::Long level)
-{
- m_context->make_current();
-
- if (!is_valid_framebuffer_binding_target(m_context->webgl_version(), target)) {
- set_error(GL_INVALID_ENUM);
- return;
- }
-
- if (!is_valid_framebuffer_attachment(m_context->webgl_version(), extension_enabled("WEBGL_draw_buffers"sv), attachment)) {
- set_error(GL_INVALID_ENUM);
- return;
- }
-
- if (!is_valid_framebuffer_texture_2d_target(textarget)) {
- set_error(GL_INVALID_ENUM);
- return;
- }
-
- if (level < 0 || (m_context->webgl_version() == WebGLVersion::WebGL1 && level != 0)) {
- set_error(GL_INVALID_VALUE);
- return;
- }
-
- if (!m_framebuffer_binding) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
-
- auto texture_handle = 0;
- if (texture) {
- auto handle_or_error = texture->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- texture_handle = handle_or_error.release_value();
- }
- m_context->framebuffer_texture2d(target, attachment, textarget, texture_handle, level);
- m_framebuffer_binding->set_texture_attachment(attachment, texture, textarget, level);
-}
-
-void WebGLRenderingContextImpl::front_face(WebIDL::UnsignedLong mode)
-{
- m_context->make_current();
- m_context->front_face(mode);
-}
-
-void WebGLRenderingContextImpl::generate_mipmap(WebIDL::UnsignedLong target)
-{
- m_context->make_current();
- m_context->generate_mipmap(target);
-}
-
-GC::Ptr<WebGLActiveInfo> WebGLRenderingContextImpl::get_active_attrib(GC::Ref<WebGLProgram> program, WebIDL::UnsignedLong index)
-{
- m_context->make_current();
-
- auto handle_or_error = program->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return {};
- }
- auto program_handle = handle_or_error.release_value();
-
- GLint size = 0;
- GLenum type = 0;
- GLsizei buf_size = 256;
- GLsizei length = 0;
- GLchar name[256];
- m_context->get_active_attrib(program_handle, index, buf_size, &length, &size, &type, name);
- auto readonly_bytes = ReadonlyBytes { name, static_cast<size_t>(length) };
- return WebGLActiveInfo::create(realm(), Utf16String::from_ascii_without_validation(readonly_bytes), type, size);
-}
-
-GC::Ptr<WebGLActiveInfo> WebGLRenderingContextImpl::get_active_uniform(GC::Ref<WebGLProgram> program, WebIDL::UnsignedLong index)
-{
- m_context->make_current();
-
- auto handle_or_error = program->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return {};
- }
- auto program_handle = handle_or_error.release_value();
-
- GLint size = 0;
- GLenum type = 0;
- GLsizei buf_size = 256;
- GLsizei length = 0;
- GLchar name[256];
- m_context->get_active_uniform(program_handle, index, buf_size, &length, &size, &type, name);
- auto readonly_bytes = ReadonlyBytes { name, static_cast<size_t>(length) };
- return WebGLActiveInfo::create(realm(), Utf16String::from_ascii_without_validation(readonly_bytes), type, size);
-}
-
-Optional<Vector<GC::Root<WebGLShader>>> WebGLRenderingContextImpl::get_attached_shaders(GC::Ref<WebGLProgram> program)
-{
- m_context->make_current();
-
- auto handle_or_error = program->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return OptionalNone {};
- }
- auto program_handle = handle_or_error.release_value();
-
- (void)program_handle;
-
- Vector<GC::Root<WebGLShader>> result;
-
- if (program->attached_vertex_shader())
- result.append(GC::make_root(*program->attached_vertex_shader()));
-
- if (program->attached_fragment_shader())
- result.append(GC::make_root(*program->attached_fragment_shader()));
-
- return result;
-}
-
-WebIDL::Long WebGLRenderingContextImpl::get_attrib_location(GC::Ref<WebGLProgram> program, Utf16String name)
-{
- m_context->make_current();
-
- auto handle_or_error = program->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return -1;
- }
- auto program_handle = handle_or_error.release_value();
-
- auto name_null_terminated = null_terminated_utf8_string(name.utf16_view());
- return m_context->get_attrib_location(program_handle, name_null_terminated.data());
-}
-
-JS::Value WebGLRenderingContextImpl::get_buffer_parameter(WebIDL::UnsignedLong target, WebIDL::UnsignedLong pname)
-{
- m_context->make_current();
- switch (pname) {
- case GL_BUFFER_SIZE: {
- GLint result { 0 };
- m_context->get_buffer_parameteriv_robust_angle(target, GL_BUFFER_SIZE, 1, nullptr, &result);
- return JS::Value(result);
- }
-
- case GL_BUFFER_USAGE: {
- GLint result { 0 };
- m_context->get_buffer_parameteriv_robust_angle(target, GL_BUFFER_USAGE, 1, nullptr, &result);
- return JS::Value(result);
- }
-
- default:
- dbgln("Unknown WebGL buffer parameter name: {:x}", pname);
- set_error(GL_INVALID_ENUM);
- return JS::js_null();
- }
-}
-
-WebIDL::ExceptionOr<JS::Value> WebGLRenderingContextImpl::get_parameter(JS::Realm& caller_realm, WebIDL::UnsignedLong pname)
-{
- m_context->make_current();
- switch (pname) {
- case GL_ACTIVE_TEXTURE: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_ACTIVE_TEXTURE, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_ALIASED_LINE_WIDTH_RANGE: {
- Array<GLfloat, 2> result;
- result.fill(0);
- constexpr size_t buffer_size = 2 * sizeof(GLfloat);
- m_context->get_floatv_robust_angle(GL_ALIASED_LINE_WIDTH_RANGE, 2, nullptr, result.data());
- auto byte_buffer = MUST(ByteBuffer::copy(result.data(), buffer_size));
- auto array_buffer = JS::ArrayBuffer::create(realm(), move(byte_buffer));
- return JS::Float32Array::create(realm(), 2, array_buffer);
- }
- case GL_ALIASED_POINT_SIZE_RANGE: {
- Array<GLfloat, 2> result;
- result.fill(0);
- constexpr size_t buffer_size = 2 * sizeof(GLfloat);
- m_context->get_floatv_robust_angle(GL_ALIASED_POINT_SIZE_RANGE, 2, nullptr, result.data());
- auto byte_buffer = MUST(ByteBuffer::copy(result.data(), buffer_size));
- auto array_buffer = JS::ArrayBuffer::create(realm(), move(byte_buffer));
- return JS::Float32Array::create(realm(), 2, array_buffer);
- }
- case GL_ALPHA_BITS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_ALPHA_BITS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_ARRAY_BUFFER_BINDING: {
- if (!m_array_buffer_binding)
- return JS::js_null();
- return Bindings::wrap(Bindings::host_defined_wrapper_world(caller_realm), caller_realm, GC::Ref { *m_array_buffer_binding });
- }
- case GL_BLEND: {
- GLboolean result { GL_FALSE };
- m_context->get_booleanv_robust_angle(GL_BLEND, 1, nullptr, &result);
- return JS::Value(result == GL_TRUE);
- }
- case GL_BLEND_COLOR: {
- Array<GLfloat, 4> result;
- result.fill(0);
- constexpr size_t buffer_size = 4 * sizeof(GLfloat);
- m_context->get_floatv_robust_angle(GL_BLEND_COLOR, 4, nullptr, result.data());
- auto byte_buffer = MUST(ByteBuffer::copy(result.data(), buffer_size));
- auto array_buffer = JS::ArrayBuffer::create(realm(), move(byte_buffer));
- return JS::Float32Array::create(realm(), 4, array_buffer);
- }
- case GL_BLEND_DST_ALPHA: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_BLEND_DST_ALPHA, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_BLEND_DST_RGB: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_BLEND_DST_RGB, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_BLEND_EQUATION_ALPHA: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_BLEND_EQUATION_ALPHA, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_BLEND_EQUATION_RGB: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_BLEND_EQUATION_RGB, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_BLEND_SRC_ALPHA: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_BLEND_SRC_ALPHA, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_BLEND_SRC_RGB: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_BLEND_SRC_RGB, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_BLUE_BITS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_BLUE_BITS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_COLOR_CLEAR_VALUE: {
- Array<GLfloat, 4> result;
- result.fill(0);
- constexpr size_t buffer_size = 4 * sizeof(GLfloat);
- m_context->get_floatv_robust_angle(GL_COLOR_CLEAR_VALUE, 4, nullptr, result.data());
- auto byte_buffer = MUST(ByteBuffer::copy(result.data(), buffer_size));
- auto array_buffer = JS::ArrayBuffer::create(realm(), move(byte_buffer));
- return JS::Float32Array::create(realm(), 4, array_buffer);
- }
- case GL_COLOR_WRITEMASK: {
- Array<GLboolean, 4> result;
- result.fill(0);
- m_context->get_booleanv_robust_angle(GL_COLOR_WRITEMASK, 4, nullptr, result.data());
-
- auto sequence = TRY(JS::Array::create(realm(), 4));
- for (int i = 0; i < 4; i++) {
- TRY(sequence->create_data_property(JS::PropertyKey(i), JS::Value(static_cast<WebIDL::Boolean>(result[i]))));
- }
-
- return JS::Value(sequence);
- }
- case GL_CULL_FACE: {
- GLboolean result { GL_FALSE };
- m_context->get_booleanv_robust_angle(GL_CULL_FACE, 1, nullptr, &result);
- return JS::Value(result == GL_TRUE);
- }
- case GL_CULL_FACE_MODE: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_CULL_FACE_MODE, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_CURRENT_PROGRAM: {
- if (!m_current_program)
- return JS::js_null();
- return Bindings::wrap(Bindings::host_defined_wrapper_world(caller_realm), caller_realm, GC::Ref { *m_current_program });
- }
- case GL_DEPTH_BITS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_DEPTH_BITS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_DEPTH_CLEAR_VALUE: {
- GLfloat result { 0.0f };
- m_context->get_floatv_robust_angle(GL_DEPTH_CLEAR_VALUE, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_DEPTH_FUNC: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_DEPTH_FUNC, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_DEPTH_RANGE: {
- Array<GLfloat, 2> result;
- result.fill(0);
- constexpr size_t buffer_size = 2 * sizeof(GLfloat);
- m_context->get_floatv_robust_angle(GL_DEPTH_RANGE, 2, nullptr, result.data());
- auto byte_buffer = MUST(ByteBuffer::copy(result.data(), buffer_size));
- auto array_buffer = JS::ArrayBuffer::create(realm(), move(byte_buffer));
- return JS::Float32Array::create(realm(), 2, array_buffer);
- }
- case GL_DEPTH_TEST: {
- GLboolean result { GL_FALSE };
- m_context->get_booleanv_robust_angle(GL_DEPTH_TEST, 1, nullptr, &result);
- return JS::Value(result == GL_TRUE);
- }
- case GL_DEPTH_WRITEMASK: {
- GLboolean result { GL_FALSE };
- m_context->get_booleanv_robust_angle(GL_DEPTH_WRITEMASK, 1, nullptr, &result);
- return JS::Value(result == GL_TRUE);
- }
- case GL_DITHER: {
- GLboolean result { GL_FALSE };
- m_context->get_booleanv_robust_angle(GL_DITHER, 1, nullptr, &result);
- return JS::Value(result == GL_TRUE);
- }
- case GL_ELEMENT_ARRAY_BUFFER_BINDING: {
- if (!m_element_array_buffer_binding)
- return JS::js_null();
- return Bindings::wrap(Bindings::host_defined_wrapper_world(caller_realm), caller_realm, GC::Ref { *m_element_array_buffer_binding });
- }
- case GL_FRAMEBUFFER_BINDING: {
- if (!m_framebuffer_binding)
- return JS::js_null();
- return Bindings::wrap(Bindings::host_defined_wrapper_world(caller_realm), caller_realm, GC::Ref { *m_framebuffer_binding });
- }
- case GL_FRONT_FACE: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_FRONT_FACE, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_GENERATE_MIPMAP_HINT: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_GENERATE_MIPMAP_HINT, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_GREEN_BITS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_GREEN_BITS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_IMPLEMENTATION_COLOR_READ_FORMAT: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_IMPLEMENTATION_COLOR_READ_FORMAT, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_IMPLEMENTATION_COLOR_READ_TYPE: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_IMPLEMENTATION_COLOR_READ_TYPE, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_LINE_WIDTH: {
- GLfloat result { 0.0f };
- m_context->get_floatv_robust_angle(GL_LINE_WIDTH, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_MAX_CUBE_MAP_TEXTURE_SIZE: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_MAX_CUBE_MAP_TEXTURE_SIZE, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_MAX_FRAGMENT_UNIFORM_VECTORS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_MAX_FRAGMENT_UNIFORM_VECTORS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_MAX_RENDERBUFFER_SIZE: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_MAX_RENDERBUFFER_SIZE, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_MAX_TEXTURE_IMAGE_UNITS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_MAX_TEXTURE_IMAGE_UNITS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_MAX_TEXTURE_SIZE: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_MAX_TEXTURE_SIZE, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_MAX_VARYING_VECTORS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_MAX_VARYING_VECTORS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_MAX_VERTEX_ATTRIBS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_MAX_VERTEX_ATTRIBS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_MAX_VERTEX_UNIFORM_VECTORS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_MAX_VERTEX_UNIFORM_VECTORS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_MAX_VIEWPORT_DIMS: {
- Array<GLint, 2> result;
- result.fill(0);
- constexpr size_t buffer_size = 2 * sizeof(GLint);
- m_context->get_integerv_robust_angle(GL_MAX_VIEWPORT_DIMS, 2, nullptr, result.data());
- auto byte_buffer = MUST(ByteBuffer::copy(result.data(), buffer_size));
- auto array_buffer = JS::ArrayBuffer::create(realm(), move(byte_buffer));
- return JS::Int32Array::create(realm(), 2, array_buffer);
- }
- case GL_PACK_ALIGNMENT: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_PACK_ALIGNMENT, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_POLYGON_OFFSET_FACTOR: {
- GLfloat result { 0.0f };
- m_context->get_floatv_robust_angle(GL_POLYGON_OFFSET_FACTOR, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_POLYGON_OFFSET_FILL: {
- GLboolean result { GL_FALSE };
- m_context->get_booleanv_robust_angle(GL_POLYGON_OFFSET_FILL, 1, nullptr, &result);
- return JS::Value(result == GL_TRUE);
- }
- case GL_POLYGON_OFFSET_UNITS: {
- GLfloat result { 0.0f };
- m_context->get_floatv_robust_angle(GL_POLYGON_OFFSET_UNITS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_RED_BITS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_RED_BITS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_RENDERBUFFER_BINDING: {
- if (!m_renderbuffer_binding)
- return JS::js_null();
- return Bindings::wrap(Bindings::host_defined_wrapper_world(caller_realm), caller_realm, GC::Ref { *m_renderbuffer_binding });
- }
- case GL_RENDERER: {
- auto result = reinterpret_cast<char const*>(m_context->get_string(GL_RENDERER));
- return JS::PrimitiveString::create(realm().vm(), Utf16String::from_ascii_without_validation(StringView { result, strlen(result) }.bytes()));
- }
- case GL_SAMPLE_ALPHA_TO_COVERAGE: {
- GLboolean result { GL_FALSE };
- m_context->get_booleanv_robust_angle(GL_SAMPLE_ALPHA_TO_COVERAGE, 1, nullptr, &result);
- return JS::Value(result == GL_TRUE);
- }
- case GL_SAMPLE_BUFFERS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_SAMPLE_BUFFERS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_SAMPLE_COVERAGE: {
- GLboolean result { GL_FALSE };
- m_context->get_booleanv_robust_angle(GL_SAMPLE_COVERAGE, 1, nullptr, &result);
- return JS::Value(result == GL_TRUE);
- }
- case GL_SAMPLE_COVERAGE_INVERT: {
- GLboolean result { GL_FALSE };
- m_context->get_booleanv_robust_angle(GL_SAMPLE_COVERAGE_INVERT, 1, nullptr, &result);
- return JS::Value(result == GL_TRUE);
- }
- case GL_SAMPLE_COVERAGE_VALUE: {
- GLfloat result { 0.0f };
- m_context->get_floatv_robust_angle(GL_SAMPLE_COVERAGE_VALUE, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_SAMPLES: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_SAMPLES, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_SCISSOR_BOX: {
- Array<GLint, 4> result;
- result.fill(0);
- constexpr size_t buffer_size = 4 * sizeof(GLint);
- m_context->get_integerv_robust_angle(GL_SCISSOR_BOX, 4, nullptr, result.data());
- auto byte_buffer = MUST(ByteBuffer::copy(result.data(), buffer_size));
- auto array_buffer = JS::ArrayBuffer::create(realm(), move(byte_buffer));
- return JS::Int32Array::create(realm(), 4, array_buffer);
- }
- case GL_SCISSOR_TEST: {
- GLboolean result { GL_FALSE };
- m_context->get_booleanv_robust_angle(GL_SCISSOR_TEST, 1, nullptr, &result);
- return JS::Value(result == GL_TRUE);
- }
- case GL_SHADING_LANGUAGE_VERSION: {
- auto result = reinterpret_cast<char const*>(m_context->get_string(GL_SHADING_LANGUAGE_VERSION));
- return JS::PrimitiveString::create(realm().vm(), Utf16String::from_ascii_without_validation(StringView { result, strlen(result) }.bytes()));
- }
- case GL_STENCIL_BACK_FAIL: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_STENCIL_BACK_FAIL, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_STENCIL_BACK_FUNC: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_STENCIL_BACK_FUNC, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_STENCIL_BACK_PASS_DEPTH_FAIL: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_STENCIL_BACK_PASS_DEPTH_FAIL, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_STENCIL_BACK_PASS_DEPTH_PASS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_STENCIL_BACK_PASS_DEPTH_PASS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_STENCIL_BACK_REF: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_STENCIL_BACK_REF, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_STENCIL_BACK_VALUE_MASK: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_STENCIL_BACK_VALUE_MASK, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_STENCIL_BACK_WRITEMASK: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_STENCIL_BACK_WRITEMASK, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_STENCIL_BITS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_STENCIL_BITS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_STENCIL_CLEAR_VALUE: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_STENCIL_CLEAR_VALUE, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_STENCIL_FAIL: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_STENCIL_FAIL, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_STENCIL_FUNC: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_STENCIL_FUNC, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_STENCIL_PASS_DEPTH_FAIL: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_STENCIL_PASS_DEPTH_FAIL, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_STENCIL_PASS_DEPTH_PASS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_STENCIL_PASS_DEPTH_PASS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_STENCIL_REF: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_STENCIL_REF, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_STENCIL_TEST: {
- GLboolean result { GL_FALSE };
- m_context->get_booleanv_robust_angle(GL_STENCIL_TEST, 1, nullptr, &result);
- return JS::Value(result == GL_TRUE);
- }
- case GL_STENCIL_VALUE_MASK: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_STENCIL_VALUE_MASK, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_STENCIL_WRITEMASK: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_STENCIL_WRITEMASK, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_SUBPIXEL_BITS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_SUBPIXEL_BITS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_TEXTURE_BINDING_2D: {
- if (!m_texture_binding_2d)
- return JS::js_null();
- return Bindings::wrap(Bindings::host_defined_wrapper_world(caller_realm), caller_realm, GC::Ref { *m_texture_binding_2d });
- }
- case GL_TEXTURE_BINDING_CUBE_MAP: {
- if (!m_texture_binding_cube_map)
- return JS::js_null();
- return Bindings::wrap(Bindings::host_defined_wrapper_world(caller_realm), caller_realm, GC::Ref { *m_texture_binding_cube_map });
- }
- case GL_UNPACK_ALIGNMENT: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_UNPACK_ALIGNMENT, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_VENDOR: {
- auto result = reinterpret_cast<char const*>(m_context->get_string(GL_VENDOR));
- return JS::PrimitiveString::create(realm().vm(), Utf16String::from_ascii_without_validation(StringView { result, strlen(result) }.bytes()));
- }
- case GL_VERSION: {
- auto result = reinterpret_cast<char const*>(m_context->get_string(GL_VERSION));
- return JS::PrimitiveString::create(realm().vm(), Utf16String::from_ascii_without_validation(StringView { result, strlen(result) }.bytes()));
- }
- case GL_VIEWPORT: {
- Array<GLint, 4> result;
- result.fill(0);
- constexpr size_t buffer_size = 4 * sizeof(GLint);
- m_context->get_integerv_robust_angle(GL_VIEWPORT, 4, nullptr, result.data());
- auto byte_buffer = MUST(ByteBuffer::copy(result.data(), buffer_size));
- auto array_buffer = JS::ArrayBuffer::create(realm(), move(byte_buffer));
- return JS::Int32Array::create(realm(), 4, array_buffer);
- }
-
- case UNMASKED_VENDOR_WEBGL: {
- if (!extension_enabled("WEBGL_debug_renderer_info"sv)) {
- set_error(GL_INVALID_ENUM);
- return JS::js_null();
- }
- auto result = reinterpret_cast<char const*>(m_context->get_string(GL_VENDOR));
- return JS::PrimitiveString::create(realm().vm(), Utf16String::from_ascii_without_validation(StringView { result, strlen(result) }.bytes()));
- }
- case UNMASKED_RENDERER_WEBGL: {
- if (!extension_enabled("WEBGL_debug_renderer_info"sv)) {
- set_error(GL_INVALID_ENUM);
- return JS::js_null();
- }
- auto result = reinterpret_cast<char const*>(m_context->get_string(GL_RENDERER));
- return JS::PrimitiveString::create(realm().vm(), Utf16String::from_ascii_without_validation(StringView { result, strlen(result) }.bytes()));
- }
-
- case GL_FRAGMENT_SHADER_DERIVATIVE_HINT: { // NOTE: This has the same value as GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES
- if (extension_enabled("OES_standard_derivatives"sv) || m_context->webgl_version() == WebGLVersion::WebGL2) {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_FRAGMENT_SHADER_DERIVATIVE_HINT, 1, nullptr, &result);
- return JS::Value(result);
- }
-
- set_error(GL_INVALID_ENUM);
- return JS::js_null();
- }
- case GL_MAX_COLOR_ATTACHMENTS: { // NOTE: This has the same value as MAX_COLOR_ATTACHMENTS_WEBGL
- if (extension_enabled("WEBGL_draw_buffers"sv) || m_context->webgl_version() == WebGLVersion::WebGL2) {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_MAX_COLOR_ATTACHMENTS, 1, nullptr, &result);
- return JS::Value(result);
- }
-
- set_error(GL_INVALID_ENUM);
- return JS::js_null();
- }
- case GL_MAX_DRAW_BUFFERS: {
- if (m_context->webgl_version() == WebGLVersion::WebGL2) { // FIXME: Allow this code path for MAX_DRAW_BUFFERS_WEBGL
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_MAX_DRAW_BUFFERS, 1, nullptr, &result);
- return JS::Value(result);
- }
-
- set_error(GL_INVALID_ENUM);
- return JS::js_null();
- }
- case GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT: {
- if (extension_enabled("EXT_texture_filter_anisotropic"sv)) {
- GLfloat result { 0.0f };
- m_context->get_floatv_robust_angle(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, 1, nullptr, &result);
- return JS::Value(result);
- }
-
- set_error(GL_INVALID_ENUM);
- return JS::js_null();
- }
- case GL_VERTEX_ARRAY_BINDING: { // NOTE: This has the same value as VERTEX_ARRAY_BINDING_OES
- if (extension_enabled("OES_vertex_array_object"sv) || m_context->webgl_version() == WebGLVersion::WebGL2) {
- if (!m_current_vertex_array)
- return JS::js_null();
- return Bindings::wrap(Bindings::host_defined_wrapper_world(caller_realm), caller_realm, GC::Ref { *m_current_vertex_array });
- }
-
- set_error(GL_INVALID_ENUM);
- return JS::js_null();
- }
-
- case COMPRESSED_TEXTURE_FORMATS: {
- auto formats = enabled_compressed_texture_formats();
- auto byte_buffer = MUST(ByteBuffer::copy(formats.data(), formats.reinterpret<u8 const>().size()));
- auto array_buffer = JS::ArrayBuffer::create(realm(), move(byte_buffer));
- return JS::Uint32Array::create(realm(), formats.size(), array_buffer);
- }
- case UNPACK_FLIP_Y_WEBGL:
- return JS::Value(m_unpack_flip_y);
- case UNPACK_PREMULTIPLY_ALPHA_WEBGL:
- return JS::Value(m_unpack_premultiply_alpha);
- case UNPACK_COLORSPACE_CONVERSION_WEBGL:
- return JS::Value(m_unpack_colorspace_conversion);
- }
-
- if (m_context->webgl_version() == WebGLVersion::WebGL2) {
- switch (pname) {
- case GL_COPY_READ_BUFFER_BINDING: {
- if (!m_copy_read_buffer_binding)
- return JS::js_null();
- return Bindings::wrap(Bindings::host_defined_wrapper_world(caller_realm), caller_realm, GC::Ref { *m_copy_read_buffer_binding });
- }
- case GL_COPY_WRITE_BUFFER_BINDING: {
- if (!m_copy_write_buffer_binding)
- return JS::js_null();
- return Bindings::wrap(Bindings::host_defined_wrapper_world(caller_realm), caller_realm, GC::Ref { *m_copy_write_buffer_binding });
- }
- case GL_MAX_SAMPLES: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_MAX_SAMPLES, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_MAX_3D_TEXTURE_SIZE: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_MAX_3D_TEXTURE_SIZE, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_MAX_ARRAY_TEXTURE_LAYERS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_MAX_ARRAY_TEXTURE_LAYERS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_MAX_VERTEX_UNIFORM_COMPONENTS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_MAX_VERTEX_UNIFORM_COMPONENTS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_MAX_UNIFORM_BLOCK_SIZE: {
- GLint64 result { 0 };
- m_context->get_integer64v_robust_angle(GL_MAX_UNIFORM_BLOCK_SIZE, 1, nullptr, &result);
- return JS::Value(static_cast<double>(result));
- }
- case GL_MAX_UNIFORM_BUFFER_BINDINGS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_MAX_UNIFORM_BUFFER_BINDINGS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_MAX_VERTEX_UNIFORM_BLOCKS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_MAX_VERTEX_UNIFORM_BLOCKS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_MAX_FRAGMENT_INPUT_COMPONENTS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_MAX_FRAGMENT_INPUT_COMPONENTS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_MAX_FRAGMENT_UNIFORM_COMPONENTS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_MAX_COMBINED_UNIFORM_BLOCKS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_MAX_COMBINED_UNIFORM_BLOCKS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS: {
- GLint64 result { 0 };
- m_context->get_integer64v_robust_angle(GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS, 1, nullptr, &result);
- return JS::Value(static_cast<double>(result));
- }
- case GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS: {
- GLint64 result { 0 };
- m_context->get_integer64v_robust_angle(GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS, 1, nullptr, &result);
- return JS::Value(static_cast<double>(result));
- }
- case GL_MAX_ELEMENT_INDEX: {
- GLint64 result { 0 };
- m_context->get_integer64v_robust_angle(GL_MAX_ELEMENT_INDEX, 1, nullptr, &result);
- return JS::Value(static_cast<double>(result));
- }
- case GL_MAX_FRAGMENT_UNIFORM_BLOCKS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_MAX_FRAGMENT_UNIFORM_BLOCKS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_MAX_VARYING_COMPONENTS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_MAX_VARYING_COMPONENTS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_MAX_ELEMENTS_INDICES: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_MAX_ELEMENTS_INDICES, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_MAX_ELEMENTS_VERTICES: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_MAX_ELEMENTS_VERTICES, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_MAX_TEXTURE_LOD_BIAS: {
- GLfloat result { 0.0f };
- m_context->get_floatv_robust_angle(GL_MAX_TEXTURE_LOD_BIAS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_MIN_PROGRAM_TEXEL_OFFSET: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_MIN_PROGRAM_TEXEL_OFFSET, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_MAX_PROGRAM_TEXEL_OFFSET: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_MAX_PROGRAM_TEXEL_OFFSET, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_MAX_VERTEX_OUTPUT_COMPONENTS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_MAX_VERTEX_OUTPUT_COMPONENTS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_MAX_SERVER_WAIT_TIMEOUT: {
- GLint64 result { 0 };
- m_context->get_integer64v_robust_angle(GL_MAX_SERVER_WAIT_TIMEOUT, 1, nullptr, &result);
- return JS::Value(static_cast<double>(result));
- }
- case GL_PACK_ROW_LENGTH: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_PACK_ROW_LENGTH, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_PACK_SKIP_ROWS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_PACK_SKIP_ROWS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_PACK_SKIP_PIXELS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_PACK_SKIP_PIXELS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_PIXEL_PACK_BUFFER_BINDING: {
- if (!m_pixel_pack_buffer_binding)
- return JS::js_null();
- return Bindings::wrap(Bindings::host_defined_wrapper_world(caller_realm), caller_realm, GC::Ref { *m_pixel_pack_buffer_binding });
- }
- case GL_PIXEL_UNPACK_BUFFER_BINDING: {
- if (!m_pixel_unpack_buffer_binding)
- return JS::js_null();
- return Bindings::wrap(Bindings::host_defined_wrapper_world(caller_realm), caller_realm, GC::Ref { *m_pixel_unpack_buffer_binding });
- }
- case GL_TEXTURE_BINDING_2D_ARRAY: {
- if (!m_texture_binding_2d_array)
- return JS::js_null();
- return Bindings::wrap(Bindings::host_defined_wrapper_world(caller_realm), caller_realm, GC::Ref { *m_texture_binding_2d_array });
- }
- case GL_TRANSFORM_FEEDBACK_ACTIVE: {
- GLboolean result { GL_FALSE };
- m_context->get_booleanv_robust_angle(GL_TRANSFORM_FEEDBACK_ACTIVE, 1, nullptr, &result);
- return JS::Value(result == GL_TRUE);
- }
- case GL_TRANSFORM_FEEDBACK_BINDING: {
- if (!m_transform_feedback_binding)
- return JS::js_null();
- return Bindings::wrap(Bindings::host_defined_wrapper_world(caller_realm), caller_realm, GC::Ref { *m_transform_feedback_binding });
- }
- case GL_TRANSFORM_FEEDBACK_BUFFER_BINDING: {
- if (!m_transform_feedback_buffer_binding)
- return JS::js_null();
- return Bindings::wrap(Bindings::host_defined_wrapper_world(caller_realm), caller_realm, GC::Ref { *m_transform_feedback_buffer_binding });
- }
- case GL_TRANSFORM_FEEDBACK_PAUSED: {
- GLboolean result { GL_FALSE };
- m_context->get_booleanv_robust_angle(GL_TRANSFORM_FEEDBACK_PAUSED, 1, nullptr, &result);
- return JS::Value(result == GL_TRUE);
- }
- case GL_RASTERIZER_DISCARD: {
- GLboolean result { GL_FALSE };
- m_context->get_booleanv_robust_angle(GL_RASTERIZER_DISCARD, 1, nullptr, &result);
- return JS::Value(result == GL_TRUE);
- }
- case GL_SAMPLER_BINDING: {
- GLint handle { 0 };
- m_context->get_integerv_robust_angle(GL_SAMPLER_BINDING, 1, nullptr, &handle);
- return Bindings::wrap(Bindings::host_defined_wrapper_world(caller_realm), caller_realm, WebGLSampler::create(*this, handle));
- }
- case GL_UNIFORM_BUFFER_BINDING: {
- if (!m_uniform_buffer_binding)
- return JS::js_null();
- return Bindings::wrap(Bindings::host_defined_wrapper_world(caller_realm), caller_realm, GC::Ref { *m_uniform_buffer_binding });
- }
- case GL_UNPACK_IMAGE_HEIGHT: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_UNPACK_IMAGE_HEIGHT, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_UNPACK_ROW_LENGTH: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_UNPACK_ROW_LENGTH, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_UNPACK_SKIP_IMAGES: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_UNPACK_SKIP_IMAGES, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_UNPACK_SKIP_PIXELS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_UNPACK_SKIP_PIXELS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_UNPACK_SKIP_ROWS: {
- GLint result { 0 };
- m_context->get_integerv_robust_angle(GL_UNPACK_SKIP_ROWS, 1, nullptr, &result);
- return JS::Value(result);
- }
- case MAX_CLIENT_WAIT_TIMEOUT_WEBGL:
- // A page must never be able to block the compositor, so clientWaitSync
- // never waits; the host clamps the timeout to zero to match.
- return JS::Value(0);
- }
- }
-
- dbgln("Unknown WebGL parameter name: {:x}", pname);
- set_error(GL_INVALID_ENUM);
- return JS::js_null();
-}
-
-WebIDL::UnsignedLong WebGLRenderingContextImpl::get_error()
-{
- m_context->make_current();
- return get_error_value();
-}
-
-JS::Value WebGLRenderingContextImpl::get_framebuffer_attachment_parameter(JS::Realm& caller_realm, WebIDL::UnsignedLong target, WebIDL::UnsignedLong attachment, WebIDL::UnsignedLong pname)
-{
- m_context->make_current();
-
- if (!is_valid_framebuffer_binding_target(m_context->webgl_version(), target)) {
- set_error(GL_INVALID_ENUM);
- return JS::js_null();
- }
-
- if (!m_framebuffer_binding) {
- set_error(GL_INVALID_OPERATION);
- return JS::js_null();
- }
-
- if (!is_valid_framebuffer_attachment(m_context->webgl_version(), extension_enabled("WEBGL_draw_buffers"sv), attachment)) {
- set_error(GL_INVALID_ENUM);
- return JS::js_null();
- }
-
- auto const* framebuffer_attachment = m_framebuffer_binding->attachment(attachment);
- if (!framebuffer_attachment) {
- if (pname == GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE)
- return JS::Value(GL_NONE);
- if (pname == GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME && m_context->webgl_version() == WebGLVersion::WebGL2)
- return JS::js_null();
- set_error(m_context->webgl_version() == WebGLVersion::WebGL2 ? GL_INVALID_OPERATION : GL_INVALID_ENUM);
- return JS::js_null();
- }
-
- switch (pname) {
- case GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE:
- if (framebuffer_attachment->texture)
- return JS::Value(GL_TEXTURE);
- return JS::Value(GL_RENDERBUFFER);
- case GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME:
- if (framebuffer_attachment->texture)
- return Bindings::wrap(Bindings::host_defined_wrapper_world(caller_realm), caller_realm, GC::Ref { *framebuffer_attachment->texture });
- return Bindings::wrap(Bindings::host_defined_wrapper_world(caller_realm), caller_realm, GC::Ref { *framebuffer_attachment->renderbuffer });
- case GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL:
- if (framebuffer_attachment->texture)
- return JS::Value(framebuffer_attachment->texture_level);
- break;
- case GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE:
- if (framebuffer_attachment->texture)
- return JS::Value(is_cube_map_face(framebuffer_attachment->texture_target) ? framebuffer_attachment->texture_target : 0);
- break;
- }
-
- set_error(GL_INVALID_ENUM);
- return JS::js_null();
-}
-
-JS::Value WebGLRenderingContextImpl::get_program_parameter(GC::Ref<WebGLProgram> program, WebIDL::UnsignedLong pname)
-{
- m_context->make_current();
-
- auto handle_or_error = program->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return JS::js_null();
- }
- auto program_handle = handle_or_error.release_value();
-
- GLint result = 0;
- m_context->get_programiv_robust_angle(program_handle, pname, 1, nullptr, &result);
- switch (pname) {
- case GL_ATTACHED_SHADERS:
- case GL_ACTIVE_ATTRIBUTES:
- case GL_ACTIVE_UNIFORMS:
- return JS::Value(result);
-
- case GL_TRANSFORM_FEEDBACK_BUFFER_MODE:
- case GL_TRANSFORM_FEEDBACK_VARYINGS:
- case GL_ACTIVE_UNIFORM_BLOCKS:
- if (m_context->webgl_version() == WebGLVersion::WebGL2)
- return JS::Value(result);
-
- set_error(GL_INVALID_ENUM);
- return JS::js_null();
-
- case GL_DELETE_STATUS:
- case GL_LINK_STATUS:
- case GL_VALIDATE_STATUS:
- return JS::Value(result == GL_TRUE);
- default:
- dbgln("Unknown WebGL program parameter name: 0x{:04x}", pname);
- set_error(GL_INVALID_ENUM);
- return JS::js_null();
- }
-}
-
-Optional<Utf16String> WebGLRenderingContextImpl::get_program_info_log(GC::Ref<WebGLProgram> program)
-{
- m_context->make_current();
-
- auto handle_or_error = program->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return {};
- }
- auto program_handle = handle_or_error.release_value();
-
- GLint info_log_length = 0;
- m_context->get_programiv(program_handle, GL_INFO_LOG_LENGTH, &info_log_length);
- Vector<GLchar> info_log;
- info_log.resize(info_log_length);
- if (!info_log_length)
- return Utf16String {};
- m_context->get_program_info_log(program_handle, info_log_length, nullptr, info_log.data());
- return utf16_string_from_gl_string(info_log.data(), static_cast<size_t>(info_log_length - 1));
-}
-
-JS::Value WebGLRenderingContextImpl::get_renderbuffer_parameter(WebIDL::UnsignedLong target, WebIDL::UnsignedLong pname)
-{
- m_context->make_current();
-
- switch (pname) {
- case GL_RENDERBUFFER_WIDTH:
- case GL_RENDERBUFFER_HEIGHT:
- case GL_RENDERBUFFER_INTERNAL_FORMAT:
- case GL_RENDERBUFFER_RED_SIZE:
- case GL_RENDERBUFFER_GREEN_SIZE:
- case GL_RENDERBUFFER_BLUE_SIZE:
- case GL_RENDERBUFFER_ALPHA_SIZE:
- case GL_RENDERBUFFER_DEPTH_SIZE:
- case GL_RENDERBUFFER_SAMPLES:
- case GL_RENDERBUFFER_STENCIL_SIZE: {
- GLint result = 0;
- m_context->get_renderbuffer_parameteriv_robust_angle(target, pname, 1, nullptr, &result);
- return JS::Value(result);
- }
- default:
- // If pname is not in the table above, generates an INVALID_ENUM error.
- set_error(GL_INVALID_ENUM);
- return JS::js_null();
- }
-}
-
-JS::Value WebGLRenderingContextImpl::get_shader_parameter(GC::Ref<WebGLShader> shader, WebIDL::UnsignedLong pname)
-{
- m_context->make_current();
-
- auto handle_or_error = shader->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return JS::js_null();
- }
- auto shader_handle = handle_or_error.release_value();
-
- GLint result = 0;
- m_context->get_shaderiv_robust_angle(shader_handle, pname, 1, nullptr, &result);
- switch (pname) {
- case GL_SHADER_TYPE:
- return JS::Value(result);
- case GL_DELETE_STATUS:
- case GL_COMPILE_STATUS:
- return JS::Value(result == GL_TRUE);
- default:
- dbgln("Unknown WebGL shader parameter name: 0x{:04x}", pname);
- set_error(GL_INVALID_ENUM);
- return JS::js_null();
- }
-}
-
-GC::Ptr<WebGLShaderPrecisionFormat> WebGLRenderingContextImpl::get_shader_precision_format(WebIDL::UnsignedLong shadertype, WebIDL::UnsignedLong precisiontype)
-{
- m_context->make_current();
-
- GLint range[2];
- GLint precision;
- m_context->get_shader_precision_format(shadertype, precisiontype, range, &precision);
- return WebGLShaderPrecisionFormat::create(realm(), range[0], range[1], precision);
-}
-
-Optional<Utf16String> WebGLRenderingContextImpl::get_shader_info_log(GC::Ref<WebGLShader> shader)
-{
- m_context->make_current();
-
- auto handle_or_error = shader->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return {};
- }
- auto shader_handle = handle_or_error.release_value();
-
- GLint info_log_length = 0;
- m_context->get_shaderiv(shader_handle, GL_INFO_LOG_LENGTH, &info_log_length);
- Vector<GLchar> info_log;
- info_log.resize(info_log_length);
- if (!info_log_length)
- return Utf16String {};
- m_context->get_shader_info_log(shader_handle, info_log_length, nullptr, info_log.data());
- return utf16_string_from_gl_string(info_log.data(), static_cast<size_t>(info_log_length - 1));
-}
-
-Optional<Utf16String> WebGLRenderingContextImpl::get_shader_source(GC::Ref<WebGLShader> shader)
-{
- m_context->make_current();
-
- auto handle_or_error = shader->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return {};
- }
- auto shader_handle = handle_or_error.release_value();
-
- GLint shader_source_length = 0;
- m_context->get_shaderiv(shader_handle, GL_SHADER_SOURCE_LENGTH, &shader_source_length);
- if (!shader_source_length)
- return Utf16String {};
-
- auto shader_source = MUST(ByteBuffer::create_uninitialized(shader_source_length));
- m_context->get_shader_source(shader_handle, shader_source_length, nullptr, reinterpret_cast<GLchar*>(shader_source.data()));
- return utf16_string_from_gl_string(shader_source.data(), static_cast<size_t>(shader_source_length - 1));
-}
-
-JS::Value WebGLRenderingContextImpl::get_tex_parameter(WebIDL::UnsignedLong target, WebIDL::UnsignedLong pname)
-{
- m_context->make_current();
-
- switch (pname) {
- case GL_TEXTURE_MAG_FILTER:
- case GL_TEXTURE_MIN_FILTER:
- case GL_TEXTURE_WRAP_S:
- case GL_TEXTURE_WRAP_T: {
- GLint result { 0 };
- m_context->get_tex_parameteriv_robust_angle(target, pname, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_TEXTURE_MAX_ANISOTROPY_EXT: {
- if (extension_enabled("EXT_texture_filter_anisotropic"sv)) {
- GLint result { 0 };
- m_context->get_tex_parameteriv_robust_angle(target, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1, nullptr, &result);
- return JS::Value(result);
- }
-
- set_error(GL_INVALID_ENUM);
- return JS::js_null();
- }
- }
-
- if (m_context->webgl_version() == WebGLVersion::WebGL2) {
- switch (pname) {
- case GL_TEXTURE_BASE_LEVEL:
- case GL_TEXTURE_COMPARE_FUNC:
- case GL_TEXTURE_COMPARE_MODE:
- case GL_TEXTURE_IMMUTABLE_LEVELS:
- case GL_TEXTURE_MAX_LEVEL:
- case GL_TEXTURE_WRAP_R: {
- GLint result { 0 };
- m_context->get_tex_parameteriv_robust_angle(target, pname, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_TEXTURE_IMMUTABLE_FORMAT: {
- GLint result { 0 };
- m_context->get_tex_parameteriv_robust_angle(target, GL_TEXTURE_IMMUTABLE_FORMAT, 1, nullptr, &result);
- return JS::Value(result == GL_TRUE);
- }
- case GL_TEXTURE_MAX_LOD:
- case GL_TEXTURE_MIN_LOD: {
- GLfloat result { 0.0f };
- m_context->get_tex_parameterfv_robust_angle(target, GL_TEXTURE_IMMUTABLE_FORMAT, 1, nullptr, &result);
- return JS::Value(result == GL_TRUE);
- }
- }
- }
-
- set_error(GL_INVALID_ENUM);
- return JS::js_null();
-}
-
-JS::Value WebGLRenderingContextImpl::get_uniform(GC::Ref<WebGLProgram>, GC::Ref<WebGLUniformLocation>)
-{
- dbgln("FIXME: Implement get_uniform");
- return JS::Value(0);
-}
-
-GC::Ptr<WebGLUniformLocation> WebGLRenderingContextImpl::get_uniform_location(GC::Ref<WebGLProgram> program, Utf16String name)
-{
- m_context->make_current();
-
- auto handle_or_error = program->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return {};
- }
- auto program_handle = handle_or_error.release_value();
-
- auto name_null_terminated = null_terminated_utf8_string(name.utf16_view());
-
- // "This function returns -1 if name does not correspond to an active uniform variable in program or if name starts
- // with the reserved prefix "gl_"."
- // WebGL Spec: The return value is null if name does not correspond to an active uniform variable in the passed program.
- auto location = m_context->get_uniform_location(program_handle, name_null_terminated.data());
- if (location == -1)
- return nullptr;
-
- return WebGLUniformLocation::create(realm(), location, program.ptr());
-}
-
-JS::Value WebGLRenderingContextImpl::get_vertex_attrib(JS::Realm& caller_realm, WebIDL::UnsignedLong index, WebIDL::UnsignedLong pname)
-{
- switch (pname) {
- case GL_CURRENT_VERTEX_ATTRIB: {
- Array<GLfloat, 4> result;
- result.fill(0);
- m_context->get_vertex_attribfv_robust_angle(index, GL_CURRENT_VERTEX_ATTRIB, result.size(), nullptr, result.data());
-
- auto byte_buffer = MUST(ByteBuffer::copy(result.span().reinterpret<u8>()));
- auto array_buffer = JS::ArrayBuffer::create(realm(), move(byte_buffer));
- return JS::Float32Array::create(realm(), result.size(), array_buffer);
- }
- case GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: {
- GLint handle { 0 };
- m_context->get_vertex_attribiv_robust_angle(index, GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING, 1, nullptr, &handle);
- return Bindings::wrap(Bindings::host_defined_wrapper_world(caller_realm), caller_realm, WebGLBuffer::create(*this, handle));
- }
- case GL_VERTEX_ATTRIB_ARRAY_DIVISOR: { // NOTE: This has the same value as GL_VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE
- if (extension_enabled("ANGLE_instanced_arrays"sv) || m_context->webgl_version() == WebGLVersion::WebGL2) {
- GLint result { 0 };
- m_context->get_vertex_attribiv_robust_angle(index, GL_VERTEX_ATTRIB_ARRAY_DIVISOR, 1, nullptr, &result);
- return JS::Value(result);
- }
-
- set_error(GL_INVALID_ENUM);
- return JS::js_null();
- }
- case GL_VERTEX_ATTRIB_ARRAY_ENABLED: {
- GLint result { 0 };
- m_context->get_vertex_attribiv_robust_angle(index, GL_VERTEX_ATTRIB_ARRAY_ENABLED, 1, nullptr, &result);
- return JS::Value(result == GL_TRUE);
- }
- case GL_VERTEX_ATTRIB_ARRAY_INTEGER: {
- if (m_context->webgl_version() == WebGLVersion::WebGL2) {
- GLint result { 0 };
- m_context->get_vertex_attribiv_robust_angle(index, GL_VERTEX_ATTRIB_ARRAY_INTEGER, 1, nullptr, &result);
- return JS::Value(result == GL_TRUE);
- }
-
- set_error(GL_INVALID_ENUM);
- return JS::js_null();
- }
- case GL_VERTEX_ATTRIB_ARRAY_NORMALIZED: {
- GLint result { 0 };
- m_context->get_vertex_attribiv_robust_angle(index, GL_VERTEX_ATTRIB_ARRAY_NORMALIZED, 1, nullptr, &result);
- return JS::Value(result == GL_TRUE);
- }
- case GL_VERTEX_ATTRIB_ARRAY_SIZE: {
- GLint result { 0 };
- m_context->get_vertex_attribiv_robust_angle(index, GL_VERTEX_ATTRIB_ARRAY_SIZE, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_VERTEX_ATTRIB_ARRAY_STRIDE: {
- GLint result { 0 };
- m_context->get_vertex_attribiv_robust_angle(index, GL_VERTEX_ATTRIB_ARRAY_STRIDE, 1, nullptr, &result);
- return JS::Value(result);
- }
- case GL_VERTEX_ATTRIB_ARRAY_TYPE: {
- GLint result { 0 };
- m_context->get_vertex_attribiv_robust_angle(index, GL_VERTEX_ATTRIB_ARRAY_TYPE, 1, nullptr, &result);
- return JS::Value(result);
- }
- default:
- dbgln("Unknown WebGL vertex attrib name: 0x{:04x}", pname);
- set_error(GL_INVALID_ENUM);
- return JS::js_null();
- }
-}
-
-WebIDL::LongLong WebGLRenderingContextImpl::get_vertex_attrib_offset(WebIDL::UnsignedLong index, WebIDL::UnsignedLong pname)
-{
- if (pname != GL_VERTEX_ATTRIB_ARRAY_POINTER) {
- set_error(GL_INVALID_ENUM);
- return 0;
- }
-
- GLintptr result { 0 };
- m_context->get_vertex_attrib_pointerv_robust_angle(index, GL_VERTEX_ATTRIB_ARRAY_POINTER, 1, nullptr, reinterpret_cast<void**>(&result));
- return result;
-}
-
-void WebGLRenderingContextImpl::hint(WebIDL::UnsignedLong target, WebIDL::UnsignedLong mode)
-{
- m_context->make_current();
- m_context->hint(target, mode);
-}
-
-bool WebGLRenderingContextImpl::is_buffer(GC::Ptr<WebGLBuffer> buffer)
-{
- m_context->make_current();
-
- if (!buffer)
- return false;
-
- auto handle_or_error = buffer->handle_for_query(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return false;
- }
- auto buffer_handle = handle_or_error.release_value();
- if (!buffer_handle.has_value())
- return false;
- return m_context->is_buffer(buffer_handle.value());
-}
-
-bool WebGLRenderingContextImpl::is_enabled(WebIDL::UnsignedLong cap)
-{
- m_context->make_current();
- return m_context->is_enabled(cap);
-}
-
-bool WebGLRenderingContextImpl::is_framebuffer(GC::Ptr<WebGLFramebuffer> framebuffer)
-{
- m_context->make_current();
-
- if (!framebuffer)
- return false;
-
- auto handle_or_error = framebuffer->handle_for_query(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return false;
- }
- auto framebuffer_handle = handle_or_error.release_value();
- if (!framebuffer_handle.has_value())
- return false;
- return m_context->is_framebuffer(framebuffer_handle.value());
-}
-
-bool WebGLRenderingContextImpl::is_program(GC::Ptr<WebGLProgram> program)
-{
- m_context->make_current();
-
- if (!program)
- return false;
-
- auto handle_or_error = program->handle_for_query(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return false;
- }
- auto program_handle = handle_or_error.release_value();
- if (!program_handle.has_value())
- return false;
- return m_context->is_program(program_handle.value());
-}
-
-bool WebGLRenderingContextImpl::is_renderbuffer(GC::Ptr<WebGLRenderbuffer> renderbuffer)
-{
- m_context->make_current();
-
- if (!renderbuffer)
- return false;
-
- auto handle_or_error = renderbuffer->handle_for_query(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return false;
- }
- auto renderbuffer_handle = handle_or_error.release_value();
- if (!renderbuffer_handle.has_value())
- return false;
- return m_context->is_renderbuffer(renderbuffer_handle.value());
-}
-
-bool WebGLRenderingContextImpl::is_shader(GC::Ptr<WebGLShader> shader)
-{
- m_context->make_current();
-
- if (!shader)
- return false;
-
- auto handle_or_error = shader->handle_for_query(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return false;
- }
- auto shader_handle = handle_or_error.release_value();
- if (!shader_handle.has_value())
- return false;
- return m_context->is_shader(shader_handle.value());
-}
-
-bool WebGLRenderingContextImpl::is_texture(GC::Ptr<WebGLTexture> texture)
-{
- m_context->make_current();
-
- if (!texture)
- return false;
-
- auto handle_or_error = texture->handle_for_query(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return false;
- }
- auto texture_handle = handle_or_error.release_value();
- if (!texture_handle.has_value())
- return false;
- return m_context->is_texture(texture_handle.value());
-}
-
-void WebGLRenderingContextImpl::line_width(float width)
-{
- m_context->make_current();
- m_context->line_width(width);
-}
-
-void WebGLRenderingContextImpl::link_program(GC::Ref<WebGLProgram> program)
-{
- m_context->make_current();
-
- auto handle_or_error = program->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- auto program_handle = handle_or_error.release_value();
- m_context->link_program(program_handle);
-}
-
-void WebGLRenderingContextImpl::pixel_storei(WebIDL::UnsignedLong pname, WebIDL::Long param)
-{
- m_context->make_current();
-
- switch (pname) {
- case GL_UNPACK_ALIGNMENT:
- if (!first_is_one_of(param, 1, 2, 4, 8)) {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_unpack_state.alignment = param;
- break;
- case GL_UNPACK_ROW_LENGTH:
- if (m_context->webgl_version() == WebGLVersion::WebGL2 && param >= 0)
- m_unpack_state.row_length = param;
- break;
- case GL_UNPACK_SKIP_PIXELS:
- if (m_context->webgl_version() == WebGLVersion::WebGL2 && param >= 0)
- m_unpack_state.skip_pixels = param;
- break;
- case GL_UNPACK_SKIP_ROWS:
- if (m_context->webgl_version() == WebGLVersion::WebGL2 && param >= 0)
- m_unpack_state.skip_rows = param;
- break;
- case UNPACK_FLIP_Y_WEBGL:
- m_unpack_flip_y = param != GL_FALSE;
- return;
- case UNPACK_PREMULTIPLY_ALPHA_WEBGL:
- m_unpack_premultiply_alpha = param != GL_FALSE;
- return;
- case UNPACK_COLORSPACE_CONVERSION_WEBGL:
- m_unpack_colorspace_conversion = param;
- return;
- }
-
- m_context->pixel_storei(pname, param);
-}
-
-void WebGLRenderingContextImpl::polygon_offset(float factor, float units)
-{
- m_context->make_current();
- m_context->polygon_offset(factor, units);
-}
-
-void WebGLRenderingContextImpl::renderbuffer_storage(WebIDL::UnsignedLong target, WebIDL::UnsignedLong internalformat, WebIDL::Long width, WebIDL::Long height)
-{
- m_context->make_current();
-
- if (internalformat == GL_DEPTH_STENCIL)
- internalformat = GL_DEPTH24_STENCIL8;
-
- m_context->renderbuffer_storage(target, internalformat, width, height);
-}
-
-void WebGLRenderingContextImpl::sample_coverage(float value, bool invert)
-{
- m_context->make_current();
- m_context->sample_coverage(value, invert);
-}
-
-void WebGLRenderingContextImpl::scissor(WebIDL::Long x, WebIDL::Long y, WebIDL::Long width, WebIDL::Long height)
-{
- m_context->make_current();
- m_context->scissor(x, y, width, height);
-}
-
-void WebGLRenderingContextImpl::shader_source(GC::Ref<WebGLShader> shader, Utf16String source)
-{
- m_context->make_current();
-
- auto handle_or_error = shader->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- auto shader_handle = handle_or_error.release_value();
-
- Vector<GLchar*> strings;
- auto source_utf8 = source.to_utf8();
- auto string = null_terminated_string(source_utf8.bytes_as_string_view());
- strings.append(string.data());
- Vector<GLint> length;
- length.append(source_utf8.bytes().size());
- m_context->shader_source(shader_handle, 1, strings.data(), length.data());
-}
-
-void WebGLRenderingContextImpl::stencil_func(WebIDL::UnsignedLong func, WebIDL::Long ref, WebIDL::UnsignedLong mask)
-{
- m_context->make_current();
- m_context->stencil_func(func, ref, mask);
-}
-
-void WebGLRenderingContextImpl::stencil_func_separate(WebIDL::UnsignedLong face, WebIDL::UnsignedLong func, WebIDL::Long ref, WebIDL::UnsignedLong mask)
-{
- m_context->make_current();
- m_context->stencil_func_separate(face, func, ref, mask);
-}
-
-void WebGLRenderingContextImpl::stencil_mask(WebIDL::UnsignedLong mask)
-{
- m_context->make_current();
- m_context->stencil_mask(mask);
-}
-
-void WebGLRenderingContextImpl::stencil_mask_separate(WebIDL::UnsignedLong face, WebIDL::UnsignedLong mask)
-{
- m_context->make_current();
- m_context->stencil_mask_separate(face, mask);
-}
-
-void WebGLRenderingContextImpl::stencil_op(WebIDL::UnsignedLong fail, WebIDL::UnsignedLong zfail, WebIDL::UnsignedLong zpass)
-{
- m_context->make_current();
- m_context->stencil_op(fail, zfail, zpass);
-}
-
-void WebGLRenderingContextImpl::stencil_op_separate(WebIDL::UnsignedLong face, WebIDL::UnsignedLong fail, WebIDL::UnsignedLong zfail, WebIDL::UnsignedLong zpass)
-{
- m_context->make_current();
- m_context->stencil_op_separate(face, fail, zfail, zpass);
-}
-
-void WebGLRenderingContextImpl::tex_parameterf(WebIDL::UnsignedLong target, WebIDL::UnsignedLong pname, float param)
-{
- m_context->make_current();
- m_context->tex_parameterf(target, pname, param);
-}
-
-void WebGLRenderingContextImpl::tex_parameteri(WebIDL::UnsignedLong target, WebIDL::UnsignedLong pname, WebIDL::Long param)
-{
- m_context->make_current();
- m_context->tex_parameteri(target, pname, param);
-}
-
-void WebGLRenderingContextImpl::uniform1f(GC::Ptr<WebGLUniformLocation> location, float x)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- m_context->uniform1f(location_handle, x);
-}
-
-void WebGLRenderingContextImpl::uniform2f(GC::Ptr<WebGLUniformLocation> location, float x, float y)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- m_context->uniform2f(location_handle, x, y);
-}
-
-void WebGLRenderingContextImpl::uniform3f(GC::Ptr<WebGLUniformLocation> location, float x, float y, float z)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- m_context->uniform3f(location_handle, x, y, z);
-}
-
-void WebGLRenderingContextImpl::uniform4f(GC::Ptr<WebGLUniformLocation> location, float x, float y, float z, float w)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- m_context->uniform4f(location_handle, x, y, z, w);
-}
-
-void WebGLRenderingContextImpl::uniform1i(GC::Ptr<WebGLUniformLocation> location, WebIDL::Long x)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- m_context->uniform1i(location_handle, x);
-}
-
-void WebGLRenderingContextImpl::uniform2i(GC::Ptr<WebGLUniformLocation> location, WebIDL::Long x, WebIDL::Long y)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- m_context->uniform2i(location_handle, x, y);
-}
-
-void WebGLRenderingContextImpl::uniform3i(GC::Ptr<WebGLUniformLocation> location, WebIDL::Long x, WebIDL::Long y, WebIDL::Long z)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- m_context->uniform3i(location_handle, x, y, z);
-}
-
-void WebGLRenderingContextImpl::uniform4i(GC::Ptr<WebGLUniformLocation> location, WebIDL::Long x, WebIDL::Long y, WebIDL::Long z, WebIDL::Long w)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- m_context->uniform4i(location_handle, x, y, z, w);
-}
-
-void WebGLRenderingContextImpl::use_program(GC::Ptr<WebGLProgram> program)
-{
- m_context->make_current();
-
- GLuint program_handle = 0;
- if (program) {
- auto handle_or_error = program->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- program_handle = handle_or_error.release_value();
- }
-
- m_context->use_program(program_handle);
- m_current_program = program;
-}
-
-void WebGLRenderingContextImpl::validate_program(GC::Ref<WebGLProgram> program)
-{
- m_context->make_current();
-
- auto handle_or_error = program->handle(this);
- if (handle_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- auto program_handle = handle_or_error.release_value();
- m_context->validate_program(program_handle);
-}
-
-void WebGLRenderingContextImpl::vertex_attrib1f(WebIDL::UnsignedLong index, float x)
-{
- m_context->make_current();
- m_context->vertex_attrib1f(index, x);
-}
-
-void WebGLRenderingContextImpl::vertex_attrib2f(WebIDL::UnsignedLong index, float x, float y)
-{
- m_context->make_current();
- m_context->vertex_attrib2f(index, x, y);
-}
-
-void WebGLRenderingContextImpl::vertex_attrib3f(WebIDL::UnsignedLong index, float x, float y, float z)
-{
- m_context->make_current();
- m_context->vertex_attrib3f(index, x, y, z);
-}
-
-void WebGLRenderingContextImpl::vertex_attrib4f(WebIDL::UnsignedLong index, float x, float y, float z, float w)
-{
- m_context->make_current();
- m_context->vertex_attrib4f(index, x, y, z, w);
-}
-
-void WebGLRenderingContextImpl::vertex_attrib1fv(WebIDL::UnsignedLong index, Float32List values)
-{
- m_context->make_current();
-
- auto span = MUST(span_from_float32_list(values, /* src_offset= */ 0));
- if (span.size() < 1) {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_context->vertex_attrib1fv(index, span.data());
-}
-
-void WebGLRenderingContextImpl::vertex_attrib2fv(WebIDL::UnsignedLong index, Float32List values)
-{
- m_context->make_current();
-
- auto span = MUST(span_from_float32_list(values, /* src_offset= */ 0));
- if (span.size() < 2) {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_context->vertex_attrib2fv(index, span.data());
-}
-
-void WebGLRenderingContextImpl::vertex_attrib3fv(WebIDL::UnsignedLong index, Float32List values)
-{
- m_context->make_current();
-
- auto span = MUST(span_from_float32_list(values, /* src_offset= */ 0));
- if (span.size() < 3) {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_context->vertex_attrib3fv(index, span.data());
-}
-
-void WebGLRenderingContextImpl::vertex_attrib4fv(WebIDL::UnsignedLong index, Float32List values)
-{
- m_context->make_current();
-
- auto span = MUST(span_from_float32_list(values, /* src_offset= */ 0));
- if (span.size() < 4) {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_context->vertex_attrib4fv(index, span.data());
-}
-
-void WebGLRenderingContextImpl::vertex_attrib_pointer(WebIDL::UnsignedLong index, WebIDL::Long size, WebIDL::UnsignedLong type, bool normalized, WebIDL::Long stride, WebIDL::LongLong offset)
-{
- m_context->make_current();
-
- // If no WebGLBuffer is bound to the ARRAY_BUFFER target and offset is non-zero, an INVALID_OPERATION error will be generated.
- if (!m_array_buffer_binding && offset != 0) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
-
- m_context->vertex_attrib_pointer(index, size, type, normalized, stride, reinterpret_cast<void*>(offset));
-}
-
-void WebGLRenderingContextImpl::viewport(WebIDL::Long x, WebIDL::Long y, WebIDL::Long width, WebIDL::Long height)
-{
- m_context->make_current();
- m_context->viewport(x, y, width, height);
-}
-
-void WebGLRenderingContextImpl::visit_edges(JS::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
-
- visitor.visit(m_array_buffer_binding);
- visitor.visit(m_element_array_buffer_binding);
- visitor.visit(m_current_program);
- visitor.visit(m_framebuffer_binding);
- visitor.visit(m_renderbuffer_binding);
- visitor.visit(m_texture_binding_2d);
- visitor.visit(m_texture_binding_cube_map);
-
- visitor.visit(m_uniform_buffer_binding);
- visitor.visit(m_copy_read_buffer_binding);
- visitor.visit(m_copy_write_buffer_binding);
- visitor.visit(m_transform_feedback_buffer_binding);
- visitor.visit(m_texture_binding_2d_array);
- visitor.visit(m_texture_binding_3d);
- visitor.visit(m_transform_feedback_binding);
- visitor.visit(m_pixel_pack_buffer_binding);
- visitor.visit(m_pixel_unpack_buffer_binding);
- visitor.visit(m_any_samples_passed);
- visitor.visit(m_any_samples_passed_conservative);
- visitor.visit(m_transform_feedback_primitives_written);
-}
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLRenderingContextImpl.h b/Libraries/LibWeb/WebGL/WebGLRenderingContextImpl.h
deleted file mode 100644
index 10bd5daf0c8..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLRenderingContextImpl.h
+++ /dev/null
@@ -1,179 +0,0 @@
-/*
- * Copyright (c) 2024-2025, Aliaksandr Kalenik <[email protected]>
- * Copyright (c) 2024-2025, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/NonnullOwnPtr.h>
-#include <AK/Utf16String.h>
-#include <LibGC/Ptr.h>
-#include <LibWeb/Bindings/PlatformObject.h>
-#include <LibWeb/Forward.h>
-#include <LibWeb/WebGL/Types.h>
-#include <LibWeb/WebGL/WebGLRenderingContextBase.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-#include <LibWebCommon/WebIDL/Types.h>
-
-namespace Web::WebGL {
-
-using namespace Web::HTML;
-
-class WebGLRenderingContextImpl : public WebGLRenderingContextBase {
- WEB_NON_IDL_WRAPPABLE(WebGLRenderingContextImpl, WebGLRenderingContextBase);
-
-public:
- WebGLRenderingContextImpl(JS::Realm&, NonnullOwnPtr<WebGLContextProxy>);
-
- virtual WebGLContextProxy& context() override { return *m_context; }
-
- virtual void prepare_for_compositing() = 0;
- virtual void did_update_canvas_content() = 0;
-
- void active_texture(WebIDL::UnsignedLong texture);
- void attach_shader(GC::Ref<WebGLProgram> program, GC::Ref<WebGLShader> shader);
- void bind_attrib_location(GC::Ref<WebGLProgram> program, WebIDL::UnsignedLong index, Utf16String name);
- void bind_buffer(WebIDL::UnsignedLong target, GC::Ptr<WebGLBuffer> buffer);
- void bind_framebuffer(WebIDL::UnsignedLong target, GC::Ptr<WebGLFramebuffer> framebuffer);
- void bind_renderbuffer(WebIDL::UnsignedLong target, GC::Ptr<WebGLRenderbuffer> renderbuffer);
- void bind_texture(WebIDL::UnsignedLong target, GC::Ptr<WebGLTexture> texture);
- void blend_color(float red, float green, float blue, float alpha);
- void blend_equation(WebIDL::UnsignedLong mode);
- void blend_equation_separate(WebIDL::UnsignedLong mode_rgb, WebIDL::UnsignedLong mode_alpha);
- void blend_func(WebIDL::UnsignedLong sfactor, WebIDL::UnsignedLong dfactor);
- void blend_func_separate(WebIDL::UnsignedLong src_rgb, WebIDL::UnsignedLong dst_rgb, WebIDL::UnsignedLong src_alpha, WebIDL::UnsignedLong dst_alpha);
- WebIDL::UnsignedLong check_framebuffer_status(WebIDL::UnsignedLong target);
- void clear(WebIDL::UnsignedLong mask);
- void clear_color(float red, float green, float blue, float alpha);
- void clear_depth(float depth);
- void clear_stencil(WebIDL::Long s);
- void color_mask(bool red, bool green, bool blue, bool alpha);
- void compile_shader(GC::Ref<WebGLShader> shader);
- void copy_tex_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::UnsignedLong internalformat, WebIDL::Long x, WebIDL::Long y, WebIDL::Long width, WebIDL::Long height, WebIDL::Long border);
- void copy_tex_sub_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long xoffset, WebIDL::Long yoffset, WebIDL::Long x, WebIDL::Long y, WebIDL::Long width, WebIDL::Long height);
- GC::Ref<WebGLBuffer> create_buffer();
- GC::Ref<WebGLFramebuffer> create_framebuffer();
- GC::Ref<WebGLProgram> create_program();
- GC::Ref<WebGLRenderbuffer> create_renderbuffer();
- GC::Ptr<WebGLShader> create_shader(WebIDL::UnsignedLong type);
- GC::Ref<WebGLTexture> create_texture();
- void cull_face(WebIDL::UnsignedLong mode);
- void delete_buffer(GC::Ptr<WebGLBuffer> buffer);
- void delete_framebuffer(GC::Ptr<WebGLFramebuffer> framebuffer);
- void delete_program(GC::Ptr<WebGLProgram> program);
- void delete_renderbuffer(GC::Ptr<WebGLRenderbuffer> renderbuffer);
- void delete_shader(GC::Ptr<WebGLShader> shader);
- void delete_texture(GC::Ptr<WebGLTexture> texture);
- void depth_func(WebIDL::UnsignedLong func);
- void depth_mask(bool flag);
- void depth_range(float z_near, float z_far);
- void detach_shader(GC::Ref<WebGLProgram> program, GC::Ref<WebGLShader> shader);
- void disable(WebIDL::UnsignedLong cap);
- void disable_vertex_attrib_array(WebIDL::UnsignedLong index);
- void draw_arrays(WebIDL::UnsignedLong mode, WebIDL::Long first, WebIDL::Long count);
- void draw_elements(WebIDL::UnsignedLong mode, WebIDL::Long count, WebIDL::UnsignedLong type, WebIDL::LongLong offset);
- void enable(WebIDL::UnsignedLong cap);
- void enable_vertex_attrib_array(WebIDL::UnsignedLong index);
- void finish();
- void flush();
- void framebuffer_renderbuffer(WebIDL::UnsignedLong target, WebIDL::UnsignedLong attachment, WebIDL::UnsignedLong renderbuffertarget, GC::Ptr<WebGLRenderbuffer> renderbuffer);
- void framebuffer_texture2d(WebIDL::UnsignedLong target, WebIDL::UnsignedLong attachment, WebIDL::UnsignedLong textarget, GC::Ptr<WebGLTexture> texture, WebIDL::Long level);
- void front_face(WebIDL::UnsignedLong mode);
- void generate_mipmap(WebIDL::UnsignedLong target);
- GC::Ptr<WebGLActiveInfo> get_active_attrib(GC::Ref<WebGLProgram> program, WebIDL::UnsignedLong index);
- GC::Ptr<WebGLActiveInfo> get_active_uniform(GC::Ref<WebGLProgram> program, WebIDL::UnsignedLong index);
- Optional<Vector<GC::Root<WebGLShader>>> get_attached_shaders(GC::Ref<WebGLProgram> program);
- WebIDL::Long get_attrib_location(GC::Ref<WebGLProgram> program, Utf16String name);
- JS::Value get_buffer_parameter(WebIDL::UnsignedLong target, WebIDL::UnsignedLong pname);
- WebIDL::ExceptionOr<JS::Value> get_parameter(JS::Realm&, WebIDL::UnsignedLong pname);
- JS::Value get_framebuffer_attachment_parameter(JS::Realm&, WebIDL::UnsignedLong target, WebIDL::UnsignedLong attachment, WebIDL::UnsignedLong pname);
- WebIDL::UnsignedLong get_error();
- JS::Value get_program_parameter(GC::Ref<WebGLProgram> program, WebIDL::UnsignedLong pname);
- Optional<Utf16String> get_program_info_log(GC::Ref<WebGLProgram> program);
- JS::Value get_renderbuffer_parameter(WebIDL::UnsignedLong target, WebIDL::UnsignedLong pname);
- JS::Value get_shader_parameter(GC::Ref<WebGLShader> shader, WebIDL::UnsignedLong pname);
- GC::Ptr<WebGLShaderPrecisionFormat> get_shader_precision_format(WebIDL::UnsignedLong shadertype, WebIDL::UnsignedLong precisiontype);
- Optional<Utf16String> get_shader_info_log(GC::Ref<WebGLShader> shader);
- Optional<Utf16String> get_shader_source(GC::Ref<WebGLShader> shader);
- JS::Value get_tex_parameter(WebIDL::UnsignedLong target, WebIDL::UnsignedLong pname);
- JS::Value get_uniform(GC::Ref<WebGLProgram> program, GC::Ref<WebGLUniformLocation> location);
- GC::Ptr<WebGLUniformLocation> get_uniform_location(GC::Ref<WebGLProgram> program, Utf16String name);
- JS::Value get_vertex_attrib(JS::Realm&, WebIDL::UnsignedLong index, WebIDL::UnsignedLong pname);
- WebIDL::LongLong get_vertex_attrib_offset(WebIDL::UnsignedLong index, WebIDL::UnsignedLong pname);
- void hint(WebIDL::UnsignedLong target, WebIDL::UnsignedLong mode);
- bool is_buffer(GC::Ptr<WebGLBuffer> buffer);
- bool is_enabled(WebIDL::UnsignedLong cap);
- bool is_framebuffer(GC::Ptr<WebGLFramebuffer> framebuffer);
- bool is_program(GC::Ptr<WebGLProgram> program);
- bool is_renderbuffer(GC::Ptr<WebGLRenderbuffer> renderbuffer);
- bool is_shader(GC::Ptr<WebGLShader> shader);
- bool is_texture(GC::Ptr<WebGLTexture> texture);
- void line_width(float width);
- void link_program(GC::Ref<WebGLProgram> program);
- void pixel_storei(WebIDL::UnsignedLong pname, WebIDL::Long param);
- void polygon_offset(float factor, float units);
- void renderbuffer_storage(WebIDL::UnsignedLong target, WebIDL::UnsignedLong internalformat, WebIDL::Long width, WebIDL::Long height);
- void sample_coverage(float value, bool invert);
- void scissor(WebIDL::Long x, WebIDL::Long y, WebIDL::Long width, WebIDL::Long height);
- void shader_source(GC::Ref<WebGLShader> shader, Utf16String source);
- void stencil_func(WebIDL::UnsignedLong func, WebIDL::Long ref, WebIDL::UnsignedLong mask);
- void stencil_func_separate(WebIDL::UnsignedLong face, WebIDL::UnsignedLong func, WebIDL::Long ref, WebIDL::UnsignedLong mask);
- void stencil_mask(WebIDL::UnsignedLong mask);
- void stencil_mask_separate(WebIDL::UnsignedLong face, WebIDL::UnsignedLong mask);
- void stencil_op(WebIDL::UnsignedLong fail, WebIDL::UnsignedLong zfail, WebIDL::UnsignedLong zpass);
- void stencil_op_separate(WebIDL::UnsignedLong face, WebIDL::UnsignedLong fail, WebIDL::UnsignedLong zfail, WebIDL::UnsignedLong zpass);
- void tex_parameterf(WebIDL::UnsignedLong target, WebIDL::UnsignedLong pname, float param);
- void tex_parameteri(WebIDL::UnsignedLong target, WebIDL::UnsignedLong pname, WebIDL::Long param);
- void uniform1f(GC::Ptr<WebGLUniformLocation> location, float x);
- void uniform2f(GC::Ptr<WebGLUniformLocation> location, float x, float y);
- void uniform3f(GC::Ptr<WebGLUniformLocation> location, float x, float y, float z);
- void uniform4f(GC::Ptr<WebGLUniformLocation> location, float x, float y, float z, float w);
- void uniform1i(GC::Ptr<WebGLUniformLocation> location, WebIDL::Long x);
- void uniform2i(GC::Ptr<WebGLUniformLocation> location, WebIDL::Long x, WebIDL::Long y);
- void uniform3i(GC::Ptr<WebGLUniformLocation> location, WebIDL::Long x, WebIDL::Long y, WebIDL::Long z);
- void uniform4i(GC::Ptr<WebGLUniformLocation> location, WebIDL::Long x, WebIDL::Long y, WebIDL::Long z, WebIDL::Long w);
- void use_program(GC::Ptr<WebGLProgram> program);
- void validate_program(GC::Ref<WebGLProgram> program);
- void vertex_attrib1f(WebIDL::UnsignedLong index, float x);
- void vertex_attrib2f(WebIDL::UnsignedLong index, float x, float y);
- void vertex_attrib3f(WebIDL::UnsignedLong index, float x, float y, float z);
- void vertex_attrib4f(WebIDL::UnsignedLong index, float x, float y, float z, float w);
- void vertex_attrib1fv(WebIDL::UnsignedLong index, Float32List values);
- void vertex_attrib2fv(WebIDL::UnsignedLong index, Float32List values);
- void vertex_attrib3fv(WebIDL::UnsignedLong index, Float32List values);
- void vertex_attrib4fv(WebIDL::UnsignedLong index, Float32List values);
- void vertex_attrib_pointer(WebIDL::UnsignedLong index, WebIDL::Long size, WebIDL::UnsignedLong type, bool normalized, WebIDL::Long stride, WebIDL::LongLong offset);
- void viewport(WebIDL::Long x, WebIDL::Long y, WebIDL::Long width, WebIDL::Long height);
-
-protected:
- virtual void visit_edges(JS::Cell::Visitor&) override;
- virtual void reset_client_side_webgl_state() override;
-
- GC::Ptr<WebGLBuffer> m_array_buffer_binding;
- GC::Ptr<WebGLBuffer> m_element_array_buffer_binding;
- GC::Ptr<WebGLProgram> m_current_program;
- GC::Ptr<WebGLFramebuffer> m_framebuffer_binding;
- GC::Ptr<WebGLRenderbuffer> m_renderbuffer_binding;
- GC::Ptr<WebGLTexture> m_texture_binding_2d;
- GC::Ptr<WebGLTexture> m_texture_binding_cube_map;
-
- // FIXME: Those are WebGL2 only but those need to be accessible from shared methods
- GC::Ptr<WebGLBuffer> m_uniform_buffer_binding;
- GC::Ptr<WebGLBuffer> m_copy_read_buffer_binding;
- GC::Ptr<WebGLBuffer> m_copy_write_buffer_binding;
- GC::Ptr<WebGLBuffer> m_transform_feedback_buffer_binding;
- GC::Ptr<WebGLBuffer> m_pixel_pack_buffer_binding;
- GC::Ptr<WebGLBuffer> m_pixel_unpack_buffer_binding;
- GC::Ptr<WebGLTexture> m_texture_binding_2d_array;
- GC::Ptr<WebGLTexture> m_texture_binding_3d;
- GC::Ptr<WebGLTransformFeedback> m_transform_feedback_binding;
- GC::Ptr<WebGLQuery> m_any_samples_passed;
- GC::Ptr<WebGLQuery> m_any_samples_passed_conservative;
- GC::Ptr<WebGLQuery> m_transform_feedback_primitives_written;
-
- NonnullOwnPtr<WebGLContextProxy> m_context;
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLRenderingContextOverloads.cpp b/Libraries/LibWeb/WebGL/WebGLRenderingContextOverloads.cpp
deleted file mode 100644
index 88a31213326..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLRenderingContextOverloads.cpp
+++ /dev/null
@@ -1,418 +0,0 @@
-/*
- * Copyright (c) 2024-2025, Aliaksandr Kalenik <[email protected]>
- * Copyright (c) 2024-2025, Luke Wilde <[email protected]>
- * Copyright (c) 2025, Undefine <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <GLES2/gl2.h>
-#include <GLES2/gl2ext.h>
-extern "C" {
-#include <GLES2/gl2ext_angle.h>
-}
-
-#include <LibJS/Runtime/ArrayBuffer.h>
-#include <LibJS/Runtime/DataView.h>
-#include <LibJS/Runtime/TypedArray.h>
-#include <LibWeb/WebGL/WebGLContextProxy.h>
-#include <LibWeb/WebGL/WebGLRenderingContextOverloads.h>
-#include <LibWeb/WebGL/WebGLUniformLocation.h>
-
-namespace Web::WebGL {
-
-WebGLRenderingContextOverloads::WebGLRenderingContextOverloads(JS::Realm& realm, NonnullOwnPtr<WebGLContextProxy> context)
- : WebGLRenderingContextImpl(realm, move(context))
-{
-}
-
-void WebGLRenderingContextOverloads::buffer_data(WebIDL::UnsignedLong target, WebIDL::LongLong size, WebIDL::UnsignedLong usage)
-{
- m_context->make_current();
-
- m_context->buffer_data(target, size, 0, usage);
-}
-
-void WebGLRenderingContextOverloads::buffer_data(WebIDL::UnsignedLong target, WebIDL::NullableBufferSourceVariant data, WebIDL::UnsignedLong usage)
-{
- m_context->make_current();
-
- // https://registry.khronos.org/webgl/specs/latest/1.0/#5.14.5
- // If the passed data is null then an INVALID_VALUE error is generated.
- if (data.has<Empty>()) {
- set_error(GL_INVALID_VALUE);
- return;
- }
-
- SET_ERROR_VALUE_IF_ERROR(with_buffer_source_bytes(WebIDL::BufferSource { data.downcast<WebIDL::BufferSourceVariant>() }, /* src_offset= */ 0, /* src_length_override= */ 0, [&](ReadonlyBytes bytes) {
- m_context->buffer_data(target, static_cast<GLsizeiptr>(bytes.size()), bytes.data(), usage);
- }),
- GL_INVALID_VALUE);
-}
-
-void WebGLRenderingContextOverloads::buffer_sub_data(WebIDL::UnsignedLong target, WebIDL::LongLong offset, WebIDL::BufferSource data)
-{
- m_context->make_current();
-
- SET_ERROR_VALUE_IF_ERROR(with_buffer_source_bytes(data, /* src_offset= */ 0, /* src_length_override= */ 0, [&](ReadonlyBytes bytes) {
- m_context->buffer_sub_data(target, offset, bytes.size(), bytes.data());
- }),
- GL_INVALID_VALUE);
-}
-
-void WebGLRenderingContextOverloads::compressed_tex_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::UnsignedLong internalformat, WebIDL::Long width, WebIDL::Long height, WebIDL::Long border, WebIDL::ArrayBufferView data)
-{
- m_context->make_current();
-
- if (!enabled_compressed_texture_formats().contains_slow(internalformat)) {
- set_error(GL_INVALID_ENUM);
- return;
- }
-
- SET_ERROR_VALUE_IF_ERROR(with_buffer_source_bytes(WebIDL::BufferSource { data }, /* src_offset= */ 0, /* src_length_override= */ 0, [&](ReadonlyBytes bytes) {
- m_context->compressed_tex_image2d_robust_angle(target, level, internalformat, width, height, border, bytes.size(), bytes.size(), bytes.data());
- }),
- GL_INVALID_VALUE);
-}
-
-void WebGLRenderingContextOverloads::compressed_tex_sub_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long xoffset, WebIDL::Long yoffset, WebIDL::Long width, WebIDL::Long height, WebIDL::UnsignedLong format, WebIDL::ArrayBufferView data)
-{
- m_context->make_current();
-
- if (!enabled_compressed_texture_formats().contains_slow(format)) {
- set_error(GL_INVALID_ENUM);
- return;
- }
-
- SET_ERROR_VALUE_IF_ERROR(with_buffer_source_bytes(WebIDL::BufferSource { data }, /* src_offset= */ 0, /* src_length_override= */ 0, [&](ReadonlyBytes bytes) {
- m_context->compressed_tex_sub_image2d_robust_angle(target, level, xoffset, yoffset, width, height, format, bytes.size(), bytes.size(), bytes.data());
- }),
- GL_INVALID_VALUE);
-}
-
-void WebGLRenderingContextOverloads::read_pixels(WebIDL::Long x, WebIDL::Long y, WebIDL::Long width, WebIDL::Long height, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, WebIDL::NullableArrayBufferViewVariant pixels)
-{
- m_context->make_current();
-
- if (pixels.has<Empty>()) {
- set_error(GL_INVALID_VALUE);
- return;
- }
-
- WebIDL::ArrayBufferView view { pixels.downcast<WebIDL::ArrayBufferViewVariant>() };
- auto validated_view_or_error = WebIDL::validate_array_buffer_view(view);
- if (validated_view_or_error.is_error()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
- auto validated_view = validated_view_or_error.release_value();
-
- auto bytes_or_error = ByteBuffer::create_uninitialized(validated_view.byte_length);
- if (bytes_or_error.is_error()) {
- set_error(GL_OUT_OF_MEMORY);
- return;
- }
- auto bytes = bytes_or_error.release_value();
- GLsizei bytes_read = 0;
- m_context->read_pixels_robust_angle(x, y, width, height, format, type, bytes.size(), &bytes_read, nullptr, nullptr, bytes.data());
- if (bytes_read == 0)
- return;
- VERIFY(bytes_read > 0);
- if (view.write_checked(ReadonlyBytes { bytes.data(), static_cast<size_t>(bytes_read) }).is_error()) [[unlikely]]
- set_error(GL_INVALID_OPERATION);
-}
-
-void WebGLRenderingContextOverloads::tex_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long internalformat, WebIDL::Long width, WebIDL::Long height, WebIDL::Long border, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, WebIDL::NullableArrayBufferViewVariant pixels)
-{
- m_context->make_current();
-
- if (!pixels.has<Empty>()) {
- SET_ERROR_VALUE_IF_ERROR(with_buffer_source_bytes(WebIDL::BufferSource { pixels.downcast<WebIDL::ArrayBufferViewVariant>() }, /* src_offset= */ 0, /* src_length_override= */ 0, [&](ReadonlyBytes bytes) -> ErrorOr<void> {
- auto texture_data = TRY(texture_data_for_2d_upload(bytes, width, height, format, type));
- m_context->tex_image2d_robust_angle(target, level, internalformat, width, height, border, format, type, texture_data.size(), texture_data.data());
- return {};
- }),
- GL_INVALID_OPERATION);
- return;
- }
-
- Checked<size_t> bytes = 0;
- if (type == GL_UNSIGNED_SHORT_5_6_5 && format != GL_RGB) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
-
- if ((type == GL_UNSIGNED_SHORT_4_4_4_4 || type == GL_UNSIGNED_SHORT_5_5_5_1) && format != GL_RGBA) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
-
- switch (format) {
- case GL_ALPHA:
- case GL_LUMINANCE:
- case GL_LUMINANCE_ALPHA: {
- if (type != GL_UNSIGNED_BYTE) {
- set_error(GL_INVALID_ENUM);
- return;
- }
-
- bytes = format == GL_LUMINANCE_ALPHA ? 2 : 1;
- break;
- }
- case GL_RGB:
- case GL_RGBA: {
- switch (type) {
- case GL_UNSIGNED_BYTE:
- bytes = format == GL_RGB ? 3 : 4;
- break;
- case GL_UNSIGNED_SHORT_4_4_4_4:
- case GL_UNSIGNED_SHORT_5_5_5_1:
- case GL_UNSIGNED_SHORT_5_6_5:
- bytes = 2;
- break;
- default:
- set_error(GL_INVALID_ENUM);
- return;
- }
-
- break;
- }
- default:
- set_error(GL_INVALID_ENUM);
- return;
- }
-
- bytes *= width;
- bytes *= height;
-
- if (bytes.has_overflow()) {
- set_error(GL_INVALID_OPERATION);
- return;
- }
-
- auto byte_buffer = MUST(ByteBuffer::create_zeroed(bytes.value_unchecked()));
- m_context->tex_image2d_robust_angle(target, level, internalformat, width, height, border, format, type, byte_buffer.size(), byte_buffer.data());
-}
-
-void WebGLRenderingContextOverloads::tex_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long internalformat, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, TexImageSource source)
-{
- m_context->make_current();
-
- auto maybe_source_frame = read_texture_image_source(source, format, type);
- if (!maybe_source_frame.has_value())
- return;
- auto source_frame = maybe_source_frame.release_value();
- m_context->tex_image2d_from_bitmap(target, level, internalformat, format, type, move(source_frame.frame), OptionalNone {}, source_frame.flip_y, source_frame.premultiply_alpha);
-}
-
-void WebGLRenderingContextOverloads::tex_sub_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long xoffset, WebIDL::Long yoffset, WebIDL::Long width, WebIDL::Long height, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, WebIDL::NullableArrayBufferViewVariant pixels)
-{
- m_context->make_current();
-
- if (pixels.has<Empty>()) {
- set_error(GL_INVALID_VALUE);
- return;
- }
-
- SET_ERROR_VALUE_IF_ERROR(with_buffer_source_bytes(WebIDL::BufferSource { pixels.downcast<WebIDL::ArrayBufferViewVariant>() }, /* src_offset= */ 0, /* src_length_override= */ 0, [&](ReadonlyBytes bytes) -> ErrorOr<void> {
- auto texture_data = TRY(texture_data_for_2d_upload(bytes, width, height, format, type));
- m_context->tex_sub_image2d_robust_angle(target, level, xoffset, yoffset, width, height, format, type, texture_data.size(), texture_data.data());
- return {};
- }),
- GL_INVALID_OPERATION);
-}
-
-void WebGLRenderingContextOverloads::tex_sub_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long xoffset, WebIDL::Long yoffset, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, TexImageSource source)
-{
- m_context->make_current();
-
- auto maybe_source_frame = read_texture_image_source(source, format, type);
- if (!maybe_source_frame.has_value())
- return;
- auto source_frame = maybe_source_frame.release_value();
- m_context->tex_sub_image2d_from_bitmap(target, level, xoffset, yoffset, format, type, move(source_frame.frame), OptionalNone {}, source_frame.flip_y, source_frame.premultiply_alpha);
-}
-
-void WebGLRenderingContextOverloads::uniform1fv(GC::Ptr<WebGLUniformLocation> location, Float32List v)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- auto span = MUST(span_from_float32_list(v, /* src_offset= */ 0));
- m_context->uniform1fv(location_handle, span.size(), span.data());
-}
-
-void WebGLRenderingContextOverloads::uniform2fv(GC::Ptr<WebGLUniformLocation> location, Float32List v)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- auto span = MUST(span_from_float32_list(v, /* src_offset= */ 0));
- if (span.size() % 2 != 0) [[unlikely]] {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_context->uniform2fv(location_handle, span.size() / 2, span.data());
-}
-
-void WebGLRenderingContextOverloads::uniform3fv(GC::Ptr<WebGLUniformLocation> location, Float32List v)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- auto span = MUST(span_from_float32_list(v, /* src_offset= */ 0));
- if (span.size() % 3 != 0) [[unlikely]] {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_context->uniform3fv(location_handle, span.size() / 3, span.data());
-}
-
-void WebGLRenderingContextOverloads::uniform4fv(GC::Ptr<WebGLUniformLocation> location, Float32List v)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- auto span = MUST(span_from_float32_list(v, /* src_offset= */ 0));
- if (span.size() % 4 != 0) [[unlikely]] {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_context->uniform4fv(location_handle, span.size() / 4, span.data());
-}
-
-void WebGLRenderingContextOverloads::uniform1iv(GC::Ptr<WebGLUniformLocation> location, Int32List v)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- auto span = MUST(span_from_int32_list(v, /* src_offset= */ 0));
- m_context->uniform1iv(location_handle, span.size(), span.data());
-}
-
-void WebGLRenderingContextOverloads::uniform2iv(GC::Ptr<WebGLUniformLocation> location, Int32List v)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- auto span = MUST(span_from_int32_list(v, /* src_offset= */ 0));
- if (span.size() % 2 != 0) [[unlikely]] {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_context->uniform2iv(location_handle, span.size() / 2, span.data());
-}
-
-void WebGLRenderingContextOverloads::uniform3iv(GC::Ptr<WebGLUniformLocation> location, Int32List v)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- auto span = MUST(span_from_int32_list(v, /* src_offset= */ 0));
- if (span.size() % 3 != 0) [[unlikely]] {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_context->uniform3iv(location_handle, span.size() / 3, span.data());
-}
-
-void WebGLRenderingContextOverloads::uniform4iv(GC::Ptr<WebGLUniformLocation> location, Int32List v)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- auto span = MUST(span_from_int32_list(v, /* src_offset= */ 0));
- if (span.size() % 4 != 0) [[unlikely]] {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_context->uniform4iv(location_handle, span.size() / 4, span.data());
-}
-
-void WebGLRenderingContextOverloads::uniform_matrix2fv(GC::Ptr<WebGLUniformLocation> location, bool transpose, Float32List value)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- constexpr auto matrix_size = 2 * 2;
- auto span = MUST(span_from_float32_list(value, /* src_offset= */ 0));
- if (span.size() % matrix_size != 0) [[unlikely]] {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_context->uniform_matrix2fv(location_handle, span.size() / matrix_size, transpose, span.data());
-}
-
-void WebGLRenderingContextOverloads::uniform_matrix3fv(GC::Ptr<WebGLUniformLocation> location, bool transpose, Float32List value)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- constexpr auto matrix_size = 3 * 3;
- auto span = MUST(span_from_float32_list(value, /* src_offset= */ 0));
- if (span.size() % matrix_size != 0) [[unlikely]] {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_context->uniform_matrix3fv(location_handle, span.size() / matrix_size, transpose, span.data());
-}
-
-void WebGLRenderingContextOverloads::uniform_matrix4fv(GC::Ptr<WebGLUniformLocation> location, bool transpose, Float32List value)
-{
- m_context->make_current();
-
- if (!location)
- return;
-
- GLuint location_handle = SET_ERROR_VALUE_IF_ERROR(location->handle(m_current_program), GL_INVALID_OPERATION);
-
- constexpr auto matrix_size = 4 * 4;
- auto span = MUST(span_from_float32_list(value, /* src_offset= */ 0));
- if (span.size() % matrix_size != 0) [[unlikely]] {
- set_error(GL_INVALID_VALUE);
- return;
- }
- m_context->uniform_matrix4fv(location_handle, span.size() / matrix_size, transpose, span.data());
-}
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLRenderingContextOverloads.h b/Libraries/LibWeb/WebGL/WebGLRenderingContextOverloads.h
deleted file mode 100644
index 531758abf58..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLRenderingContextOverloads.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (c) 2024-2025, Aliaksandr Kalenik <[email protected]>
- * Copyright (c) 2024-2025, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/NonnullOwnPtr.h>
-#include <AK/Optional.h>
-#include <LibGC/Ptr.h>
-#include <LibWeb/Forward.h>
-#include <LibWeb/WebGL/WebGLRenderingContextImpl.h>
-#include <LibWeb/WebIDL/Buffers.h>
-#include <LibWebCommon/WebIDL/Types.h>
-
-namespace Web::WebGL {
-
-using namespace Web::HTML;
-
-class WebGLRenderingContextOverloads : public WebGLRenderingContextImpl {
- WEB_NON_IDL_WRAPPABLE(WebGLRenderingContextOverloads, WebGLRenderingContextImpl);
-
-public:
- WebGLRenderingContextOverloads(JS::Realm&, NonnullOwnPtr<WebGLContextProxy>);
-
- void buffer_data(WebIDL::UnsignedLong target, WebIDL::LongLong size, WebIDL::UnsignedLong usage);
- void buffer_data(WebIDL::UnsignedLong target, WebIDL::NullableBufferSourceVariant data, WebIDL::UnsignedLong usage);
- void buffer_sub_data(WebIDL::UnsignedLong target, WebIDL::LongLong offset, WebIDL::BufferSource data);
- void compressed_tex_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::UnsignedLong internalformat, WebIDL::Long width, WebIDL::Long height, WebIDL::Long border, WebIDL::ArrayBufferView data);
- void compressed_tex_sub_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long xoffset, WebIDL::Long yoffset, WebIDL::Long width, WebIDL::Long height, WebIDL::UnsignedLong format, WebIDL::ArrayBufferView data);
- void read_pixels(WebIDL::Long x, WebIDL::Long y, WebIDL::Long width, WebIDL::Long height, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, WebIDL::NullableArrayBufferViewVariant pixels);
- void tex_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long internalformat, WebIDL::Long width, WebIDL::Long height, WebIDL::Long border, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, WebIDL::NullableArrayBufferViewVariant pixels);
- void tex_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long internalformat, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, TexImageSource source);
- void tex_sub_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long xoffset, WebIDL::Long yoffset, WebIDL::Long width, WebIDL::Long height, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, WebIDL::NullableArrayBufferViewVariant pixels);
- void tex_sub_image2d(WebIDL::UnsignedLong target, WebIDL::Long level, WebIDL::Long xoffset, WebIDL::Long yoffset, WebIDL::UnsignedLong format, WebIDL::UnsignedLong type, TexImageSource source);
- void uniform1fv(GC::Ptr<WebGLUniformLocation> location, Float32List v);
- void uniform2fv(GC::Ptr<WebGLUniformLocation> location, Float32List v);
- void uniform3fv(GC::Ptr<WebGLUniformLocation> location, Float32List v);
- void uniform4fv(GC::Ptr<WebGLUniformLocation> location, Float32List v);
- void uniform1iv(GC::Ptr<WebGLUniformLocation> location, Int32List v);
- void uniform2iv(GC::Ptr<WebGLUniformLocation> location, Int32List v);
- void uniform3iv(GC::Ptr<WebGLUniformLocation> location, Int32List v);
- void uniform4iv(GC::Ptr<WebGLUniformLocation> location, Int32List v);
- void uniform_matrix2fv(GC::Ptr<WebGLUniformLocation> location, bool transpose, Float32List value);
- void uniform_matrix3fv(GC::Ptr<WebGLUniformLocation> location, bool transpose, Float32List value);
- void uniform_matrix4fv(GC::Ptr<WebGLUniformLocation> location, bool transpose, Float32List value);
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLRenderingContextOverloads.idl b/Libraries/LibWeb/WebGL/WebGLRenderingContextOverloads.idl
index 6004ce839f1..f6499fbbbeb 100644
--- a/Libraries/LibWeb/WebGL/WebGLRenderingContextOverloads.idl
+++ b/Libraries/LibWeb/WebGL/WebGLRenderingContextOverloads.idl
@@ -11,9 +11,9 @@ typedef (Int32Array or sequence<GLint>) Int32List;
// https://registry.khronos.org/webgl/specs/latest/1.0/#5.14
interface mixin WebGLRenderingContextOverloads {
- undefined bufferData(GLenum target, GLsizeiptr size, GLenum usage);
+ [ImplementedAs=buffer_data_with_size] undefined bufferData(GLenum target, GLsizeiptr size, GLenum usage);
// FIXME: BufferSource is really a AllowSharedBufferSource
- undefined bufferData(GLenum target, BufferSource? data, GLenum usage);
+ [ImplementedAs=buffer_data] undefined bufferData(GLenum target, BufferSource? data, GLenum usage);
undefined bufferSubData(GLenum target, GLintptr offset, BufferSource data);
undefined compressedTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, [AllowShared] ArrayBufferView data);
@@ -21,11 +21,11 @@ interface mixin WebGLRenderingContextOverloads {
undefined readPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, [AllowShared] ArrayBufferView? pixels);
- undefined texImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, [AllowShared] ArrayBufferView? pixels);
- undefined texImage2D(GLenum target, GLint level, GLint internalformat, GLenum format, GLenum type, TexImageSource source); // May throw DOMException
+ [ImplementedAs=tex_image2d] undefined texImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, [AllowShared] ArrayBufferView? pixels);
+ [ImplementedAs=tex_image2d_with_source] undefined texImage2D(GLenum target, GLint level, GLint internalformat, GLenum format, GLenum type, TexImageSource source); // May throw DOMException
- undefined texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, [AllowShared] ArrayBufferView? pixels);
- undefined texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLenum format, GLenum type, TexImageSource source); // May throw DOMException
+ [ImplementedAs=tex_sub_image2d] undefined texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, [AllowShared] ArrayBufferView? pixels);
+ [ImplementedAs=tex_sub_image2d_with_source] undefined texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLenum format, GLenum type, TexImageSource source); // May throw DOMException
undefined uniform1fv(WebGLUniformLocation? location, Float32List v);
undefined uniform2fv(WebGLUniformLocation? location, Float32List v);
diff --git a/Libraries/LibWeb/WebGL/WebGLSampler.cpp b/Libraries/LibWeb/WebGL/WebGLSampler.cpp
deleted file mode 100644
index 8769fbf22f2..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLSampler.cpp
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (c) 2024, Andrew Kaster <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/Runtime/Realm.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/Bindings/WebGLSampler.h>
-#include <LibWeb/WebGL/WebGLSampler.h>
-
-namespace Web::WebGL {
-
-GC_DEFINE_ALLOCATOR(WebGLSampler);
-
-GC::Ref<WebGLSampler> WebGLSampler::create(GC::Ref<WebGLRenderingContextBase> context, GLuint handle)
-{
- auto& realm = context->realm();
- return realm.create<WebGLSampler>(realm, context, handle);
-}
-
-WebGLSampler::WebGLSampler(JS::Realm& realm, GC::Ref<WebGLRenderingContextBase> context, GLuint handle)
- : WebGLObject(realm, context, handle)
-{
-}
-
-WebGLSampler::~WebGLSampler() = default;
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLSampler.h b/Libraries/LibWeb/WebGL/WebGLSampler.h
deleted file mode 100644
index 2a92a4f1d38..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLSampler.h
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (c) 2024, Andrew Kaster <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/WebGL/Types.h>
-#include <LibWeb/WebGL/WebGLObject.h>
-
-namespace Web::WebGL {
-
-class WebGLSampler : public WebGLObject {
- WEB_WRAPPABLE(WebGLSampler, WebGLObject);
- GC_DECLARE_ALLOCATOR(WebGLSampler);
-
-public:
- static GC::Ref<WebGLSampler> create(GC::Ref<WebGLRenderingContextBase> context, GLuint handle);
-
- virtual ~WebGLSampler() override;
-
-protected:
- explicit WebGLSampler(JS::Realm&, GC::Ref<WebGLRenderingContextBase>, GLuint handle);
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLSampler.idl b/Libraries/LibWeb/WebGL/WebGLSampler.idl
index 848093b09fd..918ce7a74d1 100644
--- a/Libraries/LibWeb/WebGL/WebGLSampler.idl
+++ b/Libraries/LibWeb/WebGL/WebGLSampler.idl
@@ -1,4 +1,4 @@
// https://registry.khronos.org/webgl/specs/latest/2.0/#3.3
-[Exposed=(Window,Worker)]
+[Exposed=(Window,Worker), ImplementedIn=Rust]
interface WebGLSampler : WebGLObject {
};
diff --git a/Libraries/LibWeb/WebGL/WebGLShader.cpp b/Libraries/LibWeb/WebGL/WebGLShader.cpp
deleted file mode 100644
index f5071b4c9a4..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLShader.cpp
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
- * Copyright (c) 2024, Aliaksandr Kalenik <[email protected]>
- * Copyright (c) 2024-2025, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/Runtime/Realm.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/Bindings/WebGLShader.h>
-#include <LibWeb/WebGL/WebGLShader.h>
-
-namespace Web::WebGL {
-
-GC_DEFINE_ALLOCATOR(WebGLShader);
-
-GC::Ref<WebGLShader> WebGLShader::create(GC::Ref<WebGLRenderingContextBase> context, GLuint handle, GLenum type)
-{
- auto& realm = context->realm();
- return realm.create<WebGLShader>(realm, context, handle, type);
-}
-
-WebGLShader::WebGLShader(JS::Realm& realm, GC::Ref<WebGLRenderingContextBase> context, GLuint handle, GLenum type)
- : WebGLObject(realm, context, handle)
- , m_type(type)
-{
-}
-
-WebGLShader::~WebGLShader() = default;
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLShader.h b/Libraries/LibWeb/WebGL/WebGLShader.h
deleted file mode 100644
index ba5f1a3b988..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLShader.h
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
- * Copyright (c) 2024, Aliaksandr Kalenik <[email protected]>
- * Copyright (c) 2024, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/WebGL/Types.h>
-#include <LibWeb/WebGL/WebGLObject.h>
-
-namespace Web::WebGL {
-
-class WebGLShader final : public WebGLObject {
- WEB_WRAPPABLE(WebGLShader, WebGLObject);
- GC_DECLARE_ALLOCATOR(WebGLShader);
-
-public:
- static GC::Ref<WebGLShader> create(GC::Ref<WebGLRenderingContextBase>, GLuint handle, GLenum type);
-
- virtual ~WebGLShader();
-
- GLenum type() const { return m_type; }
-
-protected:
- explicit WebGLShader(JS::Realm&, GC::Ref<WebGLRenderingContextBase>, GLuint handle, GLenum type);
-
-private:
- GLenum m_type { 0 };
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLShader.idl b/Libraries/LibWeb/WebGL/WebGLShader.idl
index 3a8b7063b8e..622313ec495 100644
--- a/Libraries/LibWeb/WebGL/WebGLShader.idl
+++ b/Libraries/LibWeb/WebGL/WebGLShader.idl
@@ -1,4 +1,4 @@
// https://registry.khronos.org/webgl/specs/latest/1.0/#5.8
-[Exposed=(Window,Worker)]
+[Exposed=(Window,Worker), ImplementedIn=Rust]
interface WebGLShader : WebGLObject {
};
diff --git a/Libraries/LibWeb/WebGL/WebGLShaderPrecisionFormat.cpp b/Libraries/LibWeb/WebGL/WebGLShaderPrecisionFormat.cpp
deleted file mode 100644
index 5ef7020dbf0..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLShaderPrecisionFormat.cpp
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
- * Copyright (c) 2024, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/Runtime/Realm.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/Bindings/WebGLShaderPrecisionFormat.h>
-#include <LibWeb/WebGL/WebGLShaderPrecisionFormat.h>
-
-namespace Web::WebGL {
-
-GC_DEFINE_ALLOCATOR(WebGLShaderPrecisionFormat);
-
-GC::Ref<WebGLShaderPrecisionFormat> WebGLShaderPrecisionFormat::create(JS::Realm& realm, GLint range_min, GLint range_max, GLint precision)
-{
- return realm.create<WebGLShaderPrecisionFormat>(realm, range_min, range_max, precision);
-}
-
-WebGLShaderPrecisionFormat::WebGLShaderPrecisionFormat(JS::Realm&, GLint range_min, GLint range_max, GLint precision)
- : m_range_min(range_min)
- , m_range_max(range_max)
- , m_precision(precision)
-{
-}
-
-WebGLShaderPrecisionFormat::~WebGLShaderPrecisionFormat() = default;
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLShaderPrecisionFormat.h b/Libraries/LibWeb/WebGL/WebGLShaderPrecisionFormat.h
deleted file mode 100644
index d0f11ffaa8c..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLShaderPrecisionFormat.h
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
- * Copyright (c) 2024, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/WebGL/Types.h>
-
-namespace Web::WebGL {
-
-class WebGLShaderPrecisionFormat final : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(WebGLShaderPrecisionFormat, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(WebGLShaderPrecisionFormat);
-
-public:
- static GC::Ref<WebGLShaderPrecisionFormat> create(JS::Realm& realm, GLint range_min, GLint range_max, GLint precision);
-
- virtual ~WebGLShaderPrecisionFormat() override;
-
- GLint range_min() const { return m_range_min; }
- GLint range_max() const { return m_range_max; }
- GLint precision() const { return m_precision; }
-
-protected:
- explicit WebGLShaderPrecisionFormat(JS::Realm&, GLint range_min, GLint range_max, GLint precision);
-
-private:
- GLint m_range_min { 0 };
- GLint m_range_max { 0 };
- GLint m_precision { 0 };
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLShaderPrecisionFormat.idl b/Libraries/LibWeb/WebGL/WebGLShaderPrecisionFormat.idl
index 872f9bd67fc..348a836ada3 100644
--- a/Libraries/LibWeb/WebGL/WebGLShaderPrecisionFormat.idl
+++ b/Libraries/LibWeb/WebGL/WebGLShaderPrecisionFormat.idl
@@ -1,5 +1,5 @@
// https://registry.khronos.org/webgl/specs/latest/1.0/#5.12
-[Exposed=(Window,Worker)]
+[Exposed=(Window,Worker), ImplementedIn=Rust]
interface WebGLShaderPrecisionFormat {
readonly attribute GLint rangeMin;
readonly attribute GLint rangeMax;
diff --git a/Libraries/LibWeb/WebGL/WebGLSync.cpp b/Libraries/LibWeb/WebGL/WebGLSync.cpp
deleted file mode 100644
index b9c9f423da0..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLSync.cpp
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (c) 2024, Andrew Kaster <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/Runtime/Realm.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/Bindings/WebGLSync.h>
-#include <LibWeb/WebGL/WebGLSync.h>
-
-#include <GLES2/gl2.h>
-
-namespace Web::WebGL {
-
-GC_DEFINE_ALLOCATOR(WebGLSync);
-
-GC::Ref<WebGLSync> WebGLSync::create(GC::Ref<WebGLRenderingContextBase> context, GLsyncInternal handle)
-{
- auto& realm = context->realm();
- return realm.create<WebGLSync>(realm, context, handle);
-}
-
-WebGLSync::WebGLSync(JS::Realm& realm, GC::Ref<WebGLRenderingContextBase> context, GLsyncInternal handle)
- : WebGLObject(realm, context, 0)
- , m_sync_handle(handle)
-{
-}
-
-WebGLSync::~WebGLSync() = default;
-
-ErrorOr<GLsyncInternal> WebGLSync::sync_handle(WebGLRenderingContextBase const* context) const
-{
- TRY(validate_context(context));
- if (invalidated_for_context(context))
- return Error::from_errno(GL_INVALID_OPERATION);
- return m_sync_handle;
-}
-
-ErrorOr<Optional<GLsyncInternal>> WebGLSync::sync_handle_for_deletion(WebGLRenderingContextBase const* context)
-{
- TRY(validate_context(context));
- if (invalidated_for_context(context))
- return Optional<GLsyncInternal> {};
- invalidate();
- return Optional<GLsyncInternal> { m_sync_handle };
-}
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLSync.h b/Libraries/LibWeb/WebGL/WebGLSync.h
deleted file mode 100644
index e73a3e84132..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLSync.h
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2024, Andrew Kaster <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/WebGL/Types.h>
-#include <LibWeb/WebGL/WebGLObject.h>
-
-namespace Web::WebGL {
-
-class WebGLSync : public WebGLObject {
- WEB_WRAPPABLE(WebGLSync, WebGLObject);
- GC_DECLARE_ALLOCATOR(WebGLSync);
-
-public:
- static GC::Ref<WebGLSync> create(GC::Ref<WebGLRenderingContextBase>, GLsyncInternal handle);
-
- virtual ~WebGLSync() override;
-
- ErrorOr<GLsyncInternal> sync_handle(WebGLRenderingContextBase const* context) const;
- ErrorOr<Optional<GLsyncInternal>> sync_handle_for_deletion(WebGLRenderingContextBase const* context);
-
-protected:
- explicit WebGLSync(JS::Realm&, GC::Ref<WebGLRenderingContextBase>, GLsyncInternal handle);
-
- GLsyncInternal m_sync_handle { nullptr };
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLSync.idl b/Libraries/LibWeb/WebGL/WebGLSync.idl
index b231e03ee3a..87a44c82517 100644
--- a/Libraries/LibWeb/WebGL/WebGLSync.idl
+++ b/Libraries/LibWeb/WebGL/WebGLSync.idl
@@ -1,4 +1,4 @@
// https://registry.khronos.org/webgl/specs/latest/2.0/#3.4
-[Exposed=(Window,Worker)]
+[Exposed=(Window,Worker), ImplementedIn=Rust]
interface WebGLSync : WebGLObject {
};
diff --git a/Libraries/LibWeb/WebGL/WebGLTexture.cpp b/Libraries/LibWeb/WebGL/WebGLTexture.cpp
deleted file mode 100644
index 98b5fd94824..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLTexture.cpp
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
- * Copyright (c) 2024, Aliaksandr Kalenik <[email protected]>
- * Copyright (c) 2024, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/Runtime/Realm.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/Bindings/WebGLTexture.h>
-#include <LibWeb/WebGL/WebGLTexture.h>
-
-namespace Web::WebGL {
-
-GC_DEFINE_ALLOCATOR(WebGLTexture);
-
-GC::Ref<WebGLTexture> WebGLTexture::create(GC::Ref<WebGLRenderingContextBase> context, GLuint handle)
-{
- auto& realm = context->realm();
- return realm.create<WebGLTexture>(realm, context, handle);
-}
-
-WebGLTexture::WebGLTexture(JS::Realm& realm, GC::Ref<WebGLRenderingContextBase> context, GLuint handle)
- : WebGLObject(realm, context, handle)
-{
-}
-
-WebGLTexture::~WebGLTexture() = default;
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLTexture.h b/Libraries/LibWeb/WebGL/WebGLTexture.h
deleted file mode 100644
index 04db8b55397..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLTexture.h
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
- * Copyright (c) 2024, Aliaksandr Kalenik <[email protected]>
- * Copyright (c) 2024, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/WebGL/Types.h>
-#include <LibWeb/WebGL/WebGLObject.h>
-
-namespace Web::WebGL {
-
-class WebGLTexture final : public WebGLObject {
- WEB_WRAPPABLE(WebGLTexture, WebGLObject);
- GC_DECLARE_ALLOCATOR(WebGLTexture);
-
-public:
- static GC::Ref<WebGLTexture> create(GC::Ref<WebGLRenderingContextBase>, GLuint handle);
-
- virtual ~WebGLTexture();
-
-protected:
- explicit WebGLTexture(JS::Realm&, GC::Ref<WebGLRenderingContextBase>, GLuint handle);
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLTexture.idl b/Libraries/LibWeb/WebGL/WebGLTexture.idl
index 055e9666c77..bad0c290696 100644
--- a/Libraries/LibWeb/WebGL/WebGLTexture.idl
+++ b/Libraries/LibWeb/WebGL/WebGLTexture.idl
@@ -1,4 +1,4 @@
// https://registry.khronos.org/webgl/specs/latest/1.0/#5.9
-[Exposed=(Window,Worker)]
+[Exposed=(Window,Worker), ImplementedIn=Rust]
interface WebGLTexture : WebGLObject {
};
diff --git a/Libraries/LibWeb/WebGL/WebGLTransformFeedback.cpp b/Libraries/LibWeb/WebGL/WebGLTransformFeedback.cpp
deleted file mode 100644
index 10ba6731fad..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLTransformFeedback.cpp
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (c) 2024, Andrew Kaster <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/Runtime/Realm.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/Bindings/WebGLTransformFeedback.h>
-#include <LibWeb/WebGL/WebGLTransformFeedback.h>
-
-namespace Web::WebGL {
-
-GC_DEFINE_ALLOCATOR(WebGLTransformFeedback);
-
-GC::Ref<WebGLTransformFeedback> WebGLTransformFeedback::create(GC::Ref<WebGLRenderingContextBase> context, GLuint handle)
-{
- auto& realm = context->realm();
- return realm.create<WebGLTransformFeedback>(realm, context, handle);
-}
-
-WebGLTransformFeedback::WebGLTransformFeedback(JS::Realm& realm, GC::Ref<WebGLRenderingContextBase> context, GLuint handle)
- : WebGLObject(realm, context, handle)
-{
-}
-
-WebGLTransformFeedback::~WebGLTransformFeedback() = default;
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLTransformFeedback.h b/Libraries/LibWeb/WebGL/WebGLTransformFeedback.h
deleted file mode 100644
index 542c2dc55ae..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLTransformFeedback.h
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (c) 2024, Andrew Kaster <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/WebGL/Types.h>
-#include <LibWeb/WebGL/WebGLObject.h>
-
-namespace Web::WebGL {
-
-class WebGLTransformFeedback : public WebGLObject {
- WEB_WRAPPABLE(WebGLTransformFeedback, WebGLObject);
- GC_DECLARE_ALLOCATOR(WebGLTransformFeedback);
-
-public:
- static GC::Ref<WebGLTransformFeedback> create(GC::Ref<WebGLRenderingContextBase>, GLuint handle);
-
- virtual ~WebGLTransformFeedback() override;
-
-protected:
- explicit WebGLTransformFeedback(JS::Realm&, GC::Ref<WebGLRenderingContextBase>, GLuint handle);
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLTransformFeedback.idl b/Libraries/LibWeb/WebGL/WebGLTransformFeedback.idl
index c8287efe4c4..07e99a711dc 100644
--- a/Libraries/LibWeb/WebGL/WebGLTransformFeedback.idl
+++ b/Libraries/LibWeb/WebGL/WebGLTransformFeedback.idl
@@ -1,4 +1,4 @@
// https://registry.khronos.org/webgl/specs/latest/2.0/#3.5
-[Exposed=(Window,Worker)]
+[Exposed=(Window,Worker), ImplementedIn=Rust]
interface WebGLTransformFeedback : WebGLObject {
};
diff --git a/Libraries/LibWeb/WebGL/WebGLUniformLocation.cpp b/Libraries/LibWeb/WebGL/WebGLUniformLocation.cpp
deleted file mode 100644
index 957fe13a9be..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLUniformLocation.cpp
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
- * Copyright (c) 2024, Aliaksandr Kalenik <[email protected]>
- * Copyright (c) 2024, Luke Wilde <[email protected]>
- * Copyright (c) 2025, Undefine <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/Runtime/Realm.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/Bindings/WebGLUniformLocation.h>
-#include <LibWeb/WebGL/WebGLUniformLocation.h>
-
-#include <GLES2/gl2.h>
-
-namespace Web::WebGL {
-
-GC_DEFINE_ALLOCATOR(WebGLUniformLocation);
-
-GC::Ref<WebGLUniformLocation> WebGLUniformLocation::create(JS::Realm& realm, GLuint handle, GC::Ptr<WebGLProgram> parent_shader)
-{
- return realm.create<WebGLUniformLocation>(realm, handle, parent_shader);
-}
-
-WebGLUniformLocation::WebGLUniformLocation(JS::Realm&, GLuint handle, GC::Ptr<WebGLProgram> parent_shader)
- : m_handle(handle)
- , m_parent_shader(parent_shader)
-{
-}
-
-GC::Ptr<Bindings::Wrappable> WebGLUniformLocation::relevant_global_impl() const
-{
- if (m_parent_shader)
- return static_cast<Bindings::Wrappable&>(*m_parent_shader).relevant_global_impl();
- return nullptr;
-}
-
-WebGLUniformLocation::~WebGLUniformLocation() = default;
-
-void WebGLUniformLocation::visit_edges(Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_parent_shader);
-}
-
-ErrorOr<GLuint> WebGLUniformLocation::handle(GC::Ptr<WebGLProgram> current_shader) const
-{
- if (current_shader == m_parent_shader)
- return m_handle;
- return Error::from_errno(GL_INVALID_OPERATION);
-}
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLUniformLocation.h b/Libraries/LibWeb/WebGL/WebGLUniformLocation.h
deleted file mode 100644
index 6e9008eb165..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLUniformLocation.h
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
- * Copyright (c) 2024, Aliaksandr Kalenik <[email protected]>
- * Copyright (c) 2025, Undefine <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/WebGL/Types.h>
-#include <LibWeb/WebGL/WebGLProgram.h>
-
-namespace Web::WebGL {
-
-class WebGLUniformLocation final : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(WebGLUniformLocation, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(WebGLUniformLocation);
-
-public:
- static GC::Ref<WebGLUniformLocation> create(JS::Realm& realm, GLuint handle, GC::Ptr<WebGLProgram> parent_shader);
-
- virtual ~WebGLUniformLocation();
-
- ErrorOr<GLuint> handle(GC::Ptr<WebGLProgram> current_shader) const;
-
-protected:
- explicit WebGLUniformLocation(JS::Realm&, GLuint handle, GC::Ptr<WebGLProgram> parent_shader);
-
- virtual void visit_edges(JS::Cell::Visitor&) override;
- virtual GC::Ptr<Bindings::Wrappable> relevant_global_impl() const override;
-
- GLuint m_handle { 0 };
- GC::Ptr<WebGLProgram> m_parent_shader;
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLUniformLocation.idl b/Libraries/LibWeb/WebGL/WebGLUniformLocation.idl
index 7beaaead864..29d8e00822d 100644
--- a/Libraries/LibWeb/WebGL/WebGLUniformLocation.idl
+++ b/Libraries/LibWeb/WebGL/WebGLUniformLocation.idl
@@ -1,4 +1,4 @@
// https://registry.khronos.org/webgl/specs/latest/1.0/#5.10
-[Exposed=(Window,Worker)]
+[Exposed=(Window,Worker), ImplementedIn=Rust]
interface WebGLUniformLocation {
};
diff --git a/Libraries/LibWeb/WebGL/WebGLVertexArrayObject.cpp b/Libraries/LibWeb/WebGL/WebGLVertexArrayObject.cpp
deleted file mode 100644
index ef56e333f23..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLVertexArrayObject.cpp
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (c) 2024, Andrew Kaster <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/Runtime/Realm.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/Bindings/WebGLVertexArrayObject.h>
-#include <LibWeb/WebGL/WebGLVertexArrayObject.h>
-
-namespace Web::WebGL {
-
-GC_DEFINE_ALLOCATOR(WebGLVertexArrayObject);
-
-GC::Ref<WebGLVertexArrayObject> WebGLVertexArrayObject::create(GC::Ref<WebGLRenderingContextBase> context, GLuint handle)
-{
- auto& realm = context->realm();
- return realm.create<WebGLVertexArrayObject>(realm, context, handle);
-}
-
-WebGLVertexArrayObject::WebGLVertexArrayObject(JS::Realm& realm, GC::Ref<WebGLRenderingContextBase> context, GLuint handle)
- : WebGLObject(realm, context, handle)
-{
-}
-
-WebGLVertexArrayObject::~WebGLVertexArrayObject() = default;
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLVertexArrayObject.h b/Libraries/LibWeb/WebGL/WebGLVertexArrayObject.h
deleted file mode 100644
index e5646f7fc1c..00000000000
--- a/Libraries/LibWeb/WebGL/WebGLVertexArrayObject.h
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (c) 2024, Andrew Kaster <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/WebGL/Types.h>
-#include <LibWeb/WebGL/WebGLObject.h>
-
-namespace Web::WebGL {
-
-class WebGLVertexArrayObject : public WebGLObject {
- WEB_WRAPPABLE(WebGLVertexArrayObject, WebGLObject);
- GC_DECLARE_ALLOCATOR(WebGLVertexArrayObject);
-
-public:
- static GC::Ref<WebGLVertexArrayObject> create(GC::Ref<WebGLRenderingContextBase>, GLuint handle);
-
- virtual ~WebGLVertexArrayObject() override;
-
-protected:
- explicit WebGLVertexArrayObject(JS::Realm&, GC::Ref<WebGLRenderingContextBase>, GLuint handle);
-};
-
-}
diff --git a/Libraries/LibWeb/WebGL/WebGLVertexArrayObject.idl b/Libraries/LibWeb/WebGL/WebGLVertexArrayObject.idl
index bbace143fe5..72f914d0e84 100644
--- a/Libraries/LibWeb/WebGL/WebGLVertexArrayObject.idl
+++ b/Libraries/LibWeb/WebGL/WebGLVertexArrayObject.idl
@@ -1,4 +1,4 @@
// https://registry.khronos.org/webgl/specs/latest/2.0/#3.6
-[Exposed=(Window,Worker)]
+[Exposed=(Window,Worker), ImplementedIn=Rust]
interface WebGLVertexArrayObject : WebGLObject {
};
diff --git a/Meta/CMake/libweb_generators.cmake b/Meta/CMake/libweb_generators.cmake
index 729ae45097f..4dc7f519c95 100644
--- a/Meta/CMake/libweb_generators.cmake
+++ b/Meta/CMake/libweb_generators.cmake
@@ -208,31 +208,6 @@ function (generate_html_implementation)
list(APPEND LIBWEB_ALL_GENERATED_HEADERS ${HTML_GENERATED_HEADERS})
set(LIBWEB_ALL_GENERATED_HEADERS ${LIBWEB_ALL_GENERATED_HEADERS} PARENT_SCOPE)
endfunction()
-
-function (generate_webgl_implementation)
- set(LIBCOMPOSITING_INPUT_FOLDER "${LADYBIRD_SOURCE_DIR}/Libraries/LibCompositing")
-
- invoke_py_generator(
- "WebGLContextProxy.cpp"
- "generate_libweb_webgl_proxy.py"
- "${LIBCOMPOSITING_INPUT_FOLDER}/WebGL/GLFunctions.json"
- "WebGL/WebGLContextProxy.h"
- "WebGL/WebGLContextProxy.cpp"
- arguments -j "${LIBCOMPOSITING_INPUT_FOLDER}/WebGL/GLFunctions.json"
- dependencies "${LADYBIRD_SOURCE_DIR}/Meta/Generators/libweb_webgl.py"
- )
-
- set(WEBGL_GENERATED_HEADERS
- "WebGL/WebGLContextProxy.h"
- )
- list(TRANSFORM WEBGL_GENERATED_HEADERS PREPEND "${CMAKE_CURRENT_BINARY_DIR}/")
- if (ENABLE_INSTALL_HEADERS)
- install(FILES ${WEBGL_GENERATED_HEADERS} DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/LibWeb/WebGL")
- endif()
- list(APPEND LIBWEB_ALL_GENERATED_HEADERS ${WEBGL_GENERATED_HEADERS})
- set(LIBWEB_ALL_GENERATED_HEADERS ${LIBWEB_ALL_GENERATED_HEADERS} PARENT_SCOPE)
-endfunction()
-
function (generate_js_bindings target)
set(LIBWEB_INPUT_FOLDER "${CMAKE_CURRENT_SOURCE_DIR}")
find_package(Python3 REQUIRED COMPONENTS Interpreter)
diff --git a/Meta/Generators/generate_libweb_webgl_proxy.py b/Meta/Generators/generate_libweb_webgl_proxy.py
deleted file mode 100644
index 24d40ab78a1..00000000000
--- a/Meta/Generators/generate_libweb_webgl_proxy.py
+++ /dev/null
@@ -1,227 +0,0 @@
-#!/usr/bin/env python3
-
-# Copyright (c) 2026, Aliaksandr Kalenik <[email protected]>
-#
-# SPDX-License-Identifier: BSD-2-Clause
-
-import sys
-
-from pathlib import Path
-from typing import TextIO
-
-sys.path.append(str(Path(__file__).resolve().parent))
-
-from libweb_webgl import command_name
-from libweb_webgl import is_const_pointer
-from libweb_webgl import is_pointer
-from libweb_webgl import method_signature
-from libweb_webgl import run_generator
-from libweb_webgl import snake_case
-from libweb_webgl import sync_reply_fields
-
-# Generates WebGLContextProxy, WebContent's drop-in replacement for the GL seam: the
-# same method signatures as the generated GLFunctions class, but recording commands into
-# a WebGLCommandList (flushed to the Compositor) instead of calling GL. Value-returning
-# entry points become synchronous round trips. Method parameter names match the GL
-# argument names from GLFunctions.json, so the JSON's payload-size expressions are used
-# verbatim.
-
-
-def object_id_expression(arg: dict) -> str:
- if arg["type"] == "GLsync":
- return f"static_cast<WebGLObjectId>(reinterpret_cast<uintptr_t>({arg['name']}))"
- return arg["name"]
-
-
-# Emits statements declaring `<field>_bytes` spans and a fully-initialized `command`
-# whose WebGLDataSpan fields point at them in append order.
-def emit_command_construction(out: TextIO, function: dict, command_type: str) -> list:
- blobs = [] # (field, bytes_variable)
- initializers = []
- for arg in function["args"]:
- field = snake_case(arg["name"])
- name = arg["name"]
- if arg.get("string"):
- out.write(f" ReadonlyBytes {field}_bytes {{ {name}, __builtin_strlen({name}) + 1 }};\n")
- blobs.append(field)
- initializers.append((field, None))
- elif arg.get("offset"):
- initializers.append((field, f"static_cast<GLintptr>(reinterpret_cast<uintptr_t>({name}))"))
- elif arg.get("object") and not is_pointer(arg):
- initializers.append((field, object_id_expression(arg)))
- elif (arg.get("object") and is_const_pointer(arg)) or "payload" in arg:
- size = f"static_cast<size_t>({arg['payload']})"
- if arg.get("nullable"):
- out.write(f" ReadonlyBytes {field}_bytes {{ {name}, {name} ? {size} : 0 }};\n")
- initializers.append((f"has_{field}", f"{name} != nullptr"))
- else:
- out.write(f" ReadonlyBytes {field}_bytes {{ {name}, {size} }};\n")
- blobs.append(field)
- initializers.append((field, None))
- else:
- initializers.append((field, name))
-
- fields = ", ".join(f".{field} = {value}" for field, value in initializers if value is not None)
- out.write(f" {command_type} command {{ {fields} }};\n")
- for index, field in enumerate(blobs):
- if index == 0:
- offset = "WebGLCommandList::first_inline_data_offset(sizeof(command))"
- else:
- offset = f"WebGLCommandList::next_inline_data_offset(command.{blobs[index - 1]})"
- out.write(f" command.{field} = {{ {offset}, static_cast<u32>({field}_bytes.size()) }};\n")
- return blobs
-
-
-def emit_record(out: TextIO, blobs: list) -> None:
- blob_args = "".join(f", {field}_bytes" for field in blobs)
- out.write(f" record(command{blob_args});\n")
-
-
-def emit_command_method(out: TextIO, function: dict) -> None:
- command_type = f"Compositing::WebGL::Commands::{command_name(function)}"
- out.write(f"{method_signature(function, 'WebGLContextProxy::')}\n{{\n")
- blobs = emit_command_construction(out, function, command_type)
- assert len(blobs) <= 1, f"{function['name']} needs more inline blobs than record() supports"
- emit_record(out, blobs)
- out.write("}\n\n")
-
-
-def emit_gen_method(out: TextIO, function: dict) -> None:
- command_type = f"Compositing::WebGL::Commands::{command_name(function)}"
- out.write(f"{method_signature(function, 'WebGLContextProxy::')}\n{{\n")
- if function["return"] != "void":
- scalars = "".join(f", .{snake_case(a['name'])} = {a['name']}" for a in function["args"])
- out.write(" auto id = allocate_object_id();\n")
- out.write(f" record({command_type} {{ .id = id{scalars} }});\n")
- if function["return"] == "GLsync":
- out.write(" return reinterpret_cast<GLsync>(static_cast<uintptr_t>(id));\n")
- else:
- out.write(" return id;\n")
- out.write("}\n\n")
- return
-
- count_name = function["args"][0]["name"]
- span_field = snake_case(function["args"][1]["name"])
- out_name = function["args"][1]["name"]
- out.write(f""" if ({count_name} <= 0)
- return;
- static_assert(IsSame<WebGLObjectId, GLuint>);
- for (GLsizei i = 0; i < {count_name}; ++i)
- {out_name}[i] = allocate_object_id();
- ReadonlyBytes {span_field}_bytes {{ {out_name}, static_cast<size_t>({count_name}) * sizeof(WebGLObjectId) }};
- Compositing::WebGL::Commands::{command_name(function)} command {{ .{snake_case(count_name)} = {count_name} }};
- command.{span_field} = {{ WebGLCommandList::first_inline_data_offset(sizeof(command)), static_cast<u32>({span_field}_bytes.size()) }};
- record(command, {span_field}_bytes);
-}}
-
-""")
-
-
-def emit_sync_method(out: TextIO, function: dict) -> None:
- call = f"Compositing::WebGL::SyncCalls::{command_name(function)}"
- out.write(f"{method_signature(function, 'WebGLContextProxy::')}\n{{\n")
-
- # Build the request (in-args only) plus its inline blobs.
- blobs = []
- initializers = []
- for arg in function["args"]:
- if arg.get("out"):
- continue
- field = snake_case(arg["name"])
- name = arg["name"]
- if arg.get("string"):
- out.write(f" ReadonlyBytes {field}_bytes {{ {name}, __builtin_strlen({name}) + 1 }};\n")
- blobs.append(field)
- elif "payload" in arg:
- out.write(f" ReadonlyBytes {field}_bytes {{ {name}, static_cast<size_t>({arg['payload']}) }};\n")
- blobs.append(field)
- elif arg.get("object") and not is_pointer(arg):
- initializers.append((field, object_id_expression(arg)))
- else:
- initializers.append((field, name))
- assert len(blobs) <= 1, f"{function['name']} needs more request blobs than encode_request supports"
-
- fields = ", ".join(f".{field} = {value}" for field, value in initializers)
- out.write(f" {call}::Request request {{ {fields} }};\n")
- for field in blobs:
- out.write(
- f" request.{field} = {{ WebGLCommandList::first_inline_data_offset(sizeof(request)), static_cast<u32>({field}_bytes.size()) }};\n"
- )
- blob_argument = f", {blobs[0]}_bytes" if blobs else ""
- out.write(
- f" auto reply_bytes = send_sync_call(WebGLSyncCall::encode_request<{call}>(request{blob_argument}));\n"
- )
-
- has_return = function["return"] != "void"
- failure = " return {};\n" if has_return else " return;\n"
- out.write(" if (is_lost())\n")
- out.write(failure)
- if sync_reply_fields(function):
- out.write(f" auto reply = WebGLSyncCall::decode_reply<{call}::Reply>(reply_bytes);\n")
-
- for _, field_name, arg in sync_reply_fields(function):
- if arg is None:
- continue
- name = arg["name"]
- if "payload" in arg:
- out.write(f""" if ({name})
- WebGLCommandList::copy_data_span(reply_bytes, reply.{field_name}, {{ {name}, static_cast<size_t>({arg["payload"]}) }});
-""")
- else:
- out.write(f" if ({name})\n *{name} = reply.{field_name};\n")
-
- if has_return:
- out.write(" return reply.return_value;\n")
- out.write("}\n\n")
-
-
-def write_header_file(out: TextIO, functions: list) -> None:
- out.write("""#pragma once
-
-#include <LibCompositing/WebGL/WebGLCommands.h>
-#include <LibWeb/WebGL/WebGLContextProxyBase.h>
-
-namespace Web::WebGL {
-
-// The remote-recording implementation of the GL seam: identical signatures to
-// GLFunctions, so the WebGL implementation files cannot tell the difference.
-class WEB_API WebGLContextProxy final : public WebGLContextProxyBase {
-public:
- using WebGLContextProxyBase::WebGLContextProxyBase;
-
-""")
- for function in functions:
- if function["category"] not in ("command", "gen", "sync"):
- continue
- out.write(f" {method_signature(function)};\n")
- out.write("""
- // Custom-handled entry points; defined manually in WebGLContextProxyBase.cpp.
-""")
- for function in functions:
- if function["category"] != "custom":
- continue
- out.write(f" {method_signature(function)};\n")
- out.write("""};
-
-}
-""")
-
-
-def write_implementation_file(out: TextIO, functions: list) -> None:
- out.write("""#include <LibWeb/WebGL/WebGLContextProxy.h>
-
-namespace Web::WebGL {
-
-""")
- for function in functions:
- if function["category"] == "command":
- emit_command_method(out, function)
- elif function["category"] == "gen":
- emit_gen_method(out, function)
- elif function["category"] == "sync":
- emit_sync_method(out, function)
- out.write("}\n")
-
-
-if __name__ == "__main__":
- run_generator("Generate the WebGL context proxy recorder", write_header_file, write_implementation_file)
diff --git a/Meta/Generators/libweb_bindings/glue_headers.py b/Meta/Generators/libweb_bindings/glue_headers.py
index cb6b55948a6..540c1dfd9c4 100644
--- a/Meta/Generators/libweb_bindings/glue_headers.py
+++ b/Meta/Generators/libweb_bindings/glue_headers.py
@@ -20,7 +20,6 @@ def bindings_glue_header_for_interface(interface: Interface, wrapper_interface_n
"TrustedTypes": "LibWeb/TrustedTypes/BindingsGlue.h",
"WebAssembly": "LibWeb/WebAssembly/BindingsGlue.h",
"WebAudio": "LibWeb/WebAudio/BindingsGlue.h",
- "WebGL": "LibWeb/WebGL/BindingsGlue.h",
}
if module in module_headers:
return module_headers[module]
diff --git a/Meta/Generators/libweb_bindings/intrinsics.py b/Meta/Generators/libweb_bindings/intrinsics.py
index 5be9851830f..f51c6f77396 100644
--- a/Meta/Generators/libweb_bindings/intrinsics.py
+++ b/Meta/Generators/libweb_bindings/intrinsics.py
@@ -706,7 +706,6 @@ def write_wrapper_factory_implementation(out: TextIO, interface_sets: InterfaceS
#include <LibWeb/HTML/BindingsGlue.h>
#include <LibWeb/Streams/BindingsGlue.h>
#include <LibWeb/WebAssembly/BindingsGlue.h>
-#include <LibWeb/WebGL/BindingsGlue.h>
#include <LibWeb/Bindings/PlatformObject.h>
#include <LibWeb/Bindings/Wrappable.h>
"""
diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.py
index 07ae9da5ce6..86b33018f36 100755
--- a/Meta/Linters/check_libweb_realm_mentions.py
+++ b/Meta/Linters/check_libweb_realm_mentions.py
@@ -86,7 +86,7 @@ ALLOWED_REALM_MENTIONS = {
"WebAudio buffers, AudioParamMap, and AudioWorklet APIs still materialize JS buffers and callback/promise values in selected realms",
),
"WebDriver": (2, 7, "WebDriver execute/JSON conversion still materializes JS values for automation"),
- "WebGL": (72, 120, "WebGL APIs still materialize buffers, typed arrays, extensions, and wrapper objects"),
+ "WebGL": (4, 9, "WebGL contexts are created in the realm of their canvas, and their events and promises in it"),
"WebLocks": (6, 7, "Web Locks queue/callback algorithms still use callback and promise realms"),
"XHR": (4, 7, "XHR/FormData/FileReader-style paths still materialize JS values and events"),
}
diff --git a/Tests/LibWeb/CMakeLists.txt b/Tests/LibWeb/CMakeLists.txt
index fb932aef8ee..8158fa08ee0 100644
--- a/Tests/LibWeb/CMakeLists.txt
+++ b/Tests/LibWeb/CMakeLists.txt
@@ -32,7 +32,6 @@ set(TEST_SOURCES
TestStructuredSerializeHardening.cpp
TestStructuredSerializeSharedArrayBuffer.cpp
TestStyleEngineBridge.cpp
- TestWebGLSpanWithStorage.cpp
TestWebIDLBuffers.cpp
TestWindowProxyWorld.cpp
TestWorldCallback.cpp
@@ -71,7 +70,6 @@ target_link_libraries(TestFetchResponse PRIVATE LibGC LibHTTP LibJS LibRequests
target_link_libraries(TestFetchURL PRIVATE LibURL)
target_link_libraries(TestImageData PRIVATE LibGC LibJS)
target_link_libraries(TestWebIDLBuffers PRIVATE LibGC LibJS)
-target_link_libraries(TestWebGLSpanWithStorage PRIVATE LibGC LibJS)
target_link_libraries(TestStructuredSerializeCorpus PRIVATE LibGC LibJS LibCrypto LibGfx LibIPC)
target_link_libraries(TestStructuredSerializeDurability PRIVATE LibGC LibJS LibCrypto LibGfx LibIPC)
target_link_libraries(TestStructuredSerializeFormat PRIVATE LibGC LibJS LibCrypto LibGfx LibIPC)
diff --git a/Tests/LibWeb/TestWebGLSpanWithStorage.cpp b/Tests/LibWeb/TestWebGLSpanWithStorage.cpp
deleted file mode 100644
index 6d16d585369..00000000000
--- a/Tests/LibWeb/TestWebGLSpanWithStorage.cpp
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/Array.h>
-#include <AK/ByteBuffer.h>
-#include <LibJS/Runtime/AbstractOperations.h>
-#include <LibJS/Runtime/ArrayBuffer.h>
-#include <LibJS/Runtime/Realm.h>
-#include <LibJS/Runtime/TypedArray.h>
-#include <LibJS/Runtime/VM.h>
-#include <LibTest/TestCase.h>
-#include <LibWeb/WebGL/WebGLRenderingContextBase.h>
-
-namespace {
-
-class WebGLRenderingContextBaseAccessor : public Web::WebGL::WebGLRenderingContextBase {
- WEB_NON_IDL_WRAPPABLE(WebGLRenderingContextBaseAccessor, Web::WebGL::WebGLRenderingContextBase);
-
-public:
- template<typename T>
- using SpanWithStorage = Web::WebGL::WebGLRenderingContextBase::SpanWithStorage<T>;
-
- using Web::WebGL::WebGLRenderingContextBase::span_from_float32_list;
- using Web::WebGL::WebGLRenderingContextBase::span_from_int32_list;
- using Web::WebGL::WebGLRenderingContextBase::span_from_uint32_list;
-
- template<typename T>
- static SpanWithStorage<T> make_span_with_storage(ByteBuffer storage)
- {
- return SpanWithStorage<T> { move(storage) };
- }
-
- template<typename T>
- static SpanWithStorage<T> make_span_with_storage(Span<T> span)
- {
- return SpanWithStorage<T> { span };
- }
-};
-
-struct TestVM {
- TestVM()
- : vm(JS::VM::create())
- , execution_context(MUST(JS::Realm::initialize_host_defined_realm(*vm, nullptr, nullptr)))
- {
- }
-
- ~TestVM()
- {
- vm->pop_execution_context();
- }
-
- NonnullRefPtr<JS::VM> vm;
- NonnullOwnPtr<JS::ExecutionContext> execution_context;
-};
-
-static ByteBuffer make_inline_u32_buffer(ReadonlySpan<u32> values)
-{
- auto buffer = MUST(ByteBuffer::create_uninitialized(values.size() * sizeof(u32)));
- EXPECT(buffer.is_inline());
- buffer.overwrite(0, values.data(), values.size() * sizeof(u32));
- return buffer;
-}
-
-template<typename ArrayType>
-static GC::Ref<ArrayType> create_out_of_bounds_array(JS::Realm& realm, JS::TypedArrayBase::Kind kind)
-{
- auto array_buffer = MUST(JS::ArrayBuffer::create(realm, 32));
- array_buffer->set_max_byte_length(32);
-
- auto byte_length = 4 * JS::typed_array_element_size(kind);
- auto typed_array = JS::TypedArrayBase::create_from_slots(realm, kind, array_buffer, JS::ByteLength { 4 }, JS::ByteLength { byte_length }, 16);
- MUST(JS::call(realm.vm(), MUST(array_buffer->get(realm.vm().names.resize)), JS::Value { array_buffer.ptr() }, JS::Value(4)));
-
- return as<ArrayType>(*typed_array);
-}
-
-}
-
-TEST_CASE(owning_span_rebuilds_storage_after_move_construction)
-{
- Array values { 0x10203040u, 0x50607080u, 0x90a0b0c0u, 0xd0e0f000u };
- auto original = WebGLRenderingContextBaseAccessor::make_span_with_storage<u32>(make_inline_u32_buffer(values.span()));
- auto* original_data = original.data();
-
- auto moved = move(original);
-
- EXPECT_NE(moved.data(), original_data);
- EXPECT_EQ(moved.size(), values.size());
- for (size_t i = 0; i < values.size(); ++i)
- EXPECT_EQ(moved.data()[i], values[i]);
-}
-
-TEST_CASE(owning_span_rebuilds_storage_after_move_assignment)
-{
- Array values { 0x12345678u, 0x9abcdef0u, 0x0fedcba9u, 0x87654321u };
- auto original = WebGLRenderingContextBaseAccessor::make_span_with_storage<u32>(make_inline_u32_buffer(values.span()));
- auto* original_data = original.data();
-
- Array other_values { 1u, 2u, 3u, 4u };
- auto moved = WebGLRenderingContextBaseAccessor::make_span_with_storage<u32>(make_inline_u32_buffer(other_values.span()));
- moved = move(original);
-
- EXPECT_NE(moved.data(), original_data);
- EXPECT_EQ(moved.size(), values.size());
- for (size_t i = 0; i < values.size(); ++i)
- EXPECT_EQ(moved.data()[i], values[i]);
-}
-
-TEST_CASE(non_owning_span_preserves_external_span_after_move)
-{
- Array values { 10u, 20u, 30u, 40u };
- auto original = WebGLRenderingContextBaseAccessor::make_span_with_storage<u32>(values.span());
-
- auto moved = move(original);
-
- EXPECT_EQ(moved.data(), values.data());
- EXPECT_EQ(moved.size(), values.size());
- for (size_t i = 0; i < values.size(); ++i)
- EXPECT_EQ(moved.data()[i], values[i]);
-}
-
-TEST_CASE(out_of_bounds_float32_list_without_offset_is_empty)
-{
- TestVM test_vm;
- auto& realm = *test_vm.vm->current_realm();
- Web::WebGL::WebGLRenderingContextBase::Float32List list { create_out_of_bounds_array<JS::Float32Array>(realm, JS::TypedArrayBase::Kind::Float32Array) };
-
- auto span = MUST(WebGLRenderingContextBaseAccessor::span_from_float32_list(list, 0));
-
- EXPECT_EQ(span.size(), 0u);
- EXPECT(WebGLRenderingContextBaseAccessor::span_from_float32_list(list, 1).is_error());
- EXPECT(WebGLRenderingContextBaseAccessor::span_from_float32_list(list, 0, 1).is_error());
-}
-
-TEST_CASE(out_of_bounds_int32_list_without_offset_is_empty)
-{
- TestVM test_vm;
- auto& realm = *test_vm.vm->current_realm();
- Web::WebGL::WebGLRenderingContextBase::Int32List list { create_out_of_bounds_array<JS::Int32Array>(realm, JS::TypedArrayBase::Kind::Int32Array) };
-
- auto span = MUST(WebGLRenderingContextBaseAccessor::span_from_int32_list(list, 0));
-
- EXPECT_EQ(span.size(), 0u);
- EXPECT(WebGLRenderingContextBaseAccessor::span_from_int32_list(list, 1).is_error());
- EXPECT(WebGLRenderingContextBaseAccessor::span_from_int32_list(list, 0, 1).is_error());
-}
-
-TEST_CASE(out_of_bounds_uint32_list_without_offset_is_empty)
-{
- TestVM test_vm;
- auto& realm = *test_vm.vm->current_realm();
- Web::WebGL::WebGLRenderingContextBase::Uint32List list { create_out_of_bounds_array<JS::Uint32Array>(realm, JS::TypedArrayBase::Kind::Uint32Array) };
-
- auto span = MUST(WebGLRenderingContextBaseAccessor::span_from_uint32_list(list, 0));
-
- EXPECT_EQ(span.size(), 0u);
- EXPECT(WebGLRenderingContextBaseAccessor::span_from_uint32_list(list, 1).is_error());
- EXPECT(WebGLRenderingContextBaseAccessor::span_from_uint32_list(list, 0, 1).is_error());
-}
diff --git a/Tests/LibWeb/TestWebIDLBuffers.cpp b/Tests/LibWeb/TestWebIDLBuffers.cpp
index 78796a6b566..831fe2a2309 100644
--- a/Tests/LibWeb/TestWebIDLBuffers.cpp
+++ b/Tests/LibWeb/TestWebIDLBuffers.cpp
@@ -11,7 +11,6 @@
#include <LibJS/Runtime/TypedArray.h>
#include <LibJS/Runtime/VM.h>
#include <LibTest/TestCase.h>
-#include <LibWeb/WebGL/WebGLRenderingContextBase.h>
#include <LibWeb/WebIDL/Buffers.h>
namespace {
@@ -32,21 +31,6 @@ struct TestVM {
NonnullOwnPtr<JS::ExecutionContext> execution_context;
};
-struct ExposedWebGLRenderingContextBase : Web::WebGL::WebGLRenderingContextBase {
- WEB_NON_IDL_WRAPPABLE(ExposedWebGLRenderingContextBase, Web::WebGL::WebGLRenderingContextBase);
-
- using Web::WebGL::WebGLRenderingContextBase::with_buffer_source_bytes;
-};
-
-ErrorOr<ByteBuffer> buffer_source_bytes(Web::WebIDL::BufferSource source, u64 src_offset, u32 src_length_override = 0)
-{
- ByteBuffer bytes;
- TRY(ExposedWebGLRenderingContextBase::with_buffer_source_bytes(source, src_offset, src_length_override, [&](ReadonlyBytes view) {
- bytes = MUST(ByteBuffer::copy(view));
- }));
- return bytes;
-}
-
GC::Ref<JS::ArrayBuffer> create_resizable_array_buffer(JS::VM& vm)
{
auto& realm = *vm.current_realm();
@@ -136,12 +120,6 @@ TEST_CASE(buffer_source_copy_and_checked_write_handle_in_bounds_views)
Web::WebIDL::BufferSource typed_array_source { typed_array_view };
EXPECT_EQ(typed_array_source.byte_length(), 4u);
- auto typed_array_bytes = MUST(buffer_source_bytes(typed_array_source, 1));
- EXPECT_EQ(typed_array_bytes.size(), 2uz);
- EXPECT_EQ(typed_array_bytes[0], 0x16);
- EXPECT_EQ(typed_array_bytes[1], 0x17);
- EXPECT(buffer_source_bytes(typed_array_source, 3).is_error());
-
u8 one_byte = 0xaa;
EXPECT(typed_array_view.write_checked({ &one_byte, 1 }).is_error());
@@ -156,11 +134,6 @@ TEST_CASE(buffer_source_copy_and_checked_write_handle_in_bounds_views)
Web::WebIDL::BufferSource data_view_source { data_view_view };
EXPECT_EQ(data_view_source.byte_length(), 4u);
- auto data_view_bytes = MUST(buffer_source_bytes(data_view_source, 2, 2));
- EXPECT_EQ(data_view_bytes.size(), 2uz);
- EXPECT_EQ(data_view_bytes[0], 0x1a);
- EXPECT_EQ(data_view_bytes[1], 0x1b);
-
u8 data_view_replacement[] { 0xe0, 0xe1 };
EXPECT(!data_view_view.write_checked(data_view_replacement, 1).is_error());
@@ -171,23 +144,6 @@ TEST_CASE(buffer_source_copy_and_checked_write_handle_in_bounds_views)
EXPECT_EQ(final_bytes[10], 0xe1);
}
-TEST_CASE(webgl_buffer_source_bytes_treats_out_of_bounds_views_as_empty)
-{
- TestVM test_vm;
-
- Web::WebIDL::BufferSource typed_array_source { typed_array_view(*test_vm.vm) };
- auto typed_array_bytes = MUST(buffer_source_bytes(typed_array_source, 0));
- EXPECT_EQ(typed_array_bytes.size(), 0uz);
- EXPECT(buffer_source_bytes(typed_array_source, 1).is_error());
- EXPECT(buffer_source_bytes(typed_array_source, 0, 1).is_error());
-
- Web::WebIDL::BufferSource data_view_source { make_data_view(*test_vm.vm) };
- auto data_view_bytes = MUST(buffer_source_bytes(data_view_source, 0));
- EXPECT_EQ(data_view_bytes.size(), 0uz);
- EXPECT(buffer_source_bytes(data_view_source, 1).is_error());
- EXPECT(buffer_source_bytes(data_view_source, 0, 1).is_error());
-}
-
TEST_CASE(array_buffer_view_checked_write_handles_out_of_bounds_views)
{
TestVM test_vm;