webgl: Move framebuffer initialization logic to WebGL thread.

This commit is contained in:
Josh Matthews 2018-08-24 13:43:32 -04:00
parent df8e36aa78
commit 1b08dd5232
6 changed files with 238 additions and 75 deletions

View file

@ -11,7 +11,7 @@ use offscreen_gl_context::{GLLimits, GLVersion};
use offscreen_gl_context::{NativeGLContext, NativeGLContextHandle, NativeGLContextMethods}; use offscreen_gl_context::{NativeGLContext, NativeGLContextHandle, NativeGLContextMethods};
use offscreen_gl_context::{OSMesaContext, OSMesaContextHandle}; use offscreen_gl_context::{OSMesaContext, OSMesaContextHandle};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use super::webgl_thread::WebGLImpl; use super::webgl_thread::{WebGLImpl, GLState};
/// The GLContextFactory is used to create shared GL contexts with the main thread GL context. /// The GLContextFactory is used to create shared GL contexts with the main thread GL context.
/// Currently, shared textures are used to render WebGL textures into the WR compositor. /// Currently, shared textures are used to render WebGL textures into the WR compositor.
@ -144,13 +144,13 @@ impl GLContextWrapper {
} }
} }
pub fn apply_command(&self, cmd: WebGLCommand) { pub fn apply_command(&self, cmd: WebGLCommand, state: &mut GLState) {
match *self { match *self {
GLContextWrapper::Native(ref ctx) => { GLContextWrapper::Native(ref ctx) => {
WebGLImpl::apply(ctx, cmd); WebGLImpl::apply(ctx, state, cmd);
} }
GLContextWrapper::OSMesa(ref ctx) => { GLContextWrapper::OSMesa(ref ctx) => {
WebGLImpl::apply(ctx, cmd); WebGLImpl::apply(ctx, state, cmd);
} }
} }
} }

View file

@ -18,6 +18,33 @@ use webrender_api;
/// It allows to get a WebGLThread handle for each script pipeline. /// It allows to get a WebGLThread handle for each script pipeline.
pub use ::webgl_mode::WebGLThreads; pub use ::webgl_mode::WebGLThreads;
struct GLContextData {
ctx: GLContextWrapper,
state: GLState,
}
pub struct GLState {
clear_color: (f32, f32, f32, f32),
scissor_test_enabled: bool,
stencil_write_mask: (u32, u32),
stencil_clear_value: i32,
depth_write_mask: bool,
depth_clear_value: f64,
}
impl Default for GLState {
fn default() -> GLState {
GLState {
clear_color: (0., 0., 0., 0.),
scissor_test_enabled: false,
stencil_write_mask: (0, 0),
stencil_clear_value: 0,
depth_write_mask: true,
depth_clear_value: 1.,
}
}
}
/// A WebGLThread manages the life cycle and message multiplexing of /// A WebGLThread manages the life cycle and message multiplexing of
/// a set of WebGLContexts living in the same thread. /// a set of WebGLContexts living in the same thread.
pub struct WebGLThread<VR: WebVRRenderHandler + 'static, OB: WebGLThreadObserver> { pub struct WebGLThread<VR: WebVRRenderHandler + 'static, OB: WebGLThreadObserver> {
@ -26,7 +53,7 @@ pub struct WebGLThread<VR: WebVRRenderHandler + 'static, OB: WebGLThreadObserver
/// Channel used to generate/update or delete `webrender_api::ImageKey`s. /// Channel used to generate/update or delete `webrender_api::ImageKey`s.
webrender_api: webrender_api::RenderApi, webrender_api: webrender_api::RenderApi,
/// Map of live WebGLContexts. /// Map of live WebGLContexts.
contexts: FnvHashMap<WebGLContextId, GLContextWrapper>, contexts: FnvHashMap<WebGLContextId, GLContextData>,
/// Cached information for WebGLContexts. /// Cached information for WebGLContexts.
cached_context_info: FnvHashMap<WebGLContextId, WebGLContextInfo>, cached_context_info: FnvHashMap<WebGLContextId, WebGLContextInfo>,
/// Current bound context. /// Current bound context.
@ -93,9 +120,9 @@ impl<VR: WebVRRenderHandler + 'static, OB: WebGLThreadObserver> WebGLThread<VR,
WebGLMsg::CreateContext(version, size, attributes, result_sender) => { WebGLMsg::CreateContext(version, size, attributes, result_sender) => {
let result = self.create_webgl_context(version, size, attributes); let result = self.create_webgl_context(version, size, attributes);
result_sender.send(result.map(|(id, limits, share_mode)| { result_sender.send(result.map(|(id, limits, share_mode)| {
let ctx = Self::make_current_if_needed(id, &self.contexts, &mut self.bound_context_id) let data = Self::make_current_if_needed(id, &self.contexts, &mut self.bound_context_id)
.expect("WebGLContext not found"); .expect("WebGLContext not found");
let glsl_version = Self::get_glsl_version(ctx); let glsl_version = Self::get_glsl_version(&data.ctx);
WebGLCreateContextResult { WebGLCreateContextResult {
sender: WebGLMsgSender::new(id, webgl_chan.clone()), sender: WebGLMsgSender::new(id, webgl_chan.clone()),
@ -139,8 +166,9 @@ impl<VR: WebVRRenderHandler + 'static, OB: WebGLThreadObserver> WebGLThread<VR,
/// Handles a WebGLCommand for a specific WebGLContext /// Handles a WebGLCommand for a specific WebGLContext
fn handle_webgl_command(&mut self, context_id: WebGLContextId, command: WebGLCommand) { fn handle_webgl_command(&mut self, context_id: WebGLContextId, command: WebGLCommand) {
if let Some(ctx) = Self::make_current_if_needed(context_id, &self.contexts, &mut self.bound_context_id) { let data = Self::make_current_if_needed_mut(context_id, &mut self.contexts, &mut self.bound_context_id);
ctx.apply_command(command); if let Some(data) = data {
data.ctx.apply_command(command, &mut data.state);
} }
} }
@ -158,28 +186,28 @@ impl<VR: WebVRRenderHandler + 'static, OB: WebGLThreadObserver> WebGLThread<VR,
/// Handles a lock external callback received from webrender::ExternalImageHandler /// Handles a lock external callback received from webrender::ExternalImageHandler
fn handle_lock(&mut self, context_id: WebGLContextId, sender: WebGLSender<(u32, Size2D<i32>, usize)>) { fn handle_lock(&mut self, context_id: WebGLContextId, sender: WebGLSender<(u32, Size2D<i32>, usize)>) {
let ctx = Self::make_current_if_needed(context_id, &self.contexts, &mut self.bound_context_id) let data = Self::make_current_if_needed(context_id, &self.contexts, &mut self.bound_context_id)
.expect("WebGLContext not found in a WebGLMsg::Lock message"); .expect("WebGLContext not found in a WebGLMsg::Lock message");
let info = self.cached_context_info.get_mut(&context_id).unwrap(); let info = self.cached_context_info.get_mut(&context_id).unwrap();
// Insert a OpenGL Fence sync object that sends a signal when all the WebGL commands are finished. // Insert a OpenGL Fence sync object that sends a signal when all the WebGL commands are finished.
// The related gl().wait_sync call is performed in the WR thread. See WebGLExternalImageApi for mor details. // The related gl().wait_sync call is performed in the WR thread. See WebGLExternalImageApi for mor details.
let gl_sync = ctx.gl().fence_sync(gl::SYNC_GPU_COMMANDS_COMPLETE, 0); let gl_sync = data.ctx.gl().fence_sync(gl::SYNC_GPU_COMMANDS_COMPLETE, 0);
info.gl_sync = Some(gl_sync); info.gl_sync = Some(gl_sync);
// It is important that the fence sync is properly flushed into the GPU's command queue. // It is important that the fence sync is properly flushed into the GPU's command queue.
// Without proper flushing, the sync object may never be signaled. // Without proper flushing, the sync object may never be signaled.
ctx.gl().flush(); data.ctx.gl().flush();
sender.send((info.texture_id, info.size, gl_sync as usize)).unwrap(); sender.send((info.texture_id, info.size, gl_sync as usize)).unwrap();
} }
/// Handles an unlock external callback received from webrender::ExternalImageHandler /// Handles an unlock external callback received from webrender::ExternalImageHandler
fn handle_unlock(&mut self, context_id: WebGLContextId) { fn handle_unlock(&mut self, context_id: WebGLContextId) {
let ctx = Self::make_current_if_needed(context_id, &self.contexts, &mut self.bound_context_id) let data = Self::make_current_if_needed(context_id, &self.contexts, &mut self.bound_context_id)
.expect("WebGLContext not found in a WebGLMsg::Unlock message"); .expect("WebGLContext not found in a WebGLMsg::Unlock message");
let info = self.cached_context_info.get_mut(&context_id).unwrap(); let info = self.cached_context_info.get_mut(&context_id).unwrap();
if let Some(gl_sync) = info.gl_sync.take() { if let Some(gl_sync) = info.gl_sync.take() {
// Release the GLSync object. // Release the GLSync object.
ctx.gl().delete_sync(gl_sync); data.ctx.gl().delete_sync(gl_sync);
} }
} }
@ -207,7 +235,10 @@ impl<VR: WebVRRenderHandler + 'static, OB: WebGLThreadObserver> WebGLThread<VR,
let id = WebGLContextId(self.next_webgl_id); let id = WebGLContextId(self.next_webgl_id);
let (size, texture_id, limits) = ctx.get_info(); let (size, texture_id, limits) = ctx.get_info();
self.next_webgl_id += 1; self.next_webgl_id += 1;
self.contexts.insert(id, ctx); self.contexts.insert(id, GLContextData {
ctx,
state: Default::default(),
});
self.cached_context_info.insert(id, WebGLContextInfo { self.cached_context_info.insert(id, WebGLContextInfo {
texture_id, texture_id,
size, size,
@ -232,10 +263,14 @@ impl<VR: WebVRRenderHandler + 'static, OB: WebGLThreadObserver> WebGLThread<VR,
context_id: WebGLContextId, context_id: WebGLContextId,
size: Size2D<i32>, size: Size2D<i32>,
sender: WebGLSender<Result<(), String>>) { sender: WebGLSender<Result<(), String>>) {
let ctx = Self::make_current_if_needed_mut(context_id, &mut self.contexts, &mut self.bound_context_id); let data = Self::make_current_if_needed_mut(
match ctx.resize(size) { context_id,
&mut self.contexts,
&mut self.bound_context_id
).expect("Missing WebGL context!");
match data.ctx.resize(size) {
Ok(_) => { Ok(_) => {
let (real_size, texture_id, _) = ctx.get_info(); let (real_size, texture_id, _) = data.ctx.get_info();
self.observer.on_context_resize(context_id, texture_id, real_size); self.observer.on_context_resize(context_id, texture_id, real_size);
let info = self.cached_context_info.get_mut(&context_id).unwrap(); let info = self.cached_context_info.get_mut(&context_id).unwrap();
@ -306,7 +341,7 @@ impl<VR: WebVRRenderHandler + 'static, OB: WebGLThreadObserver> WebGLThread<VR,
}) })
}, },
WebGLContextShareMode::Readback => { WebGLContextShareMode::Readback => {
let pixels = Self::raw_pixels(&self.contexts[&context_id], info.size); let pixels = Self::raw_pixels(&self.contexts[&context_id].ctx, info.size);
match info.image_key.clone() { match info.image_key.clone() {
Some(image_key) => { Some(image_key) => {
// ImageKey was already created, but WR Images must // ImageKey was already created, but WR Images must
@ -339,18 +374,20 @@ impl<VR: WebVRRenderHandler + 'static, OB: WebGLThreadObserver> WebGLThread<VR,
fn handle_dom_to_texture(&mut self, command: DOMToTextureCommand) { fn handle_dom_to_texture(&mut self, command: DOMToTextureCommand) {
match command { match command {
DOMToTextureCommand::Attach(context_id, texture_id, document_id, pipeline_id, size) => { DOMToTextureCommand::Attach(context_id, texture_id, document_id, pipeline_id, size) => {
let ctx = Self::make_current_if_needed(context_id, &self.contexts, &mut self.bound_context_id) let data = Self::make_current_if_needed(context_id, &self.contexts, &mut self.bound_context_id)
.expect("WebGLContext not found in a WebGL DOMToTextureCommand::Attach command"); .expect("WebGLContext not found in a WebGL DOMToTextureCommand::Attach command");
// Initialize the texture that WR will use for frame outputs. // Initialize the texture that WR will use for frame outputs.
ctx.gl().tex_image_2d(gl::TEXTURE_2D, data.ctx.gl().tex_image_2d(
0, gl::TEXTURE_2D,
gl::RGBA as gl::GLint, 0,
size.width, gl::RGBA as gl::GLint,
size.height, size.width,
0, size.height,
gl::RGBA, 0,
gl::UNSIGNED_BYTE, gl::RGBA,
None); gl::UNSIGNED_BYTE,
None
);
self.dom_outputs.insert(pipeline_id, DOMToTextureData { self.dom_outputs.insert(pipeline_id, DOMToTextureData {
context_id, texture_id, document_id, size context_id, texture_id, document_id, size
}); });
@ -361,14 +398,14 @@ impl<VR: WebVRRenderHandler + 'static, OB: WebGLThreadObserver> WebGLThread<VR,
DOMToTextureCommand::Lock(pipeline_id, gl_sync, sender) => { DOMToTextureCommand::Lock(pipeline_id, gl_sync, sender) => {
let contexts = &self.contexts; let contexts = &self.contexts;
let bound_context_id = &mut self.bound_context_id; let bound_context_id = &mut self.bound_context_id;
let result = self.dom_outputs.get(&pipeline_id).and_then(|data| { let result = self.dom_outputs.get(&pipeline_id).and_then(|dom_data| {
let ctx = Self::make_current_if_needed(data.context_id, contexts, bound_context_id); let data = Self::make_current_if_needed(dom_data.context_id, contexts, bound_context_id);
ctx.and_then(|ctx| { data.and_then(|data| {
// The next glWaitSync call is used to synchronize the two flows of // The next glWaitSync call is used to synchronize the two flows of
// OpenGL commands (WR and WebGL) in order to avoid using semi-ready WR textures. // OpenGL commands (WR and WebGL) in order to avoid using semi-ready WR textures.
// glWaitSync doesn't block WebGL CPU thread. // glWaitSync doesn't block WebGL CPU thread.
ctx.gl().wait_sync(gl_sync as gl::GLsync, 0, gl::TIMEOUT_IGNORED); data.ctx.gl().wait_sync(gl_sync as gl::GLsync, 0, gl::TIMEOUT_IGNORED);
Some((data.texture_id.get(), data.size)) Some((dom_data.texture_id.get(), dom_data.size))
}) })
}); });
@ -390,28 +427,37 @@ impl<VR: WebVRRenderHandler + 'static, OB: WebGLThreadObserver> WebGLThread<VR,
/// Gets a reference to a GLContextWrapper for a given WebGLContextId and makes it current if required. /// Gets a reference to a GLContextWrapper for a given WebGLContextId and makes it current if required.
fn make_current_if_needed<'a>(context_id: WebGLContextId, fn make_current_if_needed<'a>(context_id: WebGLContextId,
contexts: &'a FnvHashMap<WebGLContextId, GLContextWrapper>, contexts: &'a FnvHashMap<WebGLContextId, GLContextData>,
bound_id: &mut Option<WebGLContextId>) -> Option<&'a GLContextWrapper> { bound_id: &mut Option<WebGLContextId>) -> Option<&'a GLContextData> {
contexts.get(&context_id).and_then(|ctx| { let data = contexts.get(&context_id);
if let Some(data) = data {
if Some(context_id) != *bound_id { if Some(context_id) != *bound_id {
ctx.make_current(); data.ctx.make_current();
*bound_id = Some(context_id); *bound_id = Some(context_id);
} }
}
Some(ctx) data
})
} }
/// Gets a mutable reference to a GLContextWrapper for a WebGLContextId and makes it current if required. /// Gets a mutable reference to a GLContextWrapper for a WebGLContextId and makes it current if required.
fn make_current_if_needed_mut<'a>(context_id: WebGLContextId, fn make_current_if_needed_mut<'a>(
contexts: &'a mut FnvHashMap<WebGLContextId, GLContextWrapper>, context_id: WebGLContextId,
bound_id: &mut Option<WebGLContextId>) -> &'a mut GLContextWrapper { contexts: &'a mut FnvHashMap<WebGLContextId, GLContextData>,
let ctx = contexts.get_mut(&context_id).expect("WebGLContext not found!"); bound_id: &mut Option<WebGLContextId>)
if Some(context_id) != *bound_id { -> Option<&'a mut GLContextData>
ctx.make_current(); {
*bound_id = Some(context_id); let data = contexts.get_mut(&context_id);
if let Some(ref data) = data {
if Some(context_id) != *bound_id {
data.ctx.make_current();
*bound_id = Some(context_id);
}
} }
ctx
data
} }
/// Creates a `webrender_api::ImageKey` that uses shared textures. /// Creates a `webrender_api::ImageKey` that uses shared textures.
@ -636,7 +682,11 @@ pub struct WebGLImpl;
impl WebGLImpl { impl WebGLImpl {
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub fn apply<Native: NativeGLContextMethods>(ctx: &GLContext<Native>, command: WebGLCommand) { pub fn apply<Native: NativeGLContextMethods>(
ctx: &GLContext<Native>,
state: &mut GLState,
command: WebGLCommand
) {
match command { match command {
WebGLCommand::GetContextAttributes(ref sender) => WebGLCommand::GetContextAttributes(ref sender) =>
sender.send(*ctx.borrow_attributes()).unwrap(), sender.send(*ctx.borrow_attributes()).unwrap(),
@ -667,13 +717,19 @@ impl WebGLImpl {
}, },
WebGLCommand::Clear(mask) => WebGLCommand::Clear(mask) =>
ctx.gl().clear(mask), ctx.gl().clear(mask),
WebGLCommand::ClearColor(r, g, b, a) => WebGLCommand::ClearColor(r, g, b, a) => {
ctx.gl().clear_color(r, g, b, a), state.clear_color = (r, g, b, a);
WebGLCommand::ClearDepth(depth) => { ctx.gl().clear_color(r, g, b, a);
ctx.gl().clear_depth(depth.max(0.).min(1.) as f64) }
WebGLCommand::ClearDepth(depth) => {
let value = depth.max(0.).min(1.) as f64;
state.depth_clear_value = value;
ctx.gl().clear_depth(value)
}
WebGLCommand::ClearStencil(stencil) => {
state.stencil_clear_value = stencil;
ctx.gl().clear_stencil(stencil);
} }
WebGLCommand::ClearStencil(stencil) =>
ctx.gl().clear_stencil(stencil),
WebGLCommand::ColorMask(r, g, b, a) => WebGLCommand::ColorMask(r, g, b, a) =>
ctx.gl().color_mask(r, g, b, a), ctx.gl().color_mask(r, g, b, a),
WebGLCommand::CopyTexImage2D(target, level, internal_format, x, y, width, height, border) => WebGLCommand::CopyTexImage2D(target, level, internal_format, x, y, width, height, border) =>
@ -684,15 +740,25 @@ impl WebGLImpl {
ctx.gl().cull_face(mode), ctx.gl().cull_face(mode),
WebGLCommand::DepthFunc(func) => WebGLCommand::DepthFunc(func) =>
ctx.gl().depth_func(func), ctx.gl().depth_func(func),
WebGLCommand::DepthMask(flag) => WebGLCommand::DepthMask(flag) => {
ctx.gl().depth_mask(flag), state.depth_write_mask = flag;
ctx.gl().depth_mask(flag);
}
WebGLCommand::DepthRange(near, far) => { WebGLCommand::DepthRange(near, far) => {
ctx.gl().depth_range(near.max(0.).min(1.) as f64, far.max(0.).min(1.) as f64) ctx.gl().depth_range(near.max(0.).min(1.) as f64, far.max(0.).min(1.) as f64)
} }
WebGLCommand::Disable(cap) => WebGLCommand::Disable(cap) => {
ctx.gl().disable(cap), if cap == gl::SCISSOR_TEST {
WebGLCommand::Enable(cap) => state.scissor_test_enabled = false;
ctx.gl().enable(cap), }
ctx.gl().disable(cap);
}
WebGLCommand::Enable(cap) => {
if cap == gl::SCISSOR_TEST {
state.scissor_test_enabled = true;
}
ctx.gl().enable(cap);
}
WebGLCommand::FramebufferRenderbuffer(target, attachment, renderbuffertarget, rb) => { WebGLCommand::FramebufferRenderbuffer(target, attachment, renderbuffertarget, rb) => {
let attach = |attachment| { let attach = |attachment| {
ctx.gl().framebuffer_renderbuffer(target, attachment, ctx.gl().framebuffer_renderbuffer(target, attachment,
@ -745,10 +811,18 @@ impl WebGLImpl {
ctx.gl().stencil_func(func, ref_, mask), ctx.gl().stencil_func(func, ref_, mask),
WebGLCommand::StencilFuncSeparate(face, func, ref_, mask) => WebGLCommand::StencilFuncSeparate(face, func, ref_, mask) =>
ctx.gl().stencil_func_separate(face, func, ref_, mask), ctx.gl().stencil_func_separate(face, func, ref_, mask),
WebGLCommand::StencilMask(mask) => WebGLCommand::StencilMask(mask) => {
ctx.gl().stencil_mask(mask), state.stencil_write_mask = (mask, mask);
WebGLCommand::StencilMaskSeparate(face, mask) => ctx.gl().stencil_mask(mask);
ctx.gl().stencil_mask_separate(face, mask), }
WebGLCommand::StencilMaskSeparate(face, mask) => {
if face == gl::FRONT {
state.stencil_write_mask.0 = mask;
} else {
state.stencil_write_mask.1 = mask;
}
ctx.gl().stencil_mask_separate(face, mask);
}
WebGLCommand::StencilOp(fail, zfail, zpass) => WebGLCommand::StencilOp(fail, zfail, zpass) =>
ctx.gl().stencil_op(fail, zfail, zpass), ctx.gl().stencil_op(fail, zfail, zpass),
WebGLCommand::StencilOpSeparate(face, fail, zfail, zpass) => WebGLCommand::StencilOpSeparate(face, fail, zfail, zpass) =>
@ -1124,6 +1198,9 @@ impl WebGLImpl {
} }
sender.send(value).unwrap(); sender.send(value).unwrap();
} }
WebGLCommand::InitializeFramebuffer { color, depth, stencil } => {
Self::initialize_framebuffer(ctx.gl(), state, color, depth, stencil)
}
} }
// TODO: update test expectations in order to enable debug assertions // TODO: update test expectations in order to enable debug assertions
@ -1134,6 +1211,62 @@ impl WebGLImpl {
assert_eq!(error, gl::NO_ERROR, "Unexpected WebGL error: 0x{:x} ({})", error, error); assert_eq!(error, gl::NO_ERROR, "Unexpected WebGL error: 0x{:x} ({})", error, error);
} }
fn initialize_framebuffer(
gl: &gl::Gl,
state: &GLState,
color: bool,
depth: bool,
stencil: bool,
) {
let bits = [
(color, gl::COLOR_BUFFER_BIT),
(depth, gl::DEPTH_BUFFER_BIT),
(stencil, gl::STENCIL_BUFFER_BIT),
].iter().fold(0, |bits, &(enabled, bit)| bits | if enabled { bit } else { 0 });
if state.scissor_test_enabled {
gl.disable(gl::SCISSOR_TEST);
}
if color {
gl.clear_color(0., 0., 0., 0.);
}
if depth {
gl.depth_mask(true);
gl.clear_depth(1.);
}
if stencil {
gl.stencil_mask_separate(gl::FRONT, 0xFFFFFFFF);
gl.stencil_mask_separate(gl::BACK, 0xFFFFFFFF);
gl.clear_stencil(0);
}
gl.clear(bits);
if state.scissor_test_enabled {
gl.enable(gl::SCISSOR_TEST);
}
if color {
let (r, g, b, a) = state.clear_color;
gl.clear_color(r, g, b, a);
}
if depth {
gl.depth_mask(state.depth_write_mask);
gl.clear_depth(state.depth_clear_value);
}
if stencil {
let (front, back) = state.stencil_write_mask;
gl.stencil_mask_separate(gl::FRONT, front);
gl.stencil_mask_separate(gl::BACK, back);
gl.clear_stencil(state.stencil_clear_value);
}
}
#[allow(unsafe_code)] #[allow(unsafe_code)]
fn link_program(gl: &gl::Gl, program: WebGLProgramId) -> ProgramLinkInfo { fn link_program(gl: &gl::Gl, program: WebGLProgramId) -> ProgramLinkInfo {
gl.link_program(program.get()); gl.link_program(program.get());

View file

@ -296,6 +296,7 @@ pub enum WebGLCommand {
GetUniformFloat4(WebGLProgramId, i32, WebGLSender<[f32; 4]>), GetUniformFloat4(WebGLProgramId, i32, WebGLSender<[f32; 4]>),
GetUniformFloat9(WebGLProgramId, i32, WebGLSender<[f32; 9]>), GetUniformFloat9(WebGLProgramId, i32, WebGLSender<[f32; 9]>),
GetUniformFloat16(WebGLProgramId, i32, WebGLSender<[f32; 16]>), GetUniformFloat16(WebGLProgramId, i32, WebGLSender<[f32; 16]>),
InitializeFramebuffer { color: bool, depth: bool, stencil: bool },
} }
macro_rules! define_resource_id_struct { macro_rules! define_resource_id_struct {

View file

@ -34,10 +34,17 @@ enum WebGLFramebufferAttachment {
impl WebGLFramebufferAttachment { impl WebGLFramebufferAttachment {
fn needs_initialization(&self) -> bool { fn needs_initialization(&self) -> bool {
match *self { match *self {
WebGLFramebufferAttachment::Renderbuffer(_) => true, WebGLFramebufferAttachment::Renderbuffer(ref r) => !r.is_initialized(),
WebGLFramebufferAttachment::Texture { .. } => false, WebGLFramebufferAttachment::Texture { .. } => false,
} }
} }
fn mark_initialized(&self) {
match *self {
WebGLFramebufferAttachment::Renderbuffer(ref r) => r.mark_initialized(),
WebGLFramebufferAttachment::Texture { .. } => ()
}
}
} }
#[derive(Clone, JSTraceable, MallocSizeOf)] #[derive(Clone, JSTraceable, MallocSizeOf)]
@ -239,15 +246,14 @@ impl WebGLFramebuffer {
]; ];
let mut clear_bits = 0; let mut clear_bits = 0;
for &(attachment, bits) in &attachments { for &(attachment, bits) in &attachments {
if attachment.borrow().as_ref().map_or(false, |att| att.needs_initialization()) { if let Some(ref att) = *attachment.borrow() {
clear_bits |= bits; if att.needs_initialization() {
att.mark_initialized();
clear_bits |= bits;
}
} }
} }
if clear_bits != 0 { self.upcast::<WebGLObject>().context().initialize_framebuffer(clear_bits);
self.upcast::<WebGLObject>().context().send_command(
WebGLCommand::Clear(clear_bits)
);
}
self.is_initialized.set(true); self.is_initialized.set(true);
} }

View file

@ -23,6 +23,7 @@ pub struct WebGLRenderbuffer {
is_deleted: Cell<bool>, is_deleted: Cell<bool>,
size: Cell<Option<(i32, i32)>>, size: Cell<Option<(i32, i32)>>,
internal_format: Cell<Option<u32>>, internal_format: Cell<Option<u32>>,
is_initialized: Cell<bool>,
} }
impl WebGLRenderbuffer { impl WebGLRenderbuffer {
@ -34,6 +35,7 @@ impl WebGLRenderbuffer {
is_deleted: Cell::new(false), is_deleted: Cell::new(false),
internal_format: Cell::new(None), internal_format: Cell::new(None),
size: Cell::new(None), size: Cell::new(None),
is_initialized: Cell::new(false),
} }
} }
@ -66,6 +68,14 @@ impl WebGLRenderbuffer {
self.internal_format.get().unwrap_or(constants::RGBA4) self.internal_format.get().unwrap_or(constants::RGBA4)
} }
pub fn mark_initialized(&self) {
self.is_initialized.set(true);
}
pub fn is_initialized(&self) -> bool {
self.is_initialized.get()
}
pub fn bind(&self, target: u32) { pub fn bind(&self, target: u32) {
self.ever_bound.set(true); self.ever_bound.set(true);
self.upcast::<WebGLObject>() self.upcast::<WebGLObject>()

View file

@ -1061,6 +1061,17 @@ impl WebGLRenderingContext {
_ => Err(InvalidEnum), _ => Err(InvalidEnum),
} }
} }
pub fn initialize_framebuffer(&self, clear_bits: u32) {
if clear_bits == 0 {
return;
}
self.send_command(WebGLCommand::InitializeFramebuffer {
color: clear_bits & constants::COLOR_BUFFER_BIT != 0,
depth: clear_bits & constants::DEPTH_BUFFER_BIT != 0,
stencil: clear_bits & constants::STENCIL_BUFFER_BIT != 0,
});
}
} }
impl Drop for WebGLRenderingContext { impl Drop for WebGLRenderingContext {
@ -2727,10 +2738,12 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3
fn StencilMaskSeparate(&self, face: u32, mask: u32) { fn StencilMaskSeparate(&self, face: u32, mask: u32) {
match face { match face {
constants::FRONT | constants::BACK | constants::FRONT_AND_BACK => constants::FRONT |
constants::BACK |
constants::FRONT_AND_BACK =>
self.send_command(WebGLCommand::StencilMaskSeparate(face, mask)), self.send_command(WebGLCommand::StencilMaskSeparate(face, mask)),
_ => return self.webgl_error(InvalidEnum), _ => return self.webgl_error(InvalidEnum),
} };
} }
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3