forked from ruffle-rs/ruffle
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdisplay_object.rs
More file actions
3230 lines (2825 loc) · 116 KB
/
display_object.rs
File metadata and controls
3230 lines (2825 loc) · 116 KB
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
use crate::avm1::{
ActivationIdentifier as Avm1ActivationIdentifier, Object as Avm1Object, Value as Avm1Value,
};
use crate::avm2::{
Activation as Avm2Activation, Avm2, Error as Avm2Error, LoaderInfoObject,
Multiname as Avm2Multiname, Object as Avm2Object, StageObject as Avm2StageObject, TObject as _,
Value as Avm2Value,
};
use crate::context::{RenderContext, UpdateContext};
use crate::drawing::Drawing;
use crate::prelude::*;
use crate::string::{AvmString, WString};
use crate::tag_utils::SwfMovie;
use crate::types::{Degrees, Percent};
use crate::vminterface::Instantiator;
use bitflags::bitflags;
use gc_arena::barrier::{Write, unlock};
use gc_arena::lock::Lock;
use gc_arena::{Collect, Gc, Mutation};
use ruffle_macros::{enum_trait_object, istr};
use ruffle_render::perspective_projection::PerspectiveProjection;
use ruffle_render::pixel_bender::PixelBenderShaderHandle;
use ruffle_render::transform::{Transform, TransformStack};
use std::cell::{Cell, Ref, RefCell, RefMut};
use std::fmt::Debug;
use std::hash::Hash;
use std::num::NonZero;
use std::sync::Arc;
use swf::{ColorTransform, Fixed8};
mod avm1_button;
mod avm2_button;
mod bitmap;
mod container;
mod edit_text;
mod graphic;
mod interactive;
mod loader_display;
mod morph_shape;
mod movie_clip;
mod stage;
mod text;
mod video;
use crate::avm1::Activation;
use crate::display_object::bitmap::BitmapWeak;
pub use crate::display_object::container::{
DisplayObjectContainer, TDisplayObjectContainer, dispatch_added_event_only,
dispatch_added_to_stage_event_only,
};
pub use avm1_button::{Avm1Button, ButtonState, ButtonTracking};
pub use avm2_button::Avm2Button;
pub use bitmap::{Bitmap, BitmapClass};
#[allow(unused)]
pub use edit_text::LayoutDebugBoxesFlag;
pub use edit_text::{AutoSizeMode, EditText, TextSelection};
pub use graphic::Graphic;
pub use interactive::{Avm2MousePick, InteractiveObject, TInteractiveObject};
pub use loader_display::LoaderDisplay;
pub use morph_shape::MorphShape;
pub use movie_clip::{MovieClip, MovieClipHandle, MovieClipWeak, Scene};
use ruffle_render::backend::{BitmapCacheEntry, RenderBackend};
use ruffle_render::bitmap::{BitmapHandle, BitmapInfo, PixelSnapping};
use ruffle_render::blend::ExtendedBlendMode;
use ruffle_render::commands::{CommandHandler, CommandList, RenderBlendMode};
use ruffle_render::filters::Filter;
pub use stage::{Stage, StageAlign, StageDisplayState, StageScaleMode, WindowMode};
pub use text::{Text, TextSnapshot};
pub use video::Video;
use self::loader_display::LoaderDisplayWeak;
/// If a `DisplayObject` is marked `cacheAsBitmap` (via tag or AS),
/// this struct keeps the information required to uphold that cache.
/// A cached Display Object must have its bitmap invalidated when
/// any "visual" change happens, which can include:
/// - Changing the rotation
/// - Changing the scale
/// - Changing the alpha
/// - Changing the color transform
/// - Any "visual" change to children, **including** position changes
///
/// Position changes to the cached Display Object does not regenerate the cache,
/// allowing Display Objects to move freely without being regenerated.
///
/// Flash isn't very good at always recognising when it should be invalidated,
/// and there's cases such as changing the blend mode which don't always trigger it.
///
#[derive(Clone, Debug, Default)]
pub struct BitmapCache {
/// The `Matrix.a` value that was last used with this cache
matrix_a: f32,
/// The `Matrix.b` value that was last used with this cache
matrix_b: f32,
/// The `Matrix.c` value that was last used with this cache
matrix_c: f32,
/// The `Matrix.d` value that was last used with this cache
matrix_d: f32,
/// The width of the original bitmap, pre-filters
source_width: u32,
/// The height of the original bitmap, pre-filters
source_height: u32,
/// The offset used to draw the final bitmap (i.e. if a filter increases the size)
draw_offset: Point<i32>,
/// The current contents of the cache, if any. Values are post-filters.
bitmap: Option<BitmapInfo>,
/// Whether we warned that this bitmap was too large to be cached
warned_for_oversize: bool,
}
impl BitmapCache {
/// Forcefully make this BitmapCache invalid and require regeneration.
/// This should be used for changes that aren't automatically detected, such as children.
pub fn make_dirty(&mut self) {
// Setting the old transform to something invalid is a cheap way of making it invalid,
// without reserving an extra field for.
self.matrix_a = f32::NAN;
}
fn is_dirty(&self, other: &Matrix, source_width: u32, source_height: u32) -> bool {
self.matrix_a != other.a
|| self.matrix_b != other.b
|| self.matrix_c != other.c
|| self.matrix_d != other.d
|| self.source_width != source_width
|| self.source_height != source_height
|| self.bitmap.is_none()
}
/// Clears any dirtiness and ensure there's an appropriately sized texture allocated
#[expect(clippy::too_many_arguments)]
fn update(
&mut self,
renderer: &mut dyn RenderBackend,
matrix: Matrix,
source_width: u32,
source_height: u32,
actual_width: u32,
actual_height: u32,
draw_offset: Point<i32>,
swf_version: u8,
) {
self.matrix_a = matrix.a;
self.matrix_b = matrix.b;
self.matrix_c = matrix.c;
self.matrix_d = matrix.d;
self.source_width = source_width;
self.source_height = source_height;
self.draw_offset = draw_offset;
if let Some(current) = &mut self.bitmap
&& current.width == actual_width
&& current.height == actual_height
{
return; // No need to resize it
}
let acceptable_size = if swf_version > 9 {
let total = actual_width * actual_height;
actual_width < 8191 && actual_height < 8191 && total < 16777215
} else {
actual_width < 2880 && actual_height < 2880
};
if renderer.is_offscreen_supported()
&& let Some(actual_width) = NonZero::new(actual_width)
&& let Some(actual_height) = NonZero::new(actual_height)
&& acceptable_size
{
let handle = renderer.create_empty_texture(actual_width, actual_height);
self.bitmap = handle.ok().map(|handle| BitmapInfo {
width: actual_width.get(),
height: actual_height.get(),
handle,
});
} else {
self.bitmap = None;
}
}
/// Explicitly clears the cached value and drops any resources.
/// This should only be used in situations where you can't render to the cache and it needs to be
/// temporarily disabled.
fn clear(&mut self) {
self.bitmap = None;
}
fn handle(&self) -> Option<BitmapHandle> {
self.bitmap.as_ref().map(|b| b.handle.clone())
}
}
#[derive(Clone)]
pub struct RenderOptions {
/// Whether to skip rendering masks.
///
/// Masks are usually skipped when rendering, but when e.g. rendering
/// the mask itself, it can't be skipped.
///
/// Masks are skipped by default.
pub skip_masks: bool,
/// Whether to apply object's base transform.
///
/// For instance, when calling BitmapData.draw, object's transform is not
/// applied.
///
/// Transform is applied by default.
pub apply_transform: bool,
/// Whether to apply base transform's matrix when rendering.
///
/// Sometimes we need to render an object without applying its matrix, but
/// with applying other parts of its transform (e.g. color transform).
/// This happens e.g. when rendering alpha masks.
///
/// Matrix is applied by default.
pub apply_matrix: bool,
}
impl Default for RenderOptions {
fn default() -> Self {
Self {
apply_transform: true,
skip_masks: true,
apply_matrix: true,
}
}
}
#[derive(Clone, Collect, Debug)]
#[collect(no_drop)]
pub enum RenderMask<'gc> {
/// There's no mask.
None,
/// Stencil masks are the classic, default masks used in Flash Player.
///
/// The masker behaves like a stencil, and masks everything outside its
/// rendered pixels irrespectively of the pixels themselves.
/// The maskee acts like being masked with the masker's hit test image.
Stencil(DisplayObject<'gc>),
/// Alpha masks are the more advanced (and more intuitive) masks used when
/// CAB is enabled.
///
/// The maskee is being masked based on the value of the masker's alpha
/// channel.
Alpha(DisplayObject<'gc>),
}
#[derive(Clone, Collect)]
#[collect(no_drop)]
// Ensure this always has the same alignment as its subclasses (needed for `Gc` casts).
#[repr(align(8))]
pub struct DisplayObjectBase<'gc> {
cell: RefCell<DisplayObjectBaseMut>,
parent: Lock<Option<DisplayObject<'gc>>>,
place_frame: Cell<u16>,
depth: Cell<Depth>,
ratio: Cell<u16>,
name: Lock<Option<AvmString<'gc>>>,
clip_depth: Cell<Depth>,
// The transform of this display object.
// (Split into several fields for easier access)
matrix: Cell<Matrix>,
color_transform: Cell<ColorTransform>,
perspective_projection: Cell<Option<PerspectiveProjection>>,
// Cached transform properties `_xscale`, `_yscale`, `_rotation`.
// These are expensive to calculate, so they will be calculated and cached
// when AS requests one of these properties.
rotation: Cell<Degrees>,
scale_x: Cell<Percent>,
scale_y: Cell<Percent>,
skew: Cell<f64>,
/// The sound transform of sounds playing via this display object.
sound_transform: Cell<SoundTransform>,
/// The display object that we are being masked by.
masker: Lock<Option<DisplayObject<'gc>>>,
/// The display object we are currently masking.
maskee: Lock<Option<DisplayObject<'gc>>>,
meta_data: Lock<Option<Avm2Object<'gc>>>,
/// The blend mode used when rendering this display object.
/// Values other than the default `BlendMode::Normal` implicitly cause cache-as-bitmap behavior.
blend_mode: Cell<ExtendedBlendMode>,
#[collect(require_static)]
/// The opaque background color of this display object.
/// The bounding box of the display object will be filled with the given color. This also
/// triggers cache-as-bitmap behavior. Only solid backgrounds are supported; the alpha channel
/// is ignored.
opaque_background: Cell<Option<Color>>,
/// Bit flags for various display object properties.
flags: Cell<DisplayObjectFlags>,
/// The 'internal' scroll rect used for rendering and methods like 'localToGlobal'.
/// This is updated from 'pre_render'
scroll_rect: Cell<Option<Rectangle<Twips>>>,
/// The 'next' scroll rect, which we will copy to 'scroll_rect' from 'pre_render'.
/// This is used by the ActionScript 'DisplayObject.scrollRect' getter, which sees
/// changes immediately (without needing wait for a render)
next_scroll_rect: Cell<Rectangle<Twips>>,
/// Rectangle used for 9-slice scaling (`DisplayObject.scale9grid`).
scaling_grid: Cell<Rectangle<Twips>>,
}
#[derive(Clone)]
struct DisplayObjectBaseMut {
filters: Box<[Filter]>,
blend_shader: Option<PixelBenderShaderHandle>,
/// If this Display Object should cacheAsBitmap - and if so, the cache itself.
/// None means not cached, Some means cached.
cache: Option<BitmapCache>,
}
impl Default for DisplayObjectBase<'_> {
fn default() -> Self {
Self {
cell: RefCell::new(DisplayObjectBaseMut {
filters: Default::default(),
blend_shader: None,
cache: None,
}),
parent: Default::default(),
place_frame: Default::default(),
depth: Default::default(),
ratio: Default::default(),
name: Lock::new(None),
clip_depth: Default::default(),
matrix: Default::default(),
color_transform: Default::default(),
perspective_projection: Default::default(),
rotation: Cell::new(Degrees::from_radians(0.0)),
scale_x: Cell::new(Percent::from_unit(1.0)),
scale_y: Cell::new(Percent::from_unit(1.0)),
skew: Cell::new(0.0),
masker: Lock::new(None),
maskee: Lock::new(None),
meta_data: Lock::new(None),
sound_transform: Default::default(),
blend_mode: Default::default(),
opaque_background: Default::default(),
flags: Cell::new(DisplayObjectFlags::VISIBLE),
scroll_rect: Cell::new(None),
next_scroll_rect: Default::default(),
scaling_grid: Default::default(),
}
}
}
impl<'gc> DisplayObjectBase<'gc> {
fn contains_flag(&self, flag: DisplayObjectFlags) -> bool {
self.flags.get().contains(flag)
}
fn set_flag(&self, flag: DisplayObjectFlags, value: bool) {
let mut flags = self.flags.get();
flags.set(flag, value);
self.flags.set(flags);
}
/// Reset all properties that would be adjusted by a movie load.
fn reset_for_movie_load(&self) {
let flags_to_keep = self.flags.get() & DisplayObjectFlags::LOCK_ROOT;
self.flags.set(flags_to_keep | DisplayObjectFlags::VISIBLE);
}
fn depth(&self) -> Depth {
self.depth.get()
}
fn set_depth(&self, depth: Depth) {
self.depth.set(depth);
}
fn place_frame(&self) -> u16 {
self.place_frame.get()
}
fn set_place_frame(&self, frame: u16) {
self.place_frame.set(frame);
}
fn transform(&self, apply_matrix: bool) -> Transform {
Transform {
matrix: if apply_matrix {
self.matrix.get()
} else {
Matrix::IDENTITY
},
color_transform: self.color_transform.get(),
perspective_projection: self.perspective_projection.get(),
}
}
pub fn matrix(&self) -> Matrix {
self.matrix.get()
}
pub fn set_matrix(&self, matrix: Matrix) {
self.matrix.set(matrix);
self.set_scale_rotation_cached(false);
}
pub fn color_transform(&self) -> ColorTransform {
self.color_transform.get()
}
pub fn set_color_transform(&self, color_transform: ColorTransform) {
self.color_transform.set(color_transform);
}
pub fn perspective_projection(&self) -> Option<PerspectiveProjection> {
self.perspective_projection.get()
}
pub fn set_perspective_projection(
&self,
perspective_projection: Option<PerspectiveProjection>,
) -> bool {
let old = self.perspective_projection.replace(perspective_projection);
perspective_projection != old
}
fn x(&self) -> Twips {
self.matrix.get().tx
}
fn set_x(&self, x: Twips) -> bool {
let mut matrix = self.matrix.get();
let changed = matrix.tx != x;
matrix.tx = x;
self.matrix.set(matrix);
self.set_transformed_by_script(true);
changed
}
fn y(&self) -> Twips {
self.matrix.get().ty
}
fn set_y(&self, y: Twips) -> bool {
let mut matrix = self.matrix.get();
let changed = matrix.ty != y;
matrix.ty = y;
self.matrix.set(matrix);
self.set_transformed_by_script(true);
changed
}
/// Caches the scale and rotation factors for this display object, if necessary.
/// Calculating these requires heavy trig ops, so we only do it when `_xscale`, `_yscale` or
/// `_rotation` is accessed.
fn cache_scale_rotation(&self) {
if !self.scale_rotation_cached() {
let Matrix { a, b, c, d, .. } = self.matrix.get();
let a = f64::from(a);
let b = f64::from(b);
let c = f64::from(c);
let d = f64::from(d);
// If this object's transform matrix is:
// [[a c tx]
// [b d ty]]
// After transformation, the X-axis and Y-axis will turn into the column vectors x' = <a, b> and y' = <c, d>.
// We derive the scale, rotation, and skew values from these transformed axes.
// The skew value is not exposed by ActionScript, but is remembered internally.
// xscale = len(x')
// yscale = len(y')
// rotation = atan2(b, a) (the rotation of x' from the normal x-axis).
// skew = atan2(-c, d) - atan2(b, a) (the signed difference between y' and x' rotation)
// This can produce some surprising results due to the overlap between flipping/rotation/skewing.
// For example, in Flash, using Modify->Transform->Flip Horizontal and then tracing _xscale, _yscale, and _rotation
// will output 100, 100, and 180. (a horizontal flip could also be a 180 degree skew followed by 180 degree rotation!)
let rotation_x = f64::atan2(b, a);
let rotation_y = f64::atan2(-c, d);
let scale_x = f64::sqrt(a * a + b * b);
let scale_y = f64::sqrt(c * c + d * d);
self.rotation.set(Degrees::from_radians(rotation_x));
self.scale_x.set(Percent::from_unit(scale_x));
self.scale_y.set(Percent::from_unit(scale_y));
self.skew.set(rotation_y - rotation_x);
}
}
fn rotation(&self) -> Degrees {
self.cache_scale_rotation();
self.rotation.get()
}
fn set_rotation(&self, degrees: Degrees) -> bool {
self.set_transformed_by_script(true);
self.cache_scale_rotation();
let changed = self.rotation.get() != degrees;
self.rotation.set(degrees);
// FIXME - this isn't quite correct. In Flash player,
// trying to set rotation to NaN does nothing if the current
// matrix 'b' and 'd' terms are both zero. However, if one
// of those terms is non-zero, then the entire matrix gets
// modified in a way that depends on its starting values.
// I haven't been able to figure out how to reproduce those
// values, so for now, we never modify the matrix if the
// rotation is NaN. Hopefully, there are no SWFs depending
// on the weird behavior when b or d is non-zero.
if degrees.into_radians().is_nan() {
return changed;
}
let skew = self.skew.get();
let cos_x = f64::cos(degrees.into_radians());
let sin_x = f64::sin(degrees.into_radians());
let cos_y = f64::cos(degrees.into_radians() + skew);
let sin_y = f64::sin(degrees.into_radians() + skew);
let scale_x = self.scale_x.get().unit();
let scale_y = self.scale_y.get().unit();
let mut matrix = self.matrix.get();
matrix.a = (scale_x * cos_x) as f32;
matrix.b = (scale_x * sin_x) as f32;
matrix.c = (scale_y * -sin_y) as f32;
matrix.d = (scale_y * cos_y) as f32;
self.matrix.set(matrix);
changed
}
fn scale_x(&self) -> Percent {
self.cache_scale_rotation();
self.scale_x.get()
}
fn set_scale_x(&self, mut value: Percent) -> bool {
let changed = self.scale_x.get() != value;
self.set_transformed_by_script(true);
self.cache_scale_rotation();
self.scale_x.set(value);
// Note - in order to match Flash's behavior, the 'scale_x' field is set to NaN
// (which gets reported back to ActionScript), but we treat it as 0 for
// the purposes of updating the matrix
if value.percent().is_nan() {
value = 0.0.into();
}
// Similarly, a rotation of `NaN` can be reported to ActionScript, but we
// treat it as 0.0 when calculating the matrix
let mut rot = self.rotation.get().into_radians();
if rot.is_nan() {
rot = 0.0;
}
let cos = f64::cos(rot);
let sin = f64::sin(rot);
let mut matrix = self.matrix.get();
matrix.a = (cos * value.unit()) as f32;
matrix.b = (sin * value.unit()) as f32;
self.matrix.set(matrix);
changed
}
fn scale_y(&self) -> Percent {
self.cache_scale_rotation();
self.scale_y.get()
}
fn set_scale_y(&self, mut value: Percent) -> bool {
let changed = self.scale_y.get() != value;
self.set_transformed_by_script(true);
self.cache_scale_rotation();
self.scale_y.set(value);
// Note - in order to match Flash's behavior, the 'scale_y' field is set to NaN
// (which gets reported back to ActionScript), but we treat it as 0 for
// the purposes of updating the matrix
if value.percent().is_nan() {
value = 0.0.into();
}
// Similarly, a rotation of `NaN` can be reported to ActionScript, but we
// treat it as 0.0 when calculating the matrix
let mut rot = self.rotation.get().into_radians();
if rot.is_nan() {
rot = 0.0;
}
let skew = self.skew.get();
let cos = f64::cos(rot + skew);
let sin = f64::sin(rot + skew);
let mut matrix = self.matrix.get();
matrix.c = (-sin * value.unit()) as f32;
matrix.d = (cos * value.unit()) as f32;
self.matrix.set(matrix);
changed
}
fn name(&self) -> Option<AvmString<'gc>> {
self.name.get()
}
fn set_name(this: &Write<Self>, name: AvmString<'gc>) {
unlock!(this, Self, name).set(Some(name));
}
fn filters(&self) -> Ref<'_, [Filter]> {
Ref::map(self.cell.borrow(), |c| &*c.filters)
}
fn set_filters(&self, filters: Box<[Filter]>) -> bool {
let mut write = self.cell.borrow_mut();
let changed = filters != write.filters;
write.filters = filters;
drop(write);
if changed {
self.recheck_cache_as_bitmap();
}
changed
}
fn alpha(&self) -> f64 {
f64::from(self.color_transform().a_multiply)
}
fn set_alpha(&self, value: f64) -> bool {
self.set_transformed_by_script(true);
let value = Fixed8::from_f64(value);
let mut tf = self.color_transform.get();
let changed = tf.a_multiply != value;
tf.a_multiply = value;
self.color_transform.set(tf);
changed
}
fn clip_depth(&self) -> Depth {
self.clip_depth.get()
}
fn set_clip_depth(&self, depth: Depth) {
self.clip_depth.set(depth);
}
fn parent(&self) -> Option<DisplayObject<'gc>> {
self.parent.get()
}
/// You should almost always use `DisplayObject.set_parent` instead, which
/// properly handles 'orphan' movie clips
fn set_parent_ignoring_orphan_list(this: &Write<Self>, parent: Option<DisplayObject<'gc>>) {
unlock!(this, Self, parent).set(parent)
}
fn avm1_removed(&self) -> bool {
self.contains_flag(DisplayObjectFlags::AVM1_REMOVED)
}
fn avm1_pending_removal(&self) -> bool {
self.contains_flag(DisplayObjectFlags::AVM1_PENDING_REMOVAL)
}
pub fn should_skip_next_enter_frame(&self) -> bool {
self.contains_flag(DisplayObjectFlags::SKIP_NEXT_ENTER_FRAME)
}
pub fn set_skip_next_enter_frame(&self, skip: bool) {
self.set_flag(DisplayObjectFlags::SKIP_NEXT_ENTER_FRAME, skip);
}
fn set_avm1_removed(&self, value: bool) {
self.set_flag(DisplayObjectFlags::AVM1_REMOVED, value);
}
fn set_avm1_pending_removal(&self, value: bool) {
self.set_flag(DisplayObjectFlags::AVM1_PENDING_REMOVAL, value);
}
fn scale_rotation_cached(&self) -> bool {
self.contains_flag(DisplayObjectFlags::SCALE_ROTATION_CACHED)
}
fn set_scale_rotation_cached(&self, set_flag: bool) {
let flags = if set_flag {
self.flags.get() | DisplayObjectFlags::SCALE_ROTATION_CACHED
} else {
self.flags.get() - DisplayObjectFlags::SCALE_ROTATION_CACHED
};
self.flags.set(flags);
}
pub fn sound_transform(&self) -> SoundTransform {
self.sound_transform.get()
}
pub fn set_sound_transform(&self, sound_transform: SoundTransform) {
self.sound_transform.set(sound_transform);
}
fn visible(&self) -> bool {
self.contains_flag(DisplayObjectFlags::VISIBLE)
}
fn set_visible(&self, value: bool) -> bool {
let changed = self.visible() != value;
self.set_flag(DisplayObjectFlags::VISIBLE, value);
changed
}
fn blend_mode(&self) -> ExtendedBlendMode {
self.blend_mode.get()
}
fn set_blend_mode(&self, value: ExtendedBlendMode) -> bool {
self.blend_mode.replace(value) != value
}
fn blend_shader(&self) -> Option<PixelBenderShaderHandle> {
self.cell.borrow().blend_shader.clone()
}
fn set_blend_shader(&self, value: Option<PixelBenderShaderHandle>) {
self.cell.borrow_mut().blend_shader = value;
}
/// The opaque background color of this display object.
/// The bounding box of the display object will be filled with this color.
fn opaque_background(&self) -> Option<Color> {
self.opaque_background.get()
}
/// The opaque background color of this display object.
/// The bounding box of the display object will be filled with the given color. This also
/// triggers cache-as-bitmap behavior. Only solid backgrounds are supported; the alpha channel
/// is ignored.
fn set_opaque_background(&self, value: Option<Color>) -> bool {
let value = value.map(|mut color| {
color.a = 255;
color
});
let changed = self.opaque_background.get() != value;
self.opaque_background.set(value);
changed
}
fn is_root(&self) -> bool {
self.contains_flag(DisplayObjectFlags::IS_ROOT)
}
fn set_is_root(&self, value: bool) {
self.set_flag(DisplayObjectFlags::IS_ROOT, value);
}
fn lock_root(&self) -> bool {
self.contains_flag(DisplayObjectFlags::LOCK_ROOT)
}
fn set_lock_root(&self, value: bool) {
self.set_flag(DisplayObjectFlags::LOCK_ROOT, value);
}
fn transformed_by_script(&self) -> bool {
self.contains_flag(DisplayObjectFlags::TRANSFORMED_BY_SCRIPT)
}
fn set_transformed_by_script(&self, value: bool) {
self.set_flag(DisplayObjectFlags::TRANSFORMED_BY_SCRIPT, value);
}
fn placed_by_avm1_script(&self) -> bool {
self.contains_flag(DisplayObjectFlags::PLACED_BY_AVM1_SCRIPT)
}
fn set_placed_by_avm1_script(&self, value: bool) {
self.set_flag(DisplayObjectFlags::PLACED_BY_AVM1_SCRIPT, value);
}
fn placed_by_avm2_script(&self) -> bool {
self.contains_flag(DisplayObjectFlags::PLACED_BY_AVM2_SCRIPT)
}
fn set_placed_by_avm2_script(&self, value: bool) {
self.set_flag(DisplayObjectFlags::PLACED_BY_AVM2_SCRIPT, value);
}
fn manual_frame_construct(&self) -> bool {
self.contains_flag(DisplayObjectFlags::MANUAL_FRAME_CONSTRUCT)
}
fn set_manual_frame_construct(&self, value: bool) {
self.set_flag(DisplayObjectFlags::MANUAL_FRAME_CONSTRUCT, value);
}
fn is_bitmap_cached_preference(&self) -> bool {
self.contains_flag(DisplayObjectFlags::CACHE_AS_BITMAP)
}
fn set_bitmap_cached_preference(&self, value: bool) {
self.set_flag(DisplayObjectFlags::CACHE_AS_BITMAP, value);
self.recheck_cache_as_bitmap();
}
fn bitmap_cache_mut(&self) -> RefMut<'_, Option<BitmapCache>> {
RefMut::map(self.cell.borrow_mut(), |c| &mut c.cache)
}
/// Invalidates a cached bitmap, if it exists.
/// This may only be called once per frame - the first call will return true, regardless of
/// if there was a cache.
/// Any subsequent calls will return false, indicating that you do not need to invalidate the ancestors.
/// This is reset during rendering.
fn invalidate_cached_bitmap(&self) -> bool {
if self.contains_flag(DisplayObjectFlags::CACHE_INVALIDATED) {
return false;
}
if let Some(cache) = &mut *self.bitmap_cache_mut() {
cache.make_dirty();
}
self.set_flag(DisplayObjectFlags::CACHE_INVALIDATED, true);
true
}
fn clear_invalidate_flag(&self) {
self.set_flag(DisplayObjectFlags::CACHE_INVALIDATED, false);
}
fn recheck_cache_as_bitmap(&self) {
let mut write = self.cell.borrow_mut();
let should_cache = self.is_bitmap_cached_preference() || !write.filters.is_empty();
if should_cache {
write.cache.get_or_insert_default();
} else {
write.cache = None;
}
}
fn instantiated_by_timeline(&self) -> bool {
self.contains_flag(DisplayObjectFlags::INSTANTIATED_BY_TIMELINE)
}
fn set_instantiated_by_timeline(&self, value: bool) {
self.set_flag(DisplayObjectFlags::INSTANTIATED_BY_TIMELINE, value);
}
fn has_scroll_rect(&self) -> bool {
self.contains_flag(DisplayObjectFlags::HAS_SCROLL_RECT)
}
fn set_has_scroll_rect(&self, value: bool) {
self.set_flag(DisplayObjectFlags::HAS_SCROLL_RECT, value);
}
fn has_explicit_name(&self) -> bool {
self.contains_flag(DisplayObjectFlags::HAS_EXPLICIT_NAME)
}
fn set_has_explicit_name(&self, value: bool) {
self.set_flag(DisplayObjectFlags::HAS_EXPLICIT_NAME, value);
}
fn masker(&self) -> Option<DisplayObject<'gc>> {
self.masker.get()
}
fn set_masker(this: &Write<Self>, node: Option<DisplayObject<'gc>>) {
unlock!(this, Self, masker).set(node);
}
fn maskee(&self) -> Option<DisplayObject<'gc>> {
self.maskee.get()
}
fn set_maskee(this: &Write<Self>, node: Option<DisplayObject<'gc>>) {
unlock!(this, Self, maskee).set(node);
}
fn meta_data(&self) -> Option<Avm2Object<'gc>> {
self.meta_data.get()
}
fn set_meta_data(this: &Write<Self>, value: Avm2Object<'gc>) {
unlock!(this, Self, meta_data).set(Some(value));
}
pub fn has_matrix3d_stub(&self) -> bool {
self.contains_flag(DisplayObjectFlags::HAS_MATRIX3D_STUB)
}
pub fn set_has_matrix3d_stub(&self, value: bool) {
self.set_flag(DisplayObjectFlags::HAS_MATRIX3D_STUB, value)
}
}
/// Indicates which kind of bounds should be returned by `self_bounds`.
/// In most cases `BoundsMode::Engine` should be used.
#[derive(Copy, Clone, Debug)]
pub enum BoundsMode {
/// The bounds visible on the stage (e.g. takes MorphShape ratio into
/// account). Used for hit testing and rendering.
Engine,
/// The bounds returned by ActionScript (e.g. doesn't take MorphShape
/// ratio into account - always uses ratio 0 AKA start shape).
/// This is used in AVM1 in MovieClip::getBounds(), getRect(), _width, _height, hitTest (object)
/// Used in AVM2 in DO::getBounds(), getRect(), width, height, hitTestObject()
/// Used in both AVM1 and AVM2 for Transform.pixelBounds.
Script,
}
struct DrawCacheInfo {
handle: BitmapHandle,
dirty: bool,
base_transform: Transform,
bounds: Rectangle<Twips>,
draw_offset: Point<i32>,
filters: Vec<Filter>,
}
pub fn render_base<'gc>(
this: DisplayObject<'gc>,
context: &mut RenderContext<'_, 'gc>,
options: RenderOptions,
) {
if options.skip_masks && this.maskee().is_some() {
// Skip rendering masks (unless we are rendering one explicitly).
return;
}
if options.apply_transform {
let transform = this.base().transform(options.apply_matrix);
context.transform_stack.push(&transform);
}
let blend_mode = this.blend_mode();
let original_commands = if blend_mode != ExtendedBlendMode::Normal {
Some(std::mem::take(&mut context.commands))
} else {
None
};
let cache_info = if context.use_bitmap_cache && this.is_bitmap_cached() {
let mut cache_info: Option<DrawCacheInfo> = None;
let base_transform = context.transform_stack.transform();
let bounds: Rectangle<Twips> = this.render_bounds_with_transform(
&base_transform.matrix,
false, // we want to do the filter growth for this object ourselves, to know the offsets
&context.stage.view_matrix(),
);
let name = this.name();
let mut filters: Vec<Filter> = this.filters().to_owned();
let swf_version = this.swf_version();
filters.retain(|f| !f.impotent());
if let Some(cache) = &mut *this.base().bitmap_cache_mut() {
let width = bounds.width().to_pixels().ceil().max(0.0);
let height = bounds.height().to_pixels().ceil().max(0.0);
if width <= u16::MAX as f64 && height <= u16::MAX as f64 {
let width = width as u32;
let height = height as u32;
let mut filter_rect = Rectangle {
x_min: Twips::ZERO,
x_max: Twips::from_pixels_i32(width as i32),
y_min: Twips::ZERO,
y_max: Twips::from_pixels_i32(height as i32),
};
let stage_matrix = context.stage.view_matrix();
for filter in &mut filters {
// Scaling is done by *stage view matrix* only, nothing in-between
filter.scale(stage_matrix.a, stage_matrix.d);
filter_rect = filter.calculate_dest_rect(filter_rect);
}
let filter_rect = Rectangle {
x_min: filter_rect.x_min.to_pixels().floor() as i32,
x_max: filter_rect.x_max.to_pixels().ceil() as i32,
y_min: filter_rect.y_min.to_pixels().floor() as i32,
y_max: filter_rect.y_max.to_pixels().ceil() as i32,
};
let draw_offset = Point::new(filter_rect.x_min, filter_rect.y_min);
if cache.is_dirty(&base_transform.matrix, width, height) {
cache.update(
context.renderer,
base_transform.matrix,
width,
height,
filter_rect.width() as u32,