/
webgl_thread.rs
2247 lines (2106 loc) · 85.6 KB
/
webgl_thread.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use super::gl_context::{map_attrs_to_script_attrs, GLContextFactory, GLContextWrapper};
use byteorder::{ByteOrder, NativeEndian, WriteBytesExt};
use canvas_traits::webgl::*;
use embedder_traits::EventLoopWaker;
use euclid::default::Size2D;
use fnv::FnvHashMap;
use gleam::gl;
use half::f16;
use ipc_channel::ipc::{self, OpaqueIpcMessage};
use ipc_channel::router::ROUTER;
use offscreen_gl_context::{DrawBuffer, GLContext, NativeGLContextMethods};
use pixels::{self, PixelFormat};
use std::borrow::Cow;
use std::cell::Cell;
use std::cell::RefCell;
use std::mem;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use std::thread;
use webrender_traits::{WebrenderExternalImageRegistry, WebrenderImageHandlerType};
/// WebGL Threading API entry point that lives in the constellation.
/// It allows to get a WebGLThread handle for each script pipeline.
pub use crate::webgl_mode::{ThreadMode, 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 set of WebGLContexts living in the same thread.
pub(crate) struct WebGLThread {
/// Factory used to create a new GLContext shared with the WR/Main thread.
gl_factory: GLContextFactory,
/// Channel used to generate/update or delete `webrender_api::ImageKey`s.
webrender_api: webrender_api::RenderApi,
/// Map of live WebGLContexts.
contexts: FnvHashMap<WebGLContextId, GLContextData>,
/// Cached information for WebGLContexts.
cached_context_info: FnvHashMap<WebGLContextId, WebGLContextInfo>,
/// Current bound context.
bound_context_id: Option<WebGLContextId>,
/// Handler user to send WebVR commands.
webvr_compositor: Option<Box<dyn WebVRRenderHandler>>,
/// Texture ids and sizes used in DOM to texture outputs.
dom_outputs: FnvHashMap<webrender_api::PipelineId, DOMToTextureData>,
/// List of registered webrender external images.
/// We use it to get an unique ID for new WebGLContexts.
external_images: Arc<Mutex<WebrenderExternalImageRegistry>>,
/// The receiver that will be used for processing WebGL messages.
receiver: WebGLReceiver<WebGLMsg>,
/// The receiver that should be used to send WebGL messages for processing.
sender: WebGLSender<WebGLMsg>,
}
#[derive(PartialEq)]
enum EventLoop {
Blocking,
Nonblocking,
}
/// The data required to initialize an instance of the WebGLThread type.
pub(crate) struct WebGLThreadInit {
pub gl_factory: GLContextFactory,
pub webrender_api_sender: webrender_api::RenderApiSender,
pub webvr_compositor: Option<Box<dyn WebVRRenderHandler>>,
pub external_images: Arc<Mutex<WebrenderExternalImageRegistry>>,
pub sender: WebGLSender<WebGLMsg>,
pub receiver: WebGLReceiver<WebGLMsg>,
}
/// The extra data required to run an instance of WebGLThread when it is
/// not running in its own thread.
pub struct WebGLMainThread {
pub(crate) thread_data: RefCell<WebGLThread>,
shut_down: Cell<bool>,
}
impl WebGLMainThread {
/// Synchronously process all outstanding WebGL messages.
pub fn process(&self) {
if self.shut_down.get() {
return;
}
// Any context could be current when we start.
self.thread_data.borrow_mut().bound_context_id = None;
self.shut_down.set(
!self
.thread_data
.borrow_mut()
.process(EventLoop::Nonblocking),
);
}
/// Returns the main GL thread if called from the main thread,
/// and `None` otherwise.
pub(crate) fn on_current_thread() -> Option<Rc<WebGLMainThread>> {
WEBGL_MAIN_THREAD.with(|main_thread| main_thread.borrow().clone())
}
}
thread_local! {
static WEBGL_MAIN_THREAD: RefCell<Option<Rc<WebGLMainThread>>> = RefCell::new(None);
}
impl WebGLThread {
/// Create a new instance of WebGLThread.
pub(crate) fn new(
WebGLThreadInit {
gl_factory,
webrender_api_sender,
webvr_compositor,
external_images,
sender,
receiver,
}: WebGLThreadInit,
) -> Self {
WebGLThread {
gl_factory,
webrender_api: webrender_api_sender.create_api(),
contexts: Default::default(),
cached_context_info: Default::default(),
bound_context_id: None,
webvr_compositor,
dom_outputs: Default::default(),
external_images,
sender,
receiver,
}
}
/// Perform all initialization required to run an instance of WebGLThread
/// concurrently on the current thread. Returns a `WebGLMainThread` instance
/// that can be used to process any outstanding WebGL messages at any given
/// point in time.
pub(crate) fn run_on_current_thread(
mut init: WebGLThreadInit,
event_loop_waker: Box<dyn EventLoopWaker>,
) -> Rc<WebGLMainThread> {
if let WebGLReceiver::Ipc(ref mut receiver) = init.receiver {
// Interpose a new channel in between the existing WebGL channel endpoints.
// This will bounce all WebGL messages through the router thread adding a small
// delay, but this will also ensure that the main thread will wake up and
// process the WebGL message when it arrives.
let (from_router_sender, from_router_receiver) = ipc::channel::<WebGLMsg>().unwrap();
let old_receiver = mem::replace(receiver, from_router_receiver);
ROUTER.add_route(
old_receiver.to_opaque(),
Box::new(move |msg: OpaqueIpcMessage| {
let _ = from_router_sender.send(msg.to().unwrap());
event_loop_waker.wake();
}),
);
}
let result = Rc::new(WebGLMainThread {
thread_data: RefCell::new(WebGLThread::new(init)),
shut_down: Cell::new(false),
});
WEBGL_MAIN_THREAD.with(|main_thread| {
debug_assert!(main_thread.borrow().is_none());
*main_thread.borrow_mut() = Some(result.clone());
});
result
}
/// Perform all initialization required to run an instance of WebGLThread
/// in parallel on its own dedicated thread.
pub(crate) fn run_on_own_thread(init: WebGLThreadInit) {
thread::Builder::new()
.name("WebGL thread".to_owned())
.spawn(move || {
let mut data = WebGLThread::new(init);
data.process(EventLoop::Blocking);
})
.expect("Thread spawning failed");
}
fn process(&mut self, loop_type: EventLoop) -> bool {
let webgl_chan = WebGLChan(self.sender.clone());
while let Ok(msg) = match loop_type {
EventLoop::Blocking => self.receiver.recv(),
EventLoop::Nonblocking => self.receiver.try_recv(),
} {
let exit = self.handle_msg(msg, &webgl_chan);
if exit {
return false;
}
}
true
}
/// Handles a generic WebGLMsg message
fn handle_msg(&mut self, msg: WebGLMsg, webgl_chan: &WebGLChan) -> bool {
trace!("processing {:?}", msg);
match msg {
WebGLMsg::CreateContext(version, size, attributes, result_sender) => {
let result = self.create_webgl_context(version, size, attributes);
result_sender
.send(result.map(|(id, limits, share_mode)| {
let data = Self::make_current_if_needed(
id,
&self.contexts,
&mut self.bound_context_id,
)
.expect("WebGLContext not found");
let glsl_version = Self::get_glsl_version(&data.ctx);
let api_type = match data.ctx.gl().get_type() {
gl::GlType::Gl => GlType::Gl,
gl::GlType::Gles => GlType::Gles,
};
// FIXME(nox): Should probably be done by offscreen_gl_context.
if api_type != GlType::Gles {
// Points sprites are enabled by default in OpenGL 3.2 core
// and in GLES. Rather than doing version detection, it does
// not hurt to enable them anyways.
data.ctx.gl().enable(gl::POINT_SPRITE);
let err = data.ctx.gl().get_error();
if err != 0 {
warn!("Error enabling GL point sprites: {}", err);
}
data.ctx.gl().enable(gl::PROGRAM_POINT_SIZE);
let err = data.ctx.gl().get_error();
if err != 0 {
warn!("Error enabling GL program point size: {}", err);
}
}
WebGLCreateContextResult {
sender: WebGLMsgSender::new(id, webgl_chan.clone()),
limits,
share_mode,
glsl_version,
api_type,
}
}))
.unwrap();
},
WebGLMsg::ResizeContext(ctx_id, size, sender) => {
self.resize_webgl_context(ctx_id, size, sender);
},
WebGLMsg::RemoveContext(ctx_id) => {
self.remove_webgl_context(ctx_id);
},
WebGLMsg::WebGLCommand(ctx_id, command, backtrace) => {
self.handle_webgl_command(ctx_id, command, backtrace);
},
WebGLMsg::WebVRCommand(ctx_id, command) => {
self.handle_webvr_command(ctx_id, command);
},
WebGLMsg::Lock(ctx_id, sender) => {
self.handle_lock(ctx_id, sender);
},
WebGLMsg::Unlock(ctx_id) => {
self.handle_unlock(ctx_id);
},
WebGLMsg::UpdateWebRenderImage(ctx_id, sender) => {
self.handle_update_wr_image(ctx_id, sender);
},
WebGLMsg::DOMToTextureCommand(command) => {
self.handle_dom_to_texture(command);
},
WebGLMsg::Exit => {
return true;
},
}
false
}
/// Handles a WebGLCommand for a specific WebGLContext
fn handle_webgl_command(
&mut self,
context_id: WebGLContextId,
command: WebGLCommand,
backtrace: WebGLCommandBacktrace,
) {
let data = Self::make_current_if_needed_mut(
context_id,
&mut self.contexts,
&mut self.bound_context_id,
);
if let Some(data) = data {
data.ctx.apply_command(command, backtrace, &mut data.state);
}
}
/// Handles a WebVRCommand for a specific WebGLContext
fn handle_webvr_command(&mut self, context_id: WebGLContextId, command: WebVRCommand) {
if let Some(context) =
Self::make_current_if_needed(context_id, &self.contexts, &mut self.bound_context_id)
{
let texture = match command {
WebVRCommand::SubmitFrame(..) => self.cached_context_info.get(&context_id),
_ => None,
};
self.webvr_compositor.as_mut().unwrap().handle(
context.ctx.gl(),
command,
texture.map(|t| (t.texture_id, t.size)),
);
}
}
/// Handles a lock external callback received from webrender::ExternalImageHandler
fn handle_lock(
&mut self,
context_id: WebGLContextId,
sender: WebGLSender<(u32, Size2D<i32>, usize)>,
) {
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");
let info = self.cached_context_info.get_mut(&context_id).unwrap();
info.render_state = ContextRenderState::Locked(None);
// 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.
let gl_sync = data.ctx.gl().fence_sync(gl::SYNC_GPU_COMMANDS_COMPLETE, 0);
info.gl_sync = Some(gl_sync);
debug_assert!(data.ctx.gl().get_error() == gl::NO_ERROR);
// 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.
data.ctx.gl().flush();
debug_assert!(data.ctx.gl().get_error() == gl::NO_ERROR);
let _ = sender.send((info.texture_id, info.size, gl_sync as usize));
}
/// A version of locking that doesn't return a GLsync object,
/// used when it's being called from the same thread.
pub(crate) fn handle_lock_unsync(&mut self, context_id: WebGLContextId) -> (u32, Size2D<i32>) {
let info = self.cached_context_info.get_mut(&context_id).unwrap();
info.render_state = ContextRenderState::Locked(None);
(info.texture_id, info.size)
}
/// Handles an unlock external callback received from webrender::ExternalImageHandler
pub(crate) fn handle_unlock(&mut self, context_id: WebGLContextId) {
let info = self.cached_context_info.get_mut(&context_id).unwrap();
info.render_state = ContextRenderState::Unlocked;
if let Some(gl_sync) = info.gl_sync.take() {
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");
// Release the GLSync object.
data.ctx.gl().delete_sync(gl_sync);
debug_assert!(data.ctx.gl().get_error() == gl::NO_ERROR);
}
}
/// Creates a new WebGLContext
fn create_webgl_context(
&mut self,
version: WebGLVersion,
size: Size2D<u32>,
attributes: GLContextAttributes,
) -> Result<(WebGLContextId, GLLimits, WebGLContextShareMode), String> {
// Creating a new GLContext may make the current bound context_id dirty.
// Clear it to ensure that make_current() is called in subsequent commands.
self.bound_context_id = None;
// First try to create a shared context for the best performance.
// Fallback to readback mode if the shared context creation fails.
let (ctx, share_mode) = self
.gl_factory
.new_shared_context(version, size, attributes)
.map(|r| (r, WebGLContextShareMode::SharedTexture))
.or_else(|err| {
warn!(
"Couldn't create shared GL context ({}), using slow readback context instead.",
err
);
let ctx = self.gl_factory.new_context(version, size, attributes)?;
Ok((ctx, WebGLContextShareMode::Readback))
})
.map_err(|msg: &str| msg.to_owned())?;
let id = WebGLContextId(
self.external_images
.lock()
.unwrap()
.next_id(WebrenderImageHandlerType::WebGL)
.0 as usize,
);
let (size, texture_id, limits) = ctx.get_info();
self.contexts.insert(
id,
GLContextData {
ctx,
state: Default::default(),
},
);
self.cached_context_info.insert(
id,
WebGLContextInfo {
texture_id,
size,
alpha: attributes.alpha,
image_key: None,
share_mode,
gl_sync: None,
render_state: ContextRenderState::Unlocked,
},
);
Ok((id, limits, share_mode))
}
/// Resizes a WebGLContext
fn resize_webgl_context(
&mut self,
context_id: WebGLContextId,
size: Size2D<u32>,
sender: WebGLSender<Result<(), String>>,
) {
let data = Self::make_current_if_needed_mut(
context_id,
&mut self.contexts,
&mut self.bound_context_id,
)
.expect("Missing WebGL context!");
match data.ctx.resize(size) {
Ok(old_draw_buffer) => {
let (real_size, texture_id, _) = data.ctx.get_info();
let info = self.cached_context_info.get_mut(&context_id).unwrap();
if let ContextRenderState::Locked(ref mut in_use) = info.render_state {
// If there's already an outdated draw buffer present, we can ignore
// the newly resized one since it's not in use by the renderer.
if in_use.is_none() {
// We're resizing the context while WR is actively rendering
// it, so we need to retain the GL resources until WR is
// finished with them.
*in_use = Some(old_draw_buffer);
}
}
// Update webgl texture size. Texture id may change too.
info.texture_id = texture_id;
info.size = real_size;
// Update WR image if needed. Resize image updates are only required for SharedTexture mode.
// Readback mode already updates the image every frame to send the raw pixels.
// See `handle_update_wr_image`.
match (info.image_key, info.share_mode) {
(Some(image_key), WebGLContextShareMode::SharedTexture) => {
Self::update_wr_external_image(
&self.webrender_api,
info.size,
info.alpha,
context_id,
image_key,
);
},
_ => {},
}
sender.send(Ok(())).unwrap();
},
Err(msg) => {
sender.send(Err(msg.into())).unwrap();
},
}
}
/// Removes a WebGLContext and releases attached resources.
fn remove_webgl_context(&mut self, context_id: WebGLContextId) {
// Release webrender image keys.
if let Some(info) = self.cached_context_info.remove(&context_id) {
let mut txn = webrender_api::Transaction::new();
if let Some(image_key) = info.image_key {
txn.delete_image(image_key);
}
self.webrender_api.update_resources(txn.resource_updates)
}
// We need to make the context current so its resources can be disposed of.
let _ =
Self::make_current_if_needed(context_id, &self.contexts, &mut self.bound_context_id);
// Release GL context.
self.contexts.remove(&context_id);
// Removing a GLContext may make the current bound context_id dirty.
self.bound_context_id = None;
}
/// Handles the creation/update of webrender_api::ImageKeys for a specific WebGLContext.
/// This method is invoked from a UpdateWebRenderImage message sent by the layout thread.
/// If SharedTexture is used the UpdateWebRenderImage message is sent only after a WebGLContext creation.
/// If Readback is used UpdateWebRenderImage message is sent always on each layout iteration in order to
/// submit the updated raw pixels.
fn handle_update_wr_image(
&mut self,
context_id: WebGLContextId,
sender: WebGLSender<webrender_api::ImageKey>,
) {
let info = self.cached_context_info.get_mut(&context_id).unwrap();
let webrender_api = &self.webrender_api;
let image_key = match info.share_mode {
WebGLContextShareMode::SharedTexture => {
let size = info.size;
let alpha = info.alpha;
// Reuse existing ImageKey or generate a new one.
// When using a shared texture ImageKeys are only generated after a WebGLContext creation.
*info.image_key.get_or_insert_with(|| {
Self::create_wr_external_image(webrender_api, size, alpha, context_id)
})
},
WebGLContextShareMode::Readback => {
let pixels = Self::raw_pixels(&self.contexts[&context_id].ctx, info.size);
match info.image_key.clone() {
Some(image_key) => {
// ImageKey was already created, but WR Images must
// be updated every frame in readback mode to send the new raw pixels.
Self::update_wr_readback_image(
webrender_api,
info.size,
info.alpha,
image_key,
pixels,
);
image_key
},
None => {
// Generate a new ImageKey for Readback mode.
let image_key = Self::create_wr_readback_image(
webrender_api,
info.size,
info.alpha,
pixels,
);
info.image_key = Some(image_key);
image_key
},
}
},
};
// Send the ImageKey to the Layout thread.
sender.send(image_key).unwrap();
}
fn handle_dom_to_texture(&mut self, command: DOMToTextureCommand) {
match command {
DOMToTextureCommand::Attach(context_id, texture_id, document_id, pipeline_id, size) => {
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");
// Initialize the texture that WR will use for frame outputs.
data.ctx.gl().tex_image_2d(
gl::TEXTURE_2D,
0,
gl::RGBA as gl::GLint,
size.width,
size.height,
0,
gl::RGBA,
gl::UNSIGNED_BYTE,
None,
);
self.dom_outputs.insert(
pipeline_id,
DOMToTextureData {
context_id,
texture_id,
document_id,
size,
},
);
let mut txn = webrender_api::Transaction::new();
txn.enable_frame_output(pipeline_id, true);
self.webrender_api.send_transaction(document_id, txn);
},
DOMToTextureCommand::Lock(pipeline_id, gl_sync, sender) => {
let result = self.handle_dom_to_texture_lock(pipeline_id, gl_sync);
// Send the texture id and size to WR.
sender.send(result).unwrap();
},
DOMToTextureCommand::Detach(texture_id) => {
if let Some((pipeline_id, document_id)) = self
.dom_outputs
.iter()
.find(|&(_, v)| v.texture_id == texture_id)
.map(|(k, v)| (*k, v.document_id))
{
let mut txn = webrender_api::Transaction::new();
txn.enable_frame_output(pipeline_id, false);
self.webrender_api.send_transaction(document_id, txn);
self.dom_outputs.remove(&pipeline_id);
}
},
}
}
pub(crate) fn handle_dom_to_texture_lock(
&mut self,
pipeline_id: webrender_api::PipelineId,
gl_sync: usize,
) -> Option<(u32, Size2D<i32>)> {
let contexts = &self.contexts;
let bound_context_id = &mut self.bound_context_id;
self.dom_outputs.get(&pipeline_id).and_then(|dom_data| {
let data =
Self::make_current_if_needed(dom_data.context_id, contexts, bound_context_id);
data.and_then(|data| {
// 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.
// glWaitSync doesn't block WebGL CPU thread.
data.ctx
.gl()
.wait_sync(gl_sync as gl::GLsync, 0, gl::TIMEOUT_IGNORED);
Some((dom_data.texture_id.get(), dom_data.size))
})
})
}
/// 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,
contexts: &'a FnvHashMap<WebGLContextId, GLContextData>,
bound_id: &mut Option<WebGLContextId>,
) -> Option<&'a GLContextData> {
let data = contexts.get(&context_id);
if let Some(data) = data {
if Some(context_id) != *bound_id {
data.ctx.make_current();
*bound_id = Some(context_id);
}
}
data
}
/// 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,
contexts: &'a mut FnvHashMap<WebGLContextId, GLContextData>,
bound_id: &mut Option<WebGLContextId>,
) -> Option<&'a mut GLContextData> {
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);
}
}
data
}
/// Creates a `webrender_api::ImageKey` that uses shared textures.
fn create_wr_external_image(
webrender_api: &webrender_api::RenderApi,
size: Size2D<i32>,
alpha: bool,
context_id: WebGLContextId,
) -> webrender_api::ImageKey {
let descriptor = Self::image_descriptor(size, alpha);
let data = Self::external_image_data(context_id);
let image_key = webrender_api.generate_image_key();
let mut txn = webrender_api::Transaction::new();
txn.add_image(image_key, descriptor, data, None);
webrender_api.update_resources(txn.resource_updates);
image_key
}
/// Updates a `webrender_api::ImageKey` that uses shared textures.
fn update_wr_external_image(
webrender_api: &webrender_api::RenderApi,
size: Size2D<i32>,
alpha: bool,
context_id: WebGLContextId,
image_key: webrender_api::ImageKey,
) {
let descriptor = Self::image_descriptor(size, alpha);
let data = Self::external_image_data(context_id);
let mut txn = webrender_api::Transaction::new();
txn.update_image(image_key, descriptor, data, &webrender_api::DirtyRect::All);
webrender_api.update_resources(txn.resource_updates);
}
/// Creates a `webrender_api::ImageKey` that uses raw pixels.
fn create_wr_readback_image(
webrender_api: &webrender_api::RenderApi,
size: Size2D<i32>,
alpha: bool,
data: Vec<u8>,
) -> webrender_api::ImageKey {
let descriptor = Self::image_descriptor(size, alpha);
let data = webrender_api::ImageData::new(data);
let image_key = webrender_api.generate_image_key();
let mut txn = webrender_api::Transaction::new();
txn.add_image(image_key, descriptor, data, None);
webrender_api.update_resources(txn.resource_updates);
image_key
}
/// Updates a `webrender_api::ImageKey` that uses raw pixels.
fn update_wr_readback_image(
webrender_api: &webrender_api::RenderApi,
size: Size2D<i32>,
alpha: bool,
image_key: webrender_api::ImageKey,
data: Vec<u8>,
) {
let descriptor = Self::image_descriptor(size, alpha);
let data = webrender_api::ImageData::new(data);
let mut txn = webrender_api::Transaction::new();
txn.update_image(image_key, descriptor, data, &webrender_api::DirtyRect::All);
webrender_api.update_resources(txn.resource_updates);
}
/// Helper function to create a `webrender_api::ImageDescriptor`.
fn image_descriptor(size: Size2D<i32>, alpha: bool) -> webrender_api::ImageDescriptor {
webrender_api::ImageDescriptor {
size: webrender_api::units::DeviceIntSize::new(size.width, size.height),
stride: None,
format: webrender_api::ImageFormat::BGRA8,
offset: 0,
is_opaque: !alpha,
allow_mipmaps: false,
}
}
/// Helper function to create a `webrender_api::ImageData::External` instance.
fn external_image_data(context_id: WebGLContextId) -> webrender_api::ImageData {
let data = webrender_api::ExternalImageData {
id: webrender_api::ExternalImageId(context_id.0 as u64),
channel_index: 0,
image_type: webrender_api::ExternalImageType::TextureHandle(
webrender_api::TextureTarget::Default,
),
};
webrender_api::ImageData::External(data)
}
/// Helper function to fetch the raw pixels used in readback mode.
fn raw_pixels(context: &GLContextWrapper, size: Size2D<i32>) -> Vec<u8> {
let width = size.width as usize;
let height = size.height as usize;
let mut pixels = context.gl().read_pixels(
0,
0,
size.width as gl::GLsizei,
size.height as gl::GLsizei,
gl::RGBA,
gl::UNSIGNED_BYTE,
);
// flip image vertically (texture is upside down)
let orig_pixels = pixels.clone();
let stride = width * 4;
for y in 0..height {
let dst_start = y * stride;
let src_start = (height - y - 1) * stride;
let src_slice = &orig_pixels[src_start..src_start + stride];
(&mut pixels[dst_start..dst_start + stride]).clone_from_slice(&src_slice[..stride]);
}
pixels::rgba8_byte_swap_colors_inplace(&mut pixels);
pixels
}
/// Gets the GLSL Version supported by a GLContext.
fn get_glsl_version(context: &GLContextWrapper) -> WebGLSLVersion {
let version = context.gl().get_string(gl::SHADING_LANGUAGE_VERSION);
// Fomat used by SHADING_LANGUAGE_VERSION query : major.minor[.release] [vendor info]
let mut values = version.split(&['.', ' '][..]);
let major = values
.next()
.and_then(|v| v.parse::<u32>().ok())
.unwrap_or(1);
let minor = values
.next()
.and_then(|v| v.parse::<u32>().ok())
.unwrap_or(20);
WebGLSLVersion { major, minor }
}
}
impl Drop for WebGLThread {
fn drop(&mut self) {
// Call remove_context functions in order to correctly delete WebRender image keys.
let context_ids: Vec<WebGLContextId> = self.contexts.keys().map(|id| *id).collect();
for id in context_ids {
self.remove_webgl_context(id);
}
}
}
enum ContextRenderState {
/// The context is not being actively rendered.
Unlocked,
/// The context is actively being rendered. If a DrawBuffer value is present,
/// it is outdated but in use as long as the context is locked.
Locked(Option<DrawBuffer>),
}
/// Helper struct to store cached WebGLContext information.
struct WebGLContextInfo {
/// Render to texture identifier used by the WebGLContext.
texture_id: u32,
/// Size of the WebGLContext.
size: Size2D<i32>,
/// True if the WebGLContext uses an alpha channel.
alpha: bool,
/// Currently used WebRender image key.
image_key: Option<webrender_api::ImageKey>,
/// The sharing mode used to send the image to WebRender.
share_mode: WebGLContextShareMode,
/// GLSync Object used for a correct synchronization with Webrender external image callbacks.
gl_sync: Option<gl::GLsync>,
/// The status of this context with respect to external consumers.
render_state: ContextRenderState,
}
/// Data about the linked DOM<->WebGLTexture elements.
struct DOMToTextureData {
context_id: WebGLContextId,
texture_id: WebGLTextureId,
document_id: webrender_api::DocumentId,
size: Size2D<i32>,
}
/// WebGL Commands Implementation
pub struct WebGLImpl;
impl WebGLImpl {
#[allow(unsafe_code)]
pub fn apply<Native: NativeGLContextMethods>(
ctx: &GLContext<Native>,
state: &mut GLState,
command: WebGLCommand,
_backtrace: WebGLCommandBacktrace,
) {
match command {
WebGLCommand::GetContextAttributes(ref sender) => sender
.send(map_attrs_to_script_attrs(*ctx.borrow_attributes()))
.unwrap(),
WebGLCommand::ActiveTexture(target) => ctx.gl().active_texture(target),
WebGLCommand::AttachShader(program_id, shader_id) => {
ctx.gl().attach_shader(program_id.get(), shader_id.get())
},
WebGLCommand::DetachShader(program_id, shader_id) => {
ctx.gl().detach_shader(program_id.get(), shader_id.get())
},
WebGLCommand::BindAttribLocation(program_id, index, ref name) => ctx
.gl()
.bind_attrib_location(program_id.get(), index, &to_name_in_compiled_shader(name)),
WebGLCommand::BlendColor(r, g, b, a) => ctx.gl().blend_color(r, g, b, a),
WebGLCommand::BlendEquation(mode) => ctx.gl().blend_equation(mode),
WebGLCommand::BlendEquationSeparate(mode_rgb, mode_alpha) => {
ctx.gl().blend_equation_separate(mode_rgb, mode_alpha)
},
WebGLCommand::BlendFunc(src, dest) => ctx.gl().blend_func(src, dest),
WebGLCommand::BlendFuncSeparate(src_rgb, dest_rgb, src_alpha, dest_alpha) => ctx
.gl()
.blend_func_separate(src_rgb, dest_rgb, src_alpha, dest_alpha),
WebGLCommand::BufferData(buffer_type, ref receiver, usage) => {
gl::buffer_data(ctx.gl(), buffer_type, &receiver.recv().unwrap(), usage)
},
WebGLCommand::BufferSubData(buffer_type, offset, ref receiver) => {
gl::buffer_sub_data(ctx.gl(), buffer_type, offset, &receiver.recv().unwrap())
},
WebGLCommand::Clear(mask) => ctx.gl().clear(mask),
WebGLCommand::ClearColor(r, g, b, a) => {
state.clear_color = (r, g, b, a);
ctx.gl().clear_color(r, g, b, a);
},
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::ColorMask(r, g, b, a) => ctx.gl().color_mask(r, g, b, a),
WebGLCommand::CopyTexImage2D(
target,
level,
internal_format,
x,
y,
width,
height,
border,
) => ctx.gl().copy_tex_image_2d(
target,
level,
internal_format,
x,
y,
width,
height,
border,
),
WebGLCommand::CopyTexSubImage2D(
target,
level,
xoffset,
yoffset,
x,
y,
width,
height,
) => ctx
.gl()
.copy_tex_sub_image_2d(target, level, xoffset, yoffset, x, y, width, height),
WebGLCommand::CullFace(mode) => ctx.gl().cull_face(mode),
WebGLCommand::DepthFunc(func) => ctx.gl().depth_func(func),
WebGLCommand::DepthMask(flag) => {
state.depth_write_mask = flag;
ctx.gl().depth_mask(flag);
},
WebGLCommand::DepthRange(near, far) => ctx
.gl()
.depth_range(near.max(0.).min(1.) as f64, far.max(0.).min(1.) as f64),
WebGLCommand::Disable(cap) => {
if cap == gl::SCISSOR_TEST {
state.scissor_test_enabled = false;
}
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) => {
let attach = |attachment| {
ctx.gl().framebuffer_renderbuffer(
target,
attachment,
renderbuffertarget,
rb.map_or(0, WebGLRenderbufferId::get),
)
};
if attachment == gl::DEPTH_STENCIL_ATTACHMENT {
attach(gl::DEPTH_ATTACHMENT);
attach(gl::STENCIL_ATTACHMENT);
} else {
attach(attachment);
}
},
WebGLCommand::FramebufferTexture2D(target, attachment, textarget, texture, level) => {
let attach = |attachment| {