These getters were previously calling `local_to_global`
with the unused localX/localY coordinate set to 0. Howver,
`local_to_global` does a matrix multiplication, which in general
will depend on both the x and y values. This was causing the getters
to return incorrect results when any of the `transform.matrix` values
included a non-diagonal matrix.
We now call `local_to_transform` with the real `localX` and `localY`
values.
The Newgrounds API checks `Security.sandboxType` to see if it should
run in debug mode or not (which determines whether or not medals
can actually be unlocked).
For now, desktop continues to use `localTrusted` as the default,
while web now uses `remote`. We might want to make this configurable
at some point, but this should be good enough for now (and better
match Flash's behavior).
Flash supports calling `Sound.play`, `SoundChannel.stop`, and
`SoundChannel.soundTransform` while a sound load is in progress
(e.g. immediately after calling `Sound.load`).
To support this, we queue up information inside `SoundObject`
and `SoundChannelObject` when a load is in progress. When a load
completes, we trigger any queued `Sound.play` and `SoundChannel.stop`
calls, and apply the most recent `SoundChannel.soundTransform`
If we're going to overwrite the CPU pixels with the result of a
GPU operation, make sure the GPU texture is up to date with the
latest CPU pixels. I've also renamed the method to
`overwrite_cpu_pixels_from_gpu` to better reflect how it should
be used.
This is needed by the Newgrounds API. We don't have the ability
to make fake requests to HTTP urls in our test frameworks,
so I haven't added any tests for this. However, I tested locally
that this allows the Newgrounds API to work (and got a medal
in Cloud Wars).
When removing a clip, first check if it has an unload event listener somewhere
it's hierarchy.
If it does, enqueue the removal to happen on the next frame, by moving it to a negative depth.
* Take two: Delay reading image back from render backend using `SyncHandle`
This allows us to avoid blocking immediately after a `BitmapData.draw` call.
Instead, we only attempt to use the `SyncHandle` when performing an operation
that requires the CPU-side pixels (e.g. BitmapData.getPixel or BitmapData.setPixel).
In the best case, the SWF will never explicitly access the pixels of
the target BitmapData, removing the need to ever copy back the render backend
image to our BitmapData. If the SWF doesn't require access to the pixels immediately,
we can delay copying the pixels until they're actually needed, hopefully allowing
the render backend to finish processing the BitmapData.draw operation in
the backenground before we need the result.
Now that the CPU and GPU pixels can be intentionally out of sync with
each other, we need to ensure that we don't accidentally expose 'stale'
CPU-side pixels to ActionScript (which needs to remain unaware of
our internal laziness). We now use a wrapper type `BitmapDataWrapper`
to enforce that the `SyncHandle` is consumed before accessing the
underlying `BitmapData.
* core: Skip GPU->CPU sync for source and target BitmapData during draw
* Introduce DirtyState enum
This change makes it so that if there is a goto to a specific frame,
then a frame script is registered for that frame, and then a goto to the
same frame again, the frame script will not be skipped. At least one movie
appears to depend on this behaviour.
Now that a `Bitmap` always stores a `BitmapData`, we can read the pixels
directly from the `BitmapData`, instead of duplicating them in an
`initial_data` field
This makes `Bitmap` delegate to `BitmapData` for
all of the bitmap-related information (handle, width, and height).
As a result, we now unconditionally store a `BitmapData` in `Bitmap`.
As a result, swapping the underling `BitmapData` instance will
automatically change the properties (and rendered image) of a `Bitmap`.
This required some refactoring in the render backends in order to
get access to a `BitmapHandle` through `BitmapData`.
In future versions of `gc-arena`, the `Debug` impl. of `Gc`
and `GcCell` will print the pointed-to value, which will cause
derived `Debug` impls. to enter an infinite recursion.
As such, this manually implements `Debug` on types wrapping a
`Gc/GcCell` to maintain the current behavior.
Previous behaviour defaulted to undefined and applied the format to the
range [0,0) instead of defaulting to -1 and applying the format to the
full length of the TextField.
This code was always wrong; and only saved from breaking by other wrong code elsewhere. Specifically:
* `SimpleButton.construct_frame` sets the wrong initial state
* but `MovieClip.instantiate_child` fires frame events before `post_instantiation`
* and `SimpleButton.post_instantiation` sets the correct state
This works now because all object placement and removal happens in `enter_frame`. Constructing those objects right away causes them to drop added events.
We cannot remove other instances of `construct_frame`, however - those are in places where we actually do expect constructors to run, not just see things get placed.
This also centralizes all the code we added in the prior commit into `on_construction_complete`, which should be called whenever an AVM2 object finishes construction.
This has a few other knock-on effects:
* AVM2 added-to-timeline events are fired by each object after it constructs its AVM2 side. This is opposed to before when we fired them after object instantiation and placement. This also gets rid of a prior hack we had for the AVM2 root movie getting added to the stage - or, more accurately, adopts it for everything.
* The supercall constructor for `DisplayObject` runs `construct_frame` on all children. This matches Flash Player behavior.
NOTE: This currently breaks the `placed_with_name` check, so there's going to be a lot of spurious can't set warnings
Usage of TObject::as_script_object was always followed by an unwrap, and
only SuperObject returned None.
The name change is intended to make clearer the fact that using the
returned object may bypass special behavior.
* tests: Add a test for issue #8630
* core: No-op gotos in AS3 do not actually do anything, even though they emit events
Fixes issue #8630
* tests: Add more tests for various #8630-adjacent cases
* tests: Ignore the tests with script removal as they expect MovieClip children to be nulled upon removal
* chore: Case sensitive filesystem fix
Co-authored-by: Adrian Wielgosik <adrian.wielgosik@gmail.com>
`BitmapHandle` now holds `Arc<dyn BitmapHandleImpl>`.
This allows us to move all of the per-bitmap backend data into
`BitmapHandle`, instead of holding an id to a backend-specific
hashmap.
This fixes the memory leak issue with bitmaps. Once the AVM side of a
bitmap (`Bitmap`/`BitmapData`) gets garbage-collected, the
`BitmapHandle` will get dropped, freeing all of the GPU resources
assoicated with the bitmap.
This PR implements core 'stage3D' APIs. We are now able
to render at least two demos from the Context3D docs - a simple
triangle render, and a rotating cube.
Implemented in this PR:
* Stage3D access and Context3D creation
* IndexBuffer3D and VertexBuffer3D creation, uploading, and usage
* Program3D uploading and usage (via `naga-agal`)
* Context3D: configureBackBuffer, clear, drawTriangles, and present
Not yet implemented:
* Any 'dispose()' methods
* Depth and stencil buffers
* Context3D texture apis
* Scissor rectangle
General implementation strategy:
A new `Object` variant is added for each of the Stage3D objects
(VertexBuffer3D, Program3D, etc). This stores a handle to the
parent `Context3D`, and (depending on the object) a handle
to the underlying native resource, via `Rc<dyn
SomeRenderBackendTrait>`).
Calling methods on Context3D does not usually result in an immediate
call to a `wgpu` method. Instead, we queue up commands in our
`Context3D` instance, and execute them all on a call to `present`.
This avoids some nasty wgpu lifetime issues, and is very similar
to the approah we use for normal rendering.
The actual rendering happens on a `Texture`, with dimensions
determined by `createBackBuffer`. During 'Stage' rendering,
we render all of these Stage3D textures *behind* the normal
stage (but in front of the overall stage background color).
We only called `get_bitmap_pixels` when creating a `BitmapData`
for an SWF-provided `Bitmap`. We now store the initial pixels
in `Character::Bitmap`, and use them to initialize a `BitmapData`
when needed.
This lets us simplify the wgpu backend, which no longer needs
to store a `Bitmap` object. In addition to saving space for
`BitmapData` objects that lack an SWF `Bitmap`, this will make
it easier to move data from `bitmap_registry` into `BitmapHandle`
itself.
D.O.s removed by the timeline may only be removed from the depth list
(if they were manipulated by AS3 scripts), but their unload method
would still be called, which is wrong.
This is linked to the legacy DisplayObject::Text, which can
only be created by Flash CS6 (but is allowed in AVM2 swfs).
The 'StaticText' class cannot be constructed from ActionScript.
To support this, I've added support for native initializers to
playerglobal. This allows us to throw an exception in the
ActionScript constructor in Test.as, and do nothing in the native
intiializer (so that we can construct it from a DisplayObject).
I've left StaticText.text unimplemented for now, since it will require
dealing with Glyphs
Co-authored-by: kmeisthax <dcrkid@yahoo.com>
This is done by:
- using the global constant pool instead of a fresh empty one:
- OK, as no call-site is directly executing arbitrary bytecode that
could care about the contents of the constant pool.
- pre-allocating the global scope object in the `Avm1` context
- using the global scope directly instead of allocating a local scope:
- OK, because no call-site is directly defining locals on the
returned Activation's scope.
Currently, we rely on ShapeTessellator being able to get a BitmapHandle
without a RenderBackend. With the upcoming BitmapData refactor,
we will always need a RenderBackend to get a BitmapHandle, which creates
borrow-checker issues in ShapeTessellator (which is stored in a
RenderBackend).
To solve this, we split BitmapSource.bitmap into two methods -
BitmapSource.bitmap and BitmapSource.bitmap_handle. ShapeTessellator
continues to use BitmapSource.bitmap, and uses the u16 bitmap id
instead of a BitmapHandle. The BitmapSource.bitmap_handle method
is used inside each render backend to convert the id to a BitmapHandle,
avoiding borrow-checker issues.
`tag_length` isn't really necessary since each tag is read using
a dedicated `swf::Reader`, which keeps track of the tag boundary
internally.
As a result, `tag_len` can be avoided passed around many times in
`movie_clip.rs`.
The call to `super_init` will initialize a `DisplayObject` (if unset)
in the `Sprite` constructor, using exactly the same logic that we're
attempting to use. The code in `MovieClip` is unreachable, and can
be deleted.
The desktop player now takes a `--spoof-url` argument, which overrides
the movie URL provided to ActionScript. This does not affect non-root
movies loaded through `Loader`.
This PR fixes a numbe of interconnected bugs:
* We weren't consistently uploading a dirty BitmapData to the render
backend before drawing to/from it.
* BitmapData.draw should *not* add a fill color - it should draw over
the current contents of the BitmapData
* After drawing to a non-transparent BitmapData, we need to manually
set the opacity back to 255 for each pixel (the drawing process
takes transparency into account, but the opacity information is
thrown away at the end).
Change `Bitmap::new()` to accept a `ruffle_render::bitmap::Bitmap`
directly, instead of `width`, `height` and `bitmap_handle`. As a
consequence, all `RenderBackend::register_bitmap_*` methods are no
longer necessary - we can use `ruffle_redner::utils::*` to obtain
a `ruffle_render::bitmap::Bitmap` right before calling `Bitmap::new()`.
`NaN` and large numbers are actually treated like `i32::MIN`. As described
in https://github.com/ruffle-rs/ruffle/issues/7772#issuecomment-1235977709,
Flash (at least 7+) fails to convert `i32::MIN` to a string due to a bug.
Since `i32::MIN` has no `i32` positive counterpart, digits extracted using
modulo are actually negative and characters before ASCII `'0'` are selected.
Flash 6- somehow return just `0` in those cases. This was Ruffle's behavior
up until this commit. This commit matches Ruffle behavior to latest Flash
Player, as we usually prefer. A `TODO` is still there in case we ever add
player version emulation.
These methods were incorrectly treating the argument as a local name,
instead of a qualified name. Additionally, 'getDefinition' now throws
an AVM error.
Previously, we would display an empty string for the method name.
We can now store a `&'static str` again in `NativeMethod`,
instead of needing a `Cow`
Instead of propagating the underlying compression library errors.
Also, make `ByteArray.deflate` and `ByteArray.inflate` pure-ActionScript
methods that call into the native `ByteArray.compress` and `ByteArray.uncompress`
native methods, respectively.
Since `serde-wasm-bindgen` doesn't support `#[serde(default)]` (https://github.com/cloudflare/serde-wasm-bindgen/issues/20),
we no longer able to deserialize a partial `Config` object. As a solution,
take care to pass a full object from the TypeScript side.
And make it generic, as a first step towards making it a general-purpose
data structure for the whole codebase. Some potential replacements are:
* `BoundingBox` in `render/src/bounding_box.rs`.
* `BoxBounds` in `core/src/html/dimensions.rs`.
* Parameters to a bunch of `BitmapData` methods in
`core/src/bitmap/bitmap_data.rs`.
Now that we have a custom `Error` enum, this is very straightforwawrd.
I've converted `getDefinitionByName` return an AVM error, since this
is commonly used by games to test for a class.
Main changes:
* Merge `ColorTransformParams` into `ColorTransformObject`, as it's only relevant for AVM1.
* Make `BitmapData::color_transform` work with a generic `ColorTransform`, which uses fixed-point
arithmetic.
Note that Ruffle still calculates color transforms slightly different from Flash. This is probably
caused by inaccuracy of the current `ColorTransformObject` to `ColorTransform` conversion and/or the
`ColorTransform` application logic itself. Since this requires further research, it'll be fixed in a
future PR.
While doing this I also noticed that we were incorrectly producing AmfValue::Integer if our
target AMF version is AMF0. This is incorrect because AMF0 is based on AS2, which does not
recognise Integer as a valid type, and therefore must be represented with Number instead.
This prevents the root from being constructed until we know its `SymbolClass`, and is roughly equivalent to delaying the work until `ShowFrame`. (We don't actually run any work on `ShowFrame` in our current movieclip impl.)
This is currently somewhat buggy, `homestuck_02791.swf` stops at 12% for some reason. I tried handing it both compressed and uncompressed lengths with no luck.
This requires estimating a count of bytes loaded of the original compressed stream, even though we only have uncompressed byte totals at this point. I instead rescale the uncompressed bytes by the compressed count to roughly estimate what would be the `bytesLoaded` had we been actually streaming bytes in and preloading them synchronously.
Backends that need synchronous preload behavior now explicitly ask for it as follows:
* `tests` - repeatedly call `preload` in a loop with an exhausted execution limit to stress-test the chunked preload
* `exporter`, `scanner` - synchronous/unlimited preload to match prior behavior
These may change in the future.
Actions are abstract; here we're using it to count bytes loaded (as a proxy for execution time). AVM code could potentially be adapted to count operations run instead.
An "empty clip" is any clip created by the `new` or `new_with_avm2` function, intended for dynamically-created movie clips with no association to a movie symbol.
The preload frame counting logic starts from one and continues to the end of the file, which results in a completely preloaded movie having one more frame "loaded" than there is in the file. This fixes that.
As usual, also bump its helper crates (`js-sys`, `web-sys` and
`wasm-bindgen-futures`) to the latest versions.
Due to https://github.com/rustwasm/wasm-bindgen/pull/3031, use the
`serde-wasm-bindgen` crate as a replacement to the deprecated
`JsValue::from_serde` function.
Previously, we would only use mergeAlpha if alphaBitmapData
and alphaPoint. However, mergeAlpha can be used even when
those parameters are null.
Some of the AVM1 argument handling was also incorrect - I've fixed
it, and extended the existing test with the output-based test
added for AVM2.
In several cases, the current code seems preferable to the
code required by `clippy::bool_to_int_with_if`. Let's suppress
this for now to get the build passing, and decide later if this
is something that we want to enable.
Previously, we would always use a transparent background,
even if the BitmapData is not transparent. This would normally
be corrected on the next frame when we copied the pixels to the
CPU. However, if an SWF ran `BitmapData.draw` on every frame,
this would never be corrected.
Our AVM2 `SharedObject` support is now *almost* equivalent
to our avm1 `SharedObject` support. We implement serialization
and deserialization for primitives, arrays, and `Object` instances
with local properties. We also implement serialization for `Date`,
but not `Xml` (since our AVM2 `Xml` class is just a stub at the moment).
This is enough to make 'This is the only level too' save level
progress to disk.
Currently, we always serialize to AMF3. When we implement
the `defaultObjectEncoding` and `objectEncoding`, we'll need
to adjust this.
An AVM2 movie can repeatedly remove and add a DisplayObject from/to
a parent. This was causing SolarMax to stop working after advancing
to the next level.
We now check if a BitmapData has been disposed by checking
for a zero width or height (which cannot happen otherwise).
As a result, we no longer need the 'disposed' field on the AVM1
BitmapData object.
* avm2: Implement `BitmapData.draw` for `wgpu` backend
This method requires us to have the ability to render directly to a
texture. Fortunately, the `wgpu` backend already supports this in
the form of `TextureTarget`. However, the rendering code required
some refactoring in order to avoid creating duplicate `wgpu` resources.
The current implementation blocks on copying the pixels back
from the GPU to the CPU, so that we can immediately set them in
the Ruffle `BitmapData`. This is likely very inefficient, but will
work for a first implementation.
In the future, we could explore allowing the CPU image data and GPU
texture to be out of sync, and only synchronized when explicitly
necessary (e.g. on `getPixel` or `setPixel` calls).
* Rename `with_offscreen_backend` to `render_offscreen` and use Bitmap
* Don't panic when backend doesn't implement `render_offscreen`
We already have `&mut self` available whenever we write to it,
and we never made use of the `Clone` impl. As far as I can tell,
we don't have any unimplemented features that would require a `GcCell`.
The stub implementation was breaking code that relied on being
able to set a value for 'mask' and then retrieve it
(which used to work on a dynamic class like `MovieClip`).
Change `set_matrix` and `set_color_transform` to accept owned structs,
instead of references. This allows callers that already have an owned
struct to pass it directly, thus saving an unnecessary borrow + clone.
This also aligns with other methods, such as `set_sound_transform`,
which currently accepts an owned struct.
The existing `Object` enum representation is problematic for inherited
native objects, since "regular" `ScriptObject`s cannot be turned into
native objects, but rather a completely new native object needs to be
created. `TObject::create_bare_object` is an attempt to aid this
situation, but it works only for `ActionExtends` inheritance, and not
when the user manually wires up `prototype`/`__proto__` (#701).
In Flash, it seems like derived constructors initially have a "regular"
`this` object. But once the `super()` constructor is invoked, the same
`this` object becomes a native object.
To allow this in Ruffle, introduce a new `NativeObject` enum, and
store it as a member in `ScriptObject`. For a start, move `TextFormatObject`
from the `Object` enum to `NativeObject`. The plan is to gradually
move all `Object` enum variants to `NativeObject`, except for `ScriptObject`.
For now, I've left 'dropTarget' unimplemented - unlike in
AVM1, the drop target can be non-interactive objects like `Shape`,
so we'll need additional refactoring to implement it.
This allows 'This is the only level too' to be playable
It was only used to make structs `#[derive(gc_arena::Collect)]`, and
generally it doesn't make much sense that `render` needs to be GC-aware.
So instead annotate `render` fields in `core` with `#[collect(require_static)]`.
This brings us closer to matching the Flash Player
enumeration behavior. Unfortunately, the precise enumeration
order for ScriptObject properties depends on the precise
order in the internal avmplus hashmap. This order is deterministic,
but adding/removing a property effectively randomizes it. Hopefully
there aren't any SWFS that depend on the *exact* order.
Handle removed clips inline in `Avm1::run_frame`, such that
`DisplayObject::prev_avm1_clip` is no longer used. Thus it can be
removed in a follow-up commit.
When we run a 'goto' where the initial and target frame are the same,
we need to skip triggering any sounds in the target frame.
Some games like 'This is the only level too' rely on this behavior:
they repeatedly run 'movieClip.gotoAndStop(current_frame_id)',
where 'current_frame_id' is the id of a frame that starts playing
a sound. Without this change, the sound will restart every frame
intead of playing exactly once.
We previously used 'coerce_to_object', which produced
an error with `Value::Null`. Instead, we can just ues
`value.as_type_of`, which will correctly handle `null`
The 'charCode' and 'keyCode' properties are now implemented
on `KeyboardEvent`
The input injection code we use does not support keyboard events,
so we can't yet write a regression test for this. However,
both 'You need to burn the rope' and 'This is the Only Level TOO'
now properly handle keyboard events with this PR.
* avm2: Implement call stack
* avm2: Class traits should have a special prefix
* avm2: Stack tracebacks should also contain error message
* avm2: Move method naming to Executable
* avm2: Handle getter and setter methods in tracebacks
* chore: Formatting
* chore: Add comments
* avm2: Make full_name write to a string, instead of creating a new one
* core: Make GcArena publicly accessible
* core: Add Deref impl for Either type
* desktop: Add AVM2 call stack to panic message
* avm2: Prefix native methods with a `/`
* chore: Appease clippy
* avm2: Check if method actually contains bytecode instead of unwrapping
* web: Add AVM2 stack trace to panic message
* chore: Formatting
* chore: Clippy
* avm2: Fix stack traces for free standing functions
* core: Remove global data from context
* core: Rename GcGlobalData to GcCallstack
* core: Introduce StaticCallstack, make GcArena private again
Co-authored-by: Adrian Wielgosik <4729533+adrian17@users.noreply.github.com>
Declare `NaN`, `Infinity` and `undefined` in ActionScript, similarly
to how `avmplus` does in its `actionscript.lang.as`.
Note that `null` is only removed, without an ActionScript declaration,
as it seems like `avmplus` neither declares it. Probably `null` is
only usable as a compile-time constant.
Extract `swf::Reader::read_do_abc()` which, as the name suggests,
reads a `DoAbc` tag, and use it before calling to `Avm2::load_abc`.
Finally, introduce `DoAbcFlag` using `bitflags`.
This greatly simplifies the ABC loading code.
This is in keeping with the whole idea of a "recursive frame": gotos run the entire frame lifecycle on the target clip, including broadcasts for `frameConstructed` and `exitFrame`.
We still retain the queue system as events are fired at removal time, and those events can trigger more gotos. If such a goto happens, AS3 code will hit a clip still in the old state rather than an inconsistent one. I don't have test coverage for this exact scenario just yet.
The rationale for the catch-up logic is as follows:
* We must always enter-frame and construct objects, even if those respective display events haven't happened yet.
* Display objects created in event handlers still need to run catchup phases, otherwise they will tag-stream desync
* Frame scripts are never triggered by catchup phases
* `exit_frame` is not a catchup phase as it is *only* an event broadcast currently
Normally a function closures also closes around its base clip.
If the base clip is removed, and then the function is executed, the
base clip then defaults to `this`.
However, Ruffle was incorrectly using the wrong base clip when
loading the `_root` and `_parent` registers in this case.
Fixes#5645.
This PR implements the `Loader.load` method, as well as
the associated `LoaderInfo` properties and events.
We can now load in an external AVM2 SWf: it will be added
as a child of `Loader` object, and will render properly
to the screen.
Limitations:
* The only supported `URLRequest` property is `url`
* `LoaderContext` is not supported at all - we always use the default
behavior
* Only `Loader.load` is implemented - we do not yet support unloading.
* We fire a plain 'Event' for the 'progress' event, instead of using
the (not yet implemented) 'ProgressEvent' class
The main changes in this PR are:
* The AVM2 `Loader` class now has an associated display object,
`LoaderDisplay`. This is basically a stub, and just renders
its single child (if it exists).
* `LoaderStream::Stage` is renamed to `LoaderStream::NotYetLoaded`.
This is used for both the `Stage` and an 'uninitialized'
`Loader.contentLoaderInfo`. In both cases, certain properties throw
errors, while others return actual values.
* The rust `Loader` manager now handles both AVM1 and AVM2 movie loads.
Previously, the viewport height and width were stored in
both `Stage` and the `RenderBackend`. Any changes to the viewport
dimensions (e.g. due to window resizing) needed to be updated in both
places to keep our handling of the viewport consistent.
This PR adds a new `ViewportDimensions` type, which holds the
width, height, and scale factor. It is stored inside the
`RenderBackend` impl, and is retrieved using the newly added
method `RenderBackend.get_viewport_dimensions`. After a `Player`
has been constructed, any code that needes access to the viewport
dimensions will ultimate go through this method.
Unfortunately, `Stage` needs to use the viewport dimensions
in `build_matrices`. Therefore, any code modifying the viewport
dimensions should go through `player.set_viewport_dimensions`,
which ensures that the stage matrices are rebuilt after the render
backend is updated.
When doing mouse picking, interactive children were considered
before all non-interactives, which could cause an `_droptarget` to
be set to an underlying movieclip even if a shape occluded it.
Now consider all children in render order so that the top-most
shape will capture the mouse input.
If we try to go to a frame that doesn't exist, or hasn't been loaded yet, we will stop on the last available frame, but skip any tags that would have run there. This is technically a desync, but it hasn't caused any problems so far as any further timeline interaction would trigger a rewind (which isn't affected by desyncs).
Of course, now that we're actually testing the tag stream position it *does* cause problems. We actually have to fix up the position to be correct even though it will never be used (hopefully). It may be prudent to do this outside of the `timeline_debug` feature as well in the future.
Each render backend keeps track of a stack of BlenModes,
which are pushed and popped by 'core' as we render objects
in the displaay tree. For now, I've just implemented BlendMode.ADD,
which maps directly onto blend mode supported by each backend.
All other blend modes (besides 'NORMAL') will produce a warning
when we try to render using them. This may produce a very large amount
of log output, but it's simpler than emitting each warning only once,
and will help to point developers in the right direction when they
get otherwise inexplicable rendering issues (due to a blend mode
not being implemented).
The wgpu implementation is by far the most complicated, as we need
to construct a `RenderPipeline` for each possible
`(BlendMode, MaskState)`. I haven't been able to find any documentation
about the maximum supported number of (simultaneous) WebGPU render
pipelines - if this becomes an issue, we may need to register them
on-demand when a particular blend mode is requested.
This PR implements the 'DisplayObject.transform' getters/setters,
and most of the getters/setters in the `Transform` class
From testing in FP, it appears that each call to the
'DisplayObject.transform' property produces a new
'Transform' instance, which is permanently tied to the
owner 'DisplayObject'. All of the getters/setters in
`Transform` operate directly on owner `DisplayObject`.
However, note that the `Matrix` and `ColorTransform`
valuse *produced* the getter are plain ActionScript objects,
and have no further tie to the `DisplayObject`.
Using the `DisplayObject.transform` setter results in
values being *copied* from the input `Transform` object.
The input object retains its original owner `DisplayObject`.
Not implemented:
* Transform.concatenatedColorTransform
* Transform.pixelBounds
When a DisplayObject is not a descendant of the stage,
the `concatenatedMatrix` property produces a bizarre matrix:
a scale matrix that the depends on the global state quality.
Any DisplayObject that *is* a descendant of the stage has
a `concatenatedMatrix` that does not depend on the stage quality.
I'm not sure why the behavior occurs - for now, I just manually
mimic the values prdduced by FP. However, these values may indicate
that we need to do some internal scaling based on stage quality values,
and then 'undo' this in certain circumstances when constructing
an ActionScript matrix.
Unfortunately, some of the computed 'concatenatedMatrix' values
are off by f32::EPSILON. This is likely due to us storing some
internal values in pixels rather than twips (the rounding introduced
by round-trip twips conversions could cause this slight difference0.
For now, I've opted to mark these tests as 'approximate'.
To support this, I've extended our test framework to support providing
a regex that matches floating-point values in the output. This allows
us to print out 'Matrix.toString()' and still perform approximate
comparisons between strings of the format
'(a=0, b=0, c=0, d=0, tx=0, ty=0)'
This is the last stub needed for Wonderputt to reach the
main game screen.
As far as I know, ActionScript cannot observe a frame being rendered,
so implementing this method isn't actually necessary for correctness.
The benefit of implementing this would be to make certain animations
appear smoother, since we'll render changes to the scene without
needing to wait for the next frame. However, actually rendering
*immediately* after the event would require some refactoring -
we have a `&mut UpdateContext` while running timers, but we'd need
to bail out and obtain a `&mut Player`.
Many of the class property defintiions were wrong -
instance methods were defined as class properties,
and class properties were defined as instance properties.
This allows Wonderputt to get further (it deliberately assigns
'null' to 'URLRequest.data'). We throw an exception for any other
value, to prevent confusing errors caused by attempting an
unexpected request to a web server with a missig body.
We currently lack the ability to preserve the original
`Value<'gc>` in the error, so we're forced to stringify the error.
This means that only typeless 'catch' blocks will work properly -
however, they're the only kind of 'catch' block that we currently
implement. Implementing support for typed 'catch' blocks will naturally
allow us to preserve the original 'Value<'gc>' in the 'throw'
implementation, since we'll need to switch to a custom `Error<'gc>`
type.
* avm2: Include class name in ScriptObject debug
Currently, the `ScriptObject` debug impl is almost useless -
while you determine if two printed objects are the same
by comparing the pointer value, you'll have no idea what
kind of object it actually is.
This PR now formats the `ScriptObject` output as a struct,
printing a (fake) "class" field containing the class name.
Before/after:
```
[ERROR ruffle_core::avm2::activation] AVM2 error: Cannot coerce Object(ScriptObject(ScriptObject(GcCell(Gc { ptr: 0x55f863936db8 })))) to an QName { ns: Private("Test.as$38"), name: "Second" }
[ERROR ruffle_core::avm2::activation] AVM2 error: Cannot coerce Object(ScriptObject(ScriptObject { class: "Object", ptr: 0x55ee0ad161e0 })) to an QName { ns: Private("Test.as$38"), name: "Second" }
```
Getting access to the class name from a `Debug` impl is tricky:
Developers can (and should be able to) insert logging statements
whereever they want, so any `GcCell` may be mutably borrowed.
Panics in debug impls are extremely frustrating to deal with,
so I've ensured that we only use `try_borrow` at each step.
If any of the attempted borrows fail, we print out an error message
in the "class_name" field, but we're still able to print the
rest of the `ScriptObject`.
Additionally, we have no access to a `MutationContext`, so we
cannot allocate a new `AvmString`. To get around this,
I've created a new method `QName::to_qualified_name_no_mc`,
which uses an `Either` to return a `WString` instead of allocating
an `AvmString`. This is more cumbersome to work with than the
nrmal `QName::to_qualified_name`, so we'll only want to use
it when we have no other choice.
An exception thrown by one event handler shoud not prevent other event
handlers from running on this same event. Some SWFs like Wonderputt
depend on this behavior, as they have buggy event handlers that throw
errors.
Calling `get_trait` copies the returned `Property`, so the caching
we performed in `PropertyClass` was never actually getting used.
Instead, we now store our `PropertyClass` values in a `Vec`
indexed by slot id. `set_property` and `init_property` now perform
coercions by going through the `VTable,` which writes the updated
`PropertyClass` back into the array.
FP allows code like
`class Foo { static var INSTANCE: Foo = new Foo(); }`
However, this breaks our current property type coercion setup -
we cannot resolve the type `Foo` when setting the property `INSTANCE`,
since `Foo` is still being constructed.
Fortunately, we can perform this 'coercion' by just checking if
the object's class name and domain match the type name and domain
of the property.
This returns the approximate interval that the audio backend
updates the sound position information. This is used for syncing
animation to embedded "stream" audio tracks, and fixes some
stuttering in cases where the syncing was being too strict.
Previously, we would create a fresh `LoaderInfo` object each
time the `loaderInfo` property was accessed. However, users can
add event handlers to a `LoaderInfo`, so we need to create and
store exactly one `LoaderInfo` object per movie (and stage).
To verify that we're correctly handling the storage of `LoaderInfo`,
I've implemented firing the "init" event. This required a new
`on_frame_exit` hook, so that we can properly fire the "init"
event after the "exitFrame" for the initial frame but before
the "enterFrame" of the next frame.
The current 'setInterval/setTimeout' implementation is
moved to 'core/src/timers.rs', and now works with both
AVM1 and AVM2 objects. The `flash.utils.Timer` class is implemented
mostly in ActionScript, with minimal modifications to the actual
Ruffle timer code.
* avm2: implement string replace where pattern is string and replacement is a function
* * removed unnecessary vec!
* fixed "no newline at the end of file"
This commit adds support for combining instance allocators with
ActionScript playerglobal class definitions. This is activated
by defining the metadata `[Ruffle(InstanceAllocator = "true")]`
on the ActionScript class definition.
The implementation of this feature is very similar to native methods:
`build_playerglobal` checks for the metadata described above,
and defines a const `NATIVE_INSTANCE_ALLOCATOR_TABLE` mapping
class ids to function pointers.
To demonstrate this feature, I've converted `Event` to ActionScript
(keeping the existing instance allocator function).
I've also converted `ActivityEvent` and `ContextMenuEvent` to
`ActionScript`, to demonstrate how this simplifies inheritance.
In a future PR, we can convert the remaining events to ActionScript,
and remove the `EventData` enum entirely.
Unfortunately, `flex-sdk`'s `asc.jar` compiler strips out all metadata
when the `-optimize` option is passed. As a result, I forked
`flex-sdk` and disabled this behavior:
https://github.com/ruffle-rs/flex-sdk/releases/tag/ruffle-1.0.0
The modified `asc.jar` (built from the forked repository)
is included in this PR, and replaces the our previous 'asc.jar'
downloaded from the official Flex SDK release.
* Change metadata to `[Ruffle(InstanceAllocator)]`
* Strip out metadata before saving bytecode
* avm2: implement string.replace(...) with fn, for now regex only.
* string - added path for replacing regex with fn (replacing string
with fn is still unimplemented)
* regex - factored out common replace logic for when replacement is
a string and when it is a function
* added tests
* Addressed review comments
* removed tinkering cruft; formatting
* addressed review comments
This commit adds support for marking methods as `native`
in ActionScript classes defined in playerglobal. The
`build_playerglobal` now checks for native methods, and
generates Rust code linking them to a corresponding Rust
function definition in the codebase.
To test this functionality, I've reimplemented several
functions as native methods (and moved related code to
pure ActionScript).
* avm2: implement string.split for regex
* Compressed the testing for regexp and unwrapping thereof
* * Moved the split logic into the regex object
* Factored out a method for utf-16 matching
* Added tests
* formatting
* * replaced manual counting with storage.length()
* clippy cleanup
* Address review comments
* fix import path for WString
* remove redundant variable in return statement
* error passing via '?' instead of unwrap()
Though https://github.com/rust-lang/rust-clippy/pull/8355 has been
merged, it seems to still report false-positives on nightly channel.
For now just fix the instances reported by stable clippy, and keep
`needless_borrow` allowed.
The register index was not being increment when preloading the
`super` register which would cause issues when multiple registers
were preloaded.
Fixes#7338.
Alongside comment wordings, fix handling of non-`u8` characters by
replacing `as u8` conversions with `u8::try_from()`, that doesn't
wrap around, but rather fails gracefully.
Based on the work in #6717, plus additional adaptions mentioned in
https://github.com/gfx-rs/wgpu/blob/master/CHANGELOG.md#wgpu-013-2022-06-30,
and more not-mentioned but required changes.
Also bump `wasm-bindgen` to `0.2.81` (along with its helper crates), as
required by the new `wgpu` version.
Note that I don't fully understand some of the required changes, notably:
* `wgpu::PresentMode::Mailbox` no longer works on my machine (Windows 11) -
The `wgpu` documentation says that `wgpu::PresentMode::Fifo` is the
only guaranteed to be supported, so I switched over to it instead.
* `self.staging_belt.recall()` doesn't return a `Future` anymore -
I assume it became synchronous so I simply removed the `executor`
from there.
Properties can be declared with a type
(e.g. `var foo:MyClass = new MyClass();`). When
`set_property`/`init_property` is invoked for that property,
the VM will attempt to coerce the value to the provided type,
throwing an error if this fails. This can have observable behavior
consequences - if a property has type `integer`, for example, then
storing a floating point `Number` to that property will cause the
value to be coerced to an integer. Some SWFs (e.g. 'Solarmax') rely
on this behavior in order to implicitly coerce a floating point value
that's later used for array indexing.
This PR implements property type coercions in Ruffle. There are several
important considerations:
* The class lookup for property types needs to be done lazily, since
we can have a cycle between two classes (e.g. `var prop1:Class2;`
and `var prop2:Class1` in two different classes).
* The class lookup uses special rules (different from
`resolve_definition`), and does *not* use `ScopeStack/`ScopeTree`
This means that a private class can specified as a property name -
the lookup will succeed without using a scope, even though
`flash.utils.getDefinitionByName` would fail with the same name
* The specialized 'Vector' classes (e.g "Vector$int") can be used
as property types, even though they cannot be lookup up normally.
Some Ruffle class definitions were previously using nonexistent
classes as property types (e.g. "BareObject") - these are fixed
in this PR.
- Handle the case where both preload aud suppress flags are
set for the same variable;
- Remove `arguments` field in `Activation`; instead use a normal
local definition;
- When `suppress_this` is set, inherit the `this` value from parent
activation. (This isn't entirely correct, as FP's `this` is mutable
and seems to be part of the scope chain, but this would require a
larger refactoring)
Currently, all three render backends hold on texture-related
resources indefinitely (`register_bitmap` pushes to a `Vec`,
and never removes anything). As a result, the resources used
by the render backend (which may include GPU memory) will grow
over time, even if the corresponding `BitmapData` has been deallocated.
This commit adds a new `unregister_bitmap` method, which is called from
`BitmapData.dispose`. All render backs are changed to now use an
`FnvHashMap<BitmapHandle, _>` instead of a `Vec`, allowing us to
remove individual entries.
Currently, we only call `unregister_bitmap in response to
`BitmapData.dispose` - when `BitmapData` is freed by the
garbage collector, `unregister_bitmap` is *not* called.
This will be addressed in a future PR.
I've kept the rust `flash.geom` module, even though it's now empty,
since we'll need to add things like `flash.geom.Transform` native
methods in the future.
* AVM2: Implement escape()
* chore: Fix formatting
* avm2: Escape resolves non strings to null and use push to append
* chore: Fix nits
* avm2: Escape should coerce objects, add early returns
Previously all the `.as` files compiled into `playerglobal.swf`
were detected automatically using `walkdir`. While this might be
convenient, it can cause unexpected results when untracked `.as`
files exist. So instead, introduce two entry points - `stubs.as`
and `globals.as`, which include all stub ActionScript definitions,
and actual class implementations, respectively. This also simplifies
the `playerglobal.swf` build script a bit.
`flash.geom.Rectangle` is a good candidate, since it doesn't have
any native function, and it depends only on `flash.geom.Point`,
which was already been ported to ActionScript in #7071.
This PR adds support for building a custom `playerglobal.swf`, which can be used
to implement builtin Flash classes in ActionScript. This file is embedded into Ruffle
using `include_bytes!`, and loaded during initialization.
As an example, the `Point` class is reimplemented
in ActionScript, and `flash.text.AntiAliasType` is added.
The ActionScript compilation process is performed by `core/build.rs`.
See that file, along with `core/src/avm2/globals/README.md`, for
more details.
The `render_list` for a container always contains all of the children
under both AVM1 and AVM2 - howver, the depth_list may not contain
some children under AVM2.
When we're not performing some AVM1-specific operation
(e.g. `getInstanceAtDepth`, or dumping out AVM1 variables),
we should be using the render list.
This stubs out BlurFilter, adds properties to GlowFilter,
and make the getter for DisplayObject.filters return
an empty array instead of Undefined.
This is all of the filter-related code that 'Solarmax'
needs in order to reach the main screen (combined with
other unrelated changes I have yet to submit)
Previously, there was an off-by-one bug in `get_enumerant_name`,
which caused us to produce a spurious 'null' as a key.
However, the 'dictionary_foreach' test only checked that certain
keys were present, so the presence of an additional key didn't break
the test.
This commit makes Dictionary enumerants behave in the same way as
Array enumerants - all of the object-specific enumerants
(in this case, the non-primitive dicitonar keys) come first,
followed by 'base' enumerants from ScriptObject (in this case,
primtive/String keys). Additionally, `setPropertyIsEnumerable` is now
ignored for `Dictionary`, consistent with Flash's behavior.
The `dictionary_foreach` test is updated to print out all of
the keys when inspecting the dictionary. Since the enumeration
order is unstable (under both Flash and Ruffle) due to the dependency
on pointer hashing, the test sorts the keys before printing them.
This ensures that we get stable output which is consistent between
Ruffle and Flash.
Flash Player allows this, and returns the path to the root SWF file.
The test only checks that the returned path contains 'test.swf',
to avoid depending on a platform-specific path.
The loop to search for a `non_hole` was missing
a `break;`, so it would actually find the *first*
non-hole, rather than than the last. This was not caught
by the test, since there was only one "real" element
in the array (the other one was set on 'Array.prototype')
Since all `RenderBackend::register_bitmap_*` implementations are
identical now, move them to the default implementation of `RenderBackend`.
Also, turn `RenderBackend::register_bitmap_raw` into `RenderBackend::register_bitmap`,
which accepts a single `Bitmap` parameter.
Replace direct instatiations of `swf::Matrix` where only `tx` and
`ty` are specified, and other fields are default.
This results in a slightly more shorter, readable code.
A method called with `super` is always an instance method,
so we should be using `instance_scope` for consistency with
`call_property`. This fixes a bug where a method cannot
access static class members (via `getlex`) when called bia
`super.method()`
In several places, we read some data from a tag, and then pass
the original tag length to `resize_to_reader`. This is incorrect -
the provided length is used an an offset from the current position
in the reader, so we will extend past the end of the current tag if
we've already read some bytes.
In practice, this doesn't appear to cause any problems - AVM bytecode
has internal length fields, which end up ensuring that we will never
try to read past where the slice *should* end. However, if a `DoAbc`
tag is the last tag in the file, then we'll end up trying to use
`resize_to_reader` with an offset past the end of the movie.
This commit subtracts the number of already-read bytes from `tag_len`,
to ensure that we always construct a correctly-sized `SwfSlice`
Store just the XML declaration string itself, rather than the attributes
it consists of. Then simply return it in ActionScript's `XML.xmlDecl`
property, without using `quick_xml::Writer` at all. This also matches
Flash behavior by capturing the XML declaration as-is, preserving
whitespaces, quotes, casing etc.
Prior to this commit, executing frame scripts on a movie that doesn't have them for this frame, or didn't advance to a new frame, would cause the the movie to ignore all gotos until the next time it ran a frame script.
This PR implements the `URLLoader` class, allowing AVM2 scripts
to load data from a URL. This requires several other related
classes (`URLLoaderDataFormat`, `URLRequest`, `IOError`) to be
implemented as well.
Currently implemented:
* Fetching from URLs using the 'navigator' backend
* The `text` and `binary` data formats (which store data
in a `String` or `ByteArray` respectively)
* The `open`, `complete`, and `ioError` events
* The `bytesLoaded`, `bytesTotal`, and `data` properties
Not yet implemented:
* The HTTP and security events
* All of the properties of `IOError`
* The properties on `URLRequest` (besides `url`)
* The "variables" data format
This should be enough to get some basic uses of `URLLoader` working
(e.g. simple GET requests to a particular website).
Note that in Flash's `playerglobal`, the `URLLoader` class is just
a think wrapper around the more general `URLStream`. However,
implementing `URLStream` will require changes to `Navigator``
to support notifications when data arrives in the stream. When
that happens, we should be able to re-use a large amount of the
code in this PR.
Guarantee bitmap data after decoding has the expected length for
the given width+height+format. This eases the burden from backends
to worry about this. Pad or truncate the data if it doesn't have
the expected size.
Due to various quirks of how timeline-initiated symbols interact with AVM2, it is possible for user code to gain a reference to uninitialized objects (especially `SimpleButton` which doesn't initialize until after `exitFrame`). It is still possible to attach event handlers to them that fire correctly, and movies expect to be able to.
Internal function calls such as `toString` and event handlers
always used the base clip from the function itself, so add an
`ExecutionReason::InternalCall` to signify this and pass it along
to `call_method`.
Fix various scope behavior when executing a function:
* For function calls in SWFv6+, functions are proper closures and
close over the SWF version, base clip, and scope of their
defining function.
* Function calls in SWFv5 are not closures, and use the version,
base clip, and scope of `this` when the function is called.
Fixes#5502.
Testing under Flash shows that methods can be considered 'unchecked'
(allowing them to be called with more arguments than declared
parameters) even if they have a declared return type.
This is relied on by SteamBirds, which registers an event handler
which takes 0 parameters and an explicitly declared return type
This was recently added in https://github.com/rust-lang/rust/pull/96150
Some of the `__version` rules are currently unused, but I assume
that we still want to keep them for potential future use.
This module is now mostly empty, so move the items up to `globals`.
`getDepth` was the only shared method, so declare this property
inline in each display object type. `Video` was also incorrectly
declaring `getDepth`.
Remove `_root`, `_parent` and `_global` from `MovieClip.prototype`.
Instead, these are "magic" properties similar to `_x` and `_y`.
Add `StageObject::resolve_path_property` to handle these, alongside
the `_levelN` property.
Fixes#768.
The remaining caller was `SwfMovie::from_path`, which is now changed
to be simpler, and a little stricter (panics if `Url::from_file_path`
fails, though it shouldn't happen with canonicalized paths).
Remove the `swf_version` parameter from `Activation` constructors,
because this was incorrectly using the global or root SWF version
most times.
Instead, grab the SWF version for the activation directly from the
base clip.
Use a bare `ScriptObject` instead. This matches Flash's behavior in
many aspects:
* Attribute values can now store arbitrary AVM1 values, rather than
just strings. These are coerced to string lazily on demand (e.g.
when coercing the whole XML node to a string).
* Attributes iteration order is the same as their definition order,
not sorted by their name.
Also fix some bugs in `XmlNode::lookup_namespace_uri` (renamed from
`lookup_uri_for_namespace`):
* Iterate attributes by their definition order, so the first matching
one is returned.
* The empty prefix matches every attribute that starts with "xmlns"
(with/without a colon).
And inline `XmlNode::lookup_namespace_for_uri` into `get_prefix_for_namespace`,
and fix some bugs in there as well:
* Iterate attributes by their definition order, so the first matching
one is returned.
* Match any attribute that start with "xmlns" (with/without a colon).
The colors in a DefineBitsJPEG3 tag should be premultiplied alpha,
but in some SWFs they are incorrectly not premultiplied. Flash
Player clamps the color values to the alpha in this case to allow
these images to work more as expected.
Fixes#6893.
The resolved URL only used by `NavigatorBackend::fetch`. So simply
inline `NavigatorBackend::resolve_relative_url` into `NavigatorBackend::fetch`,
per implementation.