/
lib.rs
1320 lines (1207 loc) · 50.8 KB
/
lib.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
#![deny(clippy::unwrap_used)]
// Remove this when we start using `Rc` when compiling for wasm
#![allow(clippy::arc_with_non_send_sync)]
use ruffle_render::backend::{
BitmapCacheEntry, Context3D, Context3DProfile, PixelBenderOutput, PixelBenderTarget,
RenderBackend, ShapeHandle, ShapeHandleImpl, ViewportDimensions,
};
use ruffle_render::bitmap::{
Bitmap, BitmapHandle, BitmapHandleImpl, BitmapSource, PixelRegion, PixelSnapping, RgbaBufRead,
SyncHandle,
};
use ruffle_render::commands::{CommandHandler, CommandList, RenderBlendMode};
use ruffle_render::error::Error;
use ruffle_render::matrix::Matrix;
use ruffle_render::quality::StageQuality;
use ruffle_render::shape_utils::{DistilledShape, DrawCommand, LineScaleMode, LineScales};
use ruffle_render::transform::Transform;
use ruffle_web_common::{JsError, JsResult};
use std::borrow::Cow;
use std::sync::Arc;
use swf::{BlendMode, Color, ColorTransform, Point, Twips};
use wasm_bindgen::{Clamped, JsCast, JsValue};
use web_sys::{
CanvasGradient, CanvasPattern, CanvasRenderingContext2d, CanvasWindingRule, DomMatrix, Element,
HtmlCanvasElement, ImageData, Path2d,
};
const GRADIENT_TRANSFORM_THRESHOLD: f32 = 0.0001;
pub struct WebCanvasRenderBackend {
canvas: HtmlCanvasElement,
context: CanvasRenderingContext2d,
color_matrix: Element,
viewport_width: u32,
viewport_height: u32,
rect: Path2d,
mask_state: MaskState,
blend_modes: Vec<RenderBlendMode>,
// This is currently unused - we just store it to report
// in `get_viewport_dimensions`
viewport_scale_factor: f64,
}
/// Canvas-drawable shape data extracted from an SWF file.
#[derive(Debug)]
struct ShapeData(Vec<CanvasDrawCommand>);
impl ShapeHandleImpl for ShapeData {}
fn as_shape_data(handle: &ShapeHandle) -> &ShapeData {
<dyn ShapeHandleImpl>::downcast_ref(&*handle.0)
.expect("Shape handle must be a Canvas ShapeData")
}
#[derive(Debug)]
struct CanvasColor(Color, String);
impl From<Color> for CanvasColor {
fn from(color: Color) -> Self {
Self(
color,
format!(
"rgba({},{},{},{})",
color.r,
color.g,
color.b,
f32::from(color.a) / 255.0
),
)
}
}
impl CanvasColor {
/// Apply a color transformation to this color.
fn color_transform(&self, cxform: &ColorTransform) -> Self {
(cxform * self.0).into()
}
}
/// An individual command to be drawn to the canvas.
#[derive(Debug)]
enum CanvasDrawCommand {
/// A command to draw a path stroke with a given style.
Stroke {
path: Path2d,
line_width: f64,
stroke_style: CanvasStrokeStyle,
line_cap: String,
line_join: String,
miter_limit: f64,
scale_mode: LineScaleMode,
},
/// A command to fill a path with a given style.
Fill {
path: Path2d,
fill_style: CanvasFillStyle,
},
}
/// Fill style for a canvas path.
#[derive(Debug)]
enum CanvasFillStyle {
Color(CanvasColor),
Gradient(Gradient),
Bitmap(CanvasBitmap),
}
#[derive(Debug)]
struct Gradient {
gradient: CanvasGradient,
transform: Option<GradientTransform>,
}
/// A "complex" gradient transform, such as elliptical or skewed gradients.
///
/// Canvas does not provide an API for arbitrary gradient transforms, so we cheat by applying the
/// inverse of the gradient transform to the path, and then drawing the path with the gradient transform.
/// This results in an non-transformed shape with a transformed gradient.
#[derive(Debug)]
struct GradientTransform {
matrix: [f64; 6],
inverse_matrix: DomMatrix,
}
/// Stroke style for a canvas path.
///
/// Gradients are handled differently for strokes vs. fills.
#[derive(Debug)]
enum CanvasStrokeStyle {
Color(CanvasColor),
Gradient(swf::Gradient, Option<f64>),
Bitmap(CanvasBitmap),
}
#[derive(Debug)]
struct CanvasBitmap {
pattern: CanvasPattern,
matrix: Matrix,
smoothed: bool,
}
#[allow(dead_code)]
#[derive(Debug)]
struct BitmapData {
image_data: ImageData,
canvas: HtmlCanvasElement,
context: CanvasRenderingContext2d,
}
impl BitmapHandleImpl for BitmapData {}
fn as_bitmap_data(handle: &BitmapHandle) -> &BitmapData {
<dyn BitmapHandleImpl>::downcast_ref(&*handle.0)
.expect("Bitmap handle must be a Canvas BitmapData")
}
impl BitmapData {
/// Puts the image data into a newly created <canvas>, and caches it.
fn with_bitmap(bitmap: Bitmap) -> Result<Self, JsValue> {
let bitmap = bitmap.to_rgba();
let image_data =
ImageData::new_with_u8_clamped_array(Clamped(bitmap.data()), bitmap.width())
.into_js_result()?;
Self::with_image_data(image_data)
}
fn empty(width: u32, height: u32) -> Result<Self, JsValue> {
let image_data = ImageData::new_with_sw(width, height).into_js_result()?;
Self::with_image_data(image_data)
}
fn with_image_data(image_data: ImageData) -> Result<Self, JsValue> {
let window = web_sys::window().expect("window()");
let document = window.document().expect("document()");
let canvas: HtmlCanvasElement = document
.create_element("canvas")
.into_js_result()?
.unchecked_into();
canvas.set_width(image_data.width());
canvas.set_height(image_data.height());
let context: CanvasRenderingContext2d = canvas
.get_context("2d")?
.expect("get_context method must return a value")
.dyn_into()
.expect("get_context method returned something other than a CanvasRenderingContext2d");
context
.put_image_data(&image_data, 0.0, 0.0)
.into_js_result()?;
Ok(BitmapData {
image_data,
canvas,
context,
})
}
fn update_pixels(&self, bitmap: Bitmap) -> Result<(), JsValue> {
let bitmap = bitmap.to_rgba();
let image_data =
ImageData::new_with_u8_clamped_array(Clamped(bitmap.data()), bitmap.width())
.into_js_result()?;
self.canvas.set_width(bitmap.width());
self.canvas.set_height(bitmap.height());
self.context
.put_image_data(&image_data, 0.0, 0.0)
.into_js_result()?;
Ok(())
}
}
impl WebCanvasRenderBackend {
pub fn new(
canvas: &HtmlCanvasElement,
is_transparent: bool,
) -> Result<Self, Box<dyn std::error::Error>> {
// Request the CanvasRenderingContext2d.
// Disable alpha for possible speedup.
// TODO: Allow user to enable transparent background (transparent wmode in legacy Flash).
let context_options = js_sys::Object::new();
let _ = js_sys::Reflect::set(
&context_options,
&"alpha".into(),
&JsValue::from_bool(is_transparent),
);
let context: CanvasRenderingContext2d = canvas
.get_context_with_context_options("2d", &context_options)
.into_js_result()?
.ok_or("Could not create context")?
.dyn_into()
.map_err(|_| "Expected CanvasRenderingContext2d")?;
let window = web_sys::window().expect("window()");
let document = window.document().expect("document()");
// Create a color matrix filter to handle Flash color effects.
// We may have a previous instance if this canvas was re-used, so remove it.
if let Ok(Some(element)) = canvas.query_selector("#_svgfilter") {
element.remove();
}
let svg = document
.create_element_ns(Some("http://www.w3.org/2000/svg"), "svg")
.map_err(|_| "Couldn't make SVG")?;
svg.set_id("_svgfilter");
svg.set_attribute("width", "0")
.map_err(|_| "Couldn't make SVG")?;
svg.set_attribute("height", "0")
.map_err(|_| "Couldn't make SVG")?;
svg.set_attribute_ns(
Some("http://www.w3.org/2000/xmlns/"),
"xmlns:xlink",
"http://www.w3.org/1999/xlink",
)
.map_err(|_| "Couldn't make SVG")?;
let filter = document
.create_element_ns(Some("http://www.w3.org/2000/svg"), "filter")
.map_err(|_| "Couldn't make SVG filter")?;
filter
.set_attribute("id", "_cm")
.map_err(|_| "Couldn't make SVG filter")?;
filter
.set_attribute("color-interpolation-filters", "sRGB")
.map_err(|_| "Couldn't make SVG filter")?;
let color_matrix = document
.create_element_ns(Some("http://www.w3.org/2000/svg"), "feColorMatrix")
.map_err(|_| "Couldn't make SVG feColorMatrix element")?;
color_matrix
.set_attribute("type", "matrix")
.map_err(|_| "Couldn't make SVG feColorMatrix element")?;
color_matrix
.set_attribute("values", "1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0")
.map_err(|_| "Couldn't make SVG feColorMatrix element")?;
filter
.append_child(&color_matrix)
.map_err(|_| "append_child failed")?;
svg.append_child(&filter)
.map_err(|_| "append_child failed")?;
canvas
.append_child(&svg)
.map_err(|_| "append_child failed")?;
let rect = Path2d::new().into_js_result()?;
rect.rect(0.0, 0.0, 1.0, 1.0);
let renderer = Self {
canvas: canvas.clone(),
color_matrix,
context,
viewport_width: 0,
viewport_height: 0,
viewport_scale_factor: 1.0,
rect,
mask_state: MaskState::DrawContent,
blend_modes: vec![RenderBlendMode::Builtin(BlendMode::Normal)],
};
Ok(renderer)
}
#[allow(clippy::float_cmp)]
#[inline]
fn set_transform(&mut self, matrix: &Matrix) {
self.context
.set_transform(
matrix.a.into(),
matrix.b.into(),
matrix.c.into(),
matrix.d.into(),
matrix.tx.to_pixels(),
matrix.ty.to_pixels(),
)
.warn_on_error();
}
#[allow(clippy::float_cmp)]
#[inline]
fn set_color_filter(&self, transform: &Transform) {
let color_transform = &transform.color_transform;
if color_transform.r_multiply.is_one()
&& color_transform.g_multiply.is_one()
&& color_transform.b_multiply.is_one()
&& color_transform.r_add == 0
&& color_transform.g_add == 0
&& color_transform.b_add == 0
&& color_transform.a_add == 0
{
// Values outside the range of 0 and 1 are ignored in canvas, unlike Flash that clamps them.
self.context
.set_global_alpha(f64::from(color_transform.a_multiply).clamp(0.0, 1.0));
} else {
let mult = color_transform.mult_rgba_normalized();
let add = color_transform.add_rgba_normalized();
let matrix_str = format!(
"{} 0 0 0 {} 0 {} 0 0 {} 0 0 {} 0 {} 0 0 0 {} {}",
mult[0], add[0], mult[1], add[1], mult[2], add[2], mult[3], add[3]
);
self.color_matrix
.set_attribute("values", &matrix_str)
.warn_on_error();
self.context.set_filter("url('#_cm')");
}
}
#[inline]
fn clear_color_filter(&self) {
self.context.set_filter("none");
self.context.set_global_alpha(1.0);
}
fn apply_blend_mode(&mut self, blend: RenderBlendMode) {
// TODO: Objects with a blend mode need to be rendered to an intermediate buffer first,
// but for now we render each child directly to the canvas. This should look reasonable for most
// common cases.
// While canvas has built in support for most of the blend modes, a few aren't supported.
let mode = match blend {
RenderBlendMode::Builtin(BlendMode::Normal) => "source-over",
RenderBlendMode::Builtin(BlendMode::Layer) => "source-over", // Requires intermediate buffer.
RenderBlendMode::Builtin(BlendMode::Multiply) => "multiply",
RenderBlendMode::Builtin(BlendMode::Screen) => "screen",
RenderBlendMode::Builtin(BlendMode::Lighten) => "lighten",
RenderBlendMode::Builtin(BlendMode::Darken) => "darken",
RenderBlendMode::Builtin(BlendMode::Difference) => "difference",
RenderBlendMode::Builtin(BlendMode::Add) => "lighter",
RenderBlendMode::Builtin(BlendMode::Subtract) => "difference", // Not exposed by canvas, rendered as difference.
RenderBlendMode::Builtin(BlendMode::Invert) => "source-over", // Not exposed by canvas.
RenderBlendMode::Builtin(BlendMode::Alpha) => "source-over", // Requires intermediate buffer.
RenderBlendMode::Builtin(BlendMode::Erase) => "source-over", // Requires intermediate buffer.
RenderBlendMode::Builtin(BlendMode::Overlay) => "overlay",
RenderBlendMode::Builtin(BlendMode::HardLight) => "hard-light",
RenderBlendMode::Shader(_) => "source-over", // Canvas does not support shaders
};
self.context
.set_global_composite_operation(mode)
.expect("Failed to update BlendMode");
}
fn begin_frame(&mut self, clear: Color) {
// Reset canvas transform in case it was left in a dirty state.
self.context.reset_transform().warn_on_error();
let width = self.canvas.width();
let height = self.canvas.height();
if clear.a > 0 {
let color = format!("rgba({}, {}, {}, {})", clear.r, clear.g, clear.b, clear.a);
self.context.set_fill_style(&color.into());
let _ = self.context.set_global_composite_operation("copy");
self.context
.fill_rect(0.0, 0.0, width.into(), height.into());
let _ = self.context.set_global_composite_operation("source-over");
} else {
self.context
.clear_rect(0.0, 0.0, width.into(), height.into());
}
self.mask_state = MaskState::DrawContent;
}
fn push_blend_mode(&mut self, blend: RenderBlendMode) {
if !same_blend_mode(self.blend_modes.last(), &blend) {
self.apply_blend_mode(blend.clone());
}
self.blend_modes.push(blend);
}
fn pop_blend_mode(&mut self) {
let old = self.blend_modes.pop();
// We should never pop our base 'BlendMode::Normal'
let current = self
.blend_modes
.last()
.unwrap_or(&RenderBlendMode::Builtin(BlendMode::Normal));
if !same_blend_mode(old.as_ref(), current) {
self.apply_blend_mode(current.clone());
}
}
}
impl RenderBackend for WebCanvasRenderBackend {
fn set_viewport_dimensions(&mut self, dimensions: ViewportDimensions) {
self.viewport_width = dimensions.width;
self.viewport_height = dimensions.height;
self.viewport_scale_factor = dimensions.scale_factor;
}
fn viewport_dimensions(&self) -> ViewportDimensions {
ViewportDimensions {
width: self.viewport_width,
height: self.viewport_height,
scale_factor: self.viewport_scale_factor,
}
}
fn register_shape(
&mut self,
shape: DistilledShape,
bitmap_source: &dyn BitmapSource,
) -> ShapeHandle {
let data = swf_shape_to_canvas_commands(&shape, bitmap_source, self);
ShapeHandle(Arc::new(ShapeData(data)))
}
fn render_offscreen(
&mut self,
_handle: BitmapHandle,
_commands: CommandList,
_quality: StageQuality,
_bounds: PixelRegion,
) -> Option<Box<dyn SyncHandle>> {
None
}
fn submit_frame(
&mut self,
clear: Color,
commands: CommandList,
cache_entries: Vec<BitmapCacheEntry>,
) {
if !cache_entries.is_empty() {
panic!("Bitmap caching is unavailable on the canvas backend");
}
self.begin_frame(clear);
commands.execute(self);
}
fn register_bitmap(&mut self, bitmap: Bitmap) -> Result<BitmapHandle, Error> {
let bitmap_data = BitmapData::with_bitmap(bitmap).map_err(Error::JavascriptError)?;
Ok(BitmapHandle(Arc::new(bitmap_data)))
}
fn update_texture(
&mut self,
handle: &BitmapHandle,
bitmap: Bitmap,
_region: PixelRegion,
) -> Result<(), Error> {
let data = as_bitmap_data(handle);
data.update_pixels(bitmap).map_err(Error::JavascriptError)?;
Ok(())
}
fn create_context3d(
&mut self,
_profile: Context3DProfile,
) -> Result<Box<dyn Context3D>, Error> {
Err(Error::Unimplemented("createContext3D".into()))
}
fn context3d_present(&mut self, _context: &mut dyn Context3D) -> Result<(), Error> {
Err(Error::Unimplemented("Context3D.present".into()))
}
fn debug_info(&self) -> Cow<'static, str> {
Cow::Borrowed("Renderer: Canvas")
}
fn name(&self) -> &'static str {
"canvas"
}
fn set_quality(&mut self, _quality: StageQuality) {}
fn compile_pixelbender_shader(
&mut self,
_shader: ruffle_render::pixel_bender::PixelBenderShader,
) -> Result<ruffle_render::pixel_bender::PixelBenderShaderHandle, Error> {
Err(Error::Unimplemented("compile_pixelbender_shader".into()))
}
fn run_pixelbender_shader(
&mut self,
_handle: ruffle_render::pixel_bender::PixelBenderShaderHandle,
_arguments: &[ruffle_render::pixel_bender::PixelBenderShaderArgument],
_target: &PixelBenderTarget,
) -> Result<PixelBenderOutput, Error> {
Err(Error::Unimplemented("run_pixelbender_shader".into()))
}
fn resolve_sync_handle(
&mut self,
_handle: Box<dyn SyncHandle>,
_with_rgba: RgbaBufRead,
) -> Result<(), Error> {
Err(Error::Unimplemented("Sync handle resolution".into()))
}
fn create_empty_texture(&mut self, width: u32, height: u32) -> Result<BitmapHandle, Error> {
let bitmap_data = BitmapData::empty(width, height).map_err(Error::JavascriptError)?;
Ok(BitmapHandle(Arc::new(bitmap_data)))
}
}
impl CommandHandler for WebCanvasRenderBackend {
fn render_bitmap(
&mut self,
bitmap: BitmapHandle,
transform: Transform,
smoothing: bool,
_pixel_snapping: PixelSnapping,
) {
if self.mask_state == MaskState::ClearMask {
return;
}
self.context.set_image_smoothing_enabled(smoothing);
self.set_transform(&transform.matrix);
self.set_color_filter(&transform);
let bitmap = as_bitmap_data(&bitmap);
let _ = self
.context
.draw_image_with_html_canvas_element(&bitmap.canvas, 0.0, 0.0);
self.clear_color_filter();
}
fn render_stage3d(&mut self, _bitmap: BitmapHandle, _transform: Transform) {
panic!("Stage3D should not have been created on canvas backend")
}
fn render_shape(&mut self, shape: ShapeHandle, transform: Transform) {
let shape = as_shape_data(&shape);
match &self.mask_state {
MaskState::DrawContent => {
let mut line_scale = LineScales::new(&transform.matrix);
let dom_matrix = transform.matrix.to_dom_matrix();
let mut transform_dirty = true;
for command in shape.0.iter() {
match command {
CanvasDrawCommand::Fill { path, fill_style } => {
if transform_dirty {
let _ = self.context.set_transform(
transform.matrix.a.into(),
transform.matrix.b.into(),
transform.matrix.c.into(),
transform.matrix.d.into(),
transform.matrix.tx.to_pixels(),
transform.matrix.ty.to_pixels(),
);
transform_dirty = false;
}
match fill_style {
CanvasFillStyle::Color(color) => {
let color = color.color_transform(&transform.color_transform);
self.context.set_fill_style(&color.1.into());
self.context.fill_with_path_2d_and_winding(
path,
CanvasWindingRule::Evenodd,
);
}
CanvasFillStyle::Gradient(gradient) => {
self.set_color_filter(&transform);
self.context.set_fill_style(&gradient.gradient);
if let Some(gradient_transform) = &gradient.transform {
// Canvas has no easy way to draw gradients with an arbitrary transform,
// but we can fake it by pushing the gradient's transform to the canvas,
// then transforming the path itself by the inverse.
let matrix = &gradient_transform.matrix;
let _ = self.context.transform(
matrix[0], matrix[1], matrix[2], matrix[3], matrix[4],
matrix[5],
);
transform_dirty = true;
let untransformed_path =
Path2d::new().expect("Path2d constructor must succeed");
untransformed_path.add_path_with_transformation(
path,
gradient_transform.inverse_matrix.unchecked_ref(),
);
self.context.fill_with_path_2d_and_winding(
&untransformed_path,
CanvasWindingRule::Evenodd,
);
} else {
self.context.fill_with_path_2d_and_winding(
path,
CanvasWindingRule::Evenodd,
);
}
self.clear_color_filter();
}
CanvasFillStyle::Bitmap(bitmap) => {
self.set_color_filter(&transform);
self.context.set_image_smoothing_enabled(bitmap.smoothed);
self.context.set_fill_style(&bitmap.pattern);
self.context.fill_with_path_2d_and_winding(
path,
CanvasWindingRule::Evenodd,
);
self.clear_color_filter();
}
}
}
CanvasDrawCommand::Stroke {
path,
line_width,
stroke_style,
line_cap,
line_join,
miter_limit,
scale_mode,
} => {
// Canvas.setTransform ends up transforming the stroke geometry itself (including joins/endcaps).
// Instead, reset the canvas transform, and apply the transform to the stroke path directly so
// that the geometry remains untransformed.
let _ = self.context.reset_transform();
transform_dirty = true;
let transformed_path =
Path2d::new().expect("Path2d constructor must succeed");
transformed_path
.add_path_with_transformation(path, dom_matrix.unchecked_ref());
// Set stroke parameters.
self.context.set_line_cap(line_cap);
self.context.set_line_join(line_join);
self.context.set_miter_limit(*miter_limit);
let line_width =
line_scale.transform_width(*line_width as f32, *scale_mode);
self.context.set_line_width(line_width.into());
match stroke_style {
CanvasStrokeStyle::Color(color) => {
let color = color.color_transform(&transform.color_transform);
self.context.set_stroke_style(&color.1.into());
self.context.stroke_with_path(&transformed_path);
}
CanvasStrokeStyle::Gradient(gradient, focal_point) => {
// This is the hard case -- the Canvas API provides no good way to transform gradients,
// and the inverse-transform trick used above for gradient fills can't be used here
// because it will distort the stroke geometry.
// Another possibility is to avoid the Path2D API, instead drawing using explicit path
// commands (`context.lineTo`), then push the gradient transform, and finally stroke
// the path using `stroke()`. But this will be tons of JS calls if there are many strokes.
// So let's settle for allocating a new canvas gradient that is a best-effort match of the
// the desired transform. This will not match Flash exactly, but should be relatively rare.
let mut gradient = gradient.clone();
gradient.matrix =
(transform.matrix * Matrix::from(gradient.matrix)).into();
let gradient = match focal_point {
Some(focal_point) => create_radial_gradient(
&self.context,
&gradient,
*focal_point,
false,
),
None => {
create_linear_gradient(&self.context, &gradient, false)
}
};
if let Ok(gradient) = gradient {
self.set_color_filter(&transform);
self.context.set_stroke_style(&gradient.gradient);
self.context.stroke_with_path(&transformed_path);
self.clear_color_filter();
}
}
CanvasStrokeStyle::Bitmap(bitmap) => {
// Set the CanvasPattern's matrix to the concatenated transform.
let bitmap_matrix = transform.matrix
* bitmap.matrix
* Matrix::scale(0.05, 0.05);
bitmap.pattern.set_transform(
bitmap_matrix.to_dom_matrix().unchecked_ref(),
);
self.set_color_filter(&transform);
self.context.set_image_smoothing_enabled(bitmap.smoothed);
self.context.set_stroke_style(&bitmap.pattern);
self.context.stroke_with_path(&transformed_path);
self.clear_color_filter();
}
};
}
}
}
}
// Add the shape path to the mask path.
// Strokes are ignored.
MaskState::DrawMask(mask_path) => {
for command in shape.0.iter() {
if let CanvasDrawCommand::Fill { path, .. } = command {
mask_path.add_path_with_transformation(
path,
transform.matrix.to_dom_matrix().unchecked_ref(),
);
}
}
}
// Canvas backend doesn't have to do anything to clear masks.
MaskState::ClearMask => (),
}
}
fn draw_rect(&mut self, color: Color, matrix: Matrix) {
match &self.mask_state {
MaskState::DrawContent => {
self.set_transform(&matrix);
self.clear_color_filter();
self.context.set_fill_style(
&format!(
"rgba({},{},{},{})",
color.r,
color.g,
color.b,
f32::from(color.a) / 255.0
)
.into(),
);
self.context.fill_rect(0.0, 0.0, 1.0, 1.0);
}
MaskState::DrawMask(mask_path) => {
mask_path.add_path_with_transformation(
&self.rect,
matrix.to_dom_matrix().unchecked_ref(),
);
}
MaskState::ClearMask => (),
}
}
fn push_mask(&mut self) {
if self.mask_state == MaskState::DrawContent {
// Save the current mask layer so that it can be restored when the mask is popped.
self.context.save();
self.mask_state =
MaskState::DrawMask(Path2d::new().expect("Path2d constructor must succeed"));
}
}
fn activate_mask(&mut self) {
if let MaskState::DrawMask(mask_path) = &self.mask_state {
self.context.reset_transform().warn_on_error();
// Apply the clipping path to the canvas for future draws.
// TODO: Canvas almost, but not completely, provides a clean way to implement Flash masks.
// Subsequent calls to `CanvasRenderingContext2d.clip` support nested masks (intersection),
// but Flash art is sometimes in layers where one path is filled on top of another (union).
// We use non-zero winding here to handle this case, but this will be incorrect in the
// other cases such as self-intersecting shapes. The Flash IDE actively avoids exporting
// shapes and masks for both of these cases, so it shouldn't be common.
// Most likely it would happen with dynamiuc masks via drawing API or similar.
// A possible improvement is to choose the winding rule based on whether the shape has
// layers or not (via a flag in DistilledShape?)
self.context
.clip_with_path_2d_and_winding(mask_path, CanvasWindingRule::Nonzero);
self.mask_state = MaskState::DrawContent;
}
}
fn deactivate_mask(&mut self) {
if self.mask_state == MaskState::DrawContent {
self.mask_state = MaskState::ClearMask;
}
}
fn pop_mask(&mut self) {
if self.mask_state == MaskState::ClearMask {
// Pop the previous clipping state.
self.context.restore();
self.mask_state = MaskState::DrawContent;
}
}
fn blend(&mut self, commands: CommandList, blend: RenderBlendMode) {
self.push_blend_mode(blend);
commands.execute(self);
self.pop_blend_mode();
}
}
/// Convert a series of `DrawCommands` to a `Path2d` shape.
///
/// The path can be optionally closed by setting `is_closed` to `true`.
///
/// The resulting path is in the shape's own coordinate space and needs to be
/// transformed to fit within the shape's bounds.
fn draw_commands_to_path2d(commands: &[DrawCommand], is_closed: bool) -> Path2d {
let path = Path2d::new().expect("Path2d constructor must succeed");
for command in commands {
match command {
DrawCommand::MoveTo(move_to) => {
path.move_to(move_to.x.get().into(), move_to.y.get().into())
}
DrawCommand::LineTo(line_to) => {
path.line_to(line_to.x.get().into(), line_to.y.get().into())
}
DrawCommand::QuadraticCurveTo { control, anchor } => path.quadratic_curve_to(
control.x.get().into(),
control.y.get().into(),
anchor.x.get().into(),
anchor.y.get().into(),
),
DrawCommand::CubicCurveTo {
control_a,
control_b,
anchor,
} => path.bezier_curve_to(
control_a.x.get().into(),
control_a.y.get().into(),
control_b.x.get().into(),
control_b.y.get().into(),
anchor.x.get().into(),
anchor.y.get().into(),
),
};
}
if is_closed {
path.close_path();
}
path
}
fn swf_shape_to_canvas_commands(
shape: &DistilledShape,
bitmap_source: &dyn BitmapSource,
backend: &mut WebCanvasRenderBackend,
) -> Vec<CanvasDrawCommand> {
use ruffle_render::shape_utils::DrawPath;
use swf::{FillStyle, LineCapStyle, LineJoinStyle};
// Some browsers will vomit if you try to load/draw an image with 0 width/height.
// TODO(Herschel): Might be better to just return None in this case and skip
// rendering altogether.
let mut canvas_data = vec![];
let bounds_viewbox_matrix = DomMatrix::new().expect("DomMatrix constructor must succeed");
bounds_viewbox_matrix.set_a(1.0 / 20.0);
bounds_viewbox_matrix.set_d(1.0 / 20.0);
for path in &shape.paths {
match path {
DrawPath::Fill {
commands, style, ..
} => {
let canvas_path = Path2d::new().expect("Path2d constructor must succeed");
canvas_path.add_path_with_transformation(
&draw_commands_to_path2d(commands, false),
bounds_viewbox_matrix.unchecked_ref(),
);
let fill_style = match style {
FillStyle::Color(color) => CanvasFillStyle::Color((*color).into()),
FillStyle::LinearGradient(gradient) => CanvasFillStyle::Gradient(
create_linear_gradient(&backend.context, gradient, true)
.expect("Couldn't create linear gradient"),
),
FillStyle::RadialGradient(gradient) => CanvasFillStyle::Gradient(
create_radial_gradient(&backend.context, gradient, 0.0, true)
.expect("Couldn't create radial gradient"),
),
FillStyle::FocalGradient {
gradient,
focal_point,
} => CanvasFillStyle::Gradient(
create_radial_gradient(
&backend.context,
gradient,
focal_point.to_f64(),
true,
)
.expect("Couldn't create radial gradient"),
),
FillStyle::Bitmap {
id,
matrix,
is_smoothed,
is_repeating,
} => {
let bitmap = if let Some(bitmap) = create_bitmap_pattern(
*id,
*matrix,
*is_smoothed,
*is_repeating,
bitmap_source,
backend,
) {
bitmap
} else {
continue;
};
CanvasFillStyle::Bitmap(bitmap)
}
};
canvas_data.push(CanvasDrawCommand::Fill {
path: canvas_path,
fill_style,
});
}
DrawPath::Stroke {
commands,
style,
is_closed,
} => {
let canvas_path = Path2d::new().expect("Path2d constructor must succeed");
canvas_path.add_path_with_transformation(
&draw_commands_to_path2d(commands, *is_closed),
bounds_viewbox_matrix.unchecked_ref(),
);
let stroke_style = match style.fill_style() {
FillStyle::Color(color) => CanvasStrokeStyle::Color((*color).into()),
FillStyle::LinearGradient(gradient) => {
CanvasStrokeStyle::Gradient(gradient.clone(), None)
}
FillStyle::RadialGradient(gradient) => {
CanvasStrokeStyle::Gradient(gradient.clone(), Some(0.0))
}
FillStyle::FocalGradient {
gradient,
focal_point,
} => CanvasStrokeStyle::Gradient(gradient.clone(), Some(focal_point.to_f64())),
FillStyle::Bitmap {
id,
matrix,
is_smoothed,
is_repeating,
} => {
let bitmap = if let Some(bitmap) = create_bitmap_pattern(
*id,
*matrix,
*is_smoothed,
*is_repeating,
bitmap_source,
backend,
) {
bitmap
} else {
continue;
};
CanvasStrokeStyle::Bitmap(bitmap)
}
};
let line_cap = match style.start_cap() {
LineCapStyle::Round => "round",
LineCapStyle::Square => "square",
LineCapStyle::None => "butt",
};
let (line_join, miter_limit) = match style.join_style() {
LineJoinStyle::Round => ("round", 999_999.0),
LineJoinStyle::Bevel => ("bevel", 999_999.0),
LineJoinStyle::Miter(ml) => ("miter", ml.to_f32()),
};