Compare commits

...
278 Commits
Author SHA1 Message Date
Luke Usher 1e6e9fd36e ares v141 2024-11-04 10:19:26 +00:00
Fernap 8111bf3163 Fix for SA-1 side DMA to BWRAM banks 0x41+ (#1687)
DDA was incorrectly capped at 16 bits instead of 24, making DMAs to
BWRAM banks 0x41-43 be sent to the corresponding spot in 0x40 instead.
See [the corresponding bug in
bsnes](https://github.com/bsnes-emu/bsnes/issues/309) for some more
context.
2024-11-02 14:26:09 +00:00
jcm c287c1b225 build: macOS back-compatibility fixes (#1682)
While checking out minimum requirements for the new build system, found
a couple small issues worth fixing:

* librashader was not operable on systems pre-macOS 12 with a linker
issue; it can be resolved by setting a minimum deployment target; here
we do that by setting an environment variable on CI.
* While investigating this, I found that librashader's minimum required
macOS seems to be 10.15; this is because `glslang` seems to require
macOS 10.15.
* It wasn't possible to build the Metal driver because of the older SDK
lacking some definitions; however, we can fall back to the
`__MAC_OS_X_VERSION_MAX_ALLOWED` compile definition which we do here.
* Not sure if building on these older systems should really be
considered "supported", but since the fix here was simple enough it
seems fine to throw it in.

paraLLEl-RDP and MoltenVK seem to have [a lot of
issues](https://github.com/user-attachments/assets/088879a9-9153-4b05-a207-212cfac7f831)
on my older system's GeForce 650M. I was able to compile debug MoltenVK
locally, but Xcode GPU capture just hung, so I was unable to figure out
what was going on. Either a driver issue or a MoltenVK issue seems like
the probable culprit. In any case, performance wasn't really good enough
to make me want to investigate further. Other cores seem to work well.

Tested [on my fork's
CI](https://github.com/jcm93/ares/actions/runs/11554703214) to make sure
everything still works.
2024-10-28 15:30:08 +00:00
Giovanni Bajo 863593ed7f n64: remove call to epilogue function from the jit (#1663) 2024-10-28 11:44:11 +00:00
Giovanni Bajo c20d405006 n64: add unusual warning when using CACHE on uncached addresses (#1678)
The CACHE opcode does not work correctly when the specified virtual
address is in an uncached segment. The exact hardware behavior has not
been reversed yet (we know for instance that when doing cache
invalidation, some other cacheline is invalidated instead, but we do not
know the relation yet).

Nonetheless, the behavior is really obscure and all usages should be
considered bugs. Add a debug unusual warning for now (mainly to help
developers, as this is a known instance where Ares doesn't yet follow
hardware behavior).
2024-10-28 11:43:17 +00:00
png183 e1e1bedb2d gba: selectively synchronize CPU and APU, and add option to disable pixel accuracy (#1679)
Similarly to how the S-CPU and S-SMP are handled in the SFC core, it's
possible to run the GBA CPU and APU more asychronously as long as
synchronization is performed on FIFO or APU I/O accesses. From my
testing on Linux, this performs comparably to the performance profile
but without the accuracy downsides, so the performance/accuracy profiles
have been removed (the more accurate behaviour is now always used).

This PR also adds an option to disable pixel accuracy in the GBA core in
exchange for ~10-15% performance benefits, and makes some small PPU
timing improvements that were not feasible to implement in the
performance profile.
2024-10-28 11:43:07 +00:00
Chase Meadors 9f060c769b Allow arbitrary and possibly unaligned writes to RDRAM through gdb (#1639)
We want to allow arbitrary writes through the GDB server to the RDRAM
area. This was done in #1620, but that version has a subtle issue where
the server will still refuse to write or change writes that happen to be
of size `Byte|Half|Word|Dual` if the addressed is not aligned to that
size.
This PR fixes the issue by checking if the write is to RDRAM first,
allowing arbitrary and possibly unaligned writes. Otherwise, the write
is handled through the normal machinery where these issues may be
semantically important.
2024-10-27 15:14:30 +00:00
remutro e7f9af4bbd [N64] allow for pak swapping on controller port 1 (#1672)
This pull request allows for all pak swapping on controller port 1 only.
It also enables support for the transfer pak for the 64DD which was
previously missing.

It is being added for port 1 only now because there is additional work
to manage all the different saves, and gameboy games/saves with the
transfer pak which is a larger effort, and Luke is currently looking
into modifying settings in a more complete manner. So other ports can be
added later. For most people, being able to swap for the first
controller is likely good enough.

This pull request doesn't change any of the current initialization logic
regarding default pak selection that already existed.
2024-10-26 07:53:52 +01:00
jcm 65c34c2ea4 nall: Namespace noinline macro (#1674)
This is a change spun off from continuing build system work.

There, we've found that precompiling the `ares/ares.hpp` header can
speed up compile times for the emulator cores by 30-35%. Doing so,
however, leads to a few collisions:

* Several files in parallel-rdp use the `Hash` type, which variously
resolves to a `Hash` in its own namespace as well as nall's namespace.
* Also in the N64 core, nall's `noinline` macro conflicts with similar
definitions present in `xxhash`.

For parallel-rdp, we can simply skip precompiled headers for the
conflicting files; parallel-rdp does not use anything in the
`ares/ares.hpp` header, so including it there is unnecessary anyway.

This change resolves the second set of collisions by putting nall's
noinline preprocessor macro into its own namespace.

There are many macros remaining that are not namespaced. I did not
proceed in namespacing them for this PR, because there are a lot of
them, and it would be a fairly significant code style change that
probably merits further discussion (not to mention, it will be a decent
amount of work). However, in this instance, there is (or will be) a
material benefit that probably trumps the minor style issue.
2024-10-26 07:53:36 +01:00
png183 9babe6a02b gba: OBJ timing improvements (#1676)
Implements a couple improvements to OBJ-related timings:

- OBJs are now rendered one scanline in advance, as on hardware
- OBJ palette RAM accesses are now performed in `PPU::Objects::run`
rather than `PPU::Objects::scanline`, bringing OBJ PRAM access timings
closer to matching hardware
2024-10-26 07:53:20 +01:00
png183 7e5292cd16 gba: horizontal mosaic fixes (#1669)
Addresses an off-by-one error with BG mosaic, and fixes an oversight in
how OBJ mosaic was handled at x=0.
2024-10-22 11:32:42 +01:00
remutro a8274cd127 [N64] Add support for 40 Winks (Aftermarket) and support for additional supported regions (#1666)
40 Winks was released aftermarket on physical media, and support has
been added for this (does NOT include prototypes). The US version was
tested, but was unable to test the EU release (game Id and pak options
should be the same and should theoretically work).

Additionally, looks like ares was missing some region descriptions, so
these have been added as well based on info located at:
https://n64brew.dev/wiki/ROM_Header#Advanced_Homebrew_ROM_Header
2024-10-18 11:11:07 +01:00
Giovanni Bajo d99b0a3725 n64: use different GDB signals for different exceptions (#1667)
When debugging homebrew with gdb, it might be annoying if gdb stops at
exceptions that are correctly handled by the running application. This
is a bit hard to know so, besides providing some (debatable) default, we
need a way to selectively ignore specific exceptions.

This commit generates different GDB signals for different families of
exceptions. The mapping between MIPS exceptions and UNIX signals is
completely arbitrary; it tries to "sort of" match the meaning of the
exception where possible, and otherwise just use a random signal.

The GDB client can configure which signals should be logged, which
should cause the application to stop, and which should be ignored, using
the "handle" command.

By default, we want to ignore exceptions generated by interrupts (as
those are normally handled by the application) and those handled by the
operating system (like the COP1 exception which both libultra and
libdragon use to speed up context switching). To do so, we assign to
them signals that are ignored by default by gdb (SIGWINCH and SIGURG
respectively).
2024-10-16 06:32:31 +01:00
Luke Usher e43f3f75f7 add ymfm to update-subtrees script 2024-10-08 11:48:21 +01:00
Luke Usher f894a85253 Merge commit '09fbcc4e65efe68eefc6d4f502fd92cb9ee310b4' 2024-10-08 11:33:31 +01:00
Luke Usher 09fbcc4e65 Squashed 'thirdparty/ymfm/' changes from d641a80631..d334ab1a95
d334ab1a95 Fix left-shift signed overflows (UB) (#62)
434e793dc4 Assert that only valid timer numbers are passed to engine_timer_expired().
16e1d4281a Use snprintf instead of sprintf to fix #59. Use std::array for operators to remove the need for array_size.
4e654a3e8f Add virtual destructors to all base abstract classes, to prevent memory leaks (#55)
1a5cc66cb6 Keyon all ops on CSM mode (#56)

git-subtree-dir: thirdparty/ymfm
git-subtree-split: d334ab1a957351ce2a0aa2777b8c704664be3189
2024-10-08 11:33:31 +01:00
Luke Usher 73d90e6e7c Merge commit '38dd6defa99bb03aa5e4dc2fc1f492b2e85aa10c' 2024-10-08 11:33:15 +01:00
Luke Usher 38dd6defa9 Squashed 'thirdparty/slang-shaders/' changes from ec1b855638..263a54c414
263a54c414 Update crt-ntsc-sharp presets (#642)

git-subtree-dir: thirdparty/slang-shaders
git-subtree-split: 263a54c414681b45fd9428143a8320f4024a99ab
2024-10-08 11:33:15 +01:00
Luke Usher 030488aba7 Merge commit 'b2175473f0476248724ba73bb80b71a1c669797d' 2024-10-08 11:33:01 +01:00
Luke Usher b2175473f0 Squashed 'thirdparty/librashader/' changes from 4abd48eb24..cbdbdafecd
cbdbdafecd chore: Release
ffcb8ba1d1 doc: Update BROKEN_SHADERS.md
941275199b build: unpin cc
525c311844 cli: allow raw-id for spirv output
2fe66d958f reflect: put vars to end with running link pass to fix naga ordering
ed8bf637a9 cli: size_of not in prelude
7555bb9024 build: make librashader-reflect features-table more consistent
562e1e5f18 doc(msrv): bump msrv to 1.78
13b44e1639 cargo: revert lockfile version
240aae1bcf chore: Release
95a489ee12 cli(render): allow specifying output dimensions

git-subtree-dir: thirdparty/librashader
git-subtree-split: cbdbdafecdfd6113ef1cdc15e0a4140b46420f0b
2024-10-08 11:33:01 +01:00
Luke Usher bc2a54800f fix sljit after update 2024-10-05 12:56:24 +01:00
Stefan Schlosser 6e182d8542 thirdparty/librashader: activate runtimes in librashader_ld.h 2024-10-05 12:37:24 +01:00
jcm 38f64fa70c ruby/metal: Update to librashader ABI 2 (#1)
We elect to just remove all usage of libra_viewport_t for Metal, since the current rendering path conforms better to recommended Metal patterns than passing the drawable texture directly to librashader would.
2024-10-05 12:34:08 +01:00
Stefan Schlosser 7eb1b28671 ruby/opengl: adapt to librashader ABI 2
The libra_gl_init_context function has been removed. The OpenGL loader used to
create the filter chain, previously passed to libra_gl_init_context, is now
passed as a parameter to the libra_gl_filter_chain_create function.

The libra_output_framebuffer_gl_t and libra_source_image_gl_t structs have been
replaced with libra_image_gl_t.

The position of the viewport parameter in libra_gl_filter_chain_frame has moved
to after the output parameter, and its type has changed from libra_viewport_t to
libra_viewport_t *.

In order to retain the behaviour in ABI 1, output holds the width and height of
the previously used viewport and the viewport itself is removed and replaced
with NULL in the call to _libra.gl_filter_chain_frame.
2024-10-05 12:34:01 +01:00
Stefan Schlosser 42c16831b7 thirdparty/librashader: update SONAME of librashader.so in build-librashader.sh 2024-10-05 12:33:31 +01:00
Luke Usher 5982fa8ae3 Squashed 'thirdparty/slang-shaders/' changes from 693c632bdd..ec1b855638
ec1b855638 Add RF-nes presets to crt-royale-fast folder (#640)
a8e35920c5 Update crt-geom.slang (#639)
901441a496 Update crt-royale-fast and several presets (#638)
33876b3578 ensure testPattern() always has a return condition
5ab3c76109 update patchy-ntsc shaders and presets (#637)
edd2dd3f77 fix some errors identified by librashader scan (#636)
630fe655fe fix mudlord-pal-vhs
49c77cab02 remove another conflicting pass from preset
e1f7c6cc0e remove broken/unused pass from preset
0e29397870 add small, colored border shader (#635)
4ef678cab0 fix bad path
bd0ea94fc8 fix/update glow-trails shaders and presets (#634)
0dd9204791 Update crt-royale-fast and its presets (#633)
24f9468e2e Add crt-royale-pvm-shmup preset (#632)
0a305b879e Update crt-royale-fast and add new presets (#631)
1b2ad364b7 Add edgeNpixels shader (#630)
b9e012f25c Patchy NTSC - Bunch of last minute improvements (#629)
4cf85d3147 New NTSC shader by PlainOldPants (#627)
ef68606c0e Add edge1pixel shader (#628)
0cededfa7f ntsc-simple update to glsl version (#626)
811bb31cdb port tiny_ntsc (#625)
ef702029d8 Fix color clipping in crt-hyllian (#624)
b6b55c3995 Update crt-hyllian (#623)
26e9882eb2 Update crt-hyllian (#622)
b3d795acb9 Add crt-royale-ntsc-composite-fast preset (#620)
111fcedc3b Add crt-royale-fast shaders (#619)
b327343b77 Fix a 7-year old bug in crt-royale-bloom-approx.h (#618)
679a3321c1 Update crt-geom-mini.slang (#617)
f65a4bce69 Sync to koko-aio 1.9.30 (#616)
7d6751a07c update crt-guest to latest (#614)
05a41341be Fix input TF bug & large refactoring; Add box filter AA (#613)
5e702cfdc6 Added flat trinitron TV filters (#611)
1c6f2cd834 Add zfast_crt_geo shader (#612)
46b96cbd39 update crt-geom-mini to glsl version (#610)
959de2bb2e Reverted texture optimizations as they are breaking rendering. (#609)
23f90e3b27 crt-geom-mini update from glsl, crt-pocket fix clamp error (#607)
3796d44482 Update geom.slang (#606)
89dfd9bbd0 Add Geom shader (#605)

git-subtree-dir: thirdparty/slang-shaders
git-subtree-split: ec1b8556388317258376467c1561ecb91a06a466
2024-10-05 12:32:59 +01:00
Luke Usher 5f435345f1 Merge commit '5982fa8ae35f801150b06b8db273b628ea0f7cd9' 2024-10-05 12:32:59 +01:00
Luke Usher 8343f8136c Merge commit '4dcba4224027a101e7d4e21d23ada1f08e7baf2c' 2024-10-05 12:32:27 +01:00
Luke Usher 4dcba42240 Squashed 'thirdparty/librashader/' changes from fff80df5a0..4abd48eb24
4abd48eb24 capi(presets): support `d3d9_hlsl` VID-DRV
0007bd6d98 doc: update preset_ctx_set_runtime doc
72c72dafa0 capi(d3d12): remove unintentional IMAGE_TYPE infix for LIBRA_D3D12_IMAGE_TYPE
0fde712f3c doc: update librashader::reflect docs
2323b18710 capi(ld): add `LIBRA_RUNTIME_D3D9` define commented out
5978f95f76 reflect: make `ShaderPassArtifact` simpler as `PassResource` already includes the source data
3ee5e66c0d presets: make naming more consistent
f189468f6d ci: don't build cli for windows 7
fc47fb4c5a doc: typo
fc7739d9ab ci: update github actions
4a8a9ee444 chore: Release
756cbe63d9 cli: fix cli Cargo.toml
796b03b42b test: rework tests to work with ShaderPresetPack
742a1c8658 dep: update glslang
7c03a7e3fe doc(pack): reword doc on `ShaderPresetPack`
4ba6effc2f rt(mtl): fix test
32c99d9f4a rt: implement filter chain loading in terms of pack
75b70cc0e6 cli: add `pack` command to create a preset pack
828464c351 rt(image): helper to load image from shaderpack `TextureBuffer`
c19593e289 pack: implement shader pack library to preload resources from disk
1bbbd784d8 preset: make ShaderPassConfig and TextureConfig type aliases to PathReference
4273a833e8 pack: add librashader-pack
f14f45b3b1 rt: separate out meta information for textures
859d16e64e rt: separate out meta information to its own struct
b395b94a40 doc(abi2): add migration details for `libra_source_image_d3d12_t` layout
90a9ee754d doc: fix migration api typo
34b50059ca doc(d3d12,vk): clear up language for barriers
7a13136f9a capi(d3d12): allow d3d12 to optionally use a resource handle with chain-managed descriptors
0cb3880d7f rt(d3d12): allow construction of D3D12InputImage without a descriptor handle
c526b7043a capi(d3d12): change the layout so that descriptor is first in libra_source_image_d3d12_t
33d95ac399 rt(d3d12): allow creating input view without a CPU handle
40691cc406 rt(d3d12): allow creating output view from a resource ref
3c20c83bc9 rt(d3d12): use InterfaceRef for D3D12InputImage to avoid refcount for input image
b123f63a6e doc(reflect): fix link
4285ad2bd1 rt(d3d12): allow a pipeline to be available for multiple formats without recompilation
c57e502b78 rt(d3d12): make images with OwnedFramebuffer provenance use ManuallyDrop
7edff0ae35 rt(d3d12): allow manually specifying the strategy to get a manuallydrop for luts
dedde05c83 rt(d3d12): move update subresources to lut
7d483f2e08 rt(d3d9): take viewport by reference to avoid AddRef/Release
7b7fd99b92 rt(d3d11): take viewport by reference to avoid AddRef/Release
28931ae50a rt(d3d12): update d3d12-descriptor-heap
2fe7702957 rt(d3d11): avoid QueryInterface in GetSize
a5c8fcf4f8 doc: missing period
629070ea2f ci: build cli
da53c3df59 cli(render): make frame inclusive to ensure correct feedback and history behaviour
84e78f4e48 cli(render): add ability to specify frame options
91f8089277 cli(render): add ability to specify params and passes enabled
3993f57271 doc(cli): document CLI
55ff7a93f2 cli: rename librashader-test -> librashader-cli
227757a221 cli: parse transpile versions
a72a593029 reflect: allow indexed and non-indexed semantics to be serialized and deserialized as strings
1537c1bcd7 cli: ensure shaders are validated before compile
5573f13227 test: add CLI with multiple functions
bac09ad2a3 reflect: allow validation of shaders without reflecting against semantics
31ece05246 reflect: allow more reflection objects to be serializable
5ede061975 preprocess: allow shadersource to be serializable with serde
1676150858 presets: allow presets to be serializable with serde
eeda0d02d0 test: make RenderTest trait object safe
f7a938a00d deps: update dependencies
6394b28d40 deps: update dependencies
443fa20d22 test: clean up imports and features
5c726efe21 test(d3d12): Add D3D12 render test
d33c2a84b2 test(d3d9): Add Direct3D 9 render test
5a35a2bd1e test(render): reenable cache
41034330a7 test(mtl): Add Metal render test
a7836923d7 test: split test harnesses into features
20039b9347 test: abstract test framework
799d409ddb test(gl): Add OpenGL render test
79513a301e test(vk): Add Vulkan render test
6de2de8d12 test(wgpu): Add WGPU render test
2904a2ac10 test(d3d11): Add D3D11 triangle test to image
341fbceb82 rt(d3d12): derive clone on D3D12InputImage
c54747d398 deps: update dependencies
3888b56c83 rt(d3d9): accept input image by reference
b0df631651 rt(d3d9): load LUTS as BGRA8
dbfa822f7c rt(d3d9): disable alpha blending
e7fe96520e rt(gl): ensure framebuffers are bound
97ad0d64bf rt(gl): make FilterChain::load_from argument order consistent with other runtimes
feaebc5f44 fmt(gl): cargo fmt
ef35e2a620 presets: rename to_hashmap -> into_hashmap
987e967269 doc(capi): add error doc for infallible error
c3469520f9 examples(d3d11): fix d3d11 examples
45b98a2bdd rt(gl): use array_init instead of manually doing it with MaybeUninit
2ee9eca854 ci: ignore .DS_Store
59937aced5 fmt: cargo fmt
e4eed34c10 capi: const qualify chain in `_filter_chain_get_param` and `_filter_chain_get_active_pass_count`"
7abd679bd7 doc: add migration docs
41353ac9c4 rt(gl): remove need for explicit external FBO object
4d790e7a7b doc: update ABI versions in version.rs and readme
aeb0a16cfb rt(vk): allow specifying the queue to use
16108838b1 rt(d3d11): remove unneeded transmutes
7cfbca7755 rt(wgpu): remove unnecessary output move
8467e5cd97 rt(mtl): remove unnecessary output move
1e33b4cc03 capi: make viewport optional, defaulting to a viewport that is the entire size of the render target
eb53699590 capi(include): update headers
0cbf8024a7 build: update soname
7e354a56a1 capi: upgrade cbindgen to fix syn bug
0a87bcc657 rt: respect viewport extents when rendering
f0a7970b44 rt: add viewport extent separate from output texture dimensions
e7e6ed8fb8 capi: remove _internal_alloc from libra_preset_param_list_t
61fdaeea14 capi(gl): update to take opengl context in constructor
2552d4321b capi(gl): set output in libra_output_image_gl_t, not viewport
eaf939c861 capi(vk): set output in libra_output_image_vk_t, not viewport
14abb0362b capi(d3d12): set output in libra_output_image_d3d12_t, not viewport
e064f8d0be capi(d3d12): remove ignored fields from libra_source_image_d3d12_t
f18c22a95a capi(d3d11): take ManuallyDrop<ID3D11ShaderResourceView> directly in libra_d3d11_filter_chain_t
763c05755d rt: mark error types as non_exhaustive
e6d23f1d8f doc: update opengl example
2f9df143cf deps: consolidate and update dependencies
1bdadaa449 rt(gl): port to OpenGL runtime to glow
77b957bf5e reflect: stop adding null bytes to uniform names
1e0727f89d chore: Release
60d2c3f177 chore: Release
72a98272f3 doc(capi): document all C API members
7d0b135710 rt(mtl): remove unused 'pass lifetime
4ba5aefafc capi: don't export wrap_ok macro
6edfaed91f test: update slang-shaders
cd877d7883 build: respect CARGO env in build script
d56d92ea0f test: update slang-shaders
f49e3b58d8 doc(capi): fix rotation integer docs
1f4f1b6c12 capi: Fix Metal error message, function header
57f2dabf0c reflect: fix `CurrentSubFrame` being parsed as `TotalSubFrames`
81840a9e9c reflect: insert alias semantics for shader name through pragma
87e0405675 presets: properly trim shader name if given through pragma
e0c97f77b4 build: nicer build script messages
6e60dd6fa0 test: update slang-shaders
d55d0e4839 rt(mtl): use f32::MAX for lodMaxClamp
6cdd9247de presets: trim aliases and shader parameter names
cbe6510f76 preprocess: the step argument is optional according to slang-shaders spec
d6f8950bdc rt: only draw last pass twice if the last pass is needed as feedback
0fe5bbd57b rt: do reflection to see if the final pass is needed as feedback
eace595ebb chore: Release
66561ad2ed doc: fix header image
05d48841ad doc: update docs for stable build instructions
927740433c build: remove unneeded image dependency
316e92dc09 build: allow building stable with --stable flag
e930f90a9c capi: allow building on stable by gating #[doc] comments
2f988d5b1d rt: add stable feature to build ShaderPassArtifacts via Box<dyn CompileReflectShader>
e0a5c90103 reflect: implement stable FromCompilation
4cc3c875bf reflect: allow compilation of boxed trait objects
805854b94b reflect: simplify FromCompilation output signature
c291d9d85f capi: remove dependency on `try_blocks`
8b2ff57ee8 reflect: replace `let_chains` with `Option::filter`
3d9139b4e0 rt(d3d11): replace `let_chains` with stable alternatives
b432a1e02d rt(d3d12): replace `let_chains` with stable alternatives
ab9ab6fe68 rt(gl): use `Option::filter` instead of `let_chains`
0ba4c482b3 rt(vk): use `Option::filter` instead of `let_chains`
57f9a13ee7 rt(wgpu): use `Option::filter` instead of `let_chains`
2661effab4 chore: Release
02288554b9 rt(mtl): fix history buffer off-by-one by buffering the history read.
98d8d91c66 capi: undo const qualification of chain in `_filter_chain_get_param` and `_filter_chain_get_active_pass_count`
6f5b342c1b build: fix dev-dependencies on non-apple
bec0482513 ci: trigger ci
e24beede0b rt(mtl): draw final pass to output targets
22b2118e97 rt(mtl): don't resize if the requested format differs from optimal format
856f69113d rt(mtl): don't make mipmapper for history if not needed
477d0ae67c rt(wgpu): draw final pass to output targets
e68da7b984 rt(gl): draw final pass to output targets
666588ef0d rt(vk): draw final pass to output targets
336f540ce9 rt(d3d9): draw final pass to output targets
894d19eb81 rt(d3d12): draw final pass to output targets
1bf5d7efca rt(d3d11): draw final pass to output targets
c9205bc922 rt(mtl): remove internal_frame_count
cebc7a939a rt(mtl): fix faulty history but only copying one mipmap slice of texture
fe48fd03a5 test(mtl): update the metal test
50580cfc3b chore: Release
075a2981e1 rt(gl): fix `glShaderSource` going past the buffer
a7dd40a79f ci: allow c_str_literals to maintain a lower MSRV
fd8d6f6ab8 chore: Release
c5fdffa6aa dep: update cargo.lock
090e268c4a doc: improve docs
8856a78eb8 api: expose `FastHashMap` and `ShortString`
ec3add1616 rt(params): rename get_parameter -> parameter_value
f83fd1e98f ci: debug is broken on windows 7
c3033cfbbf reflect: port to spirv-cross2
820fb69328 reflect: remove get_prefix from get_texture_semantic/get_unique_semantic
c9a6411394 deps: consolidate and update dependencies
40a56bf165 reflect/preprocess/presets: use SmallString where it makes sense
c447e40583 rt: redesign parameters to be thread-safe across FFI using arcswap and atomicusize
ae76bf9cc1 rt(d3d12): pull out descriptor heap implementation into its own crate
e934f175ef rt(d3d12): stop leaking transition barriers
2e7c3b3273 rt(d3d12): use gpu_allocator instead of CreateCommittedResource
e90c27ebbd rt(vk): use manuallydrop for VulkanBuffer rather than Option
8fb5d48a1e chore: Release
b7fd3bc507 runtime: fix image swizzle for remainder
af05cc5bd8 ci: build for windows 7
2f0a3356d9 rel([email protected]): doc fix
0efaf2b8a0 doc: fix docsrs build on macos
436d1fe3cd chore: Release
0ce11bac71 doc: promote d3d9 to secondary support
bc269c270c rt(d3d9): remove backtrace from Direct3DError
db3d5d05a6 presets: use crate for extract_if with fully qualified syntax to avoid name collision with unstable std
1957f576ca reflect: further improve link i/o pass by ensuring that the output SPIR-V is valid according to Vulkan 1.0 semantics
5560c1ed09 runtime: use a more efficient swizzling implementation without array_chunks_mut
f8c055524b doc(readme): document shader pre-linkage
fee92113f1 ci: remove PR full test
45c3c876f4 reflect: remove explicit compile function in favour of TryFrom
28f5674a80 presets: remove rustc 1.74 compatibility
bffad12ea2 doc(presets): add docstring for ContextItem::key
321e30a0f1 capi: extend config_struct macro to handle overrides
9b40c10466 reflect: improve inout link algorithm
cd14bca23a Revert "reflect: improve inout link algorithm"
1ac78695c6 reflect: improve inout link algorithm
d1e49b7eb4 rt(d3d9): search "global" namespace for register assignments
5ef0055e05 rt(d3d9): fix vertex assignments accidentally searching fragment
1c6581d737 rt(d3d9): set colorwritemask to all
ac66b1b6f6 style: fix warnings
977975f4c7 doc: document naga reflect
3b9514ad38 doc: allow wgpu doc on apple
899fb50da6 chore: Release
162226ce44 ci: don't build locally
039fdfd41a ci: update OBS build platform
e13bb88df2 doc: update MSRV due to naga
7b375658c5 dep: update cargo.lock
3fb6e3843e dep: update to windows 0.58
3cda5b706d rt(d3d12): get rid of size in inputview
4d6793d305 rt(d3d11): get rid of input/output view wrappers
35f499f5e1 wgpu: enable pipeline caching
6ce711db26 ci: don't build Arch
d4b4366836 dep: update ash to 0.38
c646086df4 dep: update wgpu
f6cf642e50 chore: Release
98958dfb5e dep: update rustc_hash
b5d523e9f3 rt(mtl): move icrate definitions to objc2-metal
5e9ce1207c Revert "ci: temporarily remove deny-deprecated on ctypes to unblock ares"
1b0574c140 presets: show file name and details on io error
b84e104212 capi: fix malformed vulkan include

git-subtree-dir: thirdparty/librashader
git-subtree-split: 4abd48eb244e15ca40307f28fce0061627ff0143
2024-10-05 12:31:45 +01:00
Luke Usher 81d5cdba32 Merge commit '5151003fa4331d3a4473c32e6c7b4ebcd59e29ba' 2024-10-05 12:31:42 +01:00
Luke Usher 5151003fa4 Squashed 'thirdparty/libchdr/' changes from aa34b14191..aaca599e18
aaca599e18 Merge pull request #130 from notaz/release_lzma_init_buffers
2099836c2b release lzma init buffers
9b6ff6c3c2 Merge pull request #128 from scribam/zstd-legacy
85dd19217a Merge pull request #129 from scribam/arm-neon
71e57f533d lzma: extends neon support when hwcap is not available
a6c474ddee zstd: disable legacy support

git-subtree-dir: thirdparty/libchdr
git-subtree-split: aaca599e18e43933fc193bd1b715c368c306208b
2024-10-05 12:31:42 +01:00
Luke Usher c6a838d6ee Merge commit '349f1d281c29a3af9f2814399028e0e7bc829c96' 2024-10-05 12:31:38 +01:00
Luke Usher 349f1d281c Squashed 'thirdparty/sljit/' changes from c2e49625e4..f6326087b3
f6326087b3 Improve op flags operation on x86
2a79c59737 Fix sign conversion warning on Windows arm64 (#270)
7a6ceb3e03 Fix examples (#269)
2c105e2461 Fixed a compare logical case on s390x
4c4802dd4c Emit brk #0xf000 for breakpoint opcode on arm64 (#267)
3b9c0c8925 Enable public usage of SLJIT_LOCALS_OFFSET (#264)
4dd388a736 loongarch: add memory fence & support tmp register for atomic (#263)
8c089bd584 Implement m,emory fence
d21a5448f6 Fix compiler warning
f9f512c080 Support tmp register for atomic
883118537c Add action (#259)
8099661b54 Add SLJIT_ATOMIC_USE_LS/CAS support to LoongArch (#261)
728db2007a riscv: only enable SIMD if supported by toolchain (#260)
8727735933 Bitmanipulation instructions on RISC-V (#258)
c85dd1dd97 Rework sljit_emit_enter argument passing
3e5568bfcc Add more tmp reg tests
bd056ab1df Add control flags to atomic operations
ee8861243f loongarch: Implement ll/sc support for atomic operations (#254)
d3a10d1986 x86: avoid SIGILL in CPUs with AVX but without AVX2 (#256)
460f02a1b8 x86: check for extended function availability before using (#255)
0a74f16bea x86: improve execute_cpuid() portability (#251)
7b0fd86bd5 test: avoid leaking compiler on early exit (#253)
31cfa2fef2 Add shuffle support for LoongArch (#252)
06a5bafd7c Initial implementation of riscv simd
5ad2541117 x86: improve execute_get_xcr0_low() portability (#250)
6128486813 Implement atomic store on ppc and mips
fcade55c27 Update atomic on s390x
8bcd711708 Rework atomic load/store
bd221f0e86 Support non-overlaping vector registers

git-subtree-dir: thirdparty/sljit
git-subtree-split: f6326087b3404efb07c6d3deed97b3c3b8098c0c
2024-10-05 12:31:38 +01:00
Cheesemeister3k cac4aab301 #1485 [SNES] NTT Data Keypad (#1660)
Test equipment used: NTT Data Keypad, Raphnet ADAP-2XSNES-USB_V2 and
test32.sfc, Analogue Super Nt.
2024-10-05 12:25:28 +01:00
Factor 5911338cac Add support for 256KB of SRAM for SNES (#1616)
256KB of SRAM is possible on hardware and many hacks use it (Super
Metroid Practice ROM, Super Mario Bros. Maker, etc.). It could be
implemented in Ares in many ways, but I limited the ramSize to 1-8 with
a wrap-around as values higher than 8 wrap-around when used (9 is the
same as 1, 10 is the same as 2, etc. verified by
[kandowontu](https://github.com/kandowontu)).
2024-10-05 12:25:16 +01:00
png183 c0af33d4ce gba: improve SIO register handling (#1662)
Implements the following changes:

- Bits 8-11 of SIOCNT should be read/write
- Mode specified by SIOCNT uses 2 bits rather than 1
- Lower 3 bits of JOYCNT are cleared when 1's are written
2024-10-05 12:22:31 +01:00
hackgrid ea77623238 desktop-ui: enable loading rom folders from the cmd line (#1656)
Needs to merge #1654 first.

Enables loading folders instead files from cmd line.
Removes loading firmware files from rom folders in sfc mia (firmware
data would be loaded twice, db hashes would not match anymore).
2024-10-01 16:10:54 +01:00
png183 033752679f gba: add 2-cycle IRQ synchronizer and improve halted CPU timings (#1651)
Adds a 2-cycle synchronizer delay to IRQs. Unhalting the CPU also
appears to be delayed by 2 cycles.

The GBA CPU core currently steps in increments of 16 cycles when halted
or stopped to reduce emulation overhead. Since this optimization can
cause unhalt timings to be off by a few cycles, this PR reduces the step
size for halt mode and removes the optimization for stop mode.
Performance impact should be minimal in cases where performance is a
concern.
2024-09-26 14:23:54 +01:00
jcm 025fc6450a hiro/cocoa: Add bounds checking for table view context menus (#1650)
Right-clicking in a table view beyond the bounds of the defined rows in
the table would crash previously.
2024-09-25 09:57:13 +01:00
jcm d6858ad821 ruby/metal: Emit librashader shader creation errors (#1647)
Displaying errors from librashader shader loads in Metal will make
librashader debugging easier.
2024-09-18 18:34:10 +01:00
png183 0b46609e95 gba: add latches to DISPCNT background enable, object enable, and force blank bits (#1643)
Clearing the force blank bit or setting the background/object enable
bits in DISPCNT should only take effect after 3 scanlines.
2024-09-17 14:32:18 +01:00
jcm b5a8edc5d0 Address possible use of uninitialized variables (#1646)
Minor code cleanup. clang reports that it's possible under some
circumstances these variables are uninitialized when used.

Overall motivation is to utilize some stricter compiler settings in the
future and error on `-Wuninitialized`.
2024-09-17 14:32:07 +01:00
invertego 757a7dd670 Merge commit '950573df14f9307b7eaff4600370d76057aae466' into update_parallel_rdp 2024-09-15 05:27:45 -07:00
invertego 950573df14 Squashed 'ares/n64/vulkan/parallel-rdp/' changes from 7e5ad30b8..d1cc912c5
d1cc912c5 Update to 1f69c762be68feb9fcd5276d75acc6e5a6160a19
1a8cbce2f Update to fe5becd13638873db90d46e7ba7d48255971f82a
353ab9d38 Update to a2b0e8503ba525d70c61bccbe59c87d14daf89a6

git-subtree-dir: ares/n64/vulkan/parallel-rdp
git-subtree-split: d1cc912c5c47abaf9b6b155d3cd15255df65cf5b
2024-09-15 05:27:26 -07:00
Giovanni Bajo f43da416fd n64: refactor devirtualize and memory ops, force JIT only with instruction cache (#1635)
This change contains a large refactoring with no functional changes,
plus a small functional change that will help speeding up the JIT.

The refactoring allows CPU::devirtualize to return all the information
regarding the memory access. This in turn allows to simplify all memory
ops (which contained lots of duplicated code) to use devirtualize,
reducing code duplication.

The functional change is that we now use JIT only when running code from
icache (which is 99.9999% of the times). Running code without icache is
extremely slow on real hardware and only happens in specific situations
(eg: during boot when RDRAM is not initialized). By limiting the JIT to
run from icache, we open the door to implement proper icache support in
the JIT and finish remove the instruction epilogue with its slow
"instruction cache stepper" (which in addition to being slow, is also
inaccurate and make us fail cache test ROMs).
2024-09-08 13:45:09 +01:00
18f45ddc85 n64: add support for multi-byte writes to gdb (#1620)
Currently, gdb hooks in n64 doesn't allow for large sizes of writes
because it wouldn't be obvious which data size use on the bus. While
this is true, it doesn't really matter for RDRAM where all data sizes
work in the obvious, correct way. So relax the constraint to allow
writing large portions of RDRAM with a single gdb command.

Co-authored-by: Chase Meadors <[email protected]>
Co-authored-by: Luke Usher <[email protected]>
2024-09-03 09:49:40 +01:00
Giovanni Bajo 7135646c44 Update parallelRDP and MoltenVK (#1634) 2024-09-03 09:49:25 +01:00
invertegoandGiovanni Bajo 4ab8472a53 n64: fix instruction tracing with recompiler (#1629)
Co-authored-by: Giovanni Bajo <[email protected]>
2024-09-02 14:08:56 +01:00
Screwtapello a47e793b57 Stage resources into the output directory on Linux. (#1627)
Originally, to run ares on Linux after building it, you'd `make install`
which copied everything into the right places in your home directory.
Windows and macOS don't have the same traditions about installing apps,
so on those platforms the makefile staged a "portable" installation in
the output directory.

Since then, `make install` was modified to install ares system-wide.
It's possible to use it to install ares into your home directory, but a
bit overkill. For consistency, let's also stage a "portable"
installation in the output directory on Linux and the BSDs, so it's
easier to test on those platforms.
2024-09-02 11:36:41 +01:00
invertego 1ffb4f6d5a n64: use devirtualize for code block lookup (#1630)
Essentially a revert of fbaf7d8118

This optimization was found to compromise correctness due to the lack of
alignment checks. If something like this proves truly beneficial for
performance, we can bring it back.
2024-09-02 11:35:45 +01:00
remutro aa350116d4 Add option to enable TMSS boot rom for Mega Drive (#1632)
If you like to slow down booting into your game and want to read the
same old text each time on the Mega Drive, the option is yours now! This
is available as a choice in Settings > Options now. By default, this
will not be enabled (same behavior as existed prior to this PR). You
don't need to specify anything in the firmware section, ares had the
plumbing in place all along, it was just hardcoded to not load the tmss
boot rom.
2024-09-02 11:35:07 +01:00
png183 e8a5579cb7 gba: latch IE and IF values for 1 cycle, and improve stop mode emulation (#1631)
Improved interrupt timings, and made sure stop mode exits only once the
requested keypad input is registered.
2024-09-01 09:00:28 +01:00
Screwtapello f091fcfacd Fix detection of the Sufami Turbo base cartridge. (#1628)
The Sufami Turbo base cartridge is listed in the Super Famicom verified
dump database, so it did not use the heuristics. It turns out the
heuristic detection wouldn't have worked anyway - although the game's
header does contain the serial A9PJ, the heuristic revision() method
does not report that serial at all.

Meanwhile, the serial A9PJ is *also* used by the game Bishoujo Senshi
Sailor Moon SuperS - Fuwafuwa Panic, so loading this game would prompt
for Sufami Turbo mini-cartridges even though the game could not make use
of them.

I have used mia to generated heuristic manifests for every SNES/SFC game
in the No-Intro set, and the only difference introduced by this change
is that the Sufami Turbo base cartridge is now detected as having Sufami
Turbo slots, and Fuwafuwa Panic is not.

It took me a little messing around to find a syntax for comparing an
`array_view<u8>` that the compiler would accept; if there's some more
concise or idiomatic way to do it, please let me know.

Of the other emulators I surveyed, bsnes works just like ares did,
MesenS doesn't seem to support the Sufami Turbo, and snes9x uses a
slightly stricter check than I implemented:


https://github.com/snes9xgit/snes9x/blob/85591435763dede7ef111aab8070cdf2d5a7da49/memmap.cpp#L1016-L1023
2024-08-29 12:22:43 +01:00
Luke Usher fa9d350a66 md: sync more regularly when emulating 32X
Fixes a hang in Knuckles Chaotix at the cost of performance.

Needs further investigation.
2024-08-28 16:16:41 +01:00
Luke Usher 5ff5df0e2e version 140 2024-08-27 17:37:58 +01:00
png183 efb7f61f04 gba: add graphics viewer support (#1626)
Adds GBA support to the ares graphics viewer. Supports viewing VRAM
contents as Mode 3/4/5 bitmaps, or as 4bpp/8bpp tiles.
2024-08-25 10:06:06 +01:00
remutro 3cd82c8cfe Correct misspelling of interpreter (#1625)
Interpreter was spelled incorrectly in the option name, and the setting
name stored in the settings.bml file.
2024-08-23 17:26:04 +01:00
jcm ace4115c86 build: Check for clang in diagnostic pragmas (#1624)
MSVC build logs are complaining [very
loudly](https://github.com/ares-emulator/ares/actions/runs/10524248801/job/29160592080#step:10:835)
about unknown pragmas.

Only clang complains about these code areas currently, so for now, just
put these diagnostic pragmas behind a check for clang. If MSVC pragmas
end up being a good idea, could look into compiler-agnostic pragma
macros, but that doesn't seem necessary at present.
2024-08-23 15:58:48 +01:00
invertego 31ca4552ea build: fix cl build break (#1623) 2024-08-23 11:33:36 +01:00
invertego 873aded84b m32x, n64, ps1: add "force interpreter" option (#1622) 2024-08-23 11:03:39 +01:00
png183andinvertego 4dc46976ef build, n64: fix build (#1619)
Removed `__VA_ARGS__` from line 6 of interpreter.cpp, since it appears
to be unused and was causing compiler issues. Tested on Ubuntu with g++
and clang++ with both interpreter and recompiler running a default build
of n64-systemtest.

---------

Co-authored-by: invertego <[email protected]>
2024-08-23 00:23:07 -07:00
jcm 156603ceff hiro: Remove last clipsToBounds use (#1618)
Amends https://github.com/ares-emulator/ares/pull/1610
2024-08-22 14:02:57 +01:00
invertegoandGiovanni Bajo 12f0d04709 n64: remove branch state machine from epilogue (#1598)
This will bloat generated code in the short term, but some of that can
be elided with future optimizations.

Passes [n64-systemtest](https://github.com/lemmy-64/n64-systemtest) with
both the interpreter and recompiler.

---------

Co-authored-by: Giovanni Bajo <[email protected]>
2024-08-22 08:25:04 +01:00
jcm 693447d0e0 hiro/cocoa: Always draw in view bounds instead of dirtyRect (#1610)
A better fix for the problem discussed in
https://github.com/ares-emulator/ares/pull/1412.

Also unbreaks CI.

Changing `clipsToBounds` was fine, but the property isn't exposed on
older SDKs (that are still used by ares to maintain backwards
compatibility), and exposing it manually when building with an older SDK
was not great practice (and may have just been a noop anyway).

Instead, we should just not draw on the dirtyRect, when we intend to
draw on the view's `bounds`. Apple's documentation on this subject is
pretty thin on the ground, not to mention contradictory, especially
pre-macOS 14. But it seems pretty clear that in any case, a view's
`bounds` will always be the area we intend to draw on, while the view's
`dirtyRect` may or may not be. So here we make every element in hiro's
Cocoa implementation that does manual drawing always draw using
`bounds`.
2024-08-22 08:24:41 +01:00
png183 27719b391b gba: use separate latches per DMA channel (#1617)
Each DMA channel should have its own latch rather than sharing a latched
value. It's also possible to read open bus values into the latches.
2024-08-22 08:24:03 +01:00
png183 3455da48df gba: reload timer value after tick (#1614)
If a timer gets enabled while its value is 0xffff, it's possible for the
timer to overflow before its reload value is applied. Passes alyosha's
[timer-disable.gba](https://github.com/alyosha-tas/gba-tests/blob/master/timer/timer_disable.gba)
test ROM.
2024-08-21 09:13:15 +01:00
jcm dac6a2069f nall/arithmetic: ignore -Winfinite-recursion warning in square() (#1605)
More code cleanup for the new build system along with
https://github.com/ares-emulator/ares/pull/1602,
https://github.com/ares-emulator/ares/pull/1603, and
https://github.com/ares-emulator/ares/pull/1604.

This one is fairly mysterious. clang thinks that all paths through this
particular signature of the `square()` function call itself. This area
of nall is a mass of templating and operator overloads, and figuring out
exactly what's going on here would be a good one to unravel for a
large-brained, C++-enjoying individual.

For now, just ignore this warning locally so that we can compile the
rest of ares while still warning about infinite recursion elsewhere.
2024-08-18 04:12:51 +01:00
jcm 39174a2a79 Enforce newlines at end-of-file (#1604)
Enforce newlines at end-of-file in the codebase.

While every modern compiler is able to deal with not having EOF
newlines, it is still a good idea to enforce this.

ParaLLEl-RDP has a few files without EOF newlines, so I surrounded the
n64 Vulkan `include` with a diagnostic pragma to ignore it. This avoids
having to deal with compiler errors if ParaLLEl-RDP is updated, pending
newlines added upstream.
2024-08-18 04:12:18 +01:00
jcm 23e322fd57 hiro/cocoa: Fixes and code cleanup (#1603)
Fixes several issues and compiler warnings with hiro's Cocoa
implementation. Among them:

* We were technically declaring `clipsToBounds` incorrectly; properties
in subclasses aren't correct and can conflict with the system version;
rather, implement it as an instance method.
* Fix some non-strict pointer aliasing in menu-separator.cpp;
* Remove a couple blatant unused variables from desktop.cpp and
monitor.cpp;
* Fix an instance passing nil to a function that requires a non-null
argument in popup-menu.cpp;
* Some ancient C functions in Cocoa don't pass -Wwritable-strings; for
now, just surround the function that uses them with a clang diagnostic
pragma.

In C++ land:
* Various C++ functions were `override`s but were not declared as such.

Lastly, the second commit:
* In Objective-C, you declare subclasses in the `@interface` header, but
not in the implementation. hiro was including the superclasses in the
`@implementation` block, which isn't correct. For some reason, clang was
only erroring on one instance of this, but we go ahead and fix it
everywhere.
2024-08-18 04:12:01 +01:00
Adrian Siekierka 5c0c1fb4aa ws: implement cartridge SRAM open bus, clean up I/O port logic (#1607)
Also saves about 500KB of unnecessary memory use. Ouch!

I/O port open bus is not fully implemented.
2024-08-18 04:11:25 +01:00
png183 c27a62b624 gba: fix controls when screen is rotated (#1609)
Fixes a bug where D-pad controls were inverted when the screen is
rotated 90 or 270 degrees.
2024-08-18 04:10:06 +01:00
jcm 9c93735045 ruby: Remove unused OpenGL functions (#1602)
Removes apparently dead, unused functions in the OpenGL backend.

### Context

Work continues on the new build system. Among its goals are to start
compiling ares with stricter settings, where applicable, to increase
code quality. This includes removing unused functions, to satisfy
`-Wunused-function`.
2024-08-16 16:28:42 +01:00
Stefan Schlosser 9e03af99d9 nall: accept target-triples below i686 for x86 architecture (#1600)
Some systems report target-triples below i686, although they target i686
in reality. One such system is FreeBSD since version 13.0. It reports
i386 but targets i686. Without accepting target-triples below i686 such
systems can't compile ares on the x86 architecture.
2024-08-16 16:28:31 +01:00
png183 eec5104909 gba: prevent DMAs from interrupting ROM accesses (#1601)
Fixes some timing issues where DMAs were running 1 cycle too early
2024-08-16 10:09:09 +01:00
Luke Usher 00a67f1671 ps1: fix crash when display surface wraps around the framebuffer 2024-08-15 16:24:30 +01:00
png183 a76847dbd6 gba: prefetcher should halt only once DMA accesses ROM (#1597)
Currently, the prefetcher halts whenever DMAs are running. However, on
hardware the prefetcher is able to keep running until DMA accesses
cartridge ROM. This PR implements said behaviour, allowing ares to fully
pass the mGBA test suite timing tests as shown below:

![2020](https://github.com/user-attachments/assets/bbf8fd3b-c1a1-45f8-b623-8b0bc8d7784d)
2024-08-09 18:39:54 +01:00
remutro f209d544b0 Add missing serialized fields to N64 save state (#1573)
Added missing serialized fields to N64 save state, one in AI and one in
PI (both added in same commit).

Scanned the other sections looking for other missing fields so we don't
need to invalidate save states frequently and I didn't spot others that
were missing right now.
2024-08-09 14:43:43 +01:00
invertego 5453fe084a n64: (rsp/recompiler) clear r0 only when necessary (#1581) 2024-08-09 14:43:31 +01:00
曾耿森 426fb79639 feat(fc): add new new input device zapper for fc (#1592) 2024-08-09 14:43:21 +01:00
png183 33c645a441 gba: improve DMA timings (#1596)
The 2 DMA idle cycles currently processed before running a DMA channel
should instead run for 1 cycle when DMAs start, and 1 cycle when the
DMAs have all finished.
2024-08-09 14:35:01 +01:00
Luke Usher ba9a291784 ruby: fix compilation of OSS driver on Linux systems
Most (all?) linux implementations lack AFMT_S24_LE and AFMT_S32_LE
2024-08-08 13:35:53 +01:00
Stefan Schlosser 9fb67ba7a7 ruby: improve OSS audio backend (#1593)
The OSS audio backend was very limited in its capabilities and its error
handling. Essentially it supported only the initial parameters for
channels, format and frequency, e.g. 48000Hz 16bit stereo. If the audio
device didn't support these parameters, the backend would keep using the
initial values although OSS had probably adjusted the parameters to
supported values. Be aware, there are possible configurations for the
system and the audio devices which don't support the above mentioned
standard values, e.g. on FreeBSD it's possible to configure an audio
device to only accept 96000Hz 32bit 7.1 surround sound.

Now the OSS backend takes the changed parameters for channels, format
and frequency into account, updates the resampler accordingly and feeds
the audio data into the audio device with the right format.
2024-08-07 10:12:08 +01:00
invertego 54794f86d9 thirdparty: fix typos in lzma object names (#1594) 2024-08-07 10:11:35 +01:00
Adrian Siekierka 7f43d0658e v30mz: fix IP on interrupt fired when prefixes being used with non-pr… (#1591)
…efix instructions

Once again, found with a test (`80186_interrupts` in my ws-test-suite).
2024-08-04 14:05:27 +01:00
Adrian Siekierka 0d24374019 v30mz: fix instruction prefix handling (#1590)
It appears the datasheet was not entirely conclusive with regard to how
the CPU handles chains of more than 7 consecutive instruction prefixes;
in addition, Ares was incorrectly using the *first* rather than *last*
segment override in the chain.

This doesn't affect well-formed code (duplicate instruction prefixes
should never happen, nor should more than one segment override), but
brings Ares up from 2/7 to 7/7 in
[ws-test-suite](https://github.com/asiekierka/ws-test-suite)'s new
`mono/cpu/prefixes` test.
2024-08-04 13:45:54 +01:00
Adrian Siekierka 78a5e584b5 v30mz: fix DAS overflow flag emulation (#1589)
oops, typo
2024-08-03 12:38:09 +01:00
Stefan Schlosser ffe97222a1 hiro: remove QT5 deprecation warnings (#1586)
Replace deprecated elements with suggested replacements.

QApplication::hasPendingEvents() and QWidget::paintEngine() are still in
use, their replacement is way out of scope for this PR.
2024-08-01 11:21:54 +01:00
Stefan Schlosser 71e5f89f8b desktop-ui: increase height of SettingsWindow to unhide Supersampling option in QT5 builds (#1587)
The Superampling option in the Video category isn't visible in QT5
builds, the settings window is too small. Therefore increase the height
of the window by 20 to unhide the setting. This also gives the setting a
little bit more distance to the bottom edge in GTK3 builds.
2024-08-01 11:21:42 +01:00
png183 cac454a6a9 gba: reset prefetch buffer on ROM accesses from DMA (#1584)
Addresses todo item from #1377
2024-07-31 14:45:56 +01:00
invertego 6c8265577c n64: update audio stream frequency after loading state (#1583) 2024-07-30 11:16:19 +01:00
tykkiman 401aab6d64 n64: clear r0 only when it was written to (#1580)
Currently a per-instruction epilogue is needed to make sure the
read-only register r0 stays as the value 0. To improve performance of
the generated code, we'd like to move this operation to be done only
when needed.

This commit solves the above problem in two ways: simple instructions
are never emitted if their destination register is r0, and more complex
instructions now emit a clear operation right after. This way exceptions
are still thrown when needed.
2024-07-29 18:06:01 +01:00
png183 c0fb9ba815 arm7tdmi: improve ldm/stm edge case handling (#1582)
Address some edge cases of LDM/STM instructions (also affects Thumb mode
PUSH/POP):
- Using an empty register list will cause R15 to still be accessed, but
the base register will be modified as if all 16 registers were accessed
- Writeback does not occur in LDM if the base register is in the
register list
2024-07-28 15:18:09 +01:00
bachimus 356208f312 ps1: Fix Dragon Ball GT Final Bout (fix found by @LukeUsher) (#1579) 2024-07-26 11:20:34 +01:00
png183 fbf10d14fc arm7tdmi: fix reading SPSR in user and system modes (#1578)
In user and system modes, attempting to read SPSR should instead read
CPSR.
2024-07-26 11:18:40 +01:00
Stefan Schlosser 723d8a8cd4 nall: respect prefix for sharedData location on Linux/BSD (#1575)
The hardcoded `/usr/share` for the sharedData location doesn't respect
the given prefix, e.g. `~/.local` or `/usr/local`. This results in the
emulator not finding the shaders or databases in case the emulator is
not installed under `/usr` and the files are not found in the
application or user data directory.

Now the build script defines a preprocessor constant `ARES_PREFIX` which
is set to the requested prefix. With the help of the C preprocessor
stringize operator, this prefix is then used as the root of the
sharedData location.

Fixes https://github.com/ares-emulator/ares/issues/1179
2024-07-24 12:59:49 +01:00
Stefan Schlosser 6eedb9399b Improve FreeBSD compatibility (#1574)
These commits improve the compatibility with FreeBSD. Among some
cosmetic changes is a commit to unbreak the build on FreeBSD and two
commits adding an audio and an input backend to FreeBSD builds.

There's still a change needed to make ares completely buildable on
FreeBSD:
use of `CLOCK_MONOTONIC` in
`ares/n64/vulkan/parallel-rdp/util/timer.cpp`, see
https://github.com/Themaister/Granite/pull/135. This change will
propagate to ares if/when Granite upstream merges the PR, parallel-rdp
adopts the updated Granite and ares updates its parallel-rdp.
2024-07-24 12:58:20 +01:00
invertego 36f821f5ac ci: set windows image to windows-latest (#1563)
This reverts commit 762a2302f7.
2024-07-15 04:16:20 +01:00
png183 3bbfde5e9b arm7tdmi, gba: prevent debugger from advancing GBA CPU clock (#1564)
Provides a getDebugger function for the ARM debugger to read memory
without advancing CPU state, fixing a bug where GBA core CPU timings
were impacted by debugger use.
2024-07-15 04:15:07 +01:00
invertego b8e355b218 build: detect cl target architecture (#1562)
Automatically detect the (clang-)cl target architecture instead of
assuming amd64. Note that -print-target-triple is now used in favor of
-dumpmachine for all versions of clang. This option has been around for
ages in the regular clang driver but is only supported by clang-cl as of
LLVM 18, which isn't yet available via the Visual Studio installer but
is available through a standalone installer on GitHub.

This commit also adds a compiler flag to the command line when targeting
arm64 with cl to work around an optimizer bug.
2024-07-10 11:45:06 +01:00
jcmandjcm c34ed82fa3 build: Allow building on Make 3.81 (#1556)
On versions of make prior to 3.82, pattern matching rules are applied in
the order they were first defined, as opposed to the probably-desired
order of most specific to least specific. In ares, `nall`'s pattern
matching rule comes fairly early on and is thus used to build most of
ares. The parallel-rdp build code in ares defines its own pattern
matching rule, which caused building with 3.81 to not work since the
more specific rule is not used, and the less specific rule cannot be
applied successfully.

For other fun reasons, macOS still ships with make 3.81 (released in
2006).

This PR just allows building on macOS's stock `make`, which means a bit
less effort in building, as well as easier integration with IDEs (in my
testing so far, what few IDEs on macOS support direct Make integration,
seem to require or expect the stock toolchain).

There may be slightly more elegant ways to do this, but this pattern
conforms with how object paths are defined for other third party
dependencies around ares.

Eventually™, if ares migrates to CMake, there could much better cross
platform build tool integration (generating Xcode or other OS project
files as desired, for example). Until that point, it is convenient to
support the stock toolchain on all operating systems if possible.

Co-authored-by: jcm <[email protected]>
2024-07-08 10:08:28 +01:00
invertego 3de728fa3b fc: add prg ram to uxrom and cnrom mappers (#1557)
Some homebrew/aftermarket software calls for UXROM w/ PRG (NV)RAM. The
licensed title Hayauchi Super Igo pairs CNROM with SRAM.
2024-07-08 10:08:21 +01:00
invertego 2b0738ec56 fc: implement sachen-0037/tengen-800008 mapper (#1558)
Fixes #1031
2024-07-08 10:07:55 +01:00
invertego 79e25f30bf fc: implement tengen rambo-1 mappers (#1555)
Fixes #1308 and #1311
2024-07-07 12:01:00 +01:00
invertego 5bf09dac13 fc: implement camerica/codemasters mappers (#1554)
Fixes #1312
2024-07-07 12:00:34 +01:00
invertego b4fafd9028 fc, ng, sg: add missing cart ram serialization (#1552)
Add missing serialization for the following boards.

fc
- HVC-NROM
- SUNSOFT-1
- SUNSOFT-2
- SUNSOFT-3

ng
- cmc50_jockeygp

sg
- Taiwan-A
- Taiwan-B
2024-07-05 23:47:23 +01:00
jcmandjcm 21f730968b ruby: Use cleaner OpenGL render pattern, misc. CGL fixes (#1543)
### OpenGL rendering (all platforms)

- librashader specifies that the output viewport should be the same size
as the output framebuffer texture. This was not the case for the OpenGL
render code.
* Previously, librashader under OpenGL would render onto an intermediate
framebuffer sized to the "output" size (the entire window view size),
rather than the "target" size (the final composited size of the game
area within the output area). The `libra_viewport_t` would be sized to
the target size, but the underlying buffer would be larger.
* Now, we size the intermediate framebuffer to the "target" size, let
librashader render onto it with a `libra_viewport_t` that matches that
size. In the final pass we sample this buffer within an area of the
"output"-sized buffer as appropriate.

This prior behavior would lead to scaling issues with shaders in the
Metal backend. The same issues did not seem to be obviously present in
OpenGL in my testing, but we should nevertheless probably fix this in
case it is causing any of the subtle issues with shaders that have been
reported, and also in case something breaks in the future as a result of
not following this recommendation.

(The above is also unrelated to the scaling issues addressed by
https://github.com/ares-emulator/ares/pull/1508)

### CGL fix-ups (macOS)

- Backports the native fullscreen and monitor selection options to
OpenGL, and removes unnecessary custom window code from the OpenGL
driver.
- Removes a seemingly unnecessary output call from `reshape` that would
cause flickering during resizes.

This has been tested on macOS but should probably be tested on other
platforms as well to make sure nothing breaks.

Co-authored-by: jcm <[email protected]>
2024-06-21 11:02:59 +01:00
Dragorn421 6cd4470562 Enforce the "C" locale for LC_NUMERIC (fix #1526) (#1542)
Fixes #1526

The default locale in a C program is the "C" locale ( POSIX
https://pubs.opengroup.org/onlinepubs/9699919799/functions/setlocale.html
, C89 standard ), which we want for string-number formatting and parsing

gtk (
https://gitlab.gnome.org/GNOME/gtk/-/blob/a274a5ff4b2a2f9cf9731cdddbb456a0758fcbcc/gtk/gtkmain.c#L435
) and Qt ( 5
https://codebrowser.dev/qt5/qtbase/src/corelib/kernel/qcoreapplication.cpp.html#597
, 6
https://codebrowser.dev/qt6/qtbase/src/corelib/kernel/qcoreapplication.cpp.html#613
) set the locale from the environment variables instead. (by passing ""
as the locale, cf `setlocale`)

This PR sets the locale for `LC_NUMERIC` back to "C" with `setlocale`
after initializing gtk/Qt

I tested this with gtk, saw no problem in the GUI with a rom named
`/home/dragorn421/Desktop/c'est la fête/rom de noël __ やあ!.z64`

Qt codepath is not tested
2024-06-21 10:49:27 +01:00
Luke Usher 393ba03358 pce: prefer Arcade Card for Japan Region
The Arcade Card was always supported, but it was non-obvious that it could be selected; and System Card 3.0 was autodetected, so let's fix that.
2024-06-20 19:10:44 +01:00
Luke Usher 9159438401 ares v139 2024-06-19 17:15:03 +01:00
Luke Usher 3372230021 nall: set numeric locale to "C" at startup 2024-06-19 17:11:58 +01:00
remutro 8c4af6ac4c Add hash to manifest for remaining cartridge based systems (#1536)
This originally added the N64, but after inspecting remaining
cartridge/card/fixed ROM based systems I have also added the additional
four so that hash is available in manifest. This should complete adding
this info for these types of consoles.

N64
Gameboy Advance
MyVision
SG-1000
Sufami-Turbo
2024-06-17 19:38:31 +01:00
Luke Usher b5ee4124e1 nall: enforce "C" locale for toReal/fromReal 2024-06-16 09:40:32 +01:00
remutro 4dbd6fad37 Accept unh extension for unheadered NES roms (#1535)
No-Intro uses the unh extension for un-headered NES roms. Accept this as
a valid extension for the famicom core.
2024-06-16 08:15:44 +01:00
曾耿森 a876f4479d fix(mia): fix all mc-acc game type (#1532) 2024-06-15 22:02:00 +01:00
remutro afa3f08f8c Add sha256 hash to manifest for 2600 and CV (#1533)
Testing some games on Coleco Vision & Atari 2600 and noticed that the
SHA256 ROM hash was missing from the manifest for these two, which I
have now added.
2024-06-15 22:01:47 +01:00
曾耿森 371d6eeaa8 fix(mc-acc): fix mc-acc irq timing (#1531) 2024-06-15 22:01:27 +01:00
Luke Usher e1a940cafa Squashed 'thirdparty/slang-shaders/' changes from 1265cf159..693c632bd
693c632bd Add ray traced curvature shader (#604)
e5b20b142 add licences (#603)
573b339c9 add safe-120 BFI shaders and update motion interpolation for 120 FPS (#599)
ecdbd7b27 Merge pull request #602 from Hyllian/master
44de01372 Add mixed-res preset hooks

git-subtree-dir: thirdparty/slang-shaders
git-subtree-split: 693c632bddc9f8b7aad43d215c487ccc97b5129e
2024-06-15 21:58:58 +01:00
Luke Usher 7c4a36a482 Merge commit 'e1a940cafafc70d06804eb02794fcc06610f68a0' 2024-06-15 21:58:58 +01:00
Luke Usher bea295a915 Squashed 'thirdparty/librashader/' changes from d7665cac9..fff80df5a
fff80df5a ci: temporarily remove deny-deprecated on ctypes to unblock ares
875968d09 dep: update spirv_cross
fa48b936b rt: cap texture scaling to [1, 16384]
0a9fa1685 rt: update for new TAIT scope rules
d558c6e50 dep: update image dependency
48d91dfe5 dep: update image dependency

git-subtree-dir: thirdparty/librashader
git-subtree-split: fff80df5a024346d9409089e8965e323c6ab6698
2024-06-15 21:58:38 +01:00
Luke Usher db1d29ebcf Merge commit 'bea295a915cf9deec71a8ae60b05342a2e63adac' 2024-06-15 21:58:38 +01:00
Luke Usher 54845f6194 Merge commit '7c7d2c2155a4a018794345442b4b4ae6dc3d9449' 2024-06-15 21:58:34 +01:00
Luke Usher 7c7d2c2155 Squashed 'thirdparty/libchdr/' changes from 07a564abe..aa34b1419
aa34b1419 Merge pull request #126 from rtissera/stdint-types
5a39b158a Use standard types from stdint.h / cstdint
84ddc0293 Merge pull request #125 from irixxxx/master
e62ac5995 fix (U)INT types
0b5a86fe0 fix 7ztypes

git-subtree-dir: thirdparty/libchdr
git-subtree-split: aa34b14191f66797b1a64da6539a8d8004497fab
2024-06-15 21:58:33 +01:00
Luke Usher edb88e2e3a Squashed 'thirdparty/sljit/' changes from 1e0579727..c2e49625e
c2e49625e Fix incorrect argument order in x86 sljit_emit_simd_lane_mov
68bb7c7cc Support shuffle on s390x
b3f492960 Support simd shuffle operation

git-subtree-dir: thirdparty/sljit
git-subtree-split: c2e49625e4be2f1e62263044527fe83cce88d2f2
2024-06-15 21:58:25 +01:00
Luke Usher ac75269342 Merge commit 'edb88e2e3ad9bc2e3906af460c427a3b278332fa' 2024-06-15 21:58:25 +01:00
Luke Usher bfc9636403 Squashed 'ares/n64/vulkan/parallel-rdp/' changes from e8a425fab..7e5ad30b8
7e5ad30b8 Update to 43bc31642cc70d04adb828a285e68cdbde7110a9.
0f5d4b328 Update to 2549779edc659cd7f732b1e7fe6e6608ceea487d.

git-subtree-dir: ares/n64/vulkan/parallel-rdp
git-subtree-split: 7e5ad30b8c6e5b863c117997c459441649da9bc7
2024-06-15 21:58:17 +01:00
Luke Usher c6ca36e447 Merge commit 'bfc9636403036d59481741bae3d77d6209aee554' 2024-06-15 21:58:17 +01:00
曾耿森 4e97f23446 feat(fc): add board support TXC-22211A/C(132/173) (#1530)
add TXC-22211A
  add TXC-22211C
  fix TXC-22211B mirror
  pass issue #755 
  pass issue #756
2024-06-14 18:22:47 +01:00
Luke Usher d7dfae7a7a md: emit silence on PWM if uninitialized 2024-06-14 14:15:08 +01:00
Luke Usher 62f1512d44 md: determine 32x clock by 3x m68k clock
md: determine 32x clock by 3x m68k clock
2024-06-14 14:15:08 +01:00
Luke Usher e6481d975e md: determine PWM divisor from configured cycle rate 2024-06-14 14:15:08 +01:00
Luke Usher 61a94f025e md: 32x frequency differs PAL vs NTSC 2024-06-14 14:15:08 +01:00
曾耿森 d76e79076f fix(fc): fix mmc3 board (#1529)
1. fix game Mickey's Safari in Letterland (USA)
2. fix game Incredible Crash Dummies, The (USA)
2024-06-14 12:59:30 +01:00
曾耿森 a574410a03 feat(fc): add new board TXC-22211B(Mapper 172) (#1527)
pass issue #755
2024-06-13 20:09:55 +01:00
曾耿森 dc97c814a3 feat(fc): add new board support (225/255) (#1523)
pass issue #753
pass issue #754
2024-06-12 16:28:52 +01:00
曾耿森 9325b04b23 add board unl-bmc-31-in-1 (mapper 229) (#1521)
add board unl-bmc-31-in-1 (mapper 229)
pass issue #752
2024-06-11 17:23:33 +01:00
Luke Usher 762a2302f7 ci: set windows image to windows-2019
Attempting to workaround broken clang in windows-latest (2022)
2024-06-11 10:26:18 +01:00
曾耿森 2b6346df6e feat(fc): add new board support (#1520)
1. add the board unl-sachen-74ls374n support mapper id = 150 & mapper id
= 243
2. merge Famicom NTSCJ and NTSCU to NTSC
3. pass the issue #282
2024-06-11 09:47:17 +01:00
png183 587aa20dcc gba: improve video capture DMA (#1519)
Video capture DMAs should run only if the mode was enabled on scanline
162 of the previous frame, and should clear the DMA enable bit once
complete.
2024-06-10 08:26:22 +01:00
John Tur 4615a9f4b7 Fix cl build break (#1517)
Fix build break caused by #1515. Let's see what CI says...
2024-06-10 08:26:10 +01:00
曾耿森 fc7cdb57f7 Refactor fc ppu (#1518)
1. pass mmc3/3-a12_clocking.nes
2. refactor the ppu/var and ppu/scroll
3. fix ppu var and scroll read/write($2005/$2006/$2007)
4. inc serialization to v144
5. fix the color generator
6. fix the game Burai Fighter (USA)
7. pass issue #151
2024-06-08 18:29:51 +01:00
John Tur 0a8f25e7d8 Support default device in WASAPI driver (#1515)
The WASAPI sound driver now supports a "Default" audio output device:
<img
src="https://github.com/ares-emulator/ares/assets/27514983/fbf358d6-41e7-478d-8a76-fc86790d7774"
width="650" />

This uses the [Automatic Stream
Routing](https://learn.microsoft.com/en-us/windows/win32/coreaudio/automatic-stream-routing)
API that was introduced in Windows 10. A runtime check was added to
ensure that the feature does not appear on older versions of Windows.

I did some limited testing and found the feature to work without issues.

Closes https://github.com/ares-emulator/ares/issues/1514
2024-06-07 10:48:42 +01:00
Giovanni Bajo f3cdf203c3 n64: poll gdb more frequently (#1512)
Currently, gdb is polled once per frame, which seems enough for
interactive usage. Some ROM hacks would like to use the gdb interface to
provide additional emulation-only features such as online multiplayer,
but that requires a faster turnaround.

A quick solution is to poll gdb more frequently within the n64 core.
This patch does that once per screen line, approximately. Notice that
the poll is only scheduled and run if there is a gdb client connected so
it should not cause any performance impact on normal users.
2024-06-07 10:48:05 +01:00
Luke Usher 76615ce847 Squashed 'thirdparty/slang-shaders/' changes from 6cb93ce1b..1265cf159
1265cf159 Merge pull request #601 from Hyllian/master
d96718591 Add mixed-res-crt-hyllian preset
407a45729 Merge pull request #600 from Hyllian/master
8583cfee2 Update mixed-res shaders

git-subtree-dir: thirdparty/slang-shaders
git-subtree-split: 1265cf159d63253ab8978c7f9e63048e9d791e8c
2024-06-03 17:49:42 +01:00
Luke Usher 5e04d6d31b Merge commit '76615ce847483d1c158a06d513331325236819af' 2024-06-03 17:49:42 +01:00
Luke Usher 2d81319a2f Squashed 'thirdparty/sljit/' changes from a7066fdb1..1e0579727
1e0579727 Fix constant pool bug on arm32 (#249)

git-subtree-dir: thirdparty/sljit
git-subtree-split: 1e0579727f5805f0e34cca6b5e0c841dd92ebfb0
2024-06-03 17:49:25 +01:00
Luke Usher 4b3b8b9f5b Merge commit '2d81319a2f0115eec97620a389715eddde7c13fa' 2024-06-03 17:49:25 +01:00
Luke Usher 36df7ab00f Merge commit '47d6d256876d6cab7c16bd6e04c657b976339e51' 2024-06-03 17:49:04 +01:00
Luke Usher 47d6d25687 Squashed 'ares/n64/vulkan/parallel-rdp/' changes from ff3b858dd..e8a425fab
e8a425fab Update to ffc0d865836eb2f90c85e4694e4cfe363be908e6.
aba102d24 Update to e564cbc01a49d2d94d90e60cc5c2f406d9ac4aad.

git-subtree-dir: ares/n64/vulkan/parallel-rdp
git-subtree-split: e8a425fabc3a25d1855d5f217c6857e5e9bf1af2
2024-06-03 17:48:34 +01:00
jcmandjcm 117f4f7b4e UI: Initialize all video options correctly on driver settings update (#1513)
Just a small fix to account for the new video settings in Metal; the
threaded renderer, native fullscreen behavior and color space option.
These options were not fully persistent because the `videoDriverUpdate`
function (run on startup, among other times) did not account for them.
They would be set correctly in `settings.bml` and the settings object,
but would never actually be set correctly on the driver struct.

Co-authored-by: jcm <[email protected]>
2024-06-03 11:09:17 +01:00
Adrian Siekierka c23a3f736d ws, m93lcx6: improve EEPROM emulation accuracy (#1509)
* The behaviour of bits 0-3 and 7 in the control/status port were a
complete guess and had no reflection in hardware testing. They have been
adjusted to match hardware.
* The EEPROM interface always writes and reads out 16 bits to/from the
EEPROM, including the initial zeroes in the command value. The M93LCx6
code has been updated to support this case in line with the datasheet.
* The read and write data port have been separated. This was a detail
which every community documentation in existence got wrong, so no
worries about that one ^^
* Internal EEPROM protection has been implemented.
* The handling of invalid control commands (more than one bit set) has
been fixed.
* Emulation of the 93C46-family internal EEPROM on SPHINX in ASWAN mode
has been implemented. In particular, this fixes running any mono
WonderSwan game which takes advantage of the internal EEPROM on the
WonderSwan Color system's compatibility mode.

All of these changes pass the relevant tests in
[ws-test-suite](https://github.com/asiekierka/ws-test-suite)
(mono/eeprom/internal.ws) both as a WonderSwan and a WonderSwan Color.
This isn't 100% accurate (particularly, timing is not reflected; but
there are also some questions about more edge case-y behaviour), but
it's much closer.
2024-05-30 14:19:44 +01:00
jcmandjcm dd25ac4f72 n64: fix macOS build (#1507)
The paraLLEl-RDP build was broken on macOS because of a change from
February to Granite in regarding platform ifdefs for pthreads.

A PR that applies a fix has been opened
[upstream](https://github.com/Themaister/Granite/pull/131), but until an
upstream fix lands, this PR will unbreak the build for ares without
needing to roll back the recent paraLLEl-RDP update entirely.

Co-authored-by: jcm <[email protected]>
2024-05-28 15:02:15 +01:00
Luke Usher 804e6699a4 fix build after updating deps 2024-05-27 10:22:16 +01:00
Luke Usher c2dede6c85 Squashed 'thirdparty/slang-shaders/' changes from 1c0a4ccbd..6cb93ce1b
6cb93ce1b koko-aio hotfix4 (#597)
6e3cc4c11 Merge pull request #598 from keylimesoda/patch-1
36c6c7bf7 Update curvature.h
56d13de9b Sync to koko-aio 1.9.20-hotfix3 (#596)
9c930380c fixed undefined function in warp_koko() (#593)
8bdee83e3 Merge pull request #594 from Hyllian/master
37cce2aa7 Update mixed-res shaders.
ba6f00b5c Merge pull request #592 from HyperspaceMadness/master
e931b7a10 Mega Bezel V1.17.2_2024-05-18 Update of Mega Bezel with fixed paths and removed failing wildcard testers. Added an additional independent DREZ preset
7b4baaa11 Merge pull request #591 from Hyllian/master
ed50f0475 Add deblur-luma shaders
99d1bfe3b Merge pull request #590 from kokoko3k/master
0a741ee7a sync to koko-aio 1.9.20
8724e92bd Merge pull request #589 from Hyllian/master
879dcd27f Add bilateral-2p shaders
5fbd61058 Merge pull request #588 from Hyllian/master
d5a089f77 Add bilateral shader from guest.r
4968a5294 fix NSO-gbc-color.slang
7fc92d726 Merge pull request #587 from Hyllian/master
97c7ed71c Add crt-royale-downsample preset and LUTs
699402877 Merge pull request #586 from Hyllian/master
729ab1767 Update super-xbr and mixed-res shaders
3378d0160 Fishcu/pixel aa xform (#585)
f047ae72a Merge pull request #584 from Hyllian/master
096f95adc Update dilation shader
7aff4e6cc Merge pull request #583 from fishcu/fishcu/rename-includes-to-inc
31caee64d Rename files that are included but no proper shader on their own to .inc
0eb12c628 Fishcu/authentic gbc (#582)
67a1ee78e Merge pull request #581 from Hyllian/master
c562d89ec Update film-grain.slang
4de167851 Merge pull request #580 from Hyllian/master
96713a17f Add film-grain shader
e77c37fe5 Merge pull request #579 from kokoko3k/master
d49bab8d0 Add autocrop-koko shader
ca2c0223c Merge pull request #578 from Hyllian/master
71d3618ba Add crt-royale-smooth preset
2f8af209b Merge pull request #577 from Hyllian/master
40f5d882c Add n64 3-point and relief shaders
7984c9953 Merge pull request #576 from Hyllian/master
594d9a2fc Add lanczos2-5-taps
ee403bcdd Merge pull request #575 from Hyllian/master
e8287f250 Add mixed-res shaders
341aac7b7 Add 2xsal-level2-xbr shader and presets (#573)
9f2c20102 Merge pull request #572 from Hyllian/master
c342a69e3 Merge pull request #567 from mattakins/master
2e3f25c34 Add NEDI-Hybrid shaders
d7e15b9c0 Merge pull request #571 from fishcu/fishcu/minor-fixes
932d2a630 Merge pull request #570 from HyperspaceMadness/master
b5bf043b1 Change default param
5831505f0 Minor fixes found during GLSL porting of code
155e471ca Updated gameboy preset names based on feedback
b6b379281 Added drez and improved print-resolution
05414f65e Merge pull request #568 from Hyllian/master
0135078c3 Update NEDI shaders
2ac8ca7c1 Update ddt.slang
6bfb9df4d Added gameboy-advance preset
eab71b6be Added gameboy-pocket-high-contrast
69c282123 Added gameboy-color-white-bg preset for gameboy shader
f7cf08900 Restored gameboy shader Blending Mode default to 0
dd228b941 Merge pull request #566 from Hyllian/master
7b0a142a1 Add cheap-sharpen shader
2a7c19b6b Merge pull request #565 from Hyllian/master
68d982035 Add bicubic-5-taps and hermite shaders
93c954798 Merge pull request #564 from Hyllian/master
28fb09f79 Add b-spline-4-taps and catmull-rom-5-taps

git-subtree-dir: thirdparty/slang-shaders
git-subtree-split: 6cb93ce1be67b314a96f5e346befb2b58b63eb04
2024-05-27 10:05:10 +01:00
Luke Usher 6cabb5d118 Merge commit 'c2dede6c851c20e50398e724966394235221bb70' 2024-05-27 10:05:10 +01:00
Luke Usher 5c92d877c8 Squashed 'thirdparty/librashader/' changes from e8ffd8fdf3..d7665cac9b
d7665cac9b Update wgpu

git-subtree-dir: thirdparty/librashader
git-subtree-split: d7665cac9b7a9761290a1b76bd59d39205497326
2024-05-27 10:04:45 +01:00
Luke Usher 9db8decbd6 Merge commit '5c92d877c8850f0e37ca03405392530f2ba0a314' 2024-05-27 10:04:45 +01:00
Luke Usher 0ef0a3e3a7 Squashed 'thirdparty/libchdr/' changes from 5c598c2df3..07a564abe4
07a564abe4 Merge pull request #124 from rtissera/revert-libretro-changes
d1fe3009c8 Revert "Merge libretro stuff, bump to 0.3 version"
b5603a577b Merge pull request #123 from rtissera/merge-libretro-stuff
56b08d53f8 Merge libretro stuff, bump to 0.3 version
86b272076d Merge pull request #122 from scribam/zstd-disable-shared
a4fa03bba9 zstd: disable shared lib
67c96ef582 Merge pull request #121 from scribam/zstd-1.5.6
45c53ae969 deps: update zstd to version 1.5.6
f8f2f8bf77 Merge pull request #120 from scribam/bsd
d93a99ced9 cmake: remove "-Wl,--no-undefined" on OpenBSD
d670e6833c ci :add GitHub Actions for BSD
2d315cad12 Merge pull request #119 from scribam/lzma-24.05
715f33792f deps: lzma compatibility changes for switch and vita platforms
25543a5214 deps: bump LZMA SDK to 24.05 and build with asm optimizations
0841ba38ee Merge pull request #116 from notaz/missing_auxv
6c739c2f67 handle more platforms that lack getauxval/AT_HWCAP

git-subtree-dir: thirdparty/libchdr
git-subtree-split: 07a564abe462f1aece58c794a3c2a6fed688afea
2024-05-27 10:04:39 +01:00
Luke Usher dbb3b85bb3 Merge commit '0ef0a3e3a7eb717224d885b3d1e135076c360c89' 2024-05-27 10:04:39 +01:00
Luke Usher c94794e959 Squashed 'thirdparty/sljit/' changes from 5420f8bee8..a7066fdb10
a7066fdb10 Improve fop2 with single precision opcode on x86
daf33c9165 Fix TMP_REG2 usage fault in sljit_emit_simd_lane_mov for LoongArch (#248)
cb9b068274 Improve op_flags on s390x
d86e6cbf6c Implement LoongArch LSX and LASX SIMD Support (#247)
9017d72988 Allow forcing VEX prefix on x86
79256319d6 Add temporary register support to ijump
db3ca5014f msan fixup (#245)
ad89dd8ecd Fix locking region in sjlit_malloc_exec (#244)
bbeafb0ff4 Add temporary register support to select on LoongArch (#243)
5aeae2a2af Add temporary register support to select on s390x
56dbde07b0 Add xgetbv feature detection support on x86
d2374c2043 Add compare to temporary register tests
b67fc5c5eb Add temporary register support to select
14622914aa Split sljit_p to sljit_up/sp variants
42ac81c053 Fix LoongArch floating point select tests (#242)
36c6047c78 Add floating point select tests
eef5fceee3 Add simd lane mov temporary tests
c6ce9a3749 Add float conversion temporary tests
277093d3d0 Add simd temporary tests
9827eb7e00 Fix build on older macOS (#240)
19e2693245 Fix LoongArch binary temporary tests (#239)
af736af648 Add binary temporary tests on s390x
2ea42b1924 Add binary temporary tests
3d66db5ac4 Absolute jumps / fast calls should not modifiy SLJIT_TMP_DEST_REG
f9869a6810 Fix LoongArch float temporary tests (#238)
9737b3c943 Add float temporary set tests
4fd70d341d Add float temporary tests
8629fad57d Fix RISCV temporary register use
b0fd8cd2c3 Add memory temporary tests
958e8d7bcc Support addmul on LoongArch64 (#237)
c4769cbc4a Support addmul on s390x
6b8503dadc Support addmul on x86, arm, riscv, ppc, mips
c1ae218f51 Add multiplcation tests with temporary register support
a78d9ded50 Fix failing tests on ARM, PPC
120c6efc44 Add more temporary register tests
4e34ed5fb0 Improve temporary register support
46f12a2c46 Fix leaks (#236)
40eff81472 Update create compiler and generate code arguments
bf9bf14961 Support recent changes on LoongArch64 (#235)

git-subtree-dir: thirdparty/sljit
git-subtree-split: a7066fdb10a915dacd5ec39f10b4048002c7b748
2024-05-27 10:04:35 +01:00
Luke Usher 2abc056d06 Merge commit 'c94794e9599911d2bd0c22c07adb30ca127f5adf' 2024-05-27 10:04:35 +01:00
Luke Usher 9664144d1b Squashed 'ares/n64/vulkan/parallel-rdp/' changes from 37bf2967e3..ff3b858dd3
ff3b858dd3 Update to 16d3a27eab1af53021bf6a49807e5e0720862bd3.
7cdcaa3db9 Update to d7746d1f999ba1507f4d2fd8fade77ee3cbb5425.

git-subtree-dir: ares/n64/vulkan/parallel-rdp
git-subtree-split: ff3b858dd3a7ca27bd7c91fc894a7acd13fc0bcf
2024-05-27 10:04:30 +01:00
Luke Usher f31d209883 Merge commit '9664144d1bf2986191b54e97f712c6516ae15672' 2024-05-27 10:04:30 +01:00
png183 21209edad6 gba: synchronize CPU with other components more frequently (#1506)
Reduces the synchronization interval between the GBA CPU and other
components from 64 to 16 cycles, which significantly improves PPU
timings in the performance profile. These PPU timing improvements can be
observed in
[status-irq-dma.gba](https://github.com/nba-emu/hw-test/tree/master/ppu/status-irq-dma),
which now frequently gets results within a few cycles of the correct
values in situations which were previously off by dozens of cycles.
While this does impact performance by ~5-10%, in my testing this is
still faster than versions from before [commit
b145f0f](https://github.com/ares-emulator/ares/commit/b145f0f000c4e0ddedf25a62cdcfe713deea1f6a).
2024-05-26 07:04:53 +01:00
png183 8f3261e870 gba: improve BIOS open bus edge case handling (#1504)
This PR improves handling of BIOS open bus edge cases that previously
were handled incorrectly, such as unaligned 8-bit and 16-bit accesses,
and cases where the last value read from BIOS was not a 32-bit value.
2024-05-21 11:50:24 +01:00
thekovic a65bf18645 nall: fix Wcast-user-defined warning (#1494)
Compiling with GCC 14.1 in MSYS2 caused a lot of warnings of the
`-Wcast-user-defined` variety. This PR adresses that.

Note: This PR does not address
https://github.com/ares-emulator/ares/issues/1399 . Those warnings
happen at the link stage, they don't seem to be GCC-only (since issue OP
also reports them with clang), and they don't appear at lower
optimization settings (I tested `build=debug` and `build=stable` which
compiled cleanly).
2024-05-18 16:56:32 +01:00
Derek "Turtle" Roe a327e9b953 Fix some inconsistent formatting in the N64 database (#1496)
Just fixed up a few inconsistent formatting issues in the N64 database
while I was taking a peek 😄
2024-05-18 16:56:18 +01:00
曾耿森 672e81572c fix(ppu): fix some ppu bug and pass some tests (#1493)
1. fix read OAMDATA($2004)
2. fix write OAMDATA($2004)
3. refactor struct OAM access operator[]
4. remove some unused variable in ppu.io
5. spriteEvaluation.oamMainCounter is reference oamAddress
6. fix ppu sprite evaluation in pre-rederer line
7. inc fc serialization version to v143
8. pass blargg_apu_2005.07.30/09.reset_timing.nes
9. pass dmc_dma_during_read4/dma_4016_read.nes
10. pass sprdma_and_dmc_dma/sprdma_and_dmc_dma.nes
11. pass sprdma_and_dmc_dma/sprdma_and_dmc_dma_512.nes
2024-05-18 16:17:25 +01:00
曾耿森 deb1cf6d79 fix(ppu): fix some bug and pass test power_up_palette.nes (#1500)
pass blargg_ppu_tests_2005.09.15b/power_up_palette.nes
pass "Hello World" PPU test:
https://github.com/PeterLemon/NES/tree/master/HelloWorld

In https://forums.nesdev.org/viewtopic.php?t=567#top,

blargg say: "The power-up values of the palette are what my test program
reads back after powering the NES. I have one of the older units that
shows a green screen (I think newer front-loading ones had a gray
screen). These values probably vary slightly from one console to the
next."

Palette at power-up
0x09,0x01,0x00,0x01,
0x00,0x02,0x02,0x0D,
0x08,0x10,0x08,0x24,
0x00,0x00,0x04,0x2C,
0x09,0x01,0x34,0x03,
0x00,0x04,0x00,0x14,
0x08,0x3A,0x00,0x02,
0x00,0x20,0x2C,0x08,

To read/write a cgram, it needs to and 0x03, not 0x13

In https://www.nesdev.org/wiki/PPU_palettes#Memory_Map

$3F00	Universal background color
$3F10	Mirror of universal background color

$3F04	Normally unused color 1
$3F14	Mirror of unused color 1

$3F08	Normally unused color 2
$3F18	Mirror of unused color 2

$3F0C	Normally unused color 3
$3F1C	Mirror of unused color 3
2024-05-18 16:16:30 +01:00
remutro 70f833957e Resize target buffer when IPS patch extends beyond original source size (#1501)
For IPS patches that extend the original ROM beyond its initial size, we
will now resize the target buffer when patches extend the size of the
original.

Originally found testing out the Shin Megami Tensei patch by Orden
(https://www.romhacking.net/translations/2616/), which will now work
correctly.
2024-05-18 16:16:11 +01:00
曾耿森 8b5e30dad9 feat(fc-ppu): pass some ppu test (#1490)
1. pass sprite_overflow_tests/1.Basics.nes
2. pass sprite_overflow_tests/2.Details.nes
3. pass sprite_overflow_tests/3.Timing.nes
4. pass sprite_overflow_tests/4.Obscure.nes
5. pass sprite_overflow_tests/5.Emulator.nes

6. fix cpu serialization bug (miss oddCycle)
7. inc the fc serialization version
2024-05-11 21:39:04 +01:00
png183 9fb9dd59ba gba: latch timer register writes for 1 cycle (#1489)
Latches writes to timer registers for 1 cycle. This fixes common
off-by-one errors with precise timer use, which for example positively
impacts the test cases in #154.
2024-05-11 21:38:28 +01:00
jcmandjcm 67fc9ea81b ruby: Various Mac driver settings fix-ups (#1486)
This PR applies several minor fixes and improvements to macOS driver
settings and the driver settings pane.

#### Remove the "exclusive mode" video option on macOS.

* There is no real notion of exclusive presentation on macOS beyond what
already exists in normal fullscreen. If an application is covering the
screen and no other application or window is visible, the system
automatically switches to a "direct" presentation mode that optimizes
for single-application presentation performance. There is not a good
reason to show this option on macOS, even disabled.
* By contrast, it is possible (though not implemented by ares) to enter
exclusive mode on the audio device with CoreAudio, so leave that option
there, just disabled.
#### Add a "use native fullscreen" option on macOS.
* There are various good reasons to prefer either native platform
fullscreen behavior, or a custom borderless windowed fullscreen. Rather
than guess what the user wants, offer an option.
* If unchecked, make the window title bar enlarge the window rather than
fullscreen it, so we don't mix behaviors.
#### Implement fullscreen monitor selection behavior for Metal, and
correctly enumerate the user's monitor names.
* Fullscreen display on the selected monitor in the settings pane was
previously not implemented on macOS. This implementation only works if
"Use native fullscreen" is disabled, since the macOS fullscreen idiom
doesn't feature selecting a specific display.
* Additionally, the old function to retrieve the monitor's localized
name did not work reliably on newer macOS versions. Use the modern
property `localizedName` on NSScreen for macOS versions above 10.15, and
fall back to the old implementation otherwise.
* Implementing this meant adding a `uintptr` handle to the NSScreen
instance in the `Monitor` struct in ruby that uses a bridged cast to
interface with Objective-C. I would have preferred not to do this, but I
didn't see another good way to handle getting the `NSScreen` instance
that didn't involve a serious refactor.
#### (all platforms) Disable monitor selection if the video driver's
`hasMonitor()` is false.
* Just a minor fixup; the existing behavior is that the dropdown list
can be navigated and selected, but the selection does not persist. It
makes more sense to just disable it if the driver doesn't support it.

Co-authored-by: jcm <[email protected]>
2024-05-05 16:11:35 +01:00
shinra-electric 4f834bd506 CI: Update cache and checkout to v4 (#1478)
- Updates `checkout` from v2 to v4
- Updates `cache` from v3 to v4

Reasons for change: 
- Checkout@v2 runs on node 12, which has been
[discontinued](https://github.blog/changelog/2023-06-13-github-actions-all-actions-will-run-on-node16-instead-of-node12-by-default/)
- Checkout@v3 runs on node 16 and has also reached its [end of
life](https://github.blog/changelog/2023-09-22-github-actions-transitioning-from-node-16-to-node-20/),
so skip it entirely.
- Cache@v3 runs on node 16 as well, so update to v4 for the same reason.

Testing: 
- Ensure CI passes
- Check that warnings regarding `checkout` and `cache` are gone
2024-05-04 09:33:58 +01:00
曾耿森 785c148768 fix(fc): fix fc dma interrupt (#1476)
pass cpu_interrupts_v2/4-irq_and_dma.nes
2024-05-03 11:14:08 +01:00
png183 cfda608bc2 gba: improve VRAM mirroring in bitmap background modes (#1475)
Blocks accesses to the mirrored region at VRAM addresses 0x18000 to
0x1bfff when in background modes 3-5, as described
[here](https://github.com/nba-emu/hw-test/tree/master/ppu/vram-mirror).
2024-05-03 11:14:02 +01:00
shinra-electric f94e053767 CI: Update upload-artifact and download-artifact to use v4 (#1472)
- v2 will be unavailable from the end of June 2024
- v4 can be up to 98% faster than previous versions according to
[Github's
notification](https://github.blog/changelog/2024-04-16-deprecation-notice-v3-of-the-artifact-actions/)

This PR only changes the version number, and I'm submitting it to see if
it works.
It is possible that further changes are necessary, as there were some
[breaking
changes](https://github.com/actions/upload-artifact?tab=readme-ov-file#breaking-changes),
but I don't think any of them apply to ares.

Testing: 
- See if CI passes
- See if warnings regarding using v2 of `upload-artifact` and
`download-artifact` are gone (There will still be other warnings
regarding `checkout` and `cache`)
- (Optional) Compare times for the tasks using `upload-artifact` and
`download-artifact` with previous CI runs
2024-05-03 11:13:55 +01:00
remutro 6e8bcd9bda Disable run ahead for 64DD, fixes load failures (#1474)
Turns out the problem some folks experienced trying to load 64DD games
was due to run ahead not being disabled by default. An exception for
this system has been added.
2024-05-02 19:18:18 +01:00
Luke Usher 57c01b8e17 bump version to v138 2024-05-02 13:12:55 +01:00
jcmandjcm bf5536cb18 CI: Fix macOS build name errors for release action (#1468)
#1463 renamed the `macos` build to `macos-latest` and introduced
`macos-compat`. We need to address the rename in the release workflow. I
believe this PR accounts for every use of the package name. Also adds
macos-compat to the release (for now).

Co-authored-by: jcm <[email protected]>
2024-05-01 19:49:32 +01:00
jcmandjcm e33f6e4056 ruby: improve clear() in Metal to prevent possible shader crash (#1466)
clear() in Metal was implemented by outputting a (1, 1) sized output
buffer. This was very quick and dirty though generally worked.

With librashader introduced in the render output chain, outputting a (1,
1) sized buffer can sometimes, depending on the shader, introduce an
intermediate pass that involves a (0, 0) sized MTLTexture, which can
lead to assertion failures and possible crashes.

This PR adds an actual clear() implementation that just does a blank
render pass. the clear color on the drawable is already defined during
initialization so we do not need to redefine it here.

Co-authored-by: jcm <[email protected]>
2024-05-01 16:54:24 +01:00
remutro ffccbc6e9c librashader build on Linux (#1465)
Added a section for building librashader on Linux

Didn't want this to get too long or distro specific so these should be
the absolute minimal instructions for the platform.
2024-05-01 11:14:59 +01:00
jcmandjcm caecd0bca2 infra: update macOS build scripts and SDK, bump MoltenVK to 1.2.7 (#1463)
This PR does a few things:

- Updates ares to create macOS builds with the latest SDK. After
https://github.com/ares-emulator/ares/commit/65264090b06853f3d831f507a3335d9c42e8a198
there are no longer any outstanding issues doing so. Importantly, we use
Xcode 15.2, since prior versions have issues with weak linking.
- Adds `macos-compat` to CI as a compatibility build that maintains
macOS 10.9 to 10.13 compatibility. The `macos-latest` runner will target
10.13 and above. The only difference with this build is the SDK version
used to build it (Xcode 13.4); macOS weak linking handles the rest.
- Increments the MoltenVK version to 1.2.7. The version ares was
building required a Python library `distutils` that is no longer
trivially available with newer Python versions.
- Refactors the `xcode-select` usage reserved for GitHub Actions out of
the SDL script and up to the top level, before any dependency scripts
are run. This is just tidying up.
- Improves the librashader build script warning to specify that you need
to add a target with the nightly toolchain to build librashader (from
@rasky)
- Unbreaks the build.

This PR has been tested and verified to build in a local branch, but to
be safe, it would probably be good to run it here as well.

Co-authored-by: jcm <[email protected]>
2024-05-01 11:14:45 +01:00
jcmandjcm 1b3e826575 n64: Unload and save before reset() on gamepad and disk (#1464)
https://github.com/ares-emulator/ares/commit/7ad14ff6bfbd7a67fa6670101ef8a30bfa030e5e
inadvertently made it so that .pak saves (and other save data) are not
properly persisted to disk when unloading the n64 core. This PR resolves
that, calling `unload()`, which itself calls `save()`, before resetting
the gamepad and other memory.

Co-authored-by: jcm <[email protected]>
2024-04-30 10:43:07 +01:00
jcmandjcm a6d380fb57 ruby: Remove tight loops in SDL and OpenAL (#1458)
When we are synchronizing to audio and waiting for buffers to play back
before continuing in the emulation thread, the SDL and OpenAL audio
drivers currently wait inefficiently in tight loops that consume many
CPU cycles. This PR adds `usleep` calls to these loops.

In the case of the SDL driver, we sleep for ~~the time it takes one
quarter of our prescribed buffer size to play~~ precisely the amount of
time to play our queued audio that's in excess of our prescribed buffer
size.

For the OpenAL driver, it was more difficult for me to determine how to
see exactly how much time we should be waiting since the loop seems to
work slightly differently. One millisecond seemed reasonable given that
the minimum latency is 20 milliseconds, and was sufficient to introduce
significant savings without impacting performance.

Exactly how much CPU use this saves depends on a couple factors;
primarily, the host CPU and the guest core (more demanding cores will
spend a smaller share of time waiting in the audio driver). Reduction
seems independent of audio latency. Here are some sample figures for the
M1 Max:

SNES core (Super Mario World): 95-105% CPU use before, 40-50% CPU use
after with both OpenAL and SDL.
N64 core (Super Smash Bros): 100-110% CPU use before, 60-70% CPU use
after with both OpenAL and SDL.

(macOS's activity monitor measures activity as 'percent of one core',
hence the over-100% figures).

Less demanding cores and more powerful systems will benefit more from
this change, generally.

I tested this pretty thoroughly on my system to make sure that it did
not impact performance on even the lowest 10ms SDL latency on the most
demanding N64 core. However, other people putting this through its
paces, particularly on less powerful systems, would be a good idea, to
make sure that platform differences in `usleep` behavior don't have
unexpected results.

Co-authored-by: jcm <[email protected]>
2024-04-29 18:45:15 +01:00
png183 edf25196ee gba: fix timing of initial DMA wait cycles (#1461)
DMAs on the GBA wait for two cycles before taking control of the bus.
While ares implements this behaviour, ticking these cycles before
running DMAs causes the DMA to run early in ares when the current call
to `CPU::step()` runs for a number of cycles equal to or greater than
the number of DMA wait cycles left.

This PR addresses the issue by ticking DMA wait cycles after running all
DMAs that are currently ready, fixing several timing test cases in the
mGBA test suite, and improving timings in the [Hades DMA start delay
tests](https://github.com/hades-emu/Hades-Tests/blob/master/source/dma-start-delay.c).
2024-04-25 08:47:34 +01:00
png183 de8f344b89 gba: improve handling of SRAM/Flash bus (#1459)
This PR accounts for using 16- or 32-bit accesses in the cartridge
backup region, which has an 8-bit bus, and accounts for reading from
said region when no SRAM or flash memory is present. Passes all of
[jsmolka's save
tests](https://github.com/jsmolka/gba-tests/tree/master/save).
2024-04-23 11:27:45 +01:00
Luke Usher 8498b95ab5 n64: manually tick cartridge rtc
Also moves dd daysInMonth to nall::chrono
2024-04-23 11:11:17 +01:00
Luke Usher 8a547cacc0 n64: use gmtime rather than localtime when incrementing rtc 2024-04-22 15:04:47 +01:00
Luke Usher 1bdfa3e21a Merge branch 'master' of https://github.com/ares-emulator/ares 2024-04-22 11:19:49 +01:00
jcmandjcm b5cd509a77 ruby: Add Metal VRR support, various Metal driver fixes (#1455)
Adds to the Metal backend from #1431, extending host VSync functionality
to variable refresh rate (VRR) displays, enabling the ability to sync to
guest and host refresh rates simultaneously, along with an assortment of
minor changes and code cleanups:

- Adds a threaded renderer option (technically a GCD queue) to the Metal
backend; essential for VRR at lower audio latencies. At higher audio
latencies, the synchronous rendering option may function better.
- Add easier debug capabilities, including a shell script to compile a
debug `.metallib` shader library which will be used at runtime if ares
is compiled in debug mode. The debug `.metallib` enables GPU frame
capture.
- Implement `clear()` for the Metal backend; the last displayed frame
will no longer stay on the screen if a core is explicitly unloaded.
- Implement fullscreen mode. Uses a borderless window that covers the
entire screen, rather than idiomatic fullscreen, primarily in order to
render around the camera housing. Normal macOS fullscreen behavior is
available via the main window title bar controls.
- Remove unused custom window code.
- Remove redundant copy of `Shaders.metal`.
- Miscellaneous small fixes and code cleanups to resolve compiler
warnings.


https://github.com/ares-emulator/ares/assets/6864788/1e2d594a-c84f-4b95-a792-cacdde2a09b0

## ares vs. VRR
As discussed in #1431, there are some challenges in implementing smooth
VRR support for ares on Metal. Briefly:

- ares lacked a mechanism to tell the display backend the core's desired
refresh rate, in order to sync to it.
- ares on macOS lacked an effective mechanism for receiving callbacks
when frames were presented, in order to keep track of whether we were
running fast or slow, because of the way ares monopolizes the main
thread on macOS.

The first issue has been resolved by a3c57b4 and ec0b625. Cores now tell
the `Screen` instance how often they want to present, and the screen
instance will tell the display backend if it implements the
`refreshRateHint` function. This enables the display backend to quickly
respond to changing guest refresh rates even during runtime.

The second issue is a bit trickier. As discussed, `MTKViewDelegate` and
`CAMetalDisplayLink` are both effectively unavailable until ares moves
its primary emulation work off of the main thread. There is, however,
one Metal callback mechanism that can still be used by ares;
[[MTLDrawable
addPresentedHandler:]](https://developer.apple.com/documentation/metal/mtldrawable/2806858-addpresentedhandler?language=objc),
because it calls back on a dedicated serial queue
(`com.apple.coreanimation.CAMachPortUtilReplyQueue`) rather than the
main thread.

Using this presented handler, ares can use `drawable.presentedTime` to
keep a running average of how long our frames are being presented for,
determine if we are running ahead or behind, and modify our subsequent
present intervals accordingly. That is what we do for this initial VRR
implementation.

## macOS VRR

> [!NOTE]
> The following applies to "ProMotion" displays, as those are the ones
most tightly integrated with macOS and most likely to be used by Mac
users on VRR displays.

Unfortunately, VRR sync is not as simple as just picking a present
interval and telling macOS to present each frame for the guest's
requested interval. macOS only pretends to offer this capability in
exclusive fullscreen mode, and even then, present intervals cannot be
completely arbitrary. Realistically, we seem to be able to get
consistent present intervals for some integer refresh rates between 40
Hz and 120 Hz, and certain rational present intervals (59.97, 23.976
among them). The spread of achievable consistent present intervals seems
to be arbitrary enough that there isn't any sense in targeting them
specifically. Even if we can theoretically present at the exact interval
the guest wants, we inevitably end up falling behind due to transient
load conditions.

> [!NOTE]
> For background, the landscape of guest refresh rates in ares is quite
wide. Many systems present near 60 Hz; 59.97, 60.01, 59.73, 59.92,
59.82, etc. Many of these systems have PAL modes that present near 50
with similar variations. The WonderSwan presents at a maximum of ~75.47
Hz, with per-game variations. The Atari 2600 can present at completely
arbitrary intervals during runtime owing to its CRT- and
processor-centric presentation strategies. In short, It is difficult to
narrow the range of expected guest present intervals if we wanted to
simplify this problem.

Rather, we have to pursue a more holistic strategy. The strategy ares
uses with this PR is as follows:

1. The output function sends frames into a FIFO dispatch queue that can
present asynchronously, to reduce the burden of needing to present
immediately if we are in danger of blocking the main thread.
2. If we are more than 0.5% off of the targeted present interval as
determined by a weighted rolling average, start "nudging" the system to
present at earlier intervals calculated according to the difference
between the rolling average and the target, multiplied by a constant
`kVRRCorrectiveForce`.
- This is done because we can often prod the system into presenting at
rational intervals close to the target interval, resulting in an overall
smoother presentation to the user than if we were to correct more
forcefully.
3. If more than `kVRRImmediatePresentThreshold = 3` frames are in the
queue to be presented, start telling the system to present immediately
instead of "nudging."
- This is a more forceful correction toward the target present interval,
and must be kept low for systems that want to present at intervals that
are far away from any achievable consistent present interval.
4. If the queue gets much deeper, `kMaxSourceBuffersInFlight = 6`, start
dropping frames.
- This is necessary for synchronizing to neither audio nor video, or
else in rare cases where the GPU is overloaded, such as for a shader
that the system is not capable of rendering in time each frame.

This system achieves decent results across most systems in my testing. I
considered allowing these constants to be twiddled with sliders, but was
wary of presenting too many esoteric options to the user. If it's
determined to be worth exposing these constants, that can be done in
future work (if a superior VRR presentation strategy entirely is not
discovered by that point).

## Miscellany

- The threaded renderer is necessary so that we do not ever block the
main thread in the worst case present interval conditions. However, it
only works well at relatively low audio latencies. At higher audio
latencies (as for users on lower-specced systems), the queue overflows
easily and it works better to render synchronously.
- The threaded renderer can also have unintuitive results when
exclusively syncing to host VSync or GPU sync, so for users that expect
particular behavior from that functionality, it is better left disabled.
- For PAL refresh intervals, players will get generally better results
in exclusive fullscreen. macOS likes to render things at 60Hz and will
struggle to render near 50 Hz with other elements onscreen.
- To view the present interval graph as in these debug shots, input
`defaults write -g MetalForceHudEnabled -bool YES` at the command line
before launching ares.

## Future Work

We could possibly achieve better VRR results utilizing something like
`CAMetalDisplayLink` after freeing up the macOS main thread. In my
testing it seems to have the same limitations in terms of achievable
consistent present intervals, but it may offer a more precise picture of
host vs. guest present timing.

Regardless of the viability of other strategies, it would still be
valuable to free up the main thread on macOS for the sake of other
system APIs that may be used in the future, plus benefits of being able
to use the UI consistently and smoothly concurrently with emulation.

N64 and PS1 also do not fully implement the `refreshRateHint` API, and
the API may be buggy for some platforms. Metal refresh rate hints
currently appear in stdout, so if you are seeing an issue with VRR sync,
check the console to see the guest's requested present interval first.

## Gallery 


https://github.com/ares-emulator/ares/assets/6864788/1022c24b-fd83-4ede-b1ac-3f0c3a207972


https://github.com/ares-emulator/ares/assets/6864788/7e36bd4a-7acd-4d37-a572-7550ba1ad2b2

(PAL Super Mario World)


https://github.com/ares-emulator/ares/assets/6864788/9655fcbe-28de-48b2-88b7-7fb864991ef0

Co-authored-by: jcm <[email protected]>
2024-04-21 19:27:16 +01:00
Zeck fb2cdd9b71 fix windows tcp timeout (#1457)
Gotta love questionable platform differences. On Windows the old code
causes a disconnect after recv times out in 1 second, because errno will
always be 0. [Windows does not use errno, or
EAGAIN](https://learn.microsoft.com/en-us/windows/win32/winsock/error-codes-errno-h-errno-and-wsagetlasterror-2).
Now when the platform is windows
[WSAGetLastError](https://learn.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-wsagetlasterror)
is checked for
[WSAETIMEDOUT](https://learn.microsoft.com/en-us/windows/win32/winsock/windows-sockets-error-codes-2).

I could maybe do some more improvements in the file, (probably in
another PR) but I don't know what the project is interested in.
I did not address other uses of errno in the file.
I also did not switch from strerror, which windows does not use, to
[FormatMessage](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-formatmessage).
2024-04-21 19:26:55 +01:00
png183 eaab017b26 gba: handle ROM mirroring for Famicom Mini / Classic NES Series (#1456)
The 1MiB ROM chips used in most Famicom Mini carts and all Classic NES
series carts are mirrored, unlike with the larger ROM chips other carts
used. This PR implements the ROM mirroring behaviour and adds detection
for the affected games.

Closes #893
2024-04-21 19:26:29 +01:00
png183 74deb9351d gba: last cycle of prefetcher cannot be interrupted (#1451)
If the prefetcher is interrupted with 1 cycle left in its fetching
operation, run the final cycle regardless. Improves mGBA test suite
timings from 1890/2020 to 1904/2020, and passes a [test in the AGBEEG
Aging Cartridge dedicated to this prefetcher edge
case](https://github.com/zaydlang/AGBEEG-Aging-Cartridge/blob/master/documentation/cartridge/rom_access_during_prefetch.md).
2024-04-16 17:52:22 +01:00
曾耿森 cfa7f123de fix(fc-cpu): pass some test (#1454)
1. pass cpu_interrupts_v2/2-nmi_and_brk.nes
2. pass cpu_interrupts_v2/3-nmi_and_irq.nes
3. pass cpu_interrupts_v2/5-branch_delays_irq.nes
4. remove a26 some empty virtual function
5. add mos6502 some virtual function default impl
2024-04-16 17:52:09 +01:00
Luke Usher dd7fd4ea52 mia: load sfc boards from filesystem rather than embedding in mia 2024-04-12 14:54:01 +01:00
Luke Usher 5229e0f93a mia: include sha256 in generated sfc manifests 2024-04-12 10:29:21 +01:00
曾耿森 dc466a69f4 fix(fc-apu): fix framecounter write 4017 (#1452)
write $4017 need to clear irqPending and set cpu irq
2024-04-12 08:30:31 +01:00
Luke Usher 61a1304210 fc: some cleanup 2024-04-11 19:53:27 +01:00
Luke Usher 5b6899419c fc: remove WIP reset testing code 2024-04-11 16:44:31 +01:00
Luke Usher 9d1984a2bd mos6502: implement reset cycles 2024-04-11 16:43:08 +01:00
Luke Usher 99a87acdf2 ruby: really fix using linear rather than nearest in d3d driver 2024-04-11 16:38:26 +01:00
Luke Usher fd8e717707 ruby: fix using linear rather than nearest in d3d driver 2024-04-11 16:26:37 +01:00
Luke Usher 426947c0cb fc: don't call cartridge.main directly, handled by scheduler. 2024-04-11 15:39:46 +01:00
Luke Usher 043c5e0de1 fc: remove duplicate Thread::create in apu 2024-04-11 15:37:41 +01:00
Luke Usher 5104b34f2c fc: restore per-device co-threads
(Reverts 265ba002e6)
2024-04-11 15:34:20 +01:00
曾耿森 66ecd2e65c fix(fc-apu): pass some test (#1450)
1. let the APU inherit the Thread
2. change the execution sequence of the apu and cpu

3. pass blargg_apu_2005.07.30/08.irq_timing.nes
4. pass blargg_apu_2005.07.30/09.reset_timing.nes
2024-04-11 08:53:35 +01:00
Luke Usher 7ad14ff6bf n64: fix savedata duplication issue
This fixes an issue where upon loading a game that doesn't use a controller pak after a game that does, a .pak file would be created using the previous games data.
2024-04-10 20:18:00 +01:00
曾耿森 feffcc22cf fix(fc-apu): pass some apu test (#1449)
1. pass apu_reset/4015_cleared.nes
  2. pass apu_reset/4017_timing.nes
  3. pass apu_reset/4017_written.nes
  4. pass apu_reset/irq_flag_cleared.nes
  5. pass apu_reset/len_ctrs_enabled.nes
  6. pass apu_reset/works_immediately.nes
2024-04-10 17:55:18 +01:00
Luke Usher ca0044b663 desktop-ui: fix shaders not applying on startup 2024-04-10 10:39:40 +01:00
David DeGraw 35299b18d3 macOS: Implement mouse driver (#1446)
There are a few ways to get mouse position: GCMouse and using NSEvent.

GCMouse is newer and better, it reports mouse movement in raw x/y deltas
which is exactly what we need. The issue is that it expects you to set
up handlers for the movement events , but I couldn't figure out a way to
do that with the existing `poll()` paradigm where it passes the device
into the function. Ideally I'd be able to do
`assign(HID::Mouse::GroupID::Axis, 0, deltaX);` directly in the event
handler.

The other advantage to GCMouse is that we can use
`CGAssociateMouseAndMouseCursorPosition` and then we don't have to worry
about moving the hidden cursor over built in UI (such as the dock).

This implementation uses regular NSEvent for mouse data which works
pretty well with the current poll() paradigm. I had difficulty handing
mouse centering/zeroing so I left it out. It works pretty well both full
screen and windowed but it is possible to accidentally click the dock.

Open to feedback so please let me know what you think! I'd love to get
GCMouse working.

Demo:
https://www.youtube.com/watch?v=UwPyVNWP5hM
2024-04-09 18:05:54 +01:00
曾耿森 8316233b3e fix(fc-apu): pass some apu test (#1445)
1. pass apu_test/apu_test.nes
  2. blargg_apu_2005.07.30/05.len_timing_mode0.nes
  3. blargg_apu_2005.07.30/06.len_timing_mode1.nes
  4. blargg_apu_2005.07.30/07.irq_flag_timing.nes
  5. pass blargg_apu_2005.07.30/10. len_halt_timing.nes
  6. pass blargg_apu_2005.07.30/11.len_reload_timing.nes
  
  7. inc the fc SerializerVersion version to v139
2024-04-09 15:10:27 +01:00
Adrian Siekierka 2ad5d0a562 ws: fix refresh rate hint using line count of 0 (#1448) 2024-04-09 15:06:47 +01:00
Luke Usher ec0b625ea5 ares: update cores to use refreshRateHint api
Most systems will use an accurate refresh rate calculated from display timing

N64, PS1, PC-Engine and Neo Geo Pocket use 50hz and 60hz until we determine how to calculate.
2024-04-09 11:23:29 +01:00
jcmandjcm a3c57b4fbd screen/video: Add refresh rate hint mechanism (#1447)
This constitutes one puzzle piece that will help improve ares's frame
pacing, particularly for variable refresh rate displays.

While continued work on ares's audio drivers is likely to smooth the
pace at which ares generates video frames, transient changes in
application and system load inevitably means that frames will be
delivered earlier or later than expected. Additionally, relying on video
frames to be generated precisely when needed and presenting them
immediately is fairly demanding. If we can pace frames some distance in
advance, it can significantly lessen the burden on the CPU and GPU.

This PR is one tool to help the video backend deal with these issues.
Cores can now inform the screen of their expected rate of frame
generation at any given time, and the screen will inform the video
backend. The backend can then employ various strategies to perform
optimal frame pacing and drop frames when necessary.

The function is emphasized as a 'hint' to indicate that the rate is only
that which is expected, rather than certain. Unpredictable changes in
system conditions mean that we can never be entirely certain when a
frame will be generated or presented.

> [!NOTE]
> No concrete `refreshRateHint` implementations are added in this PR.
Given the variety of core refresh rates across ares, as well as the
consideration that for some cores refresh rates can change during
runtime, that work is left for separate PRs.

Co-authored-by: jcm <[email protected]>
2024-04-09 09:34:57 +01:00
曾耿森 e24e89b272 fix(apu): fix apu framecounter (#1442)
detail:
    1. Improve the emulational accuracy of apu framecounter
    2. pass the apu_test/4-jitter.nes

  todo:
    1. Does apu need to emulate blocking_write_4017?

  question:
1. A white screen will appear when running
blargg_apu_2005.07.30/04.clock_jitter.nes
2024-04-06 18:19:03 +01:00
Adrian Siekierka 6d3bc6044a ws: implement sound test bits 1, 2, 3 (#1441)
Up to date with the current research status quo.
2024-04-06 18:17:16 +01:00
Luke Usher ae2ec42c60 a26: bump serializer version as changes were significant 2024-04-05 12:46:13 +01:00
Luke Usher 3288e476a0 a26: rework tia, fixes most (but not all) known issues 2024-04-05 12:44:53 +01:00
Luke Usher 3da6974ae4 a26: improve hmove handling slightly
Preparing for future work
2024-04-04 11:29:39 +01:00
Luke Usher ea7f9a8c0f desktop-ui: refactor menu gen/shader loading 2024-04-03 23:00:24 +01:00
Luke Usher 1ea995f78d arcade: use mame machine names for convenience
Update mame2bml to include mame romset version

Add script to update arcade rom database (requires a MAME installation)
2024-04-03 06:57:51 +01:00
David DeGraw 4782fa43a0 Fix readme typo (#1440)
Minor markdown formatting tweak
2024-04-03 05:33:58 +01:00
jcmandjcm 5ee8f117a1 UI: update shader location when initializing (#1439)
Fix an error when cherry picking changes from a local branch for #1438.
Use the new variable for the base shaders directory when loading the
program start shader. Unbreak the build.

Co-authored-by: jcm <[email protected]>
2024-04-03 05:33:21 +01:00
jcmandjcm f515ed15c5 UI: Expose all .slangp shaders available (#1438)
Previously, the `LoadShaders()` function in `desktop-ui` searched only
two levels deep, which did not find all `.slangp` shader presets
available. The entirety of "megabezel" was not exposed, for example.

Now we properly traverse the entire directory structure of `Shaders/`
looking for `.slangp` files, exposing all that are available.

This PR does a small amount of rudimentary pruning for paths that do not
contain `.slangp` shaders, but future work, perhaps undertaken by
someone who has more fun with recursive directory traversal, should
probably properly prune all paths not containing presets.

Co-authored-by: jcm <[email protected]>
2024-04-02 22:20:09 +01:00
Adrian Siekierka 39c73a89ff ws: emulate 32KB SRAM for "8KB" cartridges (#1437)
Based on [ototo2009's PCB
scans](http://blog-imgs-131-origin.fc2.com/o/t/o/ototo2009/WS-2019-12b.html),
I have verified that every single cartridge that uses the value `0x01`
for its save type in the ROM header actually comes with 256 Kbit (or 32
KB) of SRAM.

In addition, WonderSwan ROM chips tend to use the notation of
`MHxxMyySzzzz` for a cartridge with `xx` megabits of ROM, `yy` kilobits
of SRAM (or `yyE` for EEPROM), and the ROM data ID `zzzz`. All of the
cartridges in question appear to use `256S`.

As such, it seems to me that Ares should similarly emulate 32KB of save
data for all such cartridges. It seems that this actually fixes a game,
for once.
2024-04-02 19:17:44 +01:00
曾耿森 feebb5b698 Mos6502 native (#1435)
1. fit mos6502 architecture
2. implment all mos6502 instruction
3. fc MDR using in base cpu
4. rename fc cpu.MDR to openBus
2024-04-02 15:34:46 +01:00
Luke Usher db2e0d45e1 nall: missing include 2024-04-02 13:18:19 +01:00
Luke Usher b145f0f000 screen: use condition_variable rather than polling for next frame
Use a timeout to prevent deadlocks when unloading games/if no frames are prevented.
2024-04-02 11:39:23 +01:00
Luke Usher 0af2690e50 ps1: blitter now uses a copy of the display area 2024-04-02 11:08:37 +01:00
Adrian Siekierka 7438418d97 v30mz: minor fixes (#1434)
Fixes some undefined behaviour handling and the BOUND opcode, in
accordance with [WSCpuTest](https://github.com/FluBBaOfWard/WSCpuTest/).
2024-04-02 10:25:12 +01:00
Luke Usher 8ff104393e md: lower full sync interval between MD and 32X 2024-04-01 20:20:14 +01:00
Luke Usher 8aaa89df6b ruby: Remove non-hardware accelerated video drivers
Computers old enough to need them are unlikely to be able to run ares as-is,
2024-04-01 16:57:51 +01:00
Luke Usher dd1ca486ec ruby: remove "Blur" shader, prefer slang bilinear. 2024-04-01 16:55:08 +01:00
Luke Usher fd7f5bea38 ruby: d3d9 driver does not currently support shaders 2024-04-01 16:50:45 +01:00
Luke Usher facd8afea4 ruby: implement latency selection in SDL audio driver 2024-04-01 15:05:40 +01:00
jcmandjcm 72fa7d38c3 ruby: Add Metal display backend (#1431)
This PR adds a Metal display backend to ares.

<img width="1482" alt="Screenshot 2024-03-31 at 7 02 40 PM"
src="https://github.com/ares-emulator/ares/assets/6864788/48718f19-9916-491b-8301-c16b95f95c19">

*ares N64 core on a 60Hz P3 display. Shader: "crt-maximus-royale".*

## Context

With ares's recent introduction of librashader, ares users have enjoyed
access to the sizable library of shaders in the slang format, such as
those used by the RetroArch frontend. Simultaneously, up to now, the CGL
OpenGL backend shipped by ares for Mac users has offered enough
functionality to do the (relatively) simple job of an ares display
backend; display software-rendered frame buffers and pace them
appropriately.

librashader's advanced postprocessing, however, has asked a bit more of
the display backend, and in the case of OpenGL, has laid bare various
deficiencies in macOS's OpenGL driver. These deficiencies can kneecap
ares's librashader support on macOS with compiler errors and broken
shader behavior.

Rather than chase down these errors and try to work around what is
fundamentally a broken driver shipped by Apple, we take advantage of
librashader's native Metal support by adding a Metal backend to ares.
This greatly increases baseline shader compatibility, with the added
benefit of documentation and greater platform debugging information when
issues arise. The Metal backend will also generally future-proof ares on
macOS, with OpenGL's uncertain future on macOS.

## Basics

The first iteration of this Metal driver mostly offers feature parity
with the OpenGL driver. More advanced features, particularly in the
realm of frame pacing on ProMotion displays, will arrive in future
iterations. The priority with this PR is to start getting the driver in
the hands of users with basic features and greater librashader
compatibility.

Host refresh rate sync is still a work in progress and in this iteration
will only be enabled for users above 10.15.4 on non-VRR displays
(discussed more below).

Explicit sRGB color matching is offered as a new option for those on
wide gamut displays (by default, the Metal driver will map to the native
color space, conforming to OpenGL driver behavior). This option is only
exposed on macOS, since other operating systems lack per-surface color
matching.

<img width="400" alt="Screenshot 2024-03-31 at 6 37 38 PM"
src="https://github.com/ares-emulator/ares/assets/6864788/e177a256-bba2-4a02-ad5b-9ad84cb09740">
<img width="400" alt="Screenshot 2024-03-31 at 6 37 46 PM"
src="https://github.com/ares-emulator/ares/assets/6864788/dd517394-e97e-40f6-98de-4562d62bda98">

*Left: ares presenting in Display P3. Right: ares presenting more
accurately in sRGB with "Force sRGB" enabled. Shader: crt-hyllian.*

A simple vertex and fragment shader are compiled at runtime, so we avoid
the need to add another compiler toolchain to the ares build process.
There is unfortunately some code duplicated at present; `metal.cpp` and
`Shaders.metal` both include types defined in `ShaderTypes.h`, but we
also need to place `Shaders.metal` inside the .app bundle for runtime
compilation, making for awkward `#include`s. Presently, we just bundle a
copy of `Shaders.metal` appended with `ShaderTypes.h`, inside
`desktop-ui/resource`. This will be cleaned up in future work.

The driver's draw implementation itself is fairly simple; one render
pass renders to an offscreen texture, librashader performs its work on
that offscreen texture, and a second ares Metal render pass composites
the finished texture inside ares's viewport. Since we do not use
`MTKViewDelegate`, our output function finishes with a `[view draw]`
call and the system presents at the earliest opportunity.

## Details

When it came to the details of implementing this driver, there were some
nontrivial issues encountered. Some of these will need solving in
separate PRs before this driver is feature-complete.

### ares vs. VRR

Users on fixed refresh rate displays should enjoy good frame pacing with
this driver. Unfortunately, users of more recent Mac machines with
"ProMotion" refresh rates will not have an ideal experience in terms of
pacing. To understand why, we need to take a brief detour into how ares
works and then discuss some current limitations with ares's macOS
integration.

In ares "synchronize to audio" mode, ares creates and delivers video
frames as audio frames are created. This means that the video frame
timing is completely dependent on when exactly the audio driver
processes audio frames. For display modes with a refresh rate at or
close to the core refresh rate, this is mostly no problem; the system
seems to naturally present frames in a FIFO-esque fashion, and every
once in awhile the system will just drop or duplicate a frame if two or
no draw calls fall within one refresh interval.

For recent more advanced Mac displays with "up to 120Hz" refresh rate,
the story is more complicated. We have to explicitly tell the system
when we want it to draw the frame once available. It is tempting to
answer "now"; after all, if our audio timings are correct, then video
frames should be generated precisely when they need to be shown.
Unfortunately, in higher latency modes of OpenAL or with SDL audio in
general on macOS, audio frames are processed in large batches. That
means that we end up emitting several video frames in quick succession
at 8ms intervals on a 120Hz display, then waiting as long as 75ms for a
new batch of audio (and thus video) frames:

<img width="265" alt="Screenshot 2024-03-31 at 4 55 25 PM"
src="https://github.com/ares-emulator/ares/assets/6864788/69f887a0-8ded-4f47-ac4c-4cf2b58283a7">
<img width="265" alt="Screenshot 2024-03-31 at 4 55 35 PM"
src="https://github.com/ares-emulator/ares/assets/6864788/2f7a417a-0378-44b5-b0c0-f894542c0371">
<img width="265" alt="Screenshot 2024-03-31 at 4 55 56 PM"
src="https://github.com/ares-emulator/ares/assets/6864788/13b471d9-3e77-45cd-baf4-0d786ae83e22">

*VRR macOS frame pacing across audio driver settings in v0.1 of the
Metal driver. The graph in blue shows frame present intervals over time;
the values in red show the minimum and maximum present intervals over
the graph duration.*

If we do not answer "now," we have to decide when to present.
Unfortunately, currently, there is not a satisfying way to answer that
question. Core refresh rates vary somewhat widely, sometimes during
runtime, and there is no mechanism in ares by which to inform the
graphics driver of a core's desired refresh rate.

We could elect to just duplicate the behavior for a fixed display
refresh rate and pick, e.g. 60 Hz, but unfortunately even that option is
not available, because we currently have no way of receiving callbacks
when a frame is actually presented. Why not `CAMetalDisplayLink` or even
`MTKViewDelegate` you ask? Well...

### ares vs. macOS

For most of its cores, ares performs much of its work on a single
dedicated main thread that blocks for audio and video presentation to
drive hardware-accurate timing. Unfortunately, all of this work occurs
on the macOS main thread, with lots of blocking and CPU-intensive
activity. This interferes with the macOS application run loop's ability
to perform its callbacks and call out to observers.

In practice, this means that if we try to employ delegates that
interface with macOS, that could send a callback when a frame is
presented, or tell ares the exact moment a frame needs to be presented,
these system delegates cannot actually make these calls in time in
between ares's main thread activity; upwards of 50% of `MTKViewDelegate`
callbacks are lost, for example.

This means that tools like `MTKViewDelegate` or `CAMetalDisplayLink`
that would help us solve the frame pacing problem are, unfortunately,
useless to us. We cannot leverage these tools as ares is currently
architected.

To get around these issues, we will need one of: less main thread
blocking, so delegates can interface with ares on the main thread, or an
audio driver with a processing tolerance that falls within the display's
minimum refresh interval. Our best bet for now is to emit frames to the
system within ares's main thread work as they come available, let the
system draw them as it will, and hope that our audio driver is doing a
good job pacing them.

In practice, for Metal driver users on VRR displays you cannot set to a
fixed rate, this means you should use the OpenAL driver, and set the
latency to the lowest value possible.

## Future Work

The future for the Metal driver in ares takes us down a few different
paths.

The main issue at present is making macOS system delegates work well
with ares, which is the ideal path forward. Ideally, we could move all
of the emulation-intensive work off of the main thread in macOS and into
a high priority dedicated thread, reserving the main thread for actual
UI and rendering, giving the system plenty of overhead with which to
communicate.

For the future of VRR in ares, it would be good to create a mechanism to
tell the graphics driver what refresh rate the core wants to present at.
This would be one way to pace draw calls appropriately in the absence of
reliable feedback from the system about the state of the display.

It has gone without mentioning so far due to the other issues, but long
term, it would also be good for ares or librashader to have some way of
utilizing the entire viewport for shaders; currently, shaders are
limited to the output width and height area rather than the entire
window view size. This is limiting for "bezel"-style shaders that want
to use the entire screen in fullscreen, for example.

Co-authored-by: jcm <[email protected]>
2024-04-01 14:31:28 +01:00
Luke Usher ba31eafda9 bump version to v137 2024-03-31 20:38:20 +01:00
Luke Usher 7eb0fb268b Revert "32x: more timing tweaks; still not truely accurate but better approximates sdram timing"
This reverts commit 40a461621d.
2024-03-31 19:21:22 +01:00
Luke Usher 1c876d8bf6 md: fix 32x dotshift in mode 1 2024-03-31 11:24:36 +01:00
Luke Usher 40a461621d 32x: more timing tweaks; still not truely accurate but better approximates sdram timing 2024-03-30 17:36:02 +00:00
Luke Usher 61b358e45b desktop-ui: group slang shaders by directory 2024-03-29 18:00:24 +00:00
Luke Usher ad70fadc8e Squashed 'thirdparty/libchdr/' changes from 2a1119c686..5c598c2df3
5c598c2df3 Merge pull request #115 from notaz/gitignore
4cbba6df03 add a basic .gitignore
7239eab39c Merge pull request #114 from bslenul/windows-case-include
e2589a612c Make sure all windows.h includes are lowercase

git-subtree-dir: thirdparty/libchdr
git-subtree-split: 5c598c2df3a7717552a76410d79f5af01ff51b1d
2024-03-28 11:37:46 +00:00
Luke Usher 1bd36fb2cc Merge commit 'ad70fadc8edfcded08fd3f9a326d4760fe23958d' 2024-03-28 11:37:46 +00:00
Luke Usher f7d6650c26 Squashed 'thirdparty/librashader/' changes from 4ef4b8762b..e8ffd8fdf3
e8ffd8fdf3 chore: Release
d893b6ec97 doc: update supported runtime table to include D3D9 and clarify wgpu status
8c8e386a6c capi(d3d9): expose d3d9 in capi
b7071958bd rt(d3d9): add a runtime for direct3d 9
5feac91af2 runtime: add ARGB8 pixel format
9c895caa51 wgpu: fix format mismatch for copies
7593f9f9b5 rt: pass device context to uniform binder if needed
af3ea252ba rt(d3d11): split luts out to own module
9dc0cf26fd chore: Release
2550bf7ed5 test: update shaders_slang
35fc21bbef capi: fix mtl noop free fn name
89b620a7c1 rt(gl46): fix invalid framebuffer copies
66a0ee21e3 Revert "rt(gl): account for flipped coordinate space when blitting to output"
31b7a6f33f chore: Release
ed7216990a test: update slang_shaders
623c6776f7 rt(gl): account for flipped coordinate space when blitting to output
bacfbf0791 cache: delete cache if corrupted
e02e1ae26a rt(gl): load luts with topleft origin due to MVP changes
d72519b9fd chore: Release
752417f320 rt(vk): switch from an rwlock to a mutex for allocator
10ad2d927c rt(d3d12): make descriptor heap lockfree
8a9adebb96 rt(d3d12): upgrade to windows 0.52
7719b939f9 rt(d3d11): upgrade to windows 0.52
a849f5e745 dep: unify on windows 0.52.0
f61bed3a22 vk: remove unneeded device arcs

git-subtree-dir: thirdparty/librashader
git-subtree-split: e8ffd8fdf31f29e35f0c367ef2c3c40c19088971
2024-03-28 11:37:40 +00:00
Luke Usher 69daac5356 Merge commit 'f7d6650c2622df1195b7103fc49d3d967cacc01b' 2024-03-28 11:37:40 +00:00
Luke Usher 5440ef5a4f Merge commit 'ae89968e2cad1f318c6052a9a3dc4a40891ba557' 2024-03-28 11:37:29 +00:00
Luke Usher ae89968e2c Squashed 'thirdparty/slang-shaders/' changes from 23f27e2714..1c0a4ccbd2
1c0a4ccbd2 Update fake-crt-geom-potato.slang (#563)
d367f6cf73 Update fake-crt-geom-potato.slang (#562)
23166cd3e6 fake-CRT-Geom-potato switch to kaizer (#561)
ec1d31b4b3 Merge pull request #560 from metallic77/slang
076081abe5 Update ntsc-mini.slang
c934e47f53 Merge pull request #559 from metallic77/slang
7b62243af3 Update ntsc-mini.slang
435532f92a add options/tweaks (#558)
c383e0cfd0 add ntsc-mini (#557)
7659b11f24 Merge pull request #556 from kokoko3k/master
25abcc54d9 Koko-aio: Sync to NG-1.9.13
d668788a29 Merge pull request #555 from Tatsuya79/master
d797fc81c4 Merge pull request #553 from hunterk/png_optimize
b3a7ea3597 Merge pull request #554 from kokoko3k/master
59833ccb6e crt-ntsc-sharp glow adjustments
698a9dec63 fix typos in presets. Fixes librashader tests
389c8953b5 Merge pull request #551 from Tatsuya79/master
7f250f68b0 optimize crt-yo6's texture
e0d3747724 optimize metacrt textures
779bef00e7 delete a bunch of big, unused images and optimize what's left
71c8853494 optimize console borders
2b986a6fdd optimize maximus-royale's phosphor LUTs to get another 600kb improvement
4e22b232a1 optimize frame pngs to greatly reduce the repo size
ba3d6de18b update crt-ntsc-sharp presets
3a6d6d7c48 [newpixie-mini] Small optmization. (#550)

git-subtree-dir: thirdparty/slang-shaders
git-subtree-split: 1c0a4ccbd2ded461bbfbd73881a97a88e7bcee91
2024-03-28 11:37:05 +00:00
jcmandjcm 571832a83d Make macOS SDL build portable, build script runnable locally (#1393)
Resubmission of https://github.com/ares-emulator/ares/pull/1389 with
improvements.

Now the SDL build script will not call `xcode-select`, which can have
undesired effects on the user build environment, unless it is on CI
(detected with the `$GITHUB_ACTIONS` env var).

It will also not call ``cmake --install .``, which would previously
replace the user's SDL installation.

This second change required some minor changes to ruby's makefile. We
now include the header directory from the cloned SDL source, and inform
the linker correctly of the location of the SDL .dylib.

Also added the cloned SDL repository and .dylib to the .gitignore for
easier development workflow.

To ensure compatibility with
https://github.com/ares-emulator/ares/pull/1390, the
`MACOS_COMPILED_SDL` flag is added so we can include the proper "SDL.h"
header for compiled builds and `<SDL2/SDL.h>` header for system builds.

Co-authored-by: jcm <[email protected]>
2024-03-27 15:18:14 +00:00
png183 a04c215003 gba: reading 32-bit ARM instruction from prefetch buffer takes 1 cycle (#1429)
When an instruction is already present in the prefetch buffer, fetching
the instruction should take only one cycle in both ARM and Thumb modes.
Currently, ares uses 1 cycle for each halfword read from the prefetch
buffer, which is correct for Thumb but not ARM. Fixing this discrepancy
allows ares to pass 1890/2020 of the timing tests in the mGBA test suite
(up from 1760/2020).
2024-03-27 13:47:49 +00:00
jcmandjcm 7be6217102 ruby: Add SDL audio for macOS (#1427)
Exposes the option to use SDL's audio backend on macOS. The wiring for
this is already fully present, just needs to be added to builds.

Good to have another option for Mac audio for anyone having issues with
the OpenAL backend.

Tested locally and verified to work in the Metal dev branch.

Co-authored-by: jcm <[email protected]>
2024-03-27 08:01:56 +00:00
jcmandjcm a29cd2ce58 UI: Fix confirmation logic when changing drivers with a game loaded (#1428)
Addresses a minor issue with driver change confirmation logic and the
"Apply" button in the UI.

Previously, if the player changed the video, audio, or input driver with
a title loaded and clicked "No" at the confirmation dialog, the "Apply"
button would be disabled as if the player had changed the driver, when
they had not.

With this PR the "Apply" button state correctly reflects the driver
state and the result of the confirmation modal.

Co-authored-by: jcm <[email protected]>
2024-03-27 08:01:24 +00:00
Luke Usher d5d3d169ca md: revert sdram access delays
Causes freezes in Doom 32XR, we need a better model for burst accesses, etc
2024-03-25 17:19:13 +00:00
Luke Usher 9ae2e43c68 md: more 32x timing tweaks
- Brutal: Above The Claw no longer hangs
 - The Chaotix pre-release prototypes boot again
2024-03-25 10:39:56 +00:00
Luke Usher 5815c9d746 md: approximate some 32x memory timings
Timings are still *way* off, but better;
Framebuffer and SDRAM writes are no longer free.
2024-03-24 20:04:55 +00:00
Luke Usher 3e49cebfa4 md: unused bits of 0xa1518a should be set to 0 for m32x 2024-03-24 19:37:46 +00:00
Adrian Siekierka 0c8eaf0d4e ws: APU emulation improvements (#1425)
* Significantly improved Hyper Voice implementation accuracy (verified,
at least for Sound DMA writes, with a test ROM)
* Implemented emulation of unused/undocumented debug ports (0x64-0x67,
0x69, 0x95-0x9B)
* Improved cycle accuracy of APU channel handling
* Added slightly faster "inaccurate" APU emulation mode (for most games,
output should be essentially identical; debug ports will not match up,
though)
2024-03-24 17:28:56 +00:00
jcmandjcm f0fd88f33e Disable link-time optimization for debug builds (#1418)
For some reason, on macOS, debug symbols do not seem to be available for
lldb if link-time optimization is enabled. I do not know exactly why
that's the case, but it seems safe and without downsides to just disable
LTO if we're doing a debug build.

Co-authored-by: jcm <[email protected]>
2024-03-12 20:23:14 +00:00
remutro 827babcbbc Update README with Win Librashader build instructions (#1417)
Add instructions for building librashader library locally on Windows to
the README file.

Note: Will update for Linux next.
2024-03-11 21:41:10 +00:00
Luke Usher 4666cdb9b8 build: fix an issue where make clean would halt on the librasahder flag 2024-03-11 16:09:24 +00:00
Luke Usher c9c1a0d532 pc-engine: add support for Games Express games + other fixes
Use the Games Express system card for the games that require it
Use System Card 1.0 for Altered Beast (this game is broken on other bios versions, even on hardwar
Fix CD-ROM pregap offset (Fixes Super Air Zonk, allows Games Express games to boot)
Fix PC-Engine Duo/Super CD-ROM Ram Enable Register
e)
2024-03-08 15:53:44 +00:00
Luke Usher d53fdb0087 md: fix off-by-one issue when processing sega cd sub-channels 2024-03-07 09:57:54 +00:00
png183 c564dc7bc5 gba: improve PPU timings (#1414)
This PR adjusts PPU timings as follows:

- There is a 46-cycle wait period between the start of a scanline and
the first pixel drawn, instead of a 32-cycle period between clearing
io.hblank and incrementing io.vcounter
- io.hblank is set for 226 cycles instead of 240
- Video capture DMAs occur on scanlines 2-161, instead of scanlines
0-159

These changes can be observed in
[status-irq-dma.gba](https://github.com/nba-emu/hw-test/tree/master/ppu/status-irq-dma).
When using the accuracy profile, ares now gets within 5 cycles of the
correct value for all tests except video capture DMA.
2024-03-04 10:53:48 +00:00
jcmandjcm 0111abc565 hiro: Expose clipsToBounds for macOS SDKs below 14 (#1413)
Fixes CI failing to build after #1412.

`clipsToBounds` is available as far back as 10.9 but not exposed until
14.0, so we have to expose it manually if we're building on an earlier
SDK.

In future, ares should of course be built with the current SDK, but
should support building with earlier SDKs.

Co-authored-by: jcm <[email protected]>
2024-03-03 19:31:28 +00:00
jcmandjcm 65264090b0 UI fix-ups for macOS (#1412)
### Status Bar 

When building with the macOS SDK included with macOS Sonoma, ares has
had a regression involving an overly large status bar that rendered over
the game viewport, causing confusion as well as being tricky to debug.

It turns out that this was due to a breaking change in AppKit in macOS
14 where an `NSView`'s `dirtyRect` was no longer clipped to its bounds
by default. In short, a view's `dirtyRect` is now often much larger than
its `bounds` if `clipsToBounds` is not defined explicitly. This creates
problems in views that draw by calling `NSFillRect` on the dirtyRect, a
common pattern, as it will fill a rect that is much larger than the
actual bounds.

This PR sets the `clipsToBounds` property for NSView to `true` for views
in ares that draw by filling `dirtyRect`. Accordingly these views'
`dirtyRect` will now always be the same size as their `bounds`.

This was true of `canvas.cpp`, `viewport.cpp`, and `label.cpp`. To avoid
making the change overly broad, and to enable macOS to perform whatever
optimizations it wants to perform, other view types are left alone.

### Splash Screen

This PR also addresses logo clipping issues in macOS on the splash
screen. The dimensions for the logo on the splash screen, as defined,
seemed to be a bit off previously, with the square logo rendering into a
non-square canvas area. For whatever reason, this only clipped the logo
rendering on macOS. The size and padding are adjusted slightly by this
PR. It should not result in regressions on other platforms, but should
be tested to make sure.

> [!IMPORTANT]  
> Pwease test on Windows and Linux to make sure the splash screen looks
OK.

macOS screenshot of adjusted splash screen and fixed status bar, built
with Xcode 15:
<img width="1072" alt="Screenshot 2024-03-02 at 1 43 20 AM"
src="https://github.com/ares-emulator/ares/assets/6864788/83504592-03dd-4881-8f3d-0db1fb771f44">

---------

Co-authored-by: jcm <[email protected]>
2024-03-03 15:52:58 +00:00
absindx 70f361094b sfc: implementation of SA-1 BW-RAM protection (#1409)
This PR is a change to pass the [SA-1 RAM protection
test](https://github.com/absindx/SNES-TestRoms/tree/main/SA1RamProtectionTest).

---
242e2fd1a1

BW-RAM protection was not implemented to make Kirby's Dream Land 3 work.
[Reference: Near's post
(nesdev)](https://forums.nesdev.org/viewtopic.php?p=237733#p237733)

This commit implements the conditions under which BW-RAM protection
works as determined from hardware testing.
* BW-RAM Protection will not be reflected unless protection is enabled
on both SNES and SA-1.
  * KDL3 sets `CWEN=0`, but `SWEN=80`. not protected.
* `$2228 BWPA` is a register for the SNES CPU, but it also affects the
SA-1 protection area.

---
654f5f02ce

Change the BW-RAM mapping range from $400000-$4FFFFF to $400000-$5FFFFF.
[Reference: SA-1 Hardware Behavior -
SnesLab](https://sneslab.net/wiki/SA-1_Hardware_Behavior#BW-RAM)

---
aa1da58d8b

Initialize the following at SA-1 reset. (change `$2200 CCNT.RESB` 1 to
0)
* CPU data bank register
* CPU stop flag
* IO `$222A CIWP` register

NOTE: The timing of when these registers are reset is unknown because
they cannot be observed in a stopped SA-1 CPU.
I include todo as a reminder that there are many unknown behaviors. I'll
delete it if it's not needed.

KDL3 restarts the SA-1 CPU several times on the title screen.
Before this change, KDL3(JPN: Hoshi no Kirby 3, SHA-1:
`5038596a1ec450d8f1d7cc07759737bfd996e87f`) was not restarting properly:
```log
SA1  008294  sei                              A:0000 X:0000 Y:0000 S:01ff D:0000 B:00 nv1BdIzc
SA1  008295  clc                              A:0000 X:0000 Y:0000 S:01ff D:0000 B:00 nv1BdIzc
SA1  008296  xce                              A:0000 X:0000 Y:0000 S:01ff D:0000 B:00 nv1BdIzc
# (snip)
SA1  0082b1  lda #$ff                         A:0000 X:0000 Y:0000 S:01ff D:0000 B:00 nvMXdIZC
SA1  0082b3  sta $222a              [00222a]  A:00ff X:0000 Y:0000 S:01ff D:0000 B:00 NvMXdIzC # B:00 ... write to CIWP
# (snip)
SA1  0082cf  pea $4040              [004040]  A:3600 X:37ff Y:3800 S:37ff D:3600 B:00 nvmxdIzC
SA1  0082d2  plb                              A:3600 X:37ff Y:3800 S:37fd D:3600 B:00 nvmxdIzC
SA1  0082d3  plb                              A:3600 X:37ff Y:3800 S:37fe D:3600 B:40 nvmxdIzC
# (snip)
[Omitted: 3303247]
# reboot from SNES CPU (CCNT.RESB)
SA1  008294  sei                              A:0000 X:37ff Y:3800 S:37ff D:3600 B:40 nvmxdIZC
SA1  008295  clc                              A:0000 X:37ff Y:3800 S:37ff D:3600 B:40 nvmxdIZC
SA1  008296  xce                              A:0000 X:37ff Y:3800 S:37ff D:3600 B:40 nvmxdIZc
SA1  008297  sep #$20                         A:0000 X:37ff Y:3800 S:37ff D:3600 B:40 nvmxdIZc
# (snip)
SA1  0082b1  lda #$ff                         A:0000 X:37ff Y:3800 S:37ff D:3600 B:40 nvMxdIZc
SA1  0082b3  sta $222a              [40222a]  A:00ff X:37ff Y:3800 S:37ff D:3600 B:40 NvMxdIzc # B:40 ... write to incorrect address ($40222a = BW-RAM)
```
The data bank register `B` has not been reset and an access to a
different address is occurring.

Although not related to BW-RAM protection, other registers probably need
to be reset as well.
Further hardware testing is required.

---

These commits boot KDL3 with BW-RAM protection implemented.
2024-02-29 14:08:18 +00:00
Adrian Siekierka be8fa76e7d wdc65816: emulate (direct,X) wraparound bug in emulation mode (#1410)
See https://github.com/gilyon/snes-tests/tree/main/cputest for more
details. This makes the relevant tests (and thus entirety of)
`cputest-full.sfc` pass.
2024-02-29 14:07:32 +00:00
Luke Usher 66dbed4ee0 thirdparty: fix build after libchdr update 2024-02-25 20:57:30 +00:00
Luke Usher 05c749f09b slang-shaders: optimize png images 2024-02-25 20:54:33 +00:00
Luke Usher b4399c59cc Squashed 'thirdparty/libchdr/' changes from 2648c221c..2a1119c68
2a1119c68 Merge pull request #113 from scribam/ci-switch-vita
51bd8e969 Add GitHub Actions for Switch and Vita
bd19fbd6f Merge pull request #110 from scribam/zlib-1.3
577f3276c Merge pull request #111 from scribam/c90
5f04e2fdf Merge pull request #109 from scribam/actions-checkout
16ebde42b Merge pull request #112 from scribam/dr_libs
647f42b27 dr_flac: Version 0.12.42
5fd516519 Compilation fix when using C90 with GCC
ea2da72d3 Bump zlib to 1.3.1
4e0aa45a7 Update actions/checkout to v4

git-subtree-dir: thirdparty/libchdr
git-subtree-split: 2a1119c686eb07033d02f8c6d12406f8fd373775
2024-02-25 12:22:34 +00:00
Luke Usher 37145465f7 Merge commit 'b4399c59cc4c4f0933281e9f964841b90fb737bb' 2024-02-25 12:22:34 +00:00
Luke Usher 8b88e3093e Squashed 'thirdparty/sljit/' changes from 607158516..5420f8bee
5420f8bee Update README
5c0a2c232 Support recent changes on s390x
ebe11bab4 Support target address for mov_addr operations
a5503d6dd Merge jumps and put_labels
b6b79d5c2 Remove JUMP_LABEL flag
e453c820e Refactor serial numbers of tests (#233)
f63755091 Improve sljit_generate_code on several cpus
9ee290982 Improve code generation on s390x

git-subtree-dir: thirdparty/sljit
git-subtree-split: 5420f8bee8f954fa11c72e4402bb1b9b32a2b11f
2024-02-25 12:22:29 +00:00
Luke Usher 33a00d4da0 Merge commit '8b88e3093edf5f067ada42156d796bf785238726' 2024-02-25 12:22:29 +00:00
Luke Usher 71302c0938 shaders: switch to slang-shaders rather than quark shaders via librashader 2024-02-25 12:05:36 +00:00
Luke Usher b702465cc1 scripts: update librashader and slang-shaders 2024-02-25 12:04:29 +00:00
Luke Usher b822fb3224 Squashed 'thirdparty/slang-shaders/' content from commit 23f27e271
git-subtree-dir: thirdparty/slang-shaders
git-subtree-split: 23f27e2714deb610202dbcf2cebb139b5fb6d880
2024-02-25 12:03:56 +00:00
Luke Usher cc850c7dc1 Merge commit 'b822fb32242d9ece329330929da2b5fd92fc4ef1' as 'thirdparty/slang-shaders' 2024-02-25 12:03:56 +00:00
Luke Usher f18c1f9c67 Squashed 'thirdparty/librashader/' content from commit 4ef4b8762
git-subtree-dir: thirdparty/librashader
git-subtree-split: 4ef4b8762b9ae45d012d6cb1ad2640211ffd874d
2024-02-25 12:03:36 +00:00
Luke Usher ff98ad031c Merge commit 'f18c1f9c67dd232ad8b9d2c0892101693476fb10' as 'thirdparty/librashader' 2024-02-25 12:03:36 +00:00
5549 changed files with 571925 additions and 103196 deletions

No files matched your search

+54 -18
View File
@@ -51,7 +51,11 @@ jobs:
windres: rc
shell: bash
msvc-arch: x64_arm64
- name: macos
- name: macos-compat
os: macos-12
compiler: clang++
shell: sh
- name: macos-latest
os: macos-latest
compiler: clang++
shell: sh
@@ -86,28 +90,51 @@ jobs:
keychain-name: ares-macos-keychain
keychain-password: ${{ secrets.MACOS_KEYCHAIN_PASSWORD }}
- name: Checkout source code
uses: actions/checkout@v2
uses: actions/checkout@v4
- name: Install Windows Dependencies
if: runner.os == 'Windows'
run: |
export PATH="/c/Users/runneradmin/.cargo/bin:$PATH" # correct on windows-latest as of 2024-02-19
if [[ ${{ matrix.platform.name }} == *-arm64 ]]; then
rustup toolchain install nightly
rustup default nightly
rustup target add aarch64-pc-windows-msvc
pushd thirdparty/librashader
./build-librashader.sh aarch64-pc-windows-msvc
popd
else
rustup toolchain install nightly
rustup default nightly
pushd thirdparty/librashader
./build-librashader.sh
popd
fi
- name: "macOS: recover MoltenVK cache"
if: runner.os == 'macOS'
uses: actions/cache@v3
uses: actions/cache@v4
env:
cache-name: moltenvk
with:
path: thirdparty/MoltenVK/MoltenVK
key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('thirdparty/MoltenVK/HEAD') }}
- name: "macOS: recover SDL cache"
if: runner.os == 'macOS'
uses: actions/cache@v3
env:
cache-name: sdl
with:
path: thirdparty/SDL/SDL
key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('thirdparty/SDL/HEAD') }}
- name: Install macOS Dependencies
if: runner.os == 'macOS'
run: |
if [ $ImageOS == "macos14" ]; then
sudo xcode-select -s /Applications/Xcode_15.2.app/Contents/Developer
export MACOSX_DEPLOYMENT_TARGET=10.13
echo "Set Xcode version to 15.2 for macos-latest build."
elif [ $ImageOS == "macos12" ]; then
sudo xcode-select -s /Applications/Xcode_13.4.app/Contents/Developer
export MACOSX_DEPLOYMENT_TARGET=10.9
echo "Set Xcode version to 13.4 for macos-compat build."
fi
brew install make ninja cmake
pip install --no-input setuptools
rustup toolchain install nightly
rustup default nightly
rustup target add x86_64-apple-darwin
rustup target add aarch64-apple-darwin
echo "MAKE=gmake" >> $GITHUB_ENV
pushd thirdparty/SDL
./build-SDL.sh
@@ -115,6 +142,10 @@ jobs:
pushd thirdparty/MoltenVK
./build-moltenvk.sh
popd
export MACOSX_DEPLOYMENT_TARGET=10.15
pushd thirdparty/librashader
./build-librashader.sh
popd
- name: Set up MSVC environment
if: matrix.platform.msvc-arch != ''
uses: ilammy/msvc-dev-cmd@v1
@@ -153,7 +184,7 @@ jobs:
MACOS_NOTARIZATION_PASSWORD: ${{ secrets.MACOS_NOTARIZATION_PASSWORD }}
MACOS_NOTARIZATION_TEAMID: ${{ secrets.MACOS_NOTARIZATION_TEAMID }}
- name: Upload
uses: actions/upload-artifact@v2
uses: actions/upload-artifact@v4
with:
name: ${{ matrix.program }}-${{ matrix.platform.name }}
path: desktop-ui/out/*
@@ -165,11 +196,11 @@ jobs:
needs:
- build
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4
with:
path: 'src'
- name: Download Artifacts
uses: actions/download-artifact@v2
uses: actions/download-artifact@v4
with:
path: 'bin'
- name: Package Artifacts
@@ -185,9 +216,10 @@ jobs:
bindir="${GITHUB_WORKSPACE}/bin"
# Hack: Workaround for GitHub artifacts losing attributes.
chmod +x ${bindir}/ares-macos/ares.app/Contents/MacOS/ares
chmod +x ${bindir}/ares-macos-latest/ares.app/Contents/MacOS/ares
chmod +x ${bindir}/ares-macos-compat/ares.app/Contents/MacOS/ares
for package in windows windows-msvc-arm64 macos
for package in windows windows-msvc-arm64 macos-latest macos-compat
do
mkdir "${package}"
cd "${package}"
@@ -287,10 +319,14 @@ jobs:
uses: actions/upload-release-asset@v1
env: { GITHUB_TOKEN: '${{ secrets.GITHUB_TOKEN }}' }
with: { upload_url: '${{ env.UPLOAD_URL }}', asset_path: 'ares-windows-msvc-arm64.zip', asset_name: 'ares-windows-msvc-arm64.zip', asset_content_type: 'application/zip' }
- name: Upload ares-macos
- name: Upload ares-macos-latest
uses: actions/upload-release-asset@v1
env: { GITHUB_TOKEN: '${{ secrets.GITHUB_TOKEN }}' }
with: { upload_url: '${{ env.UPLOAD_URL }}', asset_path: 'ares-macos.zip', asset_name: 'ares-macos.zip', asset_content_type: 'application/zip' }
with: { upload_url: '${{ env.UPLOAD_URL }}', asset_path: 'ares-macos-latest.zip', asset_name: 'ares-macos-latest.zip', asset_content_type: 'application/zip' }
- name: Upload ares-macos-compat
uses: actions/upload-release-asset@v1
env: { GITHUB_TOKEN: '${{ secrets.GITHUB_TOKEN }}' }
with: { upload_url: '${{ env.UPLOAD_URL }}', asset_path: 'ares-macos-compat.zip', asset_name: 'ares-macos-compat.zip', asset_content_type: 'application/zip' }
# - name: Upload ares-ubuntu
# uses: actions/upload-release-asset@v1
# env: { GITHUB_TOKEN: '${{ secrets.GITHUB_TOKEN }}' }
+7 -1
View File
@@ -1,5 +1,6 @@
*.moc
*.user
*.xcuserdata
.vs/
.vscode/
.idea/
@@ -9,4 +10,9 @@ out/
obj-amd64/
obj-arm64/
out-amd64/
out-arm64/
out-arm64/
thirdparty/SDL/SDL
thirdparty/SDL/libSDL2-2.0.0.dylib
macos-xcode/
.swiftpm
*.xcodeproj
+359
View File
@@ -470,3 +470,362 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
----------------------------------------------------------------------
librashader
Mozilla Public License Version 2.0
==================================
### 1. Definitions
**1.1. “Contributor”**
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
**1.2. “Contributor Version”**
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
**1.3. “Contribution”**
means Covered Software of a particular Contributor.
**1.4. “Covered Software”**
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
**1.5. “Incompatible With Secondary Licenses”**
means
* **(a)** that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
* **(b)** that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
**1.6. “Executable Form”**
means any form of the work other than Source Code Form.
**1.7. “Larger Work”**
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
**1.8. “License”**
means this document.
**1.9. “Licensable”**
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
**1.10. “Modifications”**
means any of the following:
* **(a)** any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
* **(b)** any new file in Source Code Form that contains any Covered
Software.
**1.11. “Patent Claims” of a Contributor**
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
**1.12. “Secondary License”**
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
**1.13. “Source Code Form”**
means the form of the work preferred for making modifications.
**1.14. “You” (or “Your”)**
means an individual or a legal entity exercising rights under this
License. For legal entities, “You” includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, “control” means **(a)** the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or **(b)** ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
### 2. License Grants and Conditions
#### 2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
* **(a)** under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
* **(b)** under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
#### 2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
#### 2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
* **(a)** for any code that a Contributor has removed from Covered Software;
or
* **(b)** for infringements caused by: **(i)** Your and any other third party's
modifications of Covered Software, or **(ii)** the combination of its
Contributions with other software (except as part of its Contributor
Version); or
* **(c)** under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
#### 2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
#### 2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
#### 2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
#### 2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
### 3. Responsibilities
#### 3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
#### 3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
* **(a)** such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
* **(b)** You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
#### 3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
#### 3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
#### 3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
### 4. Inability to Comply Due to Statute or Regulation
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: **(a)** comply with
the terms of this License to the maximum extent possible; and **(b)**
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
### 5. Termination
**5.1.** The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated **(a)** provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and **(b)** on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
**5.2.** If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
**5.3.** In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
### 6. Disclaimer of Warranty
> Covered Software is provided under this License on an “as is”
> basis, without warranty of any kind, either expressed, implied, or
> statutory, including, without limitation, warranties that the
> Covered Software is free of defects, merchantable, fit for a
> particular purpose or non-infringing. The entire risk as to the
> quality and performance of the Covered Software is with You.
> Should any Covered Software prove defective in any respect, You
> (not any Contributor) assume the cost of any necessary servicing,
> repair, or correction. This disclaimer of warranty constitutes an
> essential part of this License. No use of any Covered Software is
> authorized under this License except under this disclaimer.
### 7. Limitation of Liability
> Under no circumstances and under no legal theory, whether tort
> (including negligence), contract, or otherwise, shall any
> Contributor, or anyone who distributes Covered Software as
> permitted above, be liable to You for any direct, indirect,
> special, incidental, or consequential damages of any character
> including, without limitation, damages for lost profits, loss of
> goodwill, work stoppage, computer failure or malfunction, or any
> and all other commercial damages or losses, even if such party
> shall have been informed of the possibility of such damages. This
> limitation of liability shall not apply to liability for death or
> personal injury resulting from such party's negligence to the
> extent applicable law prohibits such limitation. Some
> jurisdictions do not allow the exclusion or limitation of
> incidental or consequential damages, so this exclusion and
> limitation may not apply to You.
### 8. Litigation
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
### 9. Miscellaneous
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
### 10. Versions of the License
#### 10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
#### 10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
#### 10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
#### 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
## Exhibit A - Source Code Form License Notice
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
## Exhibit B - “Incompatible With Secondary Licenses” Notice
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
----------------------------------------------------------------------
+41 -2
View File
@@ -28,7 +28,7 @@ g++ make pkg-config libgtk-3-dev libcanberra-gtk-module libgl-dev libasound2-dev
```
###### Additional Audio Drivers
ares supports additional audio drivers besides the ALSA drivers included above. Installing these additional packages will allow them to be selected in Settings > Drivers:
`libao-dev libopenal-dev'
`libao-dev libopenal-dev`
###### GTK2 & GTK3
By default, GTK3 is used, but support for GTK2 is available. You will need to install the additional package `libgtk2.0-dev` as well as specifying the command line option `hiro=gtk2` at compile time.
@@ -40,6 +40,19 @@ You should then be able to select SDL for input in the Settings > Drivers menu.
##### Building with clang
clang++ is now the preferred compiler for ares. If clang is detected on Windows/macOS/BSD, it will be selected by default. On Linux and other platforms, g++ remains the default if present. To build with clang, it is necessary to install both the `clang` and `lld` packages. If you would like to manually specify a compiler, you can use the following option: `compiler=[g++|clang++]`
##### Librashader Support
If you do not want to include librashader support, you can pass the following option to the `make` command to skip these requirements using: `librashader=false`
Librashader requires rust in order to build. You can install it with the following command:
```
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source ~/.cargo/env
rustup toolchain install nightly
```
In order to build librashader, change into the `ares/thirdparty/librashader` directory and run the script `build-librashader.sh`
Note that once the build completes, it will instruct you to run three copy commands to install the library on your system. These paths may be different depending on Linux distribution.
--------------
@@ -63,6 +76,32 @@ Once complete, open a CLANG64 terminal window and proceed with building ares.
###### Debug Symbols
When building with clang, by default symbols will be generated for debug builds using an MSVC compatible format (CodeView) for use with Windows debugging tools. In order to generate GDB compatible symbols, specify the following option: `symformat=gdb`
###### Librashader Support
ares has introduced support for the [librashader](https://github.com/SnowflakePowered/librashader) library, which is a preprocessor, compiler, and runtime for RetroArch 'slang' shaders. If you are not interested in working with librashaders, you can pass the following option to the `make` command to skip these requirements using: `librashader=false`
Building the librashader library on Windows requires Rust. Follow these steps to prepare your system and build the librashader library:
1. Download and execute the rustup-init.exe installer from: https://rustup.rs/
2. Open a new Windows terminal and run the following commands:
```
rustup toolchain install nightly
rustup default nightly
```
3. With Rust successfully installed, you will need to update your PATH environment variable within your MSYS2 environment. In an MSYS2 shell, open $HOME/.bash_profile and append something like the following (note you will need to replace both instances of %USER_NAME% with the real user name you used to install Rust):
```
if [ -d "/C/Users/%USER_NAME%/.cargo/bin" ] ; then
PATH="/C/Users/%USER_NAME%/.cargo/bin:${PATH}"
fi
```
4. Open a new MSYS2 based shell for the compiler you are using (MinGW64|CLANG64|UCRT64), execute `rustup` to validate the path is set properly within your MSYS2 environment.
5. In your MSYS2 compiler shell, `cd` into the `ares/thirdparty/librashader` directory
6. Execute the build script, build should complete successfully:
```
./build-librashader.sh
```
This only needs to be done once, or anytime the librashader library is updated. Once built, ares will build with librashader support by default requiring no additional flags.
Compilation
-----------
@@ -97,7 +136,7 @@ a26 fc sfc n64 sg ms md ps1 pce ng msx cv myvision gb gba ws ngp spec
Build Output
------------
There is a single binary produced at the end of compilation which can be found in `desktop-ui/out`. On OS's besides Linux, the `Database` & `Shader` directories are copied over here as well. On Linux, running `make install` after compilation will copy these directories and binary into suitable locations (see desktop-ui/GNUmakefile for details). Alternatively, these directories can be copied from `ares/Shaders/*` and `mia/Database/*`.
There is a single binary produced at the end of compilation which can be found in `desktop-ui/out`. On OS's besides Linux, the `Database` & `Shader` directories are copied over here as well. On Linux, running `make install` after compilation will copy these directories and binary into suitable locations (see desktop-ui/GNUmakefile for details). Alternatively, these directories can be copied from `thirdparty/slang-shaders/*` into a `Shader` directory, and by copying `mia/Database/*`
Command-line options
-81
View File
@@ -1,81 +0,0 @@
#version 150
//anti-aliased nearest-neighbor
precision highp float;
uniform sampler2D source[];
uniform vec4 sourceSize[];
uniform vec4 targetSize[];
in Vertex {
vec2 texCoord;
};
out vec4 fragColor;
vec4 vpow(vec4 n, float e) {
return vec4(pow(n.x, e), pow(n.y, e), pow(n.z, e), pow(n.w, e));
}
vec4 toLQV(vec3 c) {
return vec4(c.r, c.g, c.b, c.r * 0.2989 + c.g * 0.5870 + c.b * 0.1140);
}
vec3 fromLQV(vec4 c) {
float f = c.w / (c.r * 0.2989 + c.g * 0.5870 + c.b * 0.1140);
return vec3(c.rgb) * f;
}
vec3 percent(float ssize, float tsize, float coord) {
float minfull = (coord * tsize - 0.5) / tsize * ssize;
float maxfull = (coord * tsize + 0.5) / tsize * ssize;
float realfull = floor(maxfull);
if(minfull > realfull) {
return vec3(
1,
(realfull + 0.5) / ssize,
(realfull + 0.5) / ssize
);
}
return vec3(
(maxfull - realfull) / (maxfull - minfull),
(realfull - 0.5) / ssize,
(realfull + 0.5) / ssize
);
}
void main() {
float srgb = 2.1;
float gamma = 3.0;
vec3 x = percent(sourceSize[0].x, targetSize[0].x, texCoord.x);
vec3 y = percent(sourceSize[0].y, targetSize[0].y, texCoord.y);
//get points to interpolate across in linear RGB
vec4 a = toLQV(vpow(texture(source[0], vec2(x[1], y[1])), srgb).rgb);
vec4 b = toLQV(vpow(texture(source[0], vec2(x[2], y[1])), srgb).rgb);
vec4 c = toLQV(vpow(texture(source[0], vec2(x[1], y[2])), srgb).rgb);
vec4 d = toLQV(vpow(texture(source[0], vec2(x[2], y[2])), srgb).rgb);
//use perceptual gamma for luminance component
a.w = pow(a.w, 1 / gamma);
b.w = pow(b.w, 1 / gamma);
c.w = pow(c.w, 1 / gamma);
d.w = pow(d.w, 1 / gamma);
//interpolate
vec4 gammaLQV =
(1.0 - x[0]) * (1.0 - y[0]) * a +
(0.0 + x[0]) * (1.0 - y[0]) * b +
(1.0 - x[0]) * (0.0 + y[0]) * c +
(0.0 + x[0]) * (0.0 + y[0]) * d;
//convert luminance gamma back to linear
gammaLQV.w = pow(gammaLQV.w, gamma);
//convert color back to sRGB
fragColor = vpow(vec4(fromLQV(gammaLQV), 1), 1 / srgb);
}
-8
View File
@@ -1,8 +0,0 @@
input
filter: nearest
program
fragment: AANN.fs
output
filter: nearest
@@ -1,10 +0,0 @@
input
filter: nearest
program
filter: nearest
wrap: border
fragment: shadertoy.fs
output
filter: nearest
-145
View File
@@ -1,145 +0,0 @@
//
// PUBLIC DOMAIN CRT STYLED SCAN-LINE SHADER
//
// by Timothy Lottes
//
// This is more along the style of a really good CGA arcade monitor.
// With RGB inputs instead of NTSC.
// The shadow mask example has the mask rotated 90 degrees for less chromatic aberration.
//
// Left it unoptimized to show the theory behind the algorithm.
//
// It is an example what I personally would want as a display option for pixel art games.
// Please take and use, change, or whatever.
//
#version 150
uniform sampler2D source[];
uniform vec4 sourceSize[];
uniform int phase;
in Vertex {
vec2 texCoord;
};
out vec4 fragColor;
// Emulated input resolution.
vec2 res=sourceSize[0].xy;
// Hardness of scanline.
// -8.0 = soft
// -16.0 = medium
float hardScan=-8.0;
// Hardness of pixels in scanline.
// -2.0 = soft
// -4.0 = hard
float hardPix=-3.0;
// Display warp.
// 0.0 = none
// 1.0/8.0 = extreme
vec2 warp=vec2(1.0/32.0,1.0/24.0);
// Amount of shadow mask.
float maskDark=0.5;
float maskLight=1.5;
//------------------------------------------------------------------------
// sRGB to Linear.
// Assuing using sRGB typed textures this should not be needed.
float ToLinear1(float c){return(c<=0.04045)?c/12.92:pow((c+0.055)/1.055,2.4);}
vec3 ToLinear(vec3 c){return vec3(ToLinear1(c.r),ToLinear1(c.g),ToLinear1(c.b));}
// Linear to sRGB.
// Assuing using sRGB typed textures this should not be needed.
float ToSrgb1(float c){return(c<0.0031308?c*12.92:1.055*pow(c,0.41666)-0.055);}
vec3 ToSrgb(vec3 c){return vec3(ToSrgb1(c.r),ToSrgb1(c.g),ToSrgb1(c.b));}
// Nearest emulated sample given floating point position and texel offset.
// Also zero's off screen.
vec3 Fetch(vec2 pos,vec2 off){
pos=(floor(pos*res+off)+vec2(0.5,0.5))/res;
return ToLinear(1.2 * texture(source[0],pos.xy,-16.0).rgb);}
// Distance in emulated pixels to nearest texel.
vec2 Dist(vec2 pos){pos=pos*res;return -((pos-floor(pos))-vec2(0.5));}
// 1D Gaussian.
float Gaus(float pos,float scale){return exp2(scale*pos*pos);}
// 3-tap Gaussian filter along horz line.
vec3 Horz3(vec2 pos,float off){
vec3 b=Fetch(pos,vec2(-1.0,off));
vec3 c=Fetch(pos,vec2( 0.0,off));
vec3 d=Fetch(pos,vec2( 1.0,off));
float dst=Dist(pos).x;
// Convert distance to weight.
float scale=hardPix;
float wb=Gaus(dst-1.0,scale);
float wc=Gaus(dst+0.0,scale);
float wd=Gaus(dst+1.0,scale);
// Return filtered sample.
return (b*wb+c*wc+d*wd)/(wb+wc+wd);}
// 5-tap Gaussian filter along horz line.
vec3 Horz5(vec2 pos,float off){
vec3 a=Fetch(pos,vec2(-2.0,off));
vec3 b=Fetch(pos,vec2(-1.0,off));
vec3 c=Fetch(pos,vec2( 0.0,off));
vec3 d=Fetch(pos,vec2( 1.0,off));
vec3 e=Fetch(pos,vec2( 2.0,off));
float dst=Dist(pos).x;
// Convert distance to weight.
float scale=hardPix;
float wa=Gaus(dst-2.0,scale);
float wb=Gaus(dst-1.0,scale);
float wc=Gaus(dst+0.0,scale);
float wd=Gaus(dst+1.0,scale);
float we=Gaus(dst+2.0,scale);
// Return filtered sample.
return (a*wa+b*wb+c*wc+d*wd+e*we)/(wa+wb+wc+wd+we);}
// Return scanline weight.
float Scan(vec2 pos,float off){
float dst=Dist(pos).y;
return Gaus(dst+off,hardScan);}
// Allow nearest three lines to effect pixel.
vec3 Tri(vec2 pos){
vec3 a=Horz3(pos,-1.0);
vec3 b=Horz5(pos, 0.0);
vec3 c=Horz3(pos, 1.0);
float wa=Scan(pos,-1.0);
float wb=Scan(pos, 0.0);
float wc=Scan(pos, 1.0);
return a*wa+b*wb+c*wc;}
// Distortion of scanlines, and end of screen alpha.
vec2 Warp(vec2 pos){
pos=pos*2.0-1.0;
pos*=vec2(1.0+(pos.y*pos.y)*warp.x,1.0+(pos.x*pos.x)*warp.y);
return pos*0.5+0.5;}
// Shadow mask.
vec3 Mask(vec2 pos){
pos.x+=pos.y*3.0;
vec3 mask=vec3(maskDark,maskDark,maskDark);
pos.x=fract(pos.x/6.0);
if(pos.x<0.333)mask.r=maskLight;
else if(pos.x<0.666)mask.g=maskLight;
else mask.b=maskLight;
return mask;}
void main() {
vec2 pos = texCoord.xy * 1.0001;
hardScan=-12.0;
// maskDark=maskLight;
pos=Warp(pos.xy);
fragColor.rgb=Tri(pos)*Mask(gl_FragCoord.xy);
fragColor.a=1.0;
fragColor = vec4(ToSrgb(fragColor.rgb), fragColor.a);
}
-16
View File
@@ -1,16 +0,0 @@
#version 150
in vec4 position;
in vec2 texCoord;
out Vertex {
vec2 vTexCoord;
};
uniform vec4 targetSize;
uniform vec4 sourceSize[];
void main() {
gl_Position = position;
vTexCoord = texCoord;
}
@@ -1,12 +0,0 @@
input
filter: nearest
program
filter: nearest
vertex: lottes.vs
fragment: lottes.fs
output
height: 0
width: 0
filter: linear
@@ -1,21 +0,0 @@
#version 150
#define distortion 0.2
uniform sampler2D source[];
uniform vec4 sourceSize[];
in Vertex {
vec2 texCoord;
};
out vec4 fragColor;
vec2 radialDistortion(vec2 coord) {
vec2 cc = coord - vec2(0.5);
float dist = dot(cc, cc) * distortion;
return coord + cc * (1.0 - dist) * dist;
}
void main() {
fragColor = texture(source[0], radialDistortion(texCoord));
}
@@ -1,4 +0,0 @@
program
filter: linear
wrap: border
fragment: curvature.fs
@@ -1,25 +0,0 @@
#version 150
uniform sampler2D source[];
uniform vec4 sourceSize[];
in Vertex {
vec2 texCoord;
};
out vec4 fragColor;
vec3 grayscale(vec3 color) {
return vec3(dot(color, vec3(0.3, 0.59, 0.11)));
}
void main() {
vec2 offset = fract(texCoord * sourceSize[0].xy) - 0.5;
offset /= sourceSize[0].xy;
vec3 cx = texture(source[0], texCoord - offset).xyz;
vec3 cy = texture(source[0], texCoord).xyz;
vec3 cz = vec3(5.0 * grayscale(abs(cx - cy)));
fragColor = vec4(clamp(cz, 0.0, 1.0), 1.0);
}
@@ -1,4 +0,0 @@
program
filter: linear
wrap: edge
fragment: edge-detection.fs
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 KiB

@@ -1,99 +0,0 @@
#version 150
// GritsScanlines by torridgristle
// license: public domain (https://forums.libretro.com/t/lightweight-lut-based-scanline-glow-concept-prototype-glsl/18336/7)
/* Runtime parameters
#in LuminanceDawnbringer
#in LuminanceLUT
#in ScanlinesOpacity
#in GammaCorrection
#in TrinitronColors
*/
// static parameters
//#define LuminanceDawnbringer
#define LuminanceLUT
//#define TrinitronColors
#define ScanlinesOpacity 0.9
//#define GammaCorrection 1.2
uniform sampler2D source[];
uniform vec4 sourceSize[];
uniform vec4 targetSize;
uniform sampler2D pixmap[];
in Vertex {
vec2 texCoord;
};
out vec4 fragColor;
#ifdef LuminanceLUT
#define LUT_SizeLum 16.0
// Code taken from RetroArch's LUT shader
float luminancelut(vec4 org)
{
vec4 imgColorLum = org;
float redLum = ( imgColorLum.r * (LUT_SizeLum - 1.0) + 0.4999 ) / (LUT_SizeLum * LUT_SizeLum);
float greenLum = ( imgColorLum.g * (LUT_SizeLum - 1.0) + 0.4999 ) / LUT_SizeLum;
float blue1Lum = (floor( imgColorLum.b * (LUT_SizeLum - 1.0) ) / LUT_SizeLum) + redLum;
float blue2Lum = (ceil( imgColorLum.b * (LUT_SizeLum - 1.0) ) / LUT_SizeLum) + redLum;
float mixerLum = clamp(max((imgColorLum.b - blue1Lum) / (blue2Lum - blue1Lum), 0.0), 0.0, 32.0);
float color1Lum = texture(pixmap[1], vec2( blue1Lum, greenLum )).x;
float color2Lum = texture(pixmap[1], vec2( blue2Lum, greenLum )).x;
return mix(color1Lum, color2Lum, mixerLum);
}
#endif
#ifdef TrinitronColors
#define LUT_SizeTrinitron 32.0
vec4 TrinitronD50(vec4 org)
{
vec4 imgColorTrinitron = org;
float redTrinitron = ( imgColorTrinitron.r * (LUT_SizeTrinitron - 1.0) + 0.4999 ) / (LUT_SizeTrinitron * LUT_SizeTrinitron);
float greenTrinitron = ( imgColorTrinitron.g * (LUT_SizeTrinitron - 1.0) + 0.4999 ) / LUT_SizeTrinitron;
float blue1Trinitron = (floor( imgColorTrinitron.b * (LUT_SizeTrinitron - 1.0) ) / LUT_SizeTrinitron) + redTrinitron;
float blue2Trinitron = (ceil( imgColorTrinitron.b * (LUT_SizeTrinitron - 1.0) ) / LUT_SizeTrinitron) + redTrinitron;
float mixerTrinitron = clamp(max((imgColorTrinitron.b - blue1Trinitron) / (blue2Trinitron - blue1Trinitron), 0.0), 0.0, 32.0);
vec4 color1Trinitron = texture(pixmap[2], vec2( blue1Trinitron, greenTrinitron ));
vec4 color2Trinitron = texture(pixmap[2], vec2( blue2Trinitron, greenTrinitron ));
vec4 fragColorTrinitron = mix(color1Trinitron, color2Trinitron, mixerTrinitron);
return vec4(pow(fragColorTrinitron.rgb,vec3(GammaCorrection,GammaCorrection,GammaCorrection)),1.0);
}
#endif
void main() {
//Source Image
vec4 org = texture(source[0], texCoord);
#ifdef LuminanceLUT
// Use a 3DLUT instead of an equation so that it can use any arbitrary mess you can come up with.
float luminance = luminancelut(org);
#elif defined LuminanceDawnbringer
// Dawnbringer's brightness equation from Dawnbringer's Toolbox scripts for Grafx2
float luminance = sqrt(org.r*org.r*0.0676 + org.g*org.g*0.3025 + org.b*org.b*0.0361) * 1.5690256395005606;
#else
// Plain, standard, fine; slightly faster
float luminance = ((0.299*org.r) + (0.587*org.g) + (0.114*org.b));
#endif
// Don't let it exceed 1.0
luminance = clamp(luminance, 0.0, 1.0);
// Scanline Mapping, based on the Phosphor LUT shader's method of tiling a texture over the screen
vec2 LUTeffectiveCoord = vec2(luminance,fract((texCoord.y*targetSize.y)/4.0));
// Scanline Layer
vec4 screen = texture(pixmap[0], LUTeffectiveCoord);
// Output multiplying the scanlines into the original image, with control over opacity
#ifdef TrinitronColors
org = TrinitronD50(org);
#endif
fragColor = ((screen*ScanlinesOpacity)+(1.0 - ScanlinesOpacity)) * (org);
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 70 KiB

@@ -1,35 +0,0 @@
settings
LuminanceDawnbringer
active: false
LuminanceLUT
active: false
TrinitronColors
active: true
ScanlinesOpacity: 0.9
min: 0.0
max: 1.0
step: 0.05
GammaCorrection: 1.2
min: 0.5
max: 2.0
step: 0.1
program
filter: nearest
wrap: edge
width: 100%
height: 400%
fragment: GritsScanlines.fs
pixmap: Scanline-LUT-4px.png
filter: linear
wrap: edge
pixmap: Fake-Self-Illumination.png
filter: linear
wrap: edge
pixmap: Trinitron D50 Absolute Colorimetric - LUT.png
filter: linear
wrap: edge
output1
filter: linear
@@ -1,39 +0,0 @@
#version 150
/*
Interlacing
Author: hunterk
License: Public domain
Note: This shader is designed to work with the typical interlaced output from an emulator, which displays both even and odd fields twice.
This shader will un-weave the image, resulting in a standard, alternating-field interlacing.
*/
uniform sampler2D source[];
uniform vec2 targetSize;
uniform vec4 sourceSize[];
uniform int phase;
in Vertex {
vec2 texCoord;
};
out vec4 fragColor;
// This controls how bright the intermediate lines are; 0.0 = totally black
#define percent 0.0
void main()
{
vec4 res = texture(source[0], texCoord);
float y = 0.0;
// assume anything with a vertical resolution greater than 400 lines is interlaced
if (sourceSize[0].y > 400.0) y = sourceSize[0].y * texCoord.y + phase;
else
y = 2.00001 * sourceSize[0].y * texCoord.y;
if (mod(y, 2.0) > 0.99999) fragColor = res;
else
fragColor = vec4(percent) * res;
}
@@ -1,6 +0,0 @@
input
filter: nearest
program
fragment: interlace.fs
modulo: 2
@@ -1,11 +0,0 @@
input
filter: nearest
program
filter: nearest
height: 100%
fragment: pal-r57shell.fs
output
height: 0
filter: linear
@@ -1,368 +0,0 @@
#version 150
// NES PAL composite signal simulation for RetroArch
// shader by r57shell
// thanks to feos & HardWareMan & NewRisingSun
// also TV subpixels and scanlines
// LICENSE: PUBLIC DOMAIN
// NOTE: for nice TV subpixels and scanlines I recommend to
// disable this features here and apply CRT-specialized shader.
// Quality considerations
// there are three main options:
// USE_RAW (R), USE_DELAY_LINE (D), USE_COLORIMETRY (C)
// here is table of quality in decreasing order:
// RDC, RD, RC, DC, D, C
// compatibility macros
#define float2 vec2
#define float3 vec3
#define float4 vec4
#define frac(c) fract(c)
#define saturate(c) clamp(c, 0.0, 1.0)
#define fmod(x,y) mod(x,y)
#define mul(x,y) (y*x)
#define float2x2 mat2
#define float3x3 mat3
#define float4x4 mat4
#define bool2 bvec2
#define bool3 bvec3
#define bool4 bvec4
#define static
uniform sampler2D source[];
uniform vec4 sourceSize[];
uniform vec4 outputSize;
uniform int phase;
in Vertex {
vec2 texCoord;
};
out vec4 fragColor;
// TWEAKS start
// use delay line technique
// without delay line technique, color would interleave
// to avoid this, set HueRotation to zero.
#define USE_DELAY_LINE
// use this if you need to swap even/odd V sign.
// sign of V changes each scanline
// so if some scanline is positive, then next is negative
// and if you want to match picture
// to actual running PAL NES on TV
// you may want to have this option, to change signs
// if they don't match
//#define SWAP_VSIGN
// rough simulation of scanlines
// better if you use additional shader instead
// if you still use it, make sure that SizeY
// is at least twice lower than output height
#define USE_SCANLINES // FIXME: scanlines are broken and I'm too lazy to fix it right now
// to change gamma of virtual TV from 2.2 to something else
#define USE_GAMMA
// use sampled version. it's much more slower version of shader.
// because it is computing x4 more values. NOT RECOMMENDED.
//#define USE_SAMPLED
#ifndef PARAMETER_UNIFORM
// NTSC standard gamma = 2.2
// PAL standard gamma = 2.8
// according to many sources, very unlikely gamma of TV is 2.8
// most likely gamma of PAL TV is in range 2.4-2.5
const float Gamma_static = 2.8; // gamma of virtual TV
const float Brightness_static = 0.25;
const float Contrast_static = 1.1;
const float Saturation_static = 1.1;
const int
Ywidth_static = 12,
Uwidth_static = 23,
Vwidth_static = 23;
#define Brightness Brightness_static
#define Gamma Gamma_static
#define Ywidth Ywidth_static
#define Uwidth Uwidth_static
#define Vwidth Vwidth_static
#define SCANLINE_MUL (sw.x*dark_scanline+sw.y)
int Mwidth = int(max(float(Ywidth), max(float(Uwidth), float(Vwidth))));
// correct one is -2.5
// works only with USE_RAW
const float HueShift = -2.5;
// rotation of hue due to luma level.
const float HueRotation = 2.;
// touch this only if you know what you doing
const float Phase_Y = 2.; // fmod(341*10,12)
const float Phase_One = 0.; // alternating phases.
const float Phase_Two = 8.;
// screen size, scanlines = y*2; y one field, and y other field.
const int SizeX = 256;
const int SizeY = 240;
// count of pixels of virtual TV.
// value close to 1000 produce small artifacts
const int TV_Pixels = 400;
const float dark_scanline = 0.5; // half
#endif
// this is using following matrixes.
// it provides more scientific approach
// by conversion into linear XYZ space
// and back to sRGB.
// it's using Gamma setting too.
// define USE_GAMMA is not required.
#define USE_COLORIMETRY
const float3x3 RGB_to_XYZ =
mat3(
0.4306190, 0.3415419, 0.1783091,
0.2220379, 0.7066384, 0.0713236,
0.0201853, 0.1295504, 0.9390944
);
const float3x3 XYZ_to_sRGB =
mat3(
3.2406, -1.5372, -0.4986,
-0.9689, 1.8758, 0.0415,
0.0557, -0.2040, 1.0570
);
// TWEAKS end
const float YUV_u = 0.492;
const float YUV_v = 0.877;
const mat3 RGB_to_YUV =
mat3(
float3( 0.299, 0.587, 0.114), //Y
float3(-0.299,-0.587, 0.886)*YUV_u, //B-Y
float3( 0.701,-0.587,-0.114)*YUV_v //R-Y
);
#ifdef USE_DELAY_LINE
const float comb_line = 1.;
#else
const float comb_line = 2.;
#endif
static const float Voltage_0 = 0.518;
static const float Voltage_1 = 1.962;
static const float DeltaV = (Voltage_1-Voltage_0);
float RGB_y = Contrast_static/Ywidth_static/DeltaV;
float RGB_u = comb_line*Contrast_static*Saturation_static/YUV_u/Uwidth_static/DeltaV;
float RGB_v = comb_line*Contrast_static*Saturation_static/YUV_v/Vwidth_static/DeltaV;
mat3 YUV_to_RGB =
mat3(
float3(1., 1., 1.)*RGB_y,
float3(0., -0.114/0.587, 1.)*RGB_u,
float3(1., -0.299/0.587, 0.)*RGB_v
);
const float pi = 3.1415926535897932384626433832795;
float sinn(float x)
{
return sin(/*fmod(x,24)*/x*(pi*2./24.));
}
float coss(float x)
{
return cos(/*fmod(x,24)*/x*(pi*2./24.));
}
float3 monitor(sampler2D tex, float2 p)
{
float2 size = sourceSize[0].xy;//float2(SizeX,SizeY);
// align vertical coord to center of texel
float2 uv = float2(
p.x,
(floor(p.y*sourceSize[0].y)+0.5)/sourceSize[0].y);
#ifdef USE_DELAY_LINE
float2 sh = (sourceSize[0].xy/sourceSize[0].xy/size)*float2(14./10.,-1.0);
#endif
float2 pc = uv*sourceSize[0].xy/sourceSize[0].xy*size*float2(10.,1.);
float alpha = dot(floor(float2(pc.x,pc.y)),float2(2.,Phase_Y*2.));
alpha += Phase_One*2.;
// 1/size.x of screen in uv coords = sourceSize[0].x/sourceSize[0].x/size.x;
// then 1/10*size.x of screen:
float ustep = sourceSize[0].x/sourceSize[0].x/size.x/10.;
float border = sourceSize[0].x/sourceSize[0].x;
float ss = 2.0;
#ifdef SWAP_VSIGN
#define PAL_SWITCH(A) A < 1.
#else
#define PAL_SWITCH(A) A > 1.
#endif
if (PAL_SWITCH(fmod(uv.y*sourceSize[0].y/sourceSize[0].y*size.y,2.0)))
{
// cos(pi-alpha) = -cos(alpha)
// sin(pi-alpha) = sin(alpha)
// pi - alpha
alpha = -alpha+12012.0;
ss = -2.0;
}
float ysum = 0., usum = 0., vsum = 0.;
for (int i=0; i<Mwidth; ++i)
{
float4 res = texture(tex, uv);
float3 yuv = mul(RGB_to_YUV, res.xyz);
float a1 = alpha+(HueShift+2.5)*2.-yuv.x*ss*HueRotation;
float sig = yuv.x+dot(yuv.yz,sign(float2(sinn(a1),coss(a1))));
#ifdef USE_DELAY_LINE
float4 res1 = texture(tex, uv+sh);
float3 yuv1 = mul(RGB_to_YUV, res1.xyz);
float a2 = (HueShift+2.5)*2.+12012.0-alpha+yuv.x*ss*HueRotation;
float sig1 = yuv1.x+dot(yuv1.yz,sign(float2(sinn(a2),coss(a2))));
#endif
if (i < Ywidth)
ysum += sig;
#ifdef USE_DELAY_LINE
if (i < Uwidth)
usum += (sig+sig1)*sinn(alpha);
if (i < Vwidth)
vsum += (sig-sig1)*coss(alpha);
#else
if (i < Uwidth)
usum += sig*sinn(alpha);
if (i < Vwidth)
vsum += sig*coss(alpha);
#endif
alpha -= ss;
uv.x -= ustep;
}
float3 rgb = mul(float3(ysum+Brightness*Ywidth_static,usum,vsum), YUV_to_RGB);
#if defined(USE_GAMMA) && !defined(USE_COLORIMETRY)
float3 rgb1 = saturate(rgb);
rgb = pow(rgb1, Gamma/2.2);
#endif
#ifdef USE_COLORIMETRY
float3 rgb1 = saturate(rgb);
rgb = pow(rgb1, float3(Gamma, Gamma, Gamma));
#endif
#if (defined(USE_SCANLINES))
float2 q = (p*sourceSize[0].xy/sourceSize[0].xy)*float2(TV_Pixels*3.,size.y*2.);
#endif
#ifdef USE_SCANLINES
float scanlines = size.y * outputSize.z;
float top = fmod(q.y-0.5*scanlines*2.,2.);
float bottom = top+frac(scanlines)*2.;
float2 sw = saturate(min(float2(1.,2.),float2(bottom, bottom))
-max(float2(0.,1.),float2(top)))
+saturate(min(float2(3.,4.),float2(bottom, bottom))
-max(float2(2.,3.),float2(top)))
+floor(scanlines);
rgb = rgb*SCANLINE_MUL/(sw.x+sw.y);
/*
//old stupid method
float z =
#ifdef ANIMATE_SCANLINE
fmod(phase,2.0)+
#endif
0.5;
if (abs(fmod(q.y+0.5,2)-z)<0.5)
rgb *= dark_scanline;
*/
#endif
// size of pixel screen in texture coords:
//float output_pixel_size = sourceSize[0].x/(outputSize.x*sourceSize[0].x);
// correctness check
//if (fmod(p.x*output_pixel_size,2.0) < 1.0)
// rgb = float3(0.,0.,0.);
#ifdef USE_COLORIMETRY
float3 xyz1 = mul(RGB_to_XYZ,rgb);
float3 srgb = saturate(mul(XYZ_to_sRGB,xyz1));
float3 a1 = 12.92*srgb;
float3 a2 = 1.055*pow(srgb,float3(1./2.4))-0.055;
float3 ssrgb;
ssrgb.x = (srgb.x<0.0031308?a1.x:a2.x);
ssrgb.y = (srgb.y<0.0031308?a1.y:a2.y);
ssrgb.z = (srgb.z<0.0031308?a1.z:a2.z);
return ssrgb;
#else
return rgb;
#endif
}
// pos (left corner, sample size)
float4 monitor_sample(sampler2D tex, float2 p, float2 sample_)
{
// linear interpolation was...
// now other thing.
// http://imgur.com/m8Z8trV
// AT LAST IT WORKS!!!!
// going to check in retroarch...
float2 size = sourceSize[0].xy;
float2 next = float2(.25,1.)/size;
float2 f = frac(float2(4.,1.)*size*p);
sample_ *= float2(4.,1.)*size;
float2 l;
float2 r;
if (f.x+sample_.x < 1.)
{
l.x = f.x+sample_.x;
r.x = 0.;
}
else
{
l.x = 1.-f.x;
r.x = min(1.,f.x+sample_.x-1.);
}
if (f.y+sample_.y < 1.)
{
l.y = f.y+sample_.y;
r.y = 0.;
}
else
{
l.y = 1.-f.y;
r.y = min(1.,f.y+sample_.y-1.);
}
float3 top = mix(monitor(tex, p), monitor(tex, p+float2(next.x,0.)), r.x/(l.x+r.x));
float3 bottom = mix(monitor(tex, p+float2(0.,next.y)), monitor(tex, p+next), r.x/(l.x+r.x));
return float4(mix(top,bottom, r.y/(l.y+r.y)),1.0);
}
void main() {
#ifdef USE_SAMPLED
fragColor = vec4(monitor_sample(source[0], texCoord, outputSize.zw).rgb, 1.0);
#else
fragColor = float4(monitor(source[0], texCoord), 1.);
#endif
}
@@ -1,2 +0,0 @@
program
fragment: phosphorish.fs
@@ -1,56 +0,0 @@
/* Phosphorish
Copyright (C) 2011 Themaister
This program is licensed in the public domain
*/
#version 150
uniform sampler2D source[];
uniform vec4 sourceSize[];
uniform vec4 targetSize;
in Vertex {
vec2 texCoord;
};
out vec4 fragColor;
vec3 to_focus(float pixel)
{
pixel = mod(pixel + 3.0, 3.0);
if (pixel >= 2.0) // Blue
return vec3(pixel - 2.0, 0.0, 3.0 - pixel);
else if (pixel >= 1.0) // Green
return vec3(0.0, 2.0 - pixel, pixel - 1.0);
else // Red
return vec3(1.0 - pixel, pixel, 0.0);
}
void main()
{
float y = mod(texCoord.y * sourceSize[0].y, 1.0);
float intensity = exp(-0.2 * y);
vec2 one_x = vec2(1.0 / (3.0 * sourceSize[0].x), 0.0);
vec3 color = texture(source[0], texCoord.xy - 0.0 * one_x).rgb;
vec3 color_prev = texture(source[0], texCoord.xy - 1.0 * one_x).rgb;
vec3 color_prev_prev = texture(source[0], texCoord.xy - 2.0 * one_x).rgb;
float pixel_x = 3.0 * texCoord.x * sourceSize[0].x;
vec3 focus = to_focus(pixel_x - 0.0);
vec3 focus_prev = to_focus(pixel_x - 1.0);
vec3 focus_prev_prev = to_focus(pixel_x - 2.0);
vec3 result =
0.8 * color * focus +
0.6 * color_prev * focus_prev +
0.3 * color_prev_prev * focus_prev_prev;
result = 2.3 * pow(result, vec3(1.4));
fragColor = vec4(intensity * result, 1.0);
}
@@ -1,4 +0,0 @@
program
filter: linear
wrap: border
fragment: scanline.fs
-20
View File
@@ -1,20 +0,0 @@
#version 150
uniform sampler2D source[];
in Vertex {
vec2 texCoord;
};
out vec4 fragColor;
void main() {
vec4 rgba = texture(source[0], texCoord);
vec4 intensity;
if(fract(gl_FragCoord.y * (0.5 * 4.0 / 3.0)) > 0.5) {
intensity = vec4(0);
} else {
intensity = smoothstep(0.2, 0.8, rgba) + normalize(rgba);
}
fragColor = intensity * -0.25 + rgba * 1.1;
}
@@ -1,8 +0,0 @@
input
filter: linear
program
fragment: sharp-bilinear.fs
output
filter: linear
@@ -1,33 +0,0 @@
#version 150
// Sharp Bilinear
// Author: Themaister
// License: Public Domain
uniform sampler2D source[];
uniform vec4 sourceSize[];
uniform vec4 targetSize;
in Vertex {
vec2 texCoord;
};
out vec4 fragColor;
void main() {
float prescale = floor(targetSize.y / sourceSize[0].y);
vec2 texel = texCoord.xy * sourceSize[0].xy;
vec2 texel_floored = floor(texel);
vec2 s = fract(texel);
float region_range = 0.5 - 0.5 / prescale;
// Figure out where in the texel to sample to get correct pre-scaled bilinear.
// Uses the hardware bilinear interpolator to avoid having to sample 4 times manually.
vec2 center_dist = s - 0.5;
vec2 f = (center_dist - clamp(center_dist, -region_range, region_range)) * prescale + 0.5;
vec2 mod_texel = texel_floored + f;
fragColor = texture(source[0], mod_texel / sourceSize[0].xy);;
}
-3
View File
@@ -34,9 +34,6 @@ auto CPU::power(bool reset) -> void {
MOS6502::power();
Thread::create(system.frequency() / 3, {&CPU::main, this});
PC.byte(0) = readBus(0xfffc);
PC.byte(1) = readBus(0xfffd);
io = {};
}
+1 -2
View File
@@ -34,8 +34,6 @@ struct CPU : MOS6502, Thread {
//timing.cpp
auto read(n16 address) -> n8 override;
auto write(n16 address, n8 data) -> void override;
auto lastCycle() -> void override;
auto nmi(n16& vector) -> void override;
auto rdyLine(bool) -> void;
@@ -43,6 +41,7 @@ struct CPU : MOS6502, Thread {
struct IO {
n1 rdyLine = 1;
n32 scanlineCycles = 0;
n8 openBus = 0;
} io;
};
+1
View File
@@ -2,4 +2,5 @@ auto CPU::serialize(serializer& s) -> void {
MOS6502::serialize(s);
Thread::serialize(s);
s(io.rdyLine);
s(io.openBus);
}
+5 -12
View File
@@ -6,24 +6,17 @@ auto CPU::read(n16 address) -> n8 {
step(1);
}
MDR = readBus(address);
return MDR;
io.openBus = readBus(address);
return io.openBus;
}
MDR = readBus(address);
return MDR;
io.openBus = readBus(address);
return io.openBus;
}
auto CPU::write(n16 address, n8 data) -> void {
step(1);
writeBus(address, MDR = data);
}
auto CPU::lastCycle() -> void {
}
auto CPU::nmi(n16& vector) -> void {
writeBus(address, io.openBus = data);
}
auto CPU::rdyLine(bool line) -> void {
+1 -1
View File
@@ -93,4 +93,4 @@ auto RIOT::readPortB() -> n8 {
auto RIOT::writePortB(n8 data) -> void {
port[1].data = data;
}
}
+1 -1
View File
@@ -44,4 +44,4 @@ auto RIOT::power(bool reset) -> void {
tvType = 1;
}
}
}
+1 -1
View File
@@ -47,4 +47,4 @@ struct RIOT : Thread {
n1 tvTypeLatch;
};
extern RIOT riot;
extern RIOT riot;
+1 -1
View File
@@ -20,4 +20,4 @@ auto RIOT::serialize(serializer& s) -> void {
s(rightDifficultyLatch);
s(tvType);
s(tvTypeLatch);
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
static const string SerializerVersion = "v132";
static const string SerializerVersion = "v139";
auto System::serialize(bool synchronize) -> serializer {
if(synchronize) scheduler.enter(Scheduler::Mode::Synchronize);
+1 -1
View File
@@ -61,4 +61,4 @@ auto TIA::AudioChannel::phase1() -> u8 {
}
return pulseCounter.bit(0) * volume;
}
}
+16
View File
@@ -0,0 +1,16 @@
auto TIA::Ball::reset() -> void {
counter = -4; // Resetting takes 4 cycles
}
auto TIA::Ball::step(u8 clocks) -> void {
if(!clocks) return;
while(clocks--) {
if(++counter == 160) {
counter = 0;
}
const int ballSizes[4] = {1, 2, 4, 8};
output = enable[delay] && counter < ballSizes[size];
}
}
+11 -9
View File
@@ -106,10 +106,12 @@ auto TIA::cxclr() -> void {
}
auto TIA::hmove() -> void {
for(auto& p : player) p.position = (p.position - p.offset + 160) % 160;
for(auto& m : missile) m.position = (m.position - m.offset + 160) % 160;
ball.position = (ball.position - ball.offset + 160) % 160;
io.hmoveTriggered = io.vcounter;
u4 mask = 1 << 3;
for(auto& p : player) p.step(p.offset ^ mask);
for(auto& m : missile) m.step(m.offset ^ mask);
ball.step(ball.offset ^ mask);
io.hmoveTriggered = 1;
}
auto TIA::hmclr() -> void {
@@ -125,17 +127,17 @@ auto TIA::grp(n1 index, n8 data) -> void {
}
auto TIA::resp(n1 index) -> void {
player[index].position = (io.hcounter - 68 + 5) % 160;
player[index].reset();
}
auto TIA::resm(n1 index) -> void {
missile[index].position = (io.hcounter - 68 + 4) % 160;
missile[index].reset();
}
auto TIA::resmp(n1 index, n8 data) -> void {
missile[index].reset = data.bit(1);
missile[index].lockedToPlayer = data.bit(1);
}
auto TIA::resbl() -> void {
ball.position = (io.hcounter - 68 + 4) % 160;
}
ball.reset();
}
+88
View File
@@ -0,0 +1,88 @@
auto TIA::Missile::reset() -> void {
counter = -4;
}
auto TIA::Missile::start() -> void {
startCounter = 4;
starting = true;
}
auto TIA::Missile::width() -> u8 {
const int missileSizes[4] = {1, 2, 4, 8};
return missileSizes[size];
}
auto TIA::Missile::stepPixelCounter() -> void {
if(--widthCounter == 0) {
pixelCounter--;
widthCounter = width();
}
}
auto TIA::Missile::step(u8 clocks) -> void {
if(!clocks) return;
while(clocks--) {
counter++;
if(counter == 156) start();
if(counter == 160) counter = 0;
if(starting && (startCounter-- == 0)) {
starting = false;
pixelCounter = 1;
widthCounter = width();
}
output = 0;
if(pixelCounter) {
stepPixelCounter();
output = enable;
}
}
}
/*
auto TIA::runMissile(n8 x, n1 index) -> n1 {
auto& missile = this->missile[index];
auto& player = this->player[index];
auto position = missile.position;
if(missile.reset) {
auto offset = 3;
if(player.size == 5) offset = 6;
if(player.size == 7) offset = 10;
missile.position = player.position + offset;
return 0;
}
if(!missile.enable) return 0;
const int missileSizes[4] = {1, 2, 4, 8};
// Handle player stretch capability
auto width = missileSizes[missile.size];
auto repeatWidth = width;
if(player.size == 5) repeatWidth *= 2;
if(player.size == 7) repeatWidth *= 4;
// Handle repeat capability
auto repeat = 1;
if(player.size == 1 || player.size == 2 || player.size == 4) repeat = 2;
if(player.size == 3 || player.size == 6) repeat = 3;
auto spacing = 8;
if(player.size == 2 || player.size == 6) spacing = 24;
if(player.size == 4 ) spacing = 56;
for(int i = 0; i < repeat; i++) {
if (x >= position && x < position + width) {
return 1;
}
position = (position + (spacing + repeatWidth)) % 160;
}
return 0;
}
*/
+57
View File
@@ -0,0 +1,57 @@
auto TIA::Player::reset() -> void {
counter = -4;
}
auto TIA::Player::start(n1 copy) -> void {
this->copy = copy;
startCounter = 5;
starting = true;
}
auto TIA::Player::width() -> u8 {
switch(size) {
case 5: return 2;
case 7: return 4;
default: return 1;
}
}
auto TIA::Player::stepPixelCounter() -> void {
if(--widthCounter == 0) {
pixelCounter--;
widthCounter = width();
}
if(!copy && missile.lockedToPlayer && pixelCounter == 4) {
missile.reset();
}
}
auto TIA::Player::step(u8 clocks) -> void {
if(!clocks) return;
while(clocks--) {
counter++;
n1 first = size == 1 || size == 3;
n1 second = size == 2 || size == 3 || size == 6;
n1 third = size == 4 || size == 6;
if(first && counter == 12) start(true);
if(second && counter == 28) start(true);
if(third && counter == 60) start(true);
if(counter == 156) start(false);
if(counter == 160) counter = 0;
if(starting && (startCounter-- == 0)) {
starting = false;
pixelCounter = 8;
widthCounter = width();
}
output = 0;
if(pixelCounter) {
stepPixelCounter();
output = graphics[delay].bit(reflect ? (7 - pixelCounter) : pixelCounter);
}
}
}
+10
View File
@@ -0,0 +1,10 @@
auto TIA::runPlayfield(n8 x) -> n1 {
if((x % 4) == 0) {
auto pos = x >> 2;
playfield.pixel = (!playfield.mirror || pos < 20) ? playfield.graphics.bit(pos % 20)
: playfield.graphics.bit(19 - (pos % 20));
}
return playfield.pixel;
}
+22 -11
View File
@@ -30,25 +30,36 @@ auto TIA::serialize(serializer& s) -> void {
s(player[n].reflect);
s(player[n].size);
s(player[n].offset);
s(player[n].position);
s(player[n].delay);
s(player[n].counter);
s(player[n].startCounter);
s(player[n].pixelCounter);
s(player[n].widthCounter);
s(player[n].starting);
s(player[n].output);
s(player[n].copy);
}
for(auto n : range(2)) {
s(missile[n].enable);
s(missile[n].reset);
s(missile[n].lockedToPlayer);
s(missile[n].size);
s(missile[n].offset);
s(missile[n].position);
s(missile[n].counter);
s(missile[n].startCounter);
s(missile[n].pixelCounter);
s(missile[n].widthCounter);
s(missile[n].starting);
s(missile[n].output);
}
for(auto n : range(2)) {
s(ball.enable[0]);
s(ball.enable[1]);
s(ball.size);
s(ball.offset);
s(ball.position);
}
s(ball.enable[0]);
s(ball.enable[1]);
s(ball.delay);
s(ball.size);
s(ball.offset);
s(ball.counter);
s(ball.output);
s(collision.M0P0);
s(collision.M0P1);
@@ -82,4 +93,4 @@ auto TIA::serialize(serializer& s) -> void {
s(audio[n].control);
s(audio[n].frequency);
}
}
}
+69 -136
View File
@@ -7,6 +7,10 @@ TIA tia;
#include "audio.cpp"
#include "color.cpp"
#include "io.cpp"
#include "playfield.cpp"
#include "player.cpp"
#include "missile.cpp"
#include "ball.cpp"
#include "serialization.cpp"
#include "write-queue.cpp"
@@ -37,7 +41,7 @@ auto TIA::unload() -> void {
auto TIA::main() -> void {
scanline();
io.vcounter++;
io.hmoveTriggered = 255;
io.hmoveTriggered = 0;
}
auto TIA::scanline() -> void {
@@ -47,7 +51,54 @@ auto TIA::scanline() -> void {
writeQueue.step();
auto x = io.hcounter - 68;
auto y = io.vcounter - voffset();
if(x >= 0 && y > 0 && y < vlines()) pixel(x);
bool hblank = (io.hmoveTriggered && io.hcounter < 76) || io.hcounter < 68;
// Playfield ignores hmove and always begins at cycle 68
//if(io.hcounter >= 68) playfield.step();
// Objects are stepped only during active display
if(!hblank) {
ball.step();
for(auto& player : this->player) player.step();
for(auto& missile : this->missile) missile.step();
}
n8 pixel = io.bgColor;
auto pf = runPlayfield(x);
auto bl = ball.output;
auto p0 = player[0].output;
auto p1 = player[1].output;
auto m0 = missile[0].output;
auto m1 = missile[1].output;
if(!playfield.priority && (pf || bl)) pixel = io.fgColor;
if(p1 || m1) pixel = io.p1Color;
if(p0 || m0) pixel = io.p0Color;
if(playfield.priority && (pf || bl)) pixel = io.fgColor;
// Update Collision
if(m0 && p1) collision.M0P1 = 1;
if(m0 && p0) collision.M0P0 = 1;
if(m1 && p0) collision.M1P0 = 1;
if(m1 && p1) collision.M1P1 = 1;
if(p0 && pf) collision.P0PF = 1;
if(p0 && bl) collision.P0BL = 1;
if(p1 && pf) collision.P1PF = 1;
if(p1 && bl) collision.P1BL = 1;
if(m0 && pf) collision.M0PF = 1;
if(m0 && bl) collision.M0BL = 1;
if(m1 && pf) collision.M1PF = 1;
if(m1 && bl) collision.M1BL = 1;
if(bl && pf) collision.BLPF = 1;
if(p0 && p1) collision.P0P1 = 1;
if(m0 && m1) collision.M0M1 = 1;
if(x >= 0 && y > 0 && y < displayHeight()) {
if(io.vblank || hblank) pixel = 0;
auto output = screen->pixels().data() + (y * 180) + 10;
output[x] = pixel;
}
runAudio();
step();
if(io.hcounter == 0) cpu.io.rdyLine = 1;
@@ -60,139 +111,8 @@ auto TIA::scanline() -> void {
}
}
auto TIA::pixel(n8 x) -> void {
auto y = io.vcounter - voffset();
auto output = screen->pixels().data() + (y * 180) + 10;
if(y >= displayHeight()) return;
// Output only black during vblank, or for the first 8px of a scanline where hmove was triggered
if (io.vblank || (io.hmoveTriggered == io.vcounter && x < 8)) {
output[x] = 0;
return;
}
output[x] = io.bgColor;
auto pf = runPlayfield(x);
auto bl = runBall(x);
auto p0 = runPlayer(x, 0);
auto p1 = runPlayer(x, 1);
auto m0 = runMissile(x, 0);
auto m1 = runMissile(x, 1);
if(!playfield.priority && (pf || bl)) output[x] = io.fgColor;
if(p1 || m1) output[x] = io.p1Color;
if(p0 || m0) output[x] = io.p0Color;
if(playfield.priority && (pf || bl)) output[x] = io.fgColor;
// Update Collision
if(m0 && p1) collision.M0P1 = 1;
if(m0 && p0) collision.M0P0 = 1;
if(m1 && p0) collision.M1P0 = 1;
if(m1 && p1) collision.M1P1 = 1;
if(p0 && pf) collision.P0PF = 1;
if(p0 && bl) collision.P0BL = 1;
if(p1 && pf) collision.P1PF = 1;
if(p1 && bl) collision.P1BL = 1;
if(m0 && pf) collision.M0PF = 1;
if(m0 && bl) collision.M0BL = 1;
if(m1 && pf) collision.M1PF = 1;
if(m1 && bl) collision.M1BL = 1;
if(bl && pf) collision.BLPF = 1;
if(p0 && p1) collision.P0P1 = 1;
if(m0 && m1) collision.M0M1 = 1;
}
auto TIA::runPlayfield(n8 x) -> n1 {
if((x % 4) == 0) {
auto pos = x >> 2;
playfield.pixel = (!playfield.mirror || pos < 20) ? playfield.graphics.bit(pos % 20)
: playfield.graphics.bit(19 - (pos % 20));
}
return playfield.pixel;
}
auto TIA::runPlayer(n8 x, n1 index) -> n1 {
auto& player = this->player[index];
auto position = player.position;
// Handle player stretch capability
auto width = 8;
if(player.size == 5) width = 16;
if(player.size == 7) width = 32;
// Handle repeat capability
auto repeat = 1;
if(player.size == 1 || player.size == 2 || player.size == 4) repeat = 2;
if(player.size == 3 || player.size == 6) repeat = 3;
auto spacing = 8;
if(player.size == 2 || player.size == 6) spacing = 24;
if(player.size == 4 ) spacing = 56;
for(int i = 0; i < repeat; i++) {
if (x >= position && x < position + width) {
auto bit = player.reflect ? (x - position) / (width / 8) : 7 - ((x - position) / (width / 8));
return player.graphics[player.delay].bit(bit);
}
position = (position + (spacing + width)) % 160;
}
return 0;
}
auto TIA::runMissile(n8 x, n1 index) -> n1 {
auto& missile = this->missile[index];
auto& player = this->player[index];
auto position = missile.position;
if(missile.reset) {
auto offset = 3;
if(player.size == 5) offset = 6;
if(player.size == 7) offset = 10;
missile.position = player.position + offset;
return 0;
}
if(!missile.enable) return 0;
const int missileSizes[4] = {1, 2, 4, 8};
// Handle player stretch capability
auto width = missileSizes[missile.size];
auto repeatWidth = width;
if(player.size == 5) repeatWidth *= 2;
if(player.size == 7) repeatWidth *= 4;
// Handle repeat capability
auto repeat = 1;
if(player.size == 1 || player.size == 2 || player.size == 4) repeat = 2;
if(player.size == 3 || player.size == 6) repeat = 3;
auto spacing = 8;
if(player.size == 2 || player.size == 6) spacing = 24;
if(player.size == 4 ) spacing = 56;
for(int i = 0; i < repeat; i++) {
if (x >= position && x < position + width) {
return 1;
}
position = (position + (spacing + repeatWidth)) % 160;
}
return 0;
}
auto TIA::runBall(n8 x) -> n1 {
if(!ball.enable[ball.delay]) return 0;
const int ballSizes[4] = {1, 2, 4, 8};
return x >= ball.position && x < ball.position + ballSizes[ball.size];
}
auto TIA::frame() -> void {
screen->refreshRateHint(system.frequency(), 228, io.vcounter);
screen->frame();
scheduler.exit(Event::Frame);
}
@@ -207,7 +127,20 @@ auto TIA::power(bool reset) -> void {
screen->power();
io = {};
playfield = {};
for(auto& p : player) p = {};
for(auto& p : player) {
p.graphics[0] = p.graphics[1] = 0;
p.reflect = 0;
p.size = 0;
p.offset = 0;
p.delay = 0;
p.counter = 0;
p.startCounter = 0;
p.pixelCounter = 0;
p.widthCounter = 0;
p.starting = 0;
p.output = 0;
p.copy = 0;
};
for(auto& m : missile) m = {};
ball = {};
collision = {};
@@ -219,4 +152,4 @@ auto TIA::power(bool reset) -> void {
volume[15] = 0;
}
}
}
+42 -17
View File
@@ -19,7 +19,6 @@ struct TIA : Thread {
auto pixel(n8 x) -> void;
auto runPlayfield(n8 x) -> n1;
auto runBall(n8 x) -> n1;
auto runPlayer(n8 x, n1 index) -> n1;
auto runMissile(n8 x, n1 index) -> n1;
auto runCollision() -> void;
@@ -67,7 +66,7 @@ struct TIA : Thread {
struct {
u9 vcounter;
u8 hcounter;
u8 hmoveTriggered;
n1 hmoveTriggered;
n1 vsync;
n1 vblank;
@@ -86,29 +85,55 @@ struct TIA : Thread {
n1 priority;
} playfield;
struct {
struct Missile {
auto step(u8 cycles = 1) -> void;
auto start() -> void;
auto reset() -> void;
auto width() -> u8;
auto stepPixelCounter() -> void;
n1 enable;
n1 lockedToPlayer;
n2 size;
n4 offset;
i9 counter;
u8 startCounter;
u8 pixelCounter;
u8 widthCounter;
n1 starting;
n1 output;
} missile[2];
struct Player {
Missile& missile;
auto step(u8 cycles = 1) -> void;
auto start(n1 copy) -> void;
auto reset() -> void;
auto width() -> u8;
auto stepPixelCounter() -> void;
n8 graphics[2];
n1 reflect;
n3 size;
i4 offset;
n8 position;
n4 offset;
n1 delay;
} player[2];
i9 counter;
u8 startCounter;
u8 pixelCounter;
u8 widthCounter;
n1 starting;
n1 output;
n1 copy;
} player[2] {{missile[0]}, {missile[1]}};
struct {
n1 enable;
n1 reset;
n2 size;
i4 offset;
n8 position;
} missile[2];
struct Ball {
auto step(u8 cycles = 1) -> void;
auto reset() -> void;
struct {
n1 enable[2];
n2 size;
i4 offset;
n4 offset;
n1 delay;
n8 position;
i9 counter;
n1 output;
} ball;
struct {
@@ -147,4 +172,4 @@ struct TIA : Thread {
f64 volume[16];
};
extern TIA tia;
extern TIA tia;
+1 -1
View File
@@ -43,4 +43,4 @@ auto TIA::WriteQueue::QueueItem::commit() -> void {
case 0x2b: tia.hmclr(); return; // HMCLR
}
debug(unimplemented, "[TIA] writeQueue: ",hex(address), " = ", hex(data));
}
}
+1 -1
View File
@@ -10,7 +10,7 @@ Platform* platform = nullptr;
bool _runAhead = false;
const string Name = "ares";
const string Version = "136";
const string Version = "141";
const string Copyright = "ares team, Near";
const string License = "ISC";
const string LicenseURI = "https://opensource.org/licenses/ISC";
+18 -3
View File
@@ -25,11 +25,15 @@ Screen::~Screen() {
auto Screen::main(uintptr_t) -> void {
while(!_kill) {
usleep(1);
if(_frame) {
unique_lock<mutex> lock(_frameMutex);
auto timeout = std::chrono::milliseconds(10);
if(_frameCondition.wait_for(lock, timeout, [&] { return _frame.load(); })) {
refresh();
_frame = false;
}
if(_kill) break;
}
}
@@ -68,6 +72,15 @@ auto Screen::setRefresh(function<void ()> refresh) -> void {
_refresh = refresh;
}
auto Screen::refreshRateHint(double pixelFrequency, int dotsPerLine, int linesPerFrame) -> void {
refreshRateHint(1.0f / ((double)(dotsPerLine * linesPerFrame) / pixelFrequency));
}
auto Screen::refreshRateHint(double refreshRate) -> void {
lock_guard<recursive_mutex> lock(_mutex);
platform->refreshRateHint(refreshRate);
}
auto Screen::setViewport(u32 x, u32 y, u32 width, u32 height) -> void {
lock_guard<recursive_mutex> lock(_mutex);
_viewportX = x;
@@ -181,10 +194,12 @@ auto Screen::frame() -> void {
lock_guard<recursive_mutex> lock(_mutex);
_inputA.swap(_inputB);
_frame = true;
if constexpr(!ares::Video::Threaded) {
refresh();
_frame = false;
} else {
_frame = true;
_frameCondition.notify_one();
}
}
+4
View File
@@ -34,6 +34,8 @@ struct Screen : Video {
auto setRefresh(function<void ()> refresh) -> void;
auto setViewport(u32 x, u32 y, u32 width, u32 height) -> void;
auto refreshRateHint(double refreshRate) -> void;
auto refreshRateHint(double pixelFrequency, int dotsPerLine, int linesPerFrame) -> void;
auto setSize(u32 width, u32 height) -> void;
auto setScale(f64 scaleX, f64 scaleY) -> void;
@@ -97,6 +99,8 @@ protected:
//unserialized:
nall::thread _thread;
recursive_mutex _mutex;
mutex _frameMutex;
condition_variable _frameCondition;
atomic<bool> _kill = false;
atomic<bool> _frame = false;
function<void ()> _refresh;
+1
View File
@@ -18,6 +18,7 @@ struct Platform {
virtual auto log(Node::Debugger::Tracer::Tracer, string_view message) -> void {}
virtual auto status(string_view message) -> void {}
virtual auto video(Node::Video::Screen, const u32* data, u32 pitch, u32 width, u32 height) -> void {}
virtual auto refreshRateHint(double refreshRate) -> void {}
virtual auto audio(Node::Audio::Stream) -> void {}
virtual auto input(Node::Input::Input) -> void {}
virtual auto cheat(u32 addr) -> maybe<u32> { return nothing; }
@@ -165,6 +165,8 @@ auto M93LCx6::ShiftRegister::read() -> n1 {
}
auto M93LCx6::ShiftRegister::write(n1 bit) -> void {
// wait for start bit
if(!bit && !count) return;
value <<= 1;
value.bit(0) = bit;
count++;
+1 -1
View File
@@ -69,4 +69,4 @@ namespace ares {
s(state.portB);
s(state.portC);
}
}
}
+2 -1
View File
@@ -32,4 +32,5 @@ namespace ares {
n8 portC;
} state;
};
}
}
@@ -20,6 +20,7 @@ struct ARM7TDMI {
virtual auto step(u32 clocks) -> void = 0;
virtual auto sleep() -> void = 0;
virtual auto get(u32 mode, n32 address) -> n32 = 0;
virtual auto getDebugger(u32 mode, n32 address) -> n32 { return get(mode, address); }
virtual auto set(u32 mode, n32 address, n32 word) -> void = 0;
//arm7tdmi.cpp
@@ -17,12 +17,12 @@ auto ARM7TDMI::disassembleInstruction(maybe<n32> pc, maybe<boolean> thumb) -> st
_pc = pc();
if(!thumb()) {
n32 opcode = read(Word | Nonsequential, _pc & ~3);
n32 opcode = getDebugger(Word | Nonsequential, _pc & ~3);
n12 index = (opcode & 0x0ff00000) >> 16 | (opcode & 0x000000f0) >> 4;
_c = _conditions[opcode >> 28];
return pad(armDisassemble[index](opcode), -40);
} else {
n16 opcode = read(Half | Nonsequential, _pc & ~1);
n16 opcode = getDebugger(Half | Nonsequential, _pc & ~1);
return pad(thumbDisassemble[opcode](), -40);
}
}
@@ -121,7 +121,7 @@ auto ARM7TDMI::armDisassembleDataRegisterShift
auto ARM7TDMI::armDisassembleLoadImmediate
(n8 immediate, n1 half, n4 d, n4 n, n1 writeback, n1 up, n1 pre) -> string {
string data;
if(n == 15) data = {" =0x", hex(read((half ? Half : Byte) | Nonsequential,
if(n == 15) data = {" =0x", hex(getDebugger((half ? Half : Byte) | Nonsequential,
_pc + 8 + (up ? +immediate : -immediate)), half ? 4L : 2L)};
return {"ldr", _c, half ? "sh" : "sb", " ",
@@ -150,7 +150,7 @@ auto ARM7TDMI::armDisassembleMemorySwap
auto ARM7TDMI::armDisassembleMoveHalfImmediate
(n8 immediate, n4 d, n4 n, n1 mode, n1 writeback, n1 up, n1 pre) -> string {
string data;
if(n == 15) data = {" =0x", hex(read(Half | Nonsequential, _pc + (up ? +immediate : -immediate)), 4L)};
if(n == 15) data = {" =0x", hex(getDebugger(Half | Nonsequential, _pc + (up ? +immediate : -immediate)), 4L)};
return {mode ? "ldr" : "str", _c, "h ",
_r[d], ",[", _r[n],
@@ -173,7 +173,7 @@ auto ARM7TDMI::armDisassembleMoveHalfRegister
auto ARM7TDMI::armDisassembleMoveImmediateOffset
(n12 immediate, n4 d, n4 n, n1 mode, n1 writeback, n1 byte, n1 up, n1 pre) -> string {
string data;
if(n == 15) data = {" =0x", hex(read((byte ? Byte : Word) | Nonsequential,
if(n == 15) data = {" =0x", hex(getDebugger((byte ? Byte : Word) | Nonsequential,
_pc + 8 + (up ? +immediate : -immediate)), byte ? 2L : 4L)};
return {mode ? "ldr" : "str", _c, byte ? "b" : "", " ", _r[d], ",[", _r[n],
pre == 0 ? "]" : "",
@@ -308,7 +308,7 @@ auto ARM7TDMI::thumbDisassembleBranchExchange
auto ARM7TDMI::thumbDisassembleBranchFarPrefix
(i11 displacementHi) -> string {
n11 displacementLo = read(Half | Nonsequential, (_pc & ~1) + 2);
n11 displacementLo = getDebugger(Half | Nonsequential, (_pc & ~1) + 2);
i22 displacement = displacementHi << 11 | displacementLo << 0;
n32 address = _pc + 4 + displacement * 2;
return {"bl 0x", hex(address, 8L)};
@@ -340,7 +340,7 @@ auto ARM7TDMI::thumbDisassembleImmediate
auto ARM7TDMI::thumbDisassembleLoadLiteral
(n8 displacement, n3 d) -> string {
n32 address = ((_pc + 4) & ~3) + (displacement << 2);
n32 data = read(Word | Nonsequential, address);
n32 data = getDebugger(Word | Nonsequential, address);
return {"ldr ", _r[d], ",[pc,#0x", hex(address, 8L), "] =0x", hex(data, 8L)};
}
@@ -182,14 +182,15 @@ auto ARM7TDMI::armInstructionMoveImmediateOffset
auto ARM7TDMI::armInstructionMoveMultiple
(n16 list, n4 n, n1 mode, n1 writeback, n1 type, n1 up, n1 pre) -> void {
n32 rn = r(n);
n32 bitCount = list ? bit::count(list) : 16;
if(pre == 0 && up == 1) rn = rn + 0; //IA
if(pre == 1 && up == 1) rn = rn + 4; //IB
if(pre == 1 && up == 0) rn = rn - bit::count(list) * 4 + 0; //DB
if(pre == 0 && up == 0) rn = rn - bit::count(list) * 4 + 4; //DA
if(pre == 1 && up == 0) rn = rn - bitCount * 4 + 0; //DB
if(pre == 0 && up == 0) rn = rn - bitCount * 4 + 4; //DA
if(writeback && mode == 1) {
if(up == 1) r(n) = r(n) + bit::count(list) * 4; //IA,IB
if(up == 0) r(n) = r(n) - bit::count(list) * 4; //DA,DB
if(writeback && mode == 1 && !list.bit(n)) {
if(up == 1) r(n) = r(n) + bitCount * 4; //IA,IB
if(up == 0) r(n) = r(n) - bitCount * 4; //DA,DB
}
auto cpsrMode = cpsr().m;
@@ -199,12 +200,17 @@ auto ARM7TDMI::armInstructionMoveMultiple
if(usr) cpsr().m = PSR::USR;
u32 sequential = Nonsequential;
for(u32 m : range(16)) {
if(!list.bit(m)) continue;
if(mode == 1) r(m) = read(Word | sequential, rn);
if(mode == 0) write(Word | sequential, rn, r(m) + (m == 15 ? 4 : 0));
rn += 4;
sequential = Sequential;
if(!list) {
if(mode == 1) r(15) = read(Word | sequential, rn);
if(mode == 0) write(Word | sequential, rn, r(15) + 4);
} else {
for(u32 m : range(16)) {
if(!list.bit(m)) continue;
if(mode == 1) r(m) = read(Word | sequential, rn);
if(mode == 0) write(Word | sequential, rn, r(m) + (m == 15 ? 4 : 0));
rn += 4;
sequential = Sequential;
}
}
if(usr) cpsr().m = cpsrMode;
@@ -219,8 +225,8 @@ auto ARM7TDMI::armInstructionMoveMultiple
}
if(writeback && mode == 0) {
if(up == 1) r(n) = r(n) + bit::count(list) * 4; //IA,IB
if(up == 0) r(n) = r(n) - bit::count(list) * 4; //DA,DB
if(up == 1) r(n) = r(n) + bitCount * 4; //IA,IB
if(up == 0) r(n) = r(n) - bitCount * 4; //DA,DB
}
}
@@ -249,8 +255,7 @@ auto ARM7TDMI::armInstructionMoveRegisterOffset
auto ARM7TDMI::armInstructionMoveToRegisterFromStatus
(n4 d, n1 mode) -> void {
if(mode && (cpsr().m == PSR::USR || cpsr().m == PSR::SYS)) return;
r(d) = mode ? spsr() : cpsr();
r(d) = (mode && cpsr().m != PSR::USR && cpsr().m != PSR::SYS) ? spsr() : cpsr();
}
auto ARM7TDMI::armInstructionMoveToStatusFromImmediate
@@ -125,23 +125,29 @@ auto ARM7TDMI::thumbInstructionMoveHalfImmediate
auto ARM7TDMI::thumbInstructionMoveMultiple
(n8 list, n3 n, n1 mode) -> void {
n32 rn = r(n);
n32 bitCount = list ? bit::count(list) : 16;
if(mode == 1 && !list.bit(n)) r(n) = r(n) + bitCount * 4;
u32 sequential = Nonsequential;
for(u32 m : range(8)) {
if(!list.bit(m)) continue;
switch(mode) {
case 0: write(Word | sequential, rn, r(m)); break; //STMIA
case 1: r(m) = read(Word | sequential, rn); break; //LDMIA
if(!list) {
if(mode == 1) r(15) = read(Word | sequential, rn);
if(mode == 0) write(Word | sequential, rn, r(15) + 2);
} else {
for(u32 m : range(8)) {
if(!list.bit(m)) continue;
if(mode == 1) r(m) = read(Word | sequential, rn); //LDMIA
if(mode == 0) write(Word | sequential, rn, r(m)); //STMIA
rn += 4;
sequential = Sequential;
}
rn += 4;
sequential = Sequential;
}
if(mode == 0 || !list.bit(n)) r(n) = rn;
if(mode == 1) {
if(mode) {
idle();
} else {
pipeline.nonsequential = true;
r(n) = r(n) + bitCount * 4;
}
}
@@ -191,37 +197,35 @@ auto ARM7TDMI::thumbInstructionSoftwareInterrupt
auto ARM7TDMI::thumbInstructionStackMultiple
(n8 list, n1 lrpc, n1 mode) -> void {
n32 sp;
switch(mode) {
case 0: sp = r(13) - (bit::count(list) + lrpc) * 4; break; //PUSH
case 1: sp = r(13); //POP
}
n32 sp = r(13);
n32 bitCount = (list | lrpc) ? (bit::count(list) + lrpc) : 16;
if(mode == 1) r(13) = r(13) + bitCount * 4; //POP
if(mode == 0) sp = sp - bitCount * 4 + 0; //PUSH
u32 sequential = Nonsequential;
for(u32 m : range(8)) {
if(!list.bit(m)) continue;
switch(mode) {
case 0: write(Word | sequential, sp, r(m)); break; //PUSH
case 1: r(m) = read(Word | sequential, sp); break; //POP
if(bitCount == 16) {
if(mode == 1) r(15) = read(Word | sequential, sp); //POP
if(mode == 0) write(Word | sequential, sp, r(15) + 2); //PUSH
} else {
for(u32 m : range(8)) {
if(!list.bit(m)) continue;
if(mode == 1) r(m) = read(Word | sequential, sp); //POP
if(mode == 0) write(Word | sequential, sp, r(m)); //PUSH
sp += 4;
sequential = Sequential;
}
sp += 4;
sequential = Sequential;
}
if(lrpc) {
switch(mode) {
case 0: write(Word | sequential, sp, r(14)); break; //PUSH
case 1: r(15) = read(Word | sequential, sp); break; //POP
}
if(mode == 1) r(15) = read(Word | sequential, sp); //POP
if(mode == 0) write(Word | sequential, sp, r(14)); //PUSH
sp += 4;
}
if(mode == 1) {
if(mode) {
idle();
r(13) = r(13) + (bit::count(list) + lrpc) * 4; //POP
} else {
pipeline.nonsequential = true;
r(13) = r(13) - (bit::count(list) + lrpc) * 4; //PUSH
r(13) = r(13) - bitCount * 4; //PUSH
}
}
+2 -2
View File
@@ -75,8 +75,8 @@ struct GSU {
auto serialize(serializer&) -> void;
//disassembler.cpp
noinline auto disassembleInstruction() -> string;
noinline auto disassembleContext() -> string;
NALL_NOINLINE auto disassembleInstruction() -> string;
NALL_NOINLINE auto disassembleContext() -> string;
auto disassembleOpcode(char* output) -> void;
auto disassembleALT0(char* output) -> void;
+2 -2
View File
@@ -111,8 +111,8 @@ struct HG51B {
auto writeRegister(n7 address, n24 data) -> void;
//disassembler.cpp
noinline auto disassembleInstruction(maybe<n15> pb = {}, maybe<n8> pc = {}) -> string;
noinline auto disassembleContext() -> string;
NALL_NOINLINE auto disassembleInstruction(maybe<n15> pb = {}, maybe<n8> pc = {}) -> string;
NALL_NOINLINE auto disassembleContext() -> string;
protected:
struct Registers {
+2 -2
View File
@@ -124,8 +124,8 @@ struct I8080 {
auto serialize(serializer&) -> void;
//disassembler.cpp
noinline auto disassembleInstruction(maybe<n16> pc = {}) -> string;
noinline auto disassembleContext() -> string;
NALL_NOINLINE auto disassembleInstruction(maybe<n16> pc = {}) -> string;
NALL_NOINLINE auto disassembleContext() -> string;
auto disassemble(n16 pc, n8 prefix, n8 code) -> string;
@@ -0,0 +1,108 @@
auto MOS6502::addressAbsolute() -> n16 {
n16 absolute = operand();
absolute |= operand() << 8;
return absolute;
}
auto MOS6502::addressAbsoluteJMP() -> n16 {
n16 absolute = operand();
// JMP Indirect last_cycle
L absolute |= operand() << 8;
return absolute;
}
auto MOS6502::addressAbsoluteXRead() -> n16 {
n16 absolute = operand();
absolute |= operand() << 8;
idlePageCrossed(absolute, absolute + X);
return absolute + X;
}
auto MOS6502::addressAbsoluteXWrite() -> n16 {
n16 absolute = operand();
absolute |= operand() << 8;
idlePageAlways(absolute, absolute + X);
return absolute + X;
}
auto MOS6502::addressAbsoluteYRead() -> n16 {
n16 absolute = operand();
absolute |= operand() << 8;
idlePageCrossed(absolute, absolute + Y);
return absolute + Y;
}
auto MOS6502::addressAbsoluteYWrite() -> n16 {
n16 absolute = operand();
absolute |= operand() << 8;
idlePageAlways(absolute, absolute + Y);
return absolute + Y;
}
auto MOS6502::addressAccumulator() -> n16 {
return PC;
}
auto MOS6502::addressImmediate() -> n16 {
return PC++;
}
auto MOS6502::addressImplied() -> n16 {
return PC;
}
auto MOS6502::addressIndirect() -> n16 {
n16 absolute = operand();
absolute |= operand() << 8;
n16 indirect = read(absolute);
absolute.byte(0)++;
// JMP Indirect last_cycle
L indirect |= read(absolute) << 8;
return indirect;
}
auto MOS6502::addressIndirectX() -> n16 {
n8 zeroPage = operand();
idleZeroPage(zeroPage);
n16 absolute = load(zeroPage + X);
absolute |= load(zeroPage + X + 1) << 8;
return absolute;
}
auto MOS6502::addressIndirectYRead() -> n16 {
n16 zeroPage = operand();
n16 absolute = load(zeroPage + 0);
absolute |= load(zeroPage + 1) << 8;
idlePageCrossed(absolute, absolute + Y);
return absolute + Y;
}
auto MOS6502::addressIndirectYWrite() -> n16 {
n8 zeroPage = operand();
n16 absolute = load(zeroPage + 0);
absolute |= load(zeroPage + 1) << 8;
idlePageAlways(absolute, absolute + Y);
return absolute + Y;
}
auto MOS6502::addressRelative() -> n16 {
return PC++;
}
auto MOS6502::addressZeroPage() -> n16 {
return operand();
}
auto MOS6502::addressZeroPageX() -> n16 {
n8 zeropage = operand();
idleZeroPage(zeropage);
zeropage += X;
return zeropage;
}
auto MOS6502::addressZeroPageY() -> n16 {
n8 zeropage = operand();
idleZeroPage(zeropage);
zeropage += Y;
return zeropage;
}
+505 -178
View File
@@ -1,4 +1,5 @@
auto MOS6502::algorithmADC(n8 i) -> n8 {
auto MOS6502::algorithmADC() -> void {
n8 i = MDR;
i16 o = A + i + C;
if(!BCD || !D) {
C = o.bit(8);
@@ -17,197 +18,319 @@ auto MOS6502::algorithmADC(n8 i) -> n8 {
if(o > 0x9f) o += 0x60;
C = o > 0xff;
}
return o;
A = o;
}
auto MOS6502::algorithmALR(n8 i) -> n8 {
n8 o = A & i;
C = o.bit(0);
o >>= 1;
Z = o == 0;
N = o.bit(7);
return o;
auto MOS6502::algorithmAND() -> void {
A &= MDR;
Z = A == 0;
N = A.bit(7);
}
auto MOS6502::algorithmAND(n8 i) -> n8 {
n8 o = A & i;
Z = o == 0;
N = o.bit(7);
return o;
auto MOS6502::algorithmASLA() -> void {
C = A.bit(7);
A <<= 1;
Z = A == 0;
N = A.bit(7);
}
auto MOS6502::algorithmANC(n8 i) -> n8 {
n8 o = A & i;
Z = o == 0;
N = o.bit(7);
C = N;
return o;
auto MOS6502::algorithmASLM() -> void {
C = MDR.bit(7);
MDR <<= 1;
Z = MDR == 0;
N = MDR.bit(7);
}
auto MOS6502::algorithmARR(n8 i) -> n8 {
n8 o = A & i;
Z = o == 0;
N = o.bit(7);
auto MOS6502::algorithmBCC() -> void {
algorithmBranch(C == 0);
}
auto MOS6502::algorithmBCS() -> void {
algorithmBranch(C == 1);
}
auto MOS6502::algorithmBEQ() -> void {
algorithmBranch(Z == 1);
}
auto MOS6502::algorithmBIT() -> void {
Z = (A & MDR) == 0;
V = MDR.bit(6);
N = MDR.bit(7);
}
auto MOS6502::algorithmBMI() -> void {
algorithmBranch(N == 1);
}
auto MOS6502::algorithmBNE() -> void {
algorithmBranch(Z == 0);
}
auto MOS6502::algorithmBPL() -> void {
algorithmBranch(N == 0);
}
auto MOS6502::algorithmBRK() -> void {
MDR = read(MAR); // dummy implied read
PC++;
push(PCH);
push(PCL);
n16 vector = 0xfffe;
nmi(vector);
push(P | 0x30);
I = 1;
PCL = read(vector++);
cancelNmi();
PCH = read(vector++);
}
auto MOS6502::algorithmBVC() -> void {
algorithmBranch(V == 0);
}
auto MOS6502::algorithmBVS() -> void {
algorithmBranch(V == 1);
}
auto MOS6502::algorithmBranch(bool take) -> void {
if(!take) {
L MDR = read(MAR); // dummy relative read
} else {
bool irq = irqPending();
MDR = read(MAR);
n16 newPC = PC + (i8)MDR;
bool pageCrossed = newPC >> 8 != PC >> 8;
// idle page crossed without carry
if (pageCrossed) {
read(PC & 0xff00 | newPC & 0x00ff);
PC = newPC;
L idle();
} else {
// a taken non-page-crossing branch ignores
// IRQ/NMI during its last clock, so that
// next instruction executes before the IRQ
if (!irq)
delayIrq();
else
lastCycle();
PC = newPC;
// idle page crossed with carry
idle();
}
}
}
auto MOS6502::algorithmCLC() -> void {
C = 0;
}
auto MOS6502::algorithmCLD() -> void {
D = 0;
}
auto MOS6502::algorithmCLI() -> void {
I = 0;
}
auto MOS6502::algorithmCLV() -> void {
V = 0;
}
auto MOS6502::algorithmCMP() -> void {
n9 o = A - MDR;
C = !o.bit(8);
Z = n8(o) == 0;
N = o.bit(7);
}
auto MOS6502::algorithmCPX() -> void {
n9 o = X - MDR;
C = !o.bit(8);
Z = n8(o) == 0;
N = o.bit(7);
}
auto MOS6502::algorithmCPY() -> void {
n9 o = Y - MDR;
C = !o.bit(8);
Z = n8(o) == 0;
N = o.bit(7);
}
auto MOS6502::algorithmDEC() -> void {
MDR--;
Z = MDR == 0;
N = MDR.bit(7);
}
auto MOS6502::algorithmDEX() -> void {
X--;
Z = X == 0;
N = X.bit(7);
}
auto MOS6502::algorithmDEY() -> void {
Y--;
Z = Y == 0;
N = Y.bit(7);
}
auto MOS6502::algorithmEOR() -> void {
A ^= MDR;
Z = A == 0;
N = A.bit(7);
}
auto MOS6502::algorithmINC() -> void {
MDR++;
Z = MDR == 0;
N = MDR.bit(7);
}
auto MOS6502::algorithmINX() -> void {
X++;
Z = X == 0;
N = X.bit(7);
}
auto MOS6502::algorithmINY() -> void {
Y++;
Z = Y == 0;
N = Y.bit(7);
}
auto MOS6502::algorithmJMP() -> void {
PC = MAR;
}
auto MOS6502::algorithmJSR() -> void {
PC--;
push(PCH);
L push(PCL);
PC = MAR;
}
auto MOS6502::algorithmLDA() -> void {
A = MDR;
Z = A == 0;
N = A.bit(7);
}
auto MOS6502::algorithmLDX() -> void {
X = MDR;
Z = X == 0;
N = X.bit(7);
}
auto MOS6502::algorithmLDY() -> void {
Y = MDR;
Z = Y == 0;
N = Y.bit(7);
}
auto MOS6502::algorithmLSRA() -> void {
C = A.bit(0);
A >>= 1;
Z = A == 0;
N = A.bit(7);
}
auto MOS6502::algorithmLSRM() -> void {
C = MDR.bit(0);
MDR >>= 1;
Z = MDR == 0;
N = MDR.bit(7);
}
auto MOS6502::algorithmNOP() -> void {}
auto MOS6502::algorithmORA() -> void {
A |= MDR;
Z = A == 0;
N = A.bit(7);
}
auto MOS6502::algorithmPHA() -> void {
read(MAR); // dummy implied read
L push(A);
}
auto MOS6502::algorithmPHP() -> void {
MDR = read(MAR); // dummy implied read
L push(P | 0x30);
}
auto MOS6502::algorithmPLA() -> void {
MDR = read(MAR); // dummy implied read
MDR = read(0x0100 | S); // dummy stack read
L A = pull();
Z = n8(A) == 0;
N = A.bit(7);
}
auto MOS6502::algorithmPLP() -> void {
MDR = read(MAR); // dummy implied read
MDR = read(0x0100 | S); // dummy stack read
L P = pull();
}
auto MOS6502::algorithmROLA() -> void {
bool c = C;
o = c << 7 | o >> 1;
Z = o == 0;
N = o.bit(7);
C = o.bit(6);
V = o.bit(6) ^ o.bit(5);
return o;
C = A.bit(7);
A = A << 1 | c;
Z = A == 0;
N = A.bit(7);
}
auto MOS6502::algorithmASL(n8 i) -> n8 {
C = i.bit(7);
i <<= 1;
Z = i == 0;
N = i.bit(7);
return i;
}
auto MOS6502::algorithmATX(n8 i) -> n8 {
A |= 0xff; //TODO: OR value may differ on non-NES platforms
n8 o = A & i;
X = o;
Z = o == 0;
N = o.bit(7);
return o;
}
auto MOS6502::algorithmAXS(n8 i) -> n8 {
n9 o = (A & X) - i;
C = !o.bit(8);
Z = n8(o) == 0;
N = o.bit(7);
return o;
}
auto MOS6502::algorithmBIT(n8 i) -> n8 {
Z = (A & i) == 0;
V = i.bit(6);
N = i.bit(7);
return A;
}
auto MOS6502::algorithmCMP(n8 i) -> n8 {
n9 o = A - i;
C = !o.bit(8);
Z = n8(o) == 0;
N = o.bit(7);
return A;
}
auto MOS6502::algorithmCPX(n8 i) -> n8 {
n9 o = X - i;
C = !o.bit(8);
Z = n8(o) == 0;
N = o.bit(7);
return X;
}
auto MOS6502::algorithmCPY(n8 i) -> n8 {
n9 o = Y - i;
C = !o.bit(8);
Z = n8(o) == 0;
N = o.bit(7);
return Y;
}
auto MOS6502::algorithmDEC(n8 i) -> n8 {
i--;
Z = i == 0;
N = i.bit(7);
return i;
}
auto MOS6502::algorithmDCP(n8 i) -> n8 {
auto value = algorithmDEC(i);
A = algorithmCMP(value);
return value;
}
auto MOS6502::algorithmEOR(n8 i) -> n8 {
n8 o = A ^ i;
Z = o == 0;
N = o.bit(7);
return o;
}
auto MOS6502::algorithmINC(n8 i) -> n8 {
i++;
Z = i == 0;
N = i.bit(7);
return i;
}
auto MOS6502::algorithmISC(n8 i) -> n8 {
auto value = algorithmINC(i);
A = algorithmSBC(value);
return value;
}
auto MOS6502::algorithmLD(n8 i) -> n8 {
Z = i == 0;
N = i.bit(7);
return i;
}
auto MOS6502::algorithmLSR(n8 i) -> n8 {
C = i.bit(0);
i >>= 1;
Z = i == 0;
N = i.bit(7);
return i;
}
auto MOS6502::algorithmSRE(n8 i) -> n8 {
auto value = algorithmLSR(i);
A = algorithmEOR(value);
return value;
}
auto MOS6502::algorithmORA(n8 i) -> n8 {
n8 o = A | i;
Z = o == 0;
N = o.bit(7);
return o;
}
auto MOS6502::algorithmROL(n8 i) -> n8 {
auto MOS6502::algorithmROLM() -> void {
bool c = C;
C = i.bit(7);
i = i << 1 | c;
Z = i == 0;
N = i.bit(7);
return i;
C = MDR.bit(7);
MDR = MDR << 1 | c;
Z = MDR == 0;
N = MDR.bit(7);
}
auto MOS6502::algorithmRLA(n8 i) -> n8 {
auto value = algorithmROL(i);
A = algorithmAND(value);
return value;
}
auto MOS6502::algorithmROR(n8 i) -> n8 {
auto MOS6502::algorithmRORA() -> void {
bool c = C;
C = i.bit(0);
i = c << 7 | i >> 1;
Z = i == 0;
N = i.bit(7);
return i;
C = A.bit(0);
A = A >> 1 | c << 7;
Z = A == 0;
N = A.bit(7);
}
auto MOS6502::algorithmRRA(n8 i) -> n8 {
auto value = algorithmROR(i);
A = algorithmADC(value);
return value;
auto MOS6502::algorithmRORM() -> void {
bool c = C;
C = MDR.bit(0);
MDR = MDR >> 1 | c << 7;
Z = MDR == 0;
N = MDR.bit(7);
}
auto MOS6502::algorithmSBC(n8 i) -> n8 {
i = ~i;
auto MOS6502::algorithmRTI() -> void {
MDR = read(MAR); // dummy implied read
MDR = read(0x0100 | S); // dummy stack read
P = pull();
PCL = pull();
L PCH = pull();
}
auto MOS6502::algorithmRTS() -> void {
MDR = read(MAR); // dummy implied read
MDR = read(0x0100 | S); // dummy stack read
PCL = pull();
PCH = pull();
L idle();
PC++;
}
auto MOS6502::algorithmSBC() -> void {
n8 i = ~MDR;
i16 o = A + i + C;
if(!BCD || !D) {
C = o.bit(8);
@@ -226,11 +349,215 @@ auto MOS6502::algorithmSBC(n8 i) -> n8 {
if(o <= 0xff) o -= 0x60;
C = o > 0xff;
}
return o;
A = o;
}
auto MOS6502::algorithmSLO(n8 i) -> n8 {
auto value = algorithmASL(i);
A = algorithmORA(value);
return value;
}
auto MOS6502::algorithmSEC() -> void {
C = 1;
}
auto MOS6502::algorithmSED() -> void {
D = 1;
}
auto MOS6502::algorithmSEI() -> void {
I = 1;
}
auto MOS6502::algorithmSTA() -> void {
MDR = A;
}
auto MOS6502::algorithmSTX() -> void {
MDR = X;
}
auto MOS6502::algorithmSTY() -> void {
MDR = Y;
}
auto MOS6502::algorithmTAX() -> void {
X = A;
Z = X == 0;
N = X.bit(7);
}
auto MOS6502::algorithmTAY() -> void {
Y = A;
Z = Y == 0;
N = Y.bit(7);
}
auto MOS6502::algorithmTSX() -> void {
X = S;
Z = X == 0;
N = X.bit(7);
}
auto MOS6502::algorithmTXA() -> void {
A = X;
Z = A == 0;
N = A.bit(7);
}
auto MOS6502::algorithmTXS() -> void {
S = X;
}
auto MOS6502::algorithmTYA() -> void {
A = Y;
Z = A == 0;
N = A.bit(7);
}
// unofficial algorithm
auto MOS6502::algorithmAAC() -> void {
A &= MDR;
C = A.bit(7);
Z = A == 0;
N = A.bit(7);
}
auto MOS6502::algorithmAAX() -> void {
MDR = A & X;
}
// Highly unstable, do not use.
// A base value in A is determined based on the
// contets of A and a constant, which may be
// typically $00, $ff, $ee, etc. The value of
// this constant depends on temerature, the chip
// series, and maybe other factors, as well.
// In order to eliminate these uncertaincies
// from the equation, use either 0 as the operand
// or a value of $FF in the accumulator.
auto MOS6502::algorithmANE() -> void {
A = (A | 0xff) & X & MDR;
Z = A == 0;
N = A.bit(7);
}
// This operation involves the adder:
// V-flag is set according to (A AND oper) + oper
// The carry is not set, but bit 7 (sign)
// is exchanged with the carry
auto MOS6502::algorithmARR() -> void {
A = ((A & MDR) >> 1) | (C << 7);
C = A.bit(6);
Z = A == 0;
N = A.bit(7);
V = C ^ A.bit(5);
}
auto MOS6502::algorithmASR() -> void {
A &= MDR;
C = A.bit(0);
A >>= 1;
Z = A == 0;
N = A.bit(7);
}
// Highly unstable, involves a 'magic' constant, see ANE
auto MOS6502::algorithmATX() -> void {
X = A = (A | 0xff) & MDR;
Z = A == 0;
N = A.bit(7);
}
auto MOS6502::algorithmAXS() -> void {
X &= A;
n9 o = X - MDR;
C = !o.bit(8);
X = o;
Z = X == 0;
N = X.bit(7);
}
auto MOS6502::algorithmDCP() -> void {
MDR--;
algorithmCMP();
}
auto MOS6502::algorithmISC() -> void {
MDR++;
algorithmSBC();
}
auto MOS6502::algorithmLAS() -> void {
S = A = X = MDR & S;
Z = A == 0;
N = A.bit(7);
}
auto MOS6502::algorithmLAX() -> void {
A = X = MDR;
Z = A == 0;
N = A.bit(7);
}
auto MOS6502::algorithmRLA() -> void {
bool c = C;
C = MDR.bit(7);
MDR = MDR << 1 | c;
A &= MDR;
Z = A == 0;
N = A.bit(7);
}
auto MOS6502::algorithmRRA() -> void {
bool c = C;
C = MDR.bit(0);
MDR = MDR >> 1 | c << 7;
algorithmADC();
}
auto MOS6502::algorithmSLO() -> void {
C = MDR.bit(7);
MDR <<= 1;
A |= MDR;
Z = A == 0;
N = A.bit(7);
}
auto MOS6502::algorithmSRE() -> void {
C = MDR.bit(0);
MDR >>= 1;
A ^= MDR;
Z = A == 0;
N = A.bit(7);
}
// unstable: sometimes 'AND (H+1)' is dropped,
// page boundary crossings may not work (with
// the high-byte of the value used as the
// high-byte of the address)
auto MOS6502::algorithmSXA() -> void {
MAR = ((X & ((MAR >> 8) + 1)) << 8) | (MAR & 0xff);
MDR = MAR >> 8;
}
// unstable: sometimes 'AND (H+1)' is dropped,
// page boundary crossings may not work (with
// the high-byte of the value used as the
// high-byte of the address)
auto MOS6502::algorithmSYA() -> void {
MAR = ((Y & ((MAR >> 8) + 1)) << 8) | (MAR & 0xff);
MDR = MAR >> 8;
}
// unstable: sometimes 'AND (H+1)' is dropped,
// page boundary crossings may not work (with
// the high-byte of the value used as the
// high-byte of the address)
auto MOS6502::algorithmTAS() -> void {
S = A & X;
MDR = A & X & (((MAR - Y) >> 8) + 1);
}
// These instructions freeze the CPU.
// The processor will be trapped infinitely
// in T1 phase with $FF on the data bus.
// Reset required.
auto MOS6502::algorithmJAM() -> void {
PC--;
}
+273 -223
View File
@@ -1,5 +1,6 @@
#define op(id, name, ...) case id: return instruction##name(__VA_ARGS__);
#define fp(name) &MOS6502::algorithm##name
#define addr(name) &MOS6502::address##name
auto MOS6502::interrupt() -> void {
idle();
@@ -14,233 +15,282 @@ auto MOS6502::interrupt() -> void {
L PCH = read(vector++);
}
auto MOS6502::reset() -> void {
idle();
idle();
read(0x0100 | S--); // Dummy push (PCH)
read(0x0100 | S--); // Dummy push (PCL)
n16 vector = 0xfffc;
read(0x0100 | S--); // Dummy push (P)
I = 1;
PCL = read(vector++);
L PCH = read(vector++);
resetting = 0;
}
auto MOS6502::instruction() -> void {
auto code = opcode();
if(resetting) reset();
switch(code) {
op(0x00, Break)
op(0x01, IndirectXRead, fp(ORA), A)
op(0x04, NoOperationZeroPage)
op(0x05, ZeroPageRead, fp(ORA), A)
op(0x06, ZeroPageModify, fp(ASL))
op(0x07, ZeroPageModify, fp(SLO))
op(0x08, PushP)
op(0x09, Immediate, fp(ORA), A)
op(0x0a, Implied, fp(ASL), A)
op(0x0b, Immediate, fp(ANC), A)
op(0x0c, NoOperationAbsolute)
op(0x0d, AbsoluteRead, fp(ORA), A)
op(0x0e, AbsoluteModify, fp(ASL))
op(0x0f, AbsoluteModify, fp(SLO))
op(0x10, Branch, N == 0)
op(0x11, IndirectYRead, fp(ORA), A)
op(0x14, NoOperationZeroPage, X)
op(0x15, ZeroPageRead, fp(ORA), A, X)
op(0x16, ZeroPageModify, fp(ASL), X)
op(0x17, ZeroPageModify, fp(SLO), X)
op(0x18, Clear, C)
op(0x19, AbsoluteRead, fp(ORA), A, Y)
op(0x1a, NoOperation)
op(0x1b, AbsoluteModify, fp(SLO), Y)
op(0x1c, NoOperationAbsolute, X)
op(0x1d, AbsoluteRead, fp(ORA), A, X)
op(0x1e, AbsoluteModify, fp(ASL), X)
op(0x1f, AbsoluteModify, fp(SLO), X)
op(0x20, CallAbsolute)
op(0x21, IndirectXRead, fp(AND), A)
op(0x24, ZeroPageRead, fp(BIT), A)
op(0x25, ZeroPageRead, fp(AND), A)
op(0x26, ZeroPageModify, fp(ROL))
op(0x27, ZeroPageModify, fp(RLA))
op(0x28, PullP)
op(0x29, Immediate, fp(AND), A)
op(0x2a, Implied, fp(ROL), A)
op(0x2b, Immediate, fp(ANC), A)
op(0x2c, AbsoluteRead, fp(BIT), A)
op(0x2d, AbsoluteRead, fp(AND), A)
op(0x2e, AbsoluteModify, fp(ROL))
op(0x2f, AbsoluteModify, fp(RLA))
op(0x30, Branch, N == 1)
op(0x31, IndirectYRead, fp(AND), A)
op(0x34, NoOperationZeroPage, X)
op(0x35, ZeroPageRead, fp(AND), A, X)
op(0x36, ZeroPageModify, fp(ROL), X)
op(0x37, ZeroPageModify, fp(RLA), X)
op(0x38, Set, C)
op(0x39, AbsoluteRead, fp(AND), A, Y)
op(0x3a, NoOperation)
op(0x3b, AbsoluteModify, fp(RLA), Y)
op(0x3c, NoOperationAbsolute, X)
op(0x3d, AbsoluteRead, fp(AND), A, X)
op(0x3e, AbsoluteModify, fp(ROL), X)
op(0x3f, AbsoluteModify, fp(RLA), X)
op(0x40, ReturnInterrupt)
op(0x41, IndirectXRead, fp(EOR), A)
op(0x43, IndirectXRead, fp(SRE), X)
op(0x44, NoOperationZeroPage)
op(0x45, ZeroPageRead, fp(EOR), A)
op(0x46, ZeroPageModify, fp(LSR))
op(0x47, ZeroPageModify, fp(SRE))
op(0x48, Push, A)
op(0x49, Immediate, fp(EOR), A)
op(0x4a, Implied, fp(LSR), A)
op(0x4b, Immediate, fp(ALR), A)
op(0x4c, JumpAbsolute)
op(0x4d, AbsoluteRead, fp(EOR), A)
op(0x4e, AbsoluteModify, fp(LSR))
op(0x4f, AbsoluteModify, fp(SRE))
op(0x50, Branch, V == 0)
op(0x51, IndirectYRead, fp(EOR), A)
op(0x54, NoOperationZeroPage, X)
op(0x55, ZeroPageRead, fp(EOR), A, X)
op(0x56, ZeroPageModify, fp(LSR), X)
op(0x57, ZeroPageModify, fp(SRE), X)
op(0x58, Clear, I)
op(0x59, AbsoluteRead, fp(EOR), A, Y)
op(0x5a, NoOperation)
op(0x5b, AbsoluteModify, fp(SRE), Y)
op(0x5c, NoOperationAbsolute, X)
op(0x5d, AbsoluteRead, fp(EOR), A, X)
op(0x5e, AbsoluteModify, fp(LSR), X)
op(0x5f, AbsoluteModify, fp(SRE), X)
op(0x60, ReturnSubroutine)
op(0x61, IndirectXRead, fp(ADC), A)
op(0x64, NoOperationZeroPage)
op(0x65, ZeroPageRead, fp(ADC), A)
op(0x66, ZeroPageModify, fp(ROR))
op(0x67, ZeroPageModify, fp(RRA))
op(0x68, Pull, A)
op(0x69, Immediate, fp(ADC), A)
op(0x6a, Implied, fp(ROR), A)
op(0x6b, Immediate, fp(ARR), A)
op(0x6c, JumpIndirect)
op(0x6d, AbsoluteRead, fp(ADC), A)
op(0x6e, AbsoluteModify, fp(ROR))
op(0x6f, AbsoluteModify, fp(RRA))
op(0x70, Branch, V == 1)
op(0x71, IndirectYRead, fp(ADC), A)
op(0x74, NoOperationZeroPage, X)
op(0x75, ZeroPageRead, fp(ADC), A, X)
op(0x76, ZeroPageModify, fp(ROR), X)
op(0x77, ZeroPageModify, fp(RRA), X)
op(0x78, Set, I)
op(0x79, AbsoluteRead, fp(ADC), A, Y)
op(0x7a, NoOperation)
op(0x7b, AbsoluteModify, fp(RRA), Y)
op(0x7c, NoOperationAbsolute, X)
op(0x7d, AbsoluteRead, fp(ADC), A, X)
op(0x7e, AbsoluteModify, fp(ROR), X)
op(0x7f, AbsoluteModify, fp(RRA), X)
op(0x80, NoOperationImmediate)
op(0x81, IndirectXWrite, A)
op(0x82, NoOperationImmediate)
op(0x84, ZeroPageWrite, Y)
op(0x85, ZeroPageWrite, A)
op(0x86, ZeroPageWrite, X)
op(0x88, Implied, fp(DEC), Y)
op(0x89, NoOperationImmediate)
op(0x8a, Transfer, X, A, 1)
op(0x8c, AbsoluteWrite, Y)
op(0x8d, AbsoluteWrite, A)
op(0x8e, AbsoluteWrite, X)
op(0x90, Branch, C == 0)
op(0x91, IndirectYWrite, A)
op(0x94, ZeroPageWrite, Y, X)
op(0x95, ZeroPageWrite, A, X)
op(0x96, ZeroPageWrite, X, Y)
op(0x98, Transfer, Y, A, 1)
op(0x99, AbsoluteWrite, A, Y)
op(0x9a, Transfer, X, S, 0)
op(0x9d, AbsoluteWrite, A, X)
op(0xa0, Immediate, fp(LD), Y)
op(0xa1, IndirectXRead, fp(LD), A)
op(0xa2, Immediate, fp(LD), X)
op(0xa4, ZeroPageRead, fp(LD), Y)
op(0xa5, ZeroPageRead, fp(LD), A)
op(0xa6, ZeroPageRead, fp(LD), X)
op(0xa8, Transfer, A, Y, 1)
op(0xa9, Immediate, fp(LD), A)
op(0xaa, Transfer, A, X, 1)
op(0xab, Immediate, fp(ATX), A)
op(0xac, AbsoluteRead, fp(LD), Y)
op(0xad, AbsoluteRead, fp(LD), A)
op(0xae, AbsoluteRead, fp(LD), X)
op(0xb0, Branch, C == 1)
op(0xb1, IndirectYRead, fp(LD), A)
op(0xb3, IndirectYRead, fp(LD), A, X)
op(0xb4, ZeroPageRead, fp(LD), Y, X)
op(0xb5, ZeroPageRead, fp(LD), A, X)
op(0xb6, ZeroPageRead, fp(LD), X, Y)
op(0xb8, Clear, V)
op(0xb9, AbsoluteRead, fp(LD), A, Y)
op(0xba, Transfer, S, X, 1)
op(0xbc, AbsoluteRead, fp(LD), Y, X)
op(0xbd, AbsoluteRead, fp(LD), A, X)
op(0xbe, AbsoluteRead, fp(LD), X, Y)
op(0xc0, Immediate, fp(CPY), Y)
op(0xc1, IndirectXRead, fp(CMP), A)
op(0xc2, NoOperationImmediate)
op(0xc4, ZeroPageRead, fp(CPY), Y)
op(0xc5, ZeroPageRead, fp(CMP), A)
op(0xc6, ZeroPageModify, fp(DEC))
op(0xc7, ZeroPageModify, fp(DCP))
op(0xc8, Implied, fp(INC), Y)
op(0xc9, Immediate, fp(CMP), A)
op(0xca, Implied, fp(DEC), X)
op(0xcb, Immediate, fp(AXS), X)
op(0xcc, AbsoluteRead, fp(CPY), Y)
op(0xcd, AbsoluteRead, fp(CMP), A)
op(0xce, AbsoluteModify, fp(DEC))
op(0xcf, AbsoluteModify, fp(DCP))
op(0xd0, Branch, Z == 0)
op(0xd1, IndirectYRead, fp(CMP), A)
op(0xd4, NoOperationZeroPage, X)
op(0xd5, ZeroPageRead, fp(CMP), A, X)
op(0xd6, ZeroPageModify, fp(DEC), X)
op(0xd7, ZeroPageModify, fp(DCP), X)
op(0xd8, Clear, D)
op(0xd9, AbsoluteRead, fp(CMP), A, Y)
op(0xda, NoOperation)
op(0xdb, AbsoluteModify, fp(DCP), Y)
op(0xdc, NoOperationAbsolute, X)
op(0xdd, AbsoluteRead, fp(CMP), A, X)
op(0xde, AbsoluteModify, fp(DEC), X)
op(0xdf, AbsoluteModify, fp(DCP), X)
op(0xe0, Immediate, fp(CPX), X)
op(0xe1, IndirectXRead, fp(SBC), A)
op(0xe2, NoOperationImmediate)
op(0xe4, ZeroPageRead, fp(CPX), X)
op(0xe5, ZeroPageRead, fp(SBC), A)
op(0xe6, ZeroPageModify, fp(INC))
op(0xe7, ZeroPageModify, fp(ISC))
op(0xe8, Implied, fp(INC), X)
op(0xe9, Immediate, fp(SBC), A)
op(0xea, NoOperation)
op(0xeb, Immediate, fp(SBC), A)
op(0xec, AbsoluteRead, fp(CPX), X)
op(0xed, AbsoluteRead, fp(SBC), A)
op(0xee, AbsoluteModify, fp(INC))
op(0xef, AbsoluteModify, fp(ISC))
op(0xf0, Branch, Z == 1)
op(0xf1, IndirectYRead, fp(SBC), A)
op(0xf4, NoOperationZeroPage, X)
op(0xf5, ZeroPageRead, fp(SBC), A, X)
op(0xf6, ZeroPageModify, fp(INC), X)
op(0xf7, ZeroPageModify, fp(ISC), X)
op(0xf8, Set, D)
op(0xf9, AbsoluteRead, fp(SBC), A, Y)
op(0xfa, NoOperation)
op(0xfb, AbsoluteModify, fp(ISC), Y)
op(0xfc, NoOperationAbsolute, X)
op(0xfd, AbsoluteRead, fp(SBC), A, X)
op(0xfe, AbsoluteModify, fp(INC), X)
op(0xff, AbsoluteModify, fp(ISC), X)
switch(opcode()) {
op(0x00, None, addr(Implied), fp(BRK))
op(0x01, Load, addr(IndirectX), fp(ORA))
op(0x02, None, addr(Implied), fp(JAM))
op(0x03, Modify, addr(IndirectX), fp(SLO))
op(0x04, Load, addr(ZeroPage), fp(NOP))
op(0x05, Load, addr(ZeroPage), fp(ORA))
op(0x06, Modify, addr(ZeroPage), fp(ASLM))
op(0x07, Modify, addr(ZeroPage), fp(SLO))
op(0x08, None, addr(Implied), fp(PHP))
op(0x09, Load, addr(Immediate), fp(ORA))
op(0x0a, Load, addr(Accumulator), fp(ASLA))
op(0x0b, Load, addr(Immediate), fp(AAC))
op(0x0c, Load, addr(Absolute), fp(NOP))
op(0x0d, Load, addr(Absolute), fp(ORA))
op(0x0e, Modify, addr(Absolute), fp(ASLM))
op(0x0f, Modify, addr(Absolute), fp(SLO))
op(0x10, None, addr(Relative), fp(BPL))
op(0x11, Load, addr(IndirectYRead), fp(ORA))
op(0x12, None, addr(Implied), fp(JAM))
op(0x13, Modify, addr(IndirectYWrite), fp(SLO))
op(0x14, Load, addr(ZeroPageX), fp(NOP))
op(0x15, Load, addr(ZeroPageX), fp(ORA))
op(0x16, Modify, addr(ZeroPageX), fp(ASLM))
op(0x17, Modify, addr(ZeroPageX), fp(SLO))
op(0x18, Load, addr(Implied), fp(CLC))
op(0x19, Load, addr(AbsoluteYRead), fp(ORA))
op(0x1a, Load, addr(Implied), fp(NOP))
op(0x1b, Modify, addr(AbsoluteYWrite), fp(SLO))
op(0x1c, Load, addr(AbsoluteXRead), fp(NOP))
op(0x1d, Load, addr(AbsoluteXRead), fp(ORA))
op(0x1e, Modify, addr(AbsoluteXWrite), fp(ASLM))
op(0x1f, Modify, addr(AbsoluteXWrite), fp(SLO))
op(0x20, Load, addr(Absolute), fp(JSR))
op(0x21, Load, addr(IndirectX), fp(AND))
op(0x22, None, addr(Implied), fp(JAM))
op(0x23, Modify, addr(IndirectX), fp(RLA))
op(0x24, Load, addr(ZeroPage), fp(BIT))
op(0x25, Load, addr(ZeroPage), fp(AND))
op(0x26, Modify, addr(ZeroPage), fp(ROLM))
op(0x27, Modify, addr(ZeroPage), fp(RLA))
op(0x28, None, addr(Implied), fp(PLP))
op(0x29, Load, addr(Immediate), fp(AND))
op(0x2a, Load, addr(Implied), fp(ROLA))
op(0x2b, Load, addr(Immediate), fp(AAC))
op(0x2c, Load, addr(Absolute), fp(BIT))
op(0x2d, Load, addr(Absolute), fp(AND))
op(0x2e, Modify, addr(Absolute), fp(ROLM))
op(0x2f, Modify, addr(Absolute), fp(RLA))
op(0x30, None, addr(Relative), fp(BMI))
op(0x31, Load, addr(IndirectYRead), fp(AND))
op(0x32, None, addr(Implied), fp(JAM))
op(0x33, Modify, addr(IndirectYWrite), fp(RLA))
op(0x34, Load, addr(ZeroPageX), fp(NOP))
op(0x35, Load, addr(ZeroPageX), fp(AND))
op(0x36, Modify, addr(ZeroPageX), fp(ROLM))
op(0x37, Modify, addr(ZeroPageX), fp(RLA))
op(0x38, Load, addr(Implied), fp(SEC))
op(0x39, Load, addr(AbsoluteYRead), fp(AND))
op(0x3a, Load, addr(Implied), fp(NOP))
op(0x3b, Modify, addr(AbsoluteYWrite), fp(RLA))
op(0x3c, Load, addr(AbsoluteXRead), fp(NOP))
op(0x3d, Load, addr(AbsoluteXRead), fp(AND))
op(0x3e, Modify, addr(AbsoluteXWrite), fp(ROLM))
op(0x3f, Modify, addr(AbsoluteXWrite), fp(RLA))
op(0x40, None, addr(Implied), fp(RTI))
op(0x41, Load, addr(IndirectX), fp(EOR))
op(0x42, None, addr(Implied), fp(JAM))
op(0x43, Modify, addr(IndirectX), fp(SRE))
op(0x44, Load, addr(ZeroPage), fp(NOP))
op(0x45, Load, addr(ZeroPage), fp(EOR))
op(0x46, Modify, addr(ZeroPage), fp(LSRM))
op(0x47, Modify, addr(ZeroPage), fp(SRE))
op(0x48, None, addr(Implied), fp(PHA))
op(0x49, Load, addr(Immediate), fp(EOR))
op(0x4a, Load, addr(Implied), fp(LSRA))
op(0x4b, Load, addr(Immediate), fp(ASR))
op(0x4c, None, addr(AbsoluteJMP), fp(JMP))
op(0x4d, Load, addr(Absolute), fp(EOR))
op(0x4e, Modify, addr(Absolute), fp(LSRM))
op(0x4f, Modify, addr(Absolute), fp(SRE))
op(0x50, None, addr(Relative), fp(BVC))
op(0x51, Load, addr(IndirectYRead), fp(EOR))
op(0x52, None, addr(Implied), fp(JAM))
op(0x53, Modify, addr(IndirectYWrite), fp(SRE))
op(0x54, Load, addr(ZeroPageX), fp(NOP))
op(0x55, Load, addr(ZeroPageX), fp(EOR))
op(0x56, Modify, addr(ZeroPageX), fp(LSRM))
op(0x57, Modify, addr(ZeroPageX), fp(SRE))
op(0x58, Load, addr(Implied), fp(CLI))
op(0x59, Load, addr(AbsoluteYRead), fp(EOR))
op(0x5a, Load, addr(Implied), fp(NOP))
op(0x5b, Modify, addr(AbsoluteYWrite), fp(SRE))
op(0x5c, Load, addr(AbsoluteXRead), fp(NOP))
op(0x5d, Load, addr(AbsoluteXRead), fp(EOR))
op(0x5e, Modify, addr(AbsoluteXWrite), fp(LSRM))
op(0x5f, Modify, addr(AbsoluteXWrite), fp(SRE))
op(0x60, None, addr(Implied), fp(RTS))
op(0x61, Load, addr(IndirectX), fp(ADC))
op(0x62, None, addr(Implied), fp(JAM))
op(0x63, Modify, addr(IndirectX), fp(RRA))
op(0x64, Load, addr(ZeroPage), fp(NOP))
op(0x65, Load, addr(ZeroPage), fp(ADC))
op(0x66, Modify, addr(ZeroPage), fp(RORM))
op(0x67, Modify, addr(ZeroPage), fp(RRA))
op(0x68, None, addr(Implied), fp(PLA))
op(0x69, Load, addr(Immediate), fp(ADC))
op(0x6a, Load, addr(Implied), fp(RORA))
op(0x6b, Load, addr(Immediate), fp(ARR))
op(0x6c, None, addr(Indirect), fp(JMP))
op(0x6d, Load, addr(Absolute), fp(ADC))
op(0x6e, Modify, addr(Absolute), fp(RORM))
op(0x6f, Modify, addr(Absolute), fp(RRA))
op(0x70, None, addr(Relative), fp(BVS))
op(0x71, Load, addr(IndirectYRead), fp(ADC))
op(0x72, None, addr(Implied), fp(JAM))
op(0x73, Modify, addr(IndirectYWrite), fp(RRA))
op(0x74, Load, addr(ZeroPageX), fp(NOP))
op(0x75, Load, addr(ZeroPageX), fp(ADC))
op(0x76, Modify, addr(ZeroPageX), fp(RORM))
op(0x77, Modify, addr(ZeroPageX), fp(RRA))
op(0x78, Load, addr(Implied), fp(SEI))
op(0x79, Load, addr(AbsoluteYRead), fp(ADC))
op(0x7a, Load, addr(Implied), fp(NOP))
op(0x7b, Modify, addr(AbsoluteYWrite), fp(RRA))
op(0x7c, Load, addr(AbsoluteXRead), fp(NOP))
op(0x7d, Load, addr(AbsoluteXRead), fp(ADC))
op(0x7e, Modify, addr(AbsoluteXWrite), fp(RORM))
op(0x7f, Modify, addr(AbsoluteXWrite), fp(RRA))
op(0x80, Load, addr(Immediate), fp(NOP))
op(0x81, Store, addr(IndirectX), fp(STA))
op(0x82, Load, addr(Immediate), fp(NOP))
op(0x83, Store, addr(IndirectX), fp(AAX))
op(0x84, Store, addr(ZeroPage), fp(STY))
op(0x85, Store, addr(ZeroPage), fp(STA))
op(0x86, Store, addr(ZeroPage), fp(STX))
op(0x87, Store, addr(ZeroPage), fp(AAX))
op(0x88, Load, addr(Implied), fp(DEY))
op(0x89, Load, addr(Immediate), fp(NOP))
op(0x8a, Load, addr(Implied), fp(TXA))
op(0x8b, Load, addr(Immediate), fp(ANE))
op(0x8c, Store, addr(Absolute), fp(STY))
op(0x8d, Store, addr(Absolute), fp(STA))
op(0x8e, Store, addr(Absolute), fp(STX))
op(0x8f, Store, addr(Absolute), fp(AAX))
op(0x90, None, addr(Relative), fp(BCC))
op(0x91, Store, addr(IndirectYWrite), fp(STA))
op(0x92, None, addr(Implied), fp(JAM))
op(0x93, Store, addr(IndirectYWrite), fp(AAX))
op(0x94, Store, addr(ZeroPageX), fp(STY))
op(0x95, Store, addr(ZeroPageX), fp(STA))
op(0x96, Store, addr(ZeroPageY), fp(STX))
op(0x97, Store, addr(ZeroPageY), fp(AAX))
op(0x98, Load, addr(Implied), fp(TYA))
op(0x99, Store, addr(AbsoluteYWrite), fp(STA))
op(0x9a, Load, addr(Implied), fp(TXS))
op(0x9b, Store, addr(AbsoluteYWrite), fp(TAS))
op(0x9c, Store, addr(AbsoluteXWrite), fp(SYA))
op(0x9d, Store, addr(AbsoluteXWrite), fp(STA))
op(0x9e, Store, addr(AbsoluteYWrite), fp(SXA))
op(0x9f, Store, addr(AbsoluteYWrite), fp(AAX))
op(0xa0, Load, addr(Immediate), fp(LDY))
op(0xa1, Load, addr(IndirectX), fp(LDA))
op(0xa2, Load, addr(Immediate), fp(LDX))
op(0xa3, Load, addr(IndirectX), fp(LAX))
op(0xa4, Load, addr(ZeroPage), fp(LDY))
op(0xa5, Load, addr(ZeroPage), fp(LDA))
op(0xa6, Load, addr(ZeroPage), fp(LDX))
op(0xa7, Load, addr(ZeroPage), fp(LAX))
op(0xa8, Load, addr(Implied), fp(TAY))
op(0xa9, Load, addr(Immediate), fp(LDA))
op(0xaa, Load, addr(Implied), fp(TAX))
op(0xab, Load, addr(Immediate), fp(ATX))
op(0xac, Load, addr(Absolute), fp(LDY))
op(0xad, Load, addr(Absolute), fp(LDA))
op(0xae, Load, addr(Absolute), fp(LDX))
op(0xaf, Load, addr(Absolute), fp(LAX))
op(0xb0, None, addr(Relative), fp(BCS))
op(0xb1, Load, addr(IndirectYRead), fp(LDA))
op(0xb2, None, addr(Implied), fp(JAM))
op(0xb3, Load, addr(IndirectYRead), fp(LAX))
op(0xb4, Load, addr(ZeroPageX), fp(LDY))
op(0xb5, Load, addr(ZeroPageX), fp(LDA))
op(0xb6, Load, addr(ZeroPageY), fp(LDX))
op(0xb7, Load, addr(ZeroPageY), fp(LAX))
op(0xb8, Load, addr(Implied), fp(CLV))
op(0xb9, Load, addr(AbsoluteYRead), fp(LDA))
op(0xba, Load, addr(Implied), fp(TSX))
op(0xbb, Load, addr(AbsoluteYRead), fp(LAS))
op(0xbc, Load, addr(AbsoluteXRead), fp(LDY))
op(0xbd, Load, addr(AbsoluteXRead), fp(LDA))
op(0xbe, Load, addr(AbsoluteYRead), fp(LDX))
op(0xbf, Load, addr(AbsoluteYRead), fp(LAX))
op(0xc0, Load, addr(Immediate), fp(CPY))
op(0xc1, Load, addr(IndirectX), fp(CMP))
op(0xc2, Load, addr(Immediate), fp(NOP))
op(0xc3, Modify, addr(IndirectX), fp(DCP))
op(0xc4, Load, addr(ZeroPage), fp(CPY))
op(0xc5, Load, addr(ZeroPage), fp(CMP))
op(0xc6, Modify, addr(ZeroPage), fp(DEC))
op(0xc7, Modify, addr(ZeroPage), fp(DCP))
op(0xc8, Load, addr(Implied), fp(INY))
op(0xc9, Load, addr(Immediate), fp(CMP))
op(0xca, Load, addr(Implied), fp(DEX))
op(0xcb, Load, addr(Immediate), fp(AXS))
op(0xcc, Load, addr(Absolute), fp(CPY))
op(0xcd, Load, addr(Absolute), fp(CMP))
op(0xce, Modify, addr(Absolute), fp(DEC))
op(0xcf, Modify, addr(Absolute), fp(DCP))
op(0xd0, None, addr(Relative), fp(BNE))
op(0xd1, Load, addr(IndirectYRead), fp(CMP))
op(0xd2, None, addr(Implied), fp(JAM))
op(0xd3, Modify, addr(IndirectYWrite), fp(DCP))
op(0xd4, Load, addr(ZeroPageX), fp(NOP))
op(0xd5, Load, addr(ZeroPageX), fp(CMP))
op(0xd6, Modify, addr(ZeroPageX), fp(DEC))
op(0xd7, Modify, addr(ZeroPageX), fp(DCP))
op(0xd8, Load, addr(Implied), fp(CLD))
op(0xd9, Load, addr(AbsoluteYRead), fp(CMP))
op(0xda, Load, addr(Implied), fp(NOP))
op(0xdb, Modify, addr(AbsoluteYWrite), fp(DCP))
op(0xdc, Load, addr(AbsoluteXRead), fp(NOP))
op(0xdd, Load, addr(AbsoluteXRead), fp(CMP))
op(0xde, Modify, addr(AbsoluteXWrite), fp(DEC))
op(0xdf, Modify, addr(AbsoluteXWrite), fp(DCP))
op(0xe0, Load, addr(Immediate), fp(CPX))
op(0xe1, Load, addr(IndirectX), fp(SBC))
op(0xe2, Load, addr(Immediate), fp(NOP))
op(0xe3, Modify, addr(IndirectX), fp(ISC))
op(0xe4, Load, addr(ZeroPage), fp(CPX))
op(0xe5, Load, addr(ZeroPage), fp(SBC))
op(0xe6, Modify, addr(ZeroPage), fp(INC))
op(0xe7, Modify, addr(ZeroPage), fp(ISC))
op(0xe8, Load, addr(Implied), fp(INX))
op(0xe9, Load, addr(Immediate), fp(SBC))
op(0xea, Load, addr(Implied), fp(NOP))
op(0xeb, Load, addr(Immediate), fp(SBC))
op(0xec, Load, addr(Absolute), fp(CPX))
op(0xed, Load, addr(Absolute), fp(SBC))
op(0xee, Modify, addr(Absolute), fp(INC))
op(0xef, Modify, addr(Absolute), fp(ISC))
op(0xf0, None, addr(Relative), fp(BEQ))
op(0xf1, Load, addr(IndirectYRead), fp(SBC))
op(0xf2, None, addr(Implied), fp(JAM))
op(0xf3, Modify, addr(IndirectYWrite), fp(ISC))
op(0xf4, Load, addr(ZeroPageX), fp(NOP))
op(0xf5, Load, addr(ZeroPageX), fp(SBC))
op(0xf6, Modify, addr(ZeroPageX), fp(INC))
op(0xf7, Modify, addr(ZeroPageX), fp(ISC))
op(0xf8, Load, addr(Implied), fp(SED))
op(0xf9, Load, addr(AbsoluteYRead), fp(SBC))
op(0xfa, Load, addr(Implied), fp(NOP))
op(0xfb, Modify, addr(AbsoluteYWrite), fp(ISC))
op(0xfc, Load, addr(AbsoluteXRead), fp(NOP))
op(0xfd, Load, addr(AbsoluteXRead), fp(SBC))
op(0xfe, Modify, addr(AbsoluteXWrite), fp(INC))
op(0xff, Modify, addr(AbsoluteXWrite), fp(ISC))
}
//unimplemented instruction
debug(unusual, "[6502] unimplemented opcode ", hex(code));
return instructionNoOperation();
}
#undef op
#undef fp
#undef addr
+17 -257
View File
@@ -1,264 +1,24 @@
auto MOS6502::instructionAbsoluteModify(fp alu) -> void {
n16 absolute = operand();
absolute |= operand() << 8;
auto data = read(absolute);
write(absolute, data);
L write(absolute, ALU(data));
auto MOS6502::instructionNone(addr mode, algorithm alg) -> void {
MAR = ADDR();
ALG();
}
auto MOS6502::instructionAbsoluteModify(fp alu, n8 index) -> void {
n16 absolute = operand();
absolute |= operand() << 8;
idlePageAlways(absolute, absolute + index);
auto data = read(absolute + index);
write(absolute + index, data);
L write(absolute + index, ALU(data));
auto MOS6502::instructionLoad(addr mode, algorithm alg) -> void {
MAR = ADDR();
L MDR = read(MAR);
ALG();
}
auto MOS6502::instructionAbsoluteRead(fp alu, n8& data) -> void {
n16 absolute = operand();
absolute |= operand() << 8;
L data = ALU(read(absolute));
auto MOS6502::instructionStore(addr mode, algorithm alg) -> void {
MAR = ADDR();
ALG();
L write(MAR, MDR);
}
auto MOS6502::instructionAbsoluteRead(fp alu, n8& data, n8 index) -> void {
n16 absolute = operand();
absolute |= operand() << 8;
idlePageCrossed(absolute, absolute + index);
L data = ALU(read(absolute + index));
}
auto MOS6502::instructionAbsoluteWrite(n8& data) -> void {
n16 absolute = operand();
absolute |= operand() << 8;
L write(absolute, data);
}
auto MOS6502::instructionAbsoluteWrite(n8& data, n8 index) -> void {
n16 absolute = operand();
absolute |= operand() << 8;
idlePageAlways(absolute, absolute + index);
L write(absolute + index, data);
}
auto MOS6502::instructionBranch(bool take) -> void {
if(!take) {
L operand();
} else {
i8 displacement = operand();
idlePageCrossed(PC, PC + displacement);
L idle();
PC = PC + displacement;
}
}
auto MOS6502::instructionBreak() -> void {
operand();
push(PCH);
push(PCL);
n16 vector = 0xfffe;
nmi(vector);
push(P | 0x30);
I = 1;
PCL = read(vector++);
L PCH = read(vector++);
}
auto MOS6502::instructionCallAbsolute() -> void {
n16 absolute = operand();
absolute |= operand() << 8;
idle();
PC--;
push(PCH);
L push(PCL);
PC = absolute;
}
auto MOS6502::instructionClear(bool& flag) -> void {
L idle();
flag = 0;
}
auto MOS6502::instructionImmediate(fp alu, n8& data) -> void {
L data = ALU(operand());
}
auto MOS6502::instructionImplied(fp alu, n8& data) -> void {
L idle();
data = ALU(data);
}
auto MOS6502::instructionIndirectXRead(fp alu, n8& data) -> void {
auto zeroPage = operand();
load(zeroPage);
n16 absolute = load(zeroPage + X + 0);
absolute |= load(zeroPage + X + 1) << 8;
L data = ALU(read(absolute));
}
auto MOS6502::instructionIndirectXWrite(n8& data) -> void {
auto zeroPage = operand();
load(zeroPage);
n16 absolute = load(zeroPage + X + 0);
absolute |= load(zeroPage + X + 1) << 8;
L write(absolute, data);
}
auto MOS6502::instructionIndirectYRead(fp alu, n8& data) -> void {
auto zeroPage = operand();
n16 absolute = load(zeroPage + 0);
absolute |= load(zeroPage + 1) << 8;
idlePageCrossed(absolute, absolute + Y);
L data = ALU(read(absolute + Y));
}
auto MOS6502::instructionIndirectYRead(fp alu, n8& data, n8& data2) -> void {
instructionIndirectYRead(alu, data);
data2 = data;
}
auto MOS6502::instructionIndirectYWrite(n8& data) -> void {
auto zeroPage = operand();
n16 absolute = load(zeroPage + 0);
absolute |= load(zeroPage + 1) << 8;
idlePageAlways(absolute, absolute + Y);
L write(absolute + Y, data);
}
auto MOS6502::instructionJumpAbsolute() -> void {
n16 absolute = operand();
L absolute |= operand() << 8;
PC = absolute;
}
auto MOS6502::instructionJumpIndirect() -> void {
n16 absolute = operand();
absolute |= operand() << 8;
n16 pc = read(absolute);
absolute.byte(0)++; //MOS6502: $00ff wraps here to $0000; not $0100
L pc |= read(absolute) << 8;
PC = pc;
}
auto MOS6502::instructionNoOperation() -> void {
L idle();
}
auto MOS6502::instructionNoOperationAbsolute() -> void {
n16 absolute = operand();
absolute |= operand() << 8;
L read(absolute);
}
auto MOS6502::instructionNoOperationAbsolute(n8 index) -> void {
n16 absolute = operand();
absolute |= operand() << 8;
idlePageCrossed(absolute, absolute + index);
L read(absolute + index);
}
auto MOS6502::instructionNoOperationImmediate() -> void {
L operand();
}
auto MOS6502::instructionNoOperationZeroPage() -> void {
auto zeroPage = operand();
L load(zeroPage);
}
auto MOS6502::instructionNoOperationZeroPage(n8 index) -> void {
auto zeroPage = operand();
load(zeroPage);
L load(zeroPage + index);
}
auto MOS6502::instructionPull(n8& data) -> void {
idle();
idle();
L data = pull();
Z = data == 0;
N = data.bit(7);
}
auto MOS6502::instructionPullP() -> void {
idle();
idle();
L P = pull();
}
auto MOS6502::instructionPush(n8& data) -> void {
idle();
L push(data);
}
auto MOS6502::instructionPushP() -> void {
idle();
L push(P | 0x30);
}
auto MOS6502::instructionReturnInterrupt() -> void {
idle();
idle();
P = pull();
PCL = pull();
L PCH = pull();
}
auto MOS6502::instructionReturnSubroutine() -> void {
idle();
idle();
PCL = pull();
PCH = pull();
L idle();
PC++;
}
auto MOS6502::instructionSet(bool& flag) -> void {
L idle();
flag = 1;
}
auto MOS6502::instructionTransfer(n8& source, n8& target, bool flag) -> void {
L idle();
target = source;
if(!flag) return;
Z = target == 0;
N = target.bit(7);
}
auto MOS6502::instructionZeroPageModify(fp alu) -> void {
auto zeroPage = operand();
auto data = load(zeroPage);
store(zeroPage, data);
L store(zeroPage, ALU(data));
}
auto MOS6502::instructionZeroPageModify(fp alu, n8 index) -> void {
auto zeroPage = operand();
load(zeroPage);
auto data = load(zeroPage + index);
store(zeroPage + index, data);
L store(zeroPage + index, ALU(data));
}
auto MOS6502::instructionZeroPageRead(fp alu, n8& data) -> void {
auto zeroPage = operand();
L data = ALU(load(zeroPage));
}
auto MOS6502::instructionZeroPageRead(fp alu, n8& data, n8 index) -> void {
auto zeroPage = operand();
load(zeroPage);
L data = ALU(load(zeroPage + index));
}
auto MOS6502::instructionZeroPageWrite(n8& data) -> void {
auto zeroPage = operand();
L store(zeroPage, data);
}
auto MOS6502::instructionZeroPageWrite(n8& data, n8 index) -> void {
auto zeroPage = operand();
read(zeroPage);
L store(zeroPage + index, data);
auto MOS6502::instructionModify(addr mode, algorithm alg) -> void {
MAR = ADDR();
MDR = read(MAR);
write(MAR, MDR); // dummy write
ALG();
L write(MAR, MDR);
}
@@ -2,6 +2,10 @@ auto MOS6502::idle() -> void {
read(PC);
}
auto MOS6502::idleZeroPage(n8 addr) -> void {
read(addr);
}
auto MOS6502::idlePageCrossed(n16 x, n16 y) -> void {
if(x >> 8 == y >> 8) return;
read((x & 0xff00) | (y & 0x00ff));
+8 -5
View File
@@ -5,7 +5,8 @@ namespace ares {
#define PCH PC.byte(1)
#define PCL PC.byte(0)
#define ALU (this->*alu)
#define ADDR (this->*mode)
#define ALG (this->*alg)
#define C P.c
#define Z P.z
#define I P.i
@@ -14,6 +15,7 @@ namespace ares {
#define N P.n
#define L lastCycle();
#include "addresses.cpp"
#include "memory.cpp"
#include "algorithms.cpp"
#include "instruction.cpp"
@@ -23,7 +25,8 @@ namespace ares {
#undef PCH
#undef PCL
#undef ALU
#undef ADDR
#undef ALG
#undef C
#undef Z
#undef I
@@ -34,17 +37,17 @@ namespace ares {
auto MOS6502::power(bool reset) -> void {
if(reset) {
S-=3;
P.i = 1;
resetting = 1;
return;
}
A = 0x00;
X = 0x00;
Y = 0x00;
S = 0xfd;
S = 0x00;
P = 0x04;
MDR = 0x00;
resetting = 1;
}
}
+123 -71
View File
@@ -9,8 +9,12 @@ struct MOS6502 {
virtual auto read(n16 addr) -> n8 = 0;
virtual auto write(n16 addr, n8 data) -> void = 0;
virtual auto lastCycle() -> void = 0;
virtual auto nmi(n16& vector) -> void = 0;
virtual auto lastCycle() -> void {}
virtual auto cancelNmi() -> void {}
virtual auto delayIrq() -> void {}
virtual auto irqPending() -> bool { return false; }
virtual auto nmi(n16& vector) -> void {}
virtual auto readDebugger(n16 addr) -> n8 { return 0; }
//mos6502.cpp
@@ -18,6 +22,7 @@ struct MOS6502 {
//memory.cpp
auto idle() -> void;
auto idleZeroPage(n8) -> void;
auto idlePageCrossed(n16, n16) -> void;
auto idlePageAlways(n16, n16) -> void;
auto opcode() -> n8;
@@ -27,87 +32,132 @@ struct MOS6502 {
auto push(n8 data) -> void;
auto pull() -> n8;
//addresses.cpp
using addr = auto (MOS6502::*)() -> n16;
auto addressAbsolute() -> n16;
auto addressAbsoluteJMP() -> n16;
auto addressAbsoluteXRead() -> n16;
auto addressAbsoluteXWrite() -> n16;
auto addressAbsoluteYRead() -> n16;
auto addressAbsoluteYWrite() -> n16;
auto addressAccumulator() -> n16;
auto addressImmediate() -> n16;
auto addressImplied() -> n16;
auto addressIndirect() -> n16;
auto addressIndirectX() -> n16;
auto addressIndirectYRead() -> n16;
auto addressIndirectYWrite() -> n16;
auto addressRelative() -> n16;
auto addressZeroPage() -> n16;
auto addressZeroPageX() -> n16;
auto addressZeroPageY() -> n16;
//algorithms.cpp
using fp = auto (MOS6502::*)(n8) -> n8;
auto algorithmADC(n8) -> n8;
auto algorithmAND(n8) -> n8;
auto algorithmANC(n8) -> n8;
auto algorithmARR(n8) -> n8;
auto algorithmASL(n8) -> n8;
auto algorithmATX(n8) -> n8;
auto algorithmALR(n8) -> n8;
auto algorithmAXS(n8) -> n8;
auto algorithmBIT(n8) -> n8;
auto algorithmCMP(n8) -> n8;
auto algorithmCPX(n8) -> n8;
auto algorithmCPY(n8) -> n8;
auto algorithmDEC(n8) -> n8;
auto algorithmDCP(n8) -> n8;
auto algorithmEOR(n8) -> n8;
auto algorithmINC(n8) -> n8;
auto algorithmISC(n8) -> n8;
auto algorithmLD (n8) -> n8;
auto algorithmLSR(n8) -> n8;
auto algorithmSRE(n8) -> n8;
auto algorithmORA(n8) -> n8;
auto algorithmROL(n8) -> n8;
auto algorithmRLA(n8) -> n8;
auto algorithmROR(n8) -> n8;
auto algorithmRRA(n8) -> n8;
auto algorithmSBC(n8) -> n8;
auto algorithmSLO(n8) -> n8;
using algorithm = auto (MOS6502::*)() -> void;
// official algorithms
auto algorithmADC() -> void;
auto algorithmAND() -> void;
auto algorithmASLA() -> void;
auto algorithmASLM() -> void;
auto algorithmBCC() -> void;
auto algorithmBCS() -> void;
auto algorithmBEQ() -> void;
auto algorithmBIT() -> void;
auto algorithmBMI() -> void;
auto algorithmBNE() -> void;
auto algorithmBPL() -> void;
auto algorithmBRK() -> void;
auto algorithmBVC() -> void;
auto algorithmBVS() -> void;
auto algorithmBranch(bool take) -> void;
auto algorithmCLC() -> void;
auto algorithmCLD() -> void;
auto algorithmCLI() -> void;
auto algorithmCLV() -> void;
auto algorithmCMP() -> void;
auto algorithmCPX() -> void;
auto algorithmCPY() -> void;
auto algorithmDEC() -> void;
auto algorithmDEX() -> void;
auto algorithmDEY() -> void;
auto algorithmEOR() -> void;
auto algorithmINC() -> void;
auto algorithmINX() -> void;
auto algorithmINY() -> void;
auto algorithmJMP() -> void;
auto algorithmJSR() -> void;
auto algorithmNOP() -> void;
auto algorithmLDA() -> void;
auto algorithmLDX() -> void;
auto algorithmLDY() -> void;
auto algorithmLSRA() -> void;
auto algorithmLSRM() -> void;
auto algorithmORA() -> void;
auto algorithmPHA() -> void;
auto algorithmPHP() -> void;
auto algorithmPLA() -> void;
auto algorithmPLP() -> void;
auto algorithmROLA() -> void;
auto algorithmROLM() -> void;
auto algorithmRORA() -> void;
auto algorithmRORM() -> void;
auto algorithmRTI() -> void;
auto algorithmRTS() -> void;
auto algorithmSBC() -> void;
auto algorithmSEC() -> void;
auto algorithmSED() -> void;
auto algorithmSEI() -> void;
auto algorithmSTA() -> void;
auto algorithmSTX() -> void;
auto algorithmSTY() -> void;
auto algorithmTAX() -> void;
auto algorithmTAY() -> void;
auto algorithmTSX() -> void;
auto algorithmTXA() -> void;
auto algorithmTXS() -> void;
auto algorithmTYA() -> void;
// unofficial algorithms
auto algorithmAAC() -> void;
auto algorithmAAX() -> void;
auto algorithmANE() -> void;
auto algorithmARR() -> void;
auto algorithmASR() -> void;
auto algorithmATX() -> void;
auto algorithmAXS() -> void;
auto algorithmDCP() -> void;
auto algorithmISC() -> void;
auto algorithmLAS() -> void;
auto algorithmLAX() -> void;
auto algorithmRLA() -> void;
auto algorithmRRA() -> void;
auto algorithmSLO() -> void;
auto algorithmSRE() -> void;
auto algorithmSXA() -> void;
auto algorithmSYA() -> void;
auto algorithmTAS() -> void;
// freeze algorithms: need reset
auto algorithmJAM() -> void;
//instruction.cpp
auto interrupt() -> void;
auto reset() -> void;
auto instruction() -> void;
//instructions.cpp
auto instructionAbsoluteModify(fp alu) -> void;
auto instructionAbsoluteModify(fp alu, n8 index) -> void;
auto instructionAbsoluteRead(fp alu, n8& data) -> void;
auto instructionAbsoluteRead(fp alu, n8& data, n8 index) -> void;
auto instructionAbsoluteWrite(n8& data) -> void;
auto instructionAbsoluteWrite(n8& data, n8 index) -> void;
auto instructionBranch(bool take) -> void;
auto instructionBreak() -> void;
auto instructionCallAbsolute() -> void;
auto instructionClear(bool& flag) -> void;
auto instructionImmediate(fp alu, n8& data) -> void;
auto instructionImplied(fp alu, n8& data) -> void;
auto instructionIndirectXRead(fp alu, n8& data) -> void;
auto instructionIndirectXWrite(n8& data) -> void;
auto instructionIndirectYRead(fp alu, n8& data) -> void;
auto instructionIndirectYRead(fp, n8& data, n8& data2) -> void;
auto instructionIndirectYWrite(n8& data) -> void;
auto instructionJumpAbsolute() -> void;
auto instructionJumpIndirect() -> void;
auto instructionNoOperation() -> void;
auto instructionNoOperationAbsolute() -> void;
auto instructionNoOperationAbsolute(n8 index) -> void;
auto instructionNoOperationImmediate() -> void;
auto instructionNoOperationZeroPage() -> void;
auto instructionNoOperationZeroPage(n8 index) -> void;
auto instructionPull(n8& data) -> void;
auto instructionPullP() -> void;
auto instructionPush(n8& data) -> void;
auto instructionPushP() -> void;
auto instructionReturnInterrupt() -> void;
auto instructionReturnSubroutine() -> void;
auto instructionSet(bool& flag) -> void;
auto instructionTransfer(n8& source, n8& target, bool flag) -> void;
auto instructionZeroPageModify(fp alu) -> void;
auto instructionZeroPageModify(fp alu, n8 index) -> void;
auto instructionZeroPageRead(fp alu, n8& data) -> void;
auto instructionZeroPageRead(fp alu, n8& data, n8 index) -> void;
auto instructionZeroPageWrite(n8& data) -> void;
auto instructionZeroPageWrite(n8& data, n8 index) -> void;
auto instructionNone(addr mode, algorithm alg) -> void;
auto instructionLoad(addr mode, algorithm alg) -> void;
auto instructionStore(addr mode, algorithm alg) -> void;
auto instructionModify(addr mode, algorithm alg) -> void;
//serialization.cpp
auto serialize(serializer&) -> void;
//disassembler.cpp
noinline auto disassembleInstruction(maybe<n16> pc = {}) -> string;
noinline auto disassembleContext() -> string;
NALL_NOINLINE auto disassembleInstruction(maybe<n16> pc = {}) -> string;
NALL_NOINLINE auto disassembleContext() -> string;
struct PR {
bool c; //carry
@@ -138,7 +188,9 @@ struct MOS6502 {
n8 S;
PR P;
n16 PC;
n16 MAR;
n8 MDR;
n1 resetting = 0;
};
}
@@ -11,5 +11,7 @@ auto MOS6502::serialize(serializer& s) -> void {
s(P.v);
s(P.n);
s(PC);
s(MAR);
s(MDR);
s(resetting);
}
+3 -5
View File
@@ -14,7 +14,7 @@ auto SH2::delaySlot(u32 pc) -> void {
}
auto SH2::instruction() -> void {
if constexpr(Accuracy::Interpreter) {
if(Accuracy::Interpreter || !recompiler.enabled) {
step(1);
exceptionHandler();
if constexpr(Accuracy::AddressErrors) {
@@ -26,9 +26,7 @@ auto SH2::instruction() -> void {
instructionPrologue(opcode);
execute(opcode);
instructionEpilogue();
}
if constexpr(Accuracy::Recompiler) {
} else {
exceptionHandler();
// Recompiled blocks may be very small, negating the impact
@@ -36,6 +34,7 @@ auto SH2::instruction() -> void {
do {
auto block = recompiler.block(PC - 4);
block->execute(*this);
ID = 0;
} while (CCR < cyclesUntilRecompilerExit);
// Reset the count as it may have been set to 0 for an early exit
@@ -43,7 +42,6 @@ auto SH2::instruction() -> void {
step(CCR);
CCR = 0;
ID = 0;
}
}
@@ -513,19 +513,19 @@ auto SH2::MOVI(u32 i, u32 n) -> void {
}
//MOV.W @(disp,PC),Rn
noinline auto SH2::MOVWI(u32 d, u32 n) -> void {
NALL_NOINLINE auto SH2::MOVWI(u32 d, u32 n) -> void {
u32 pc = inDelaySlot() ? PPC - 2 : PC;
R[n] = (s16)readWord(pc + d * 2);
}
//MOV.L @(disp,PC),Rn
noinline auto SH2::MOVLI(u32 d, u32 n) -> void {
NALL_NOINLINE auto SH2::MOVLI(u32 d, u32 n) -> void {
u32 pc = inDelaySlot() ? PPC - 2 : PC;
R[n] = readLong((pc & ~3) + d * 4);
}
//MOVA @(disp,PC),R0
noinline auto SH2::MOVA(u32 d) -> void {
NALL_NOINLINE auto SH2::MOVA(u32 d) -> void {
u32 pc = inDelaySlot() ? PPC - 2 : PC;
R[0] = (pc & ~3) + d * 4;
}
+1
View File
@@ -300,6 +300,7 @@ struct SH2 {
static auto mask(u8 address, u8 size) -> u64;
bool enabled = false;
bool callInstructionPrologue = false;
bool inDelaySlot;
u32 generation;
+2 -2
View File
@@ -29,8 +29,8 @@ struct SM83 {
//disassembler.cpp
virtual auto readDebugger(n16 address) -> n8 { return 0; }
noinline auto disassembleInstruction(maybe<n16> pc = {}) -> string;
noinline auto disassembleContext() -> string;
NALL_NOINLINE auto disassembleInstruction(maybe<n16> pc = {}) -> string;
NALL_NOINLINE auto disassembleContext() -> string;
//memory.cpp
auto operand() -> n8;
+3 -3
View File
@@ -117,9 +117,9 @@ struct SPC700 {
auto serialize(serializer&) -> void;
//disassembler.cpp
noinline auto disassembleInstruction(n16 address, n1 p) -> string;
noinline auto disassembleInstruction() -> string;
noinline auto disassembleContext() -> string;
NALL_NOINLINE auto disassembleInstruction(n16 address, n1 p) -> string;
NALL_NOINLINE auto disassembleInstruction() -> string;
NALL_NOINLINE auto disassembleContext() -> string;
struct Flags {
bool c; //carry
@@ -1,4 +1,4 @@
noinline auto TLCS900H::disassembleInstruction() -> string {
NALL_NOINLINE auto TLCS900H::disassembleInstruction() -> string {
string output;
auto pc = load(PC);
@@ -636,7 +636,7 @@ noinline auto TLCS900H::disassembleInstruction() -> string {
return pad(output, -48);
}
noinline auto TLCS900H::disassembleContext() -> string {
NALL_NOINLINE auto TLCS900H::disassembleContext() -> string {
string output;
output.append("XWA:", hex(r.xwa[RFP].l.l0, 8L), " ");
output.append("XBC:", hex(r.xbc[RFP].l.l0, 8L), " ");
@@ -25,8 +25,8 @@ struct uPD96050 {
auto writeDP(n12 address, n8 data) -> void;
//disassembler.cpp
noinline auto disassembleInstruction(maybe<n14> ip = {}) -> string;
noinline auto disassembleContext() -> string;
NALL_NOINLINE auto disassembleInstruction(maybe<n14> ip = {}) -> string;
NALL_NOINLINE auto disassembleContext() -> string;
enum class Revision : u32 { uPD7725, uPD96050 } revision;
n24 programROM[16384];
+12 -5
View File
@@ -1,3 +1,10 @@
auto V30MZ::prefixFlush() -> void {
prefix.count = 0;
prefix.lock = 0;
prefix.repeat = 0;
prefix.segment = 0;
}
auto V30MZ::interrupt(u8 vector, InterruptSource source) -> bool {
if(source == InterruptSource::INT) wait(32);
else if (source == InterruptSource::NMI) wait(26);
@@ -5,15 +12,15 @@ auto V30MZ::interrupt(u8 vector, InterruptSource source) -> bool {
state.halt = 0;
state.poll = 1;
state.prefix = 0;
//if an IRQ fires during a rep string instruction;
//flush prefix queue and seek back to first prefix.
//this allows the transfer to resume after the IRQ.
if(repeat()) {
PC -= prefixes.size();
prefixes.flush();
if(state.prefix) {
state.prefix = 0;
PC -= prefix.count;
}
prefixFlush();
auto pc = read<Word>(0x0000, vector * 4 + 0);
auto ps = read<Word>(0x0000, vector * 4 + 2);
@@ -309,7 +316,7 @@ auto V30MZ::instruction() -> void {
op(0xff, Group4MemImm<Word>)
}
if(!state.prefix) prefixes.flush();
if(!state.prefix) prefixFlush();
if(PSW.BRK) interrupt(1, InterruptSource::SingleStep);
}
@@ -14,7 +14,7 @@ auto V30MZ::instructionDecimalAdjust(bool negate) -> void {
al = AL;
AL += negate ? -0x60 : 0x60;
PSW.CY = 1;
if(negate) PSW.V |= (al ^ 0x06) & (al ^ AL) & 0x80; // undefined
if(negate) PSW.V |= (al ^ 0x60) & (al ^ AL) & 0x80; // undefined
else PSW.V |= (AL ^ al) & (AL ^ 0x60) & 0x80; // undefined
} else {
PSW.CY = 0;
@@ -220,8 +220,5 @@ auto V30MZ::instructionPopMem() -> void {
wait(1);
modRM();
auto data = pop();
//NEC bug: pop into a register will adjust the stack, but fail to set the register properly
//in practice, this isn't an issue as assemblers will favor one-byte pop instructions,
//but this difference can be used to distinguish Intel x86 chips from NEC V20/V30 chips.
if(modrm.mod != 3) setMemory<Word>(data);
setMemory<Word>(data);
}
@@ -1,21 +1,21 @@
auto V30MZ::instructionSegment(n16 segment) -> void {
if(prefixes.full()) prefixes.read(0);
prefixes.write(opcode);
prefix.segment = opcode;
prefix.count++;
state.prefix = 1;
state.poll = 0;
}
auto V30MZ::instructionRepeat() -> void {
if(prefixes.full()) prefixes.read(0);
prefixes.write(opcode);
prefix.repeat = opcode;
prefix.count++;
wait(4);
state.prefix = 1;
state.poll = 0;
}
auto V30MZ::instructionLock() -> void {
if(prefixes.full()) prefixes.read(0);
prefixes.write(opcode);
prefix.lock = opcode;
prefix.count++;
state.prefix = 1;
state.poll = 0;
}
@@ -75,8 +75,8 @@ auto V30MZ::instructionTranslate() -> void {
auto V30MZ::instructionBound() -> void {
wait(12);
modRM();
auto lo = getMemory<Word>(0);
auto hi = getMemory<Word>(2);
auto reg = getRegister<Word>();
i16 lo = (i16)getMemory<Word>(0);
i16 hi = (i16)getMemory<Word>(2);
i16 reg = (i16)getRegister<Word>();
if(reg < lo || reg > hi) interrupt(5, InterruptSource::CPU);
}
@@ -65,13 +65,13 @@ template<u32 size> auto V30MZ::instructionExchangeMemReg() -> void {
auto V30MZ::instructionLoadEffectiveAddressRegMem() -> void {
wait(1);
modRM();
modRM(true);
setRegister<Word>(modrm.address);
}
auto V30MZ::instructionLoadSegmentMem(u16& segment) -> void {
wait(4);
modRM();
modRM(true);
setRegister<Word>(getMemory<Word>());
segment = getMemory<Word>(2);
}
@@ -1,11 +1,11 @@
template<u32 size> auto V30MZ::instructionInString() -> void {
wait(3);
if(!repeat() || CW) {
if(!prefix.repeat || CW) {
auto data = in<size>(DW);
write<size>(DS1, IY, data);
IY += PSW.DIR ? -size : size;
if(!repeat() || !--CW) return;
if(!prefix.repeat || !--CW) return;
state.prefix = 1;
PC--;
@@ -15,12 +15,12 @@ template<u32 size> auto V30MZ::instructionInString() -> void {
template<u32 size> auto V30MZ::instructionOutString() -> void {
wait(3);
if(!repeat() || CW) {
if(!prefix.repeat || CW) {
auto data = read<size>(segment(DS0), IX);
out<size>(DW, data);
IX += PSW.DIR ? -size : size;
if(!repeat() || !--CW) return;
if(!prefix.repeat || !--CW) return;
state.prefix = 1;
PC--;
@@ -30,13 +30,13 @@ template<u32 size> auto V30MZ::instructionOutString() -> void {
template<u32 size> auto V30MZ::instructionMoveString() -> void {
wait(3);
if(!repeat() || CW) {
if(!prefix.repeat || CW) {
auto data = read<size>(segment(DS0), IX);
write<size>(DS1, IY, data);
IX += PSW.DIR ? -size : size;
IY += PSW.DIR ? -size : size;
if(!repeat() || !--CW) return;
if(!prefix.repeat || !--CW) return;
state.prefix = 1;
PC--;
@@ -46,16 +46,16 @@ template<u32 size> auto V30MZ::instructionMoveString() -> void {
template<u32 size> auto V30MZ::instructionCompareString() -> void {
wait(4);
if(!repeat() || CW) {
if(!prefix.repeat || CW) {
auto x = read<size>(segment(DS0), IX);
auto y = read<size>(DS1, IY);
IX += PSW.DIR ? -size : size;
IY += PSW.DIR ? -size : size;
SUB<size>(x, y);
if(!repeat() || !--CW) return;
if(repeat() == RepeatWhileZeroLo && PSW.Z == 1) return;
if(repeat() == RepeatWhileZeroHi && PSW.Z == 0) return;
if(!prefix.repeat || !--CW) return;
if(prefix.repeat == RepeatWhileZeroLo && PSW.Z == 1) return;
if(prefix.repeat == RepeatWhileZeroHi && PSW.Z == 0) return;
state.prefix = 1;
PC--;
@@ -65,11 +65,11 @@ template<u32 size> auto V30MZ::instructionCompareString() -> void {
template<u32 size> auto V30MZ::instructionStoreString() -> void {
wait(2);
if(!repeat() || CW) {
if(!prefix.repeat || CW) {
write<size>(DS1, IY, getAccumulator<size>());
IY += PSW.DIR ? -size : size;
if(!repeat() || !--CW) return;
if(!prefix.repeat || !--CW) return;
state.prefix = 1;
PC--;
@@ -79,11 +79,11 @@ template<u32 size> auto V30MZ::instructionStoreString() -> void {
template<u32 size> auto V30MZ::instructionLoadString() -> void {
wait(2);
if(!repeat() || CW) {
if(!prefix.repeat || CW) {
setAccumulator<size>(read<size>(segment(DS0), IX));
IX += PSW.DIR ? -size : size;
if(!repeat() || !--CW) return;
if(!prefix.repeat || !--CW) return;
state.prefix = 1;
PC--;
@@ -93,15 +93,15 @@ template<u32 size> auto V30MZ::instructionLoadString() -> void {
template<u32 size> auto V30MZ::instructionScanString() -> void {
wait(3);
if(!repeat() || CW) {
if(!prefix.repeat || CW) {
auto x = getAccumulator<size>();
auto y = read<size>(DS1, IY);
IY += PSW.DIR ? -size : size;
SUB<size>(x, y);
if(!repeat() || !--CW) return;
if(repeat() == RepeatWhileZeroLo && PSW.Z == 1) return;
if(repeat() == RepeatWhileZeroHi && PSW.Z == 0) return;
if(!prefix.repeat || !--CW) return;
if(prefix.repeat == RepeatWhileZeroLo && PSW.Z == 1) return;
if(prefix.repeat == RepeatWhileZeroHi && PSW.Z == 0) return;
state.prefix = 1;
PC--;
+24 -6
View File
@@ -1,13 +1,31 @@
auto V30MZ::modRM() -> void {
auto V30MZ::modRM(bool forceAddress) -> void {
auto data = fetch<Byte>();
modrm.mem = data >> 0 & 7;
modrm.reg = data >> 3 & 7;
modrm.mod = data >> 6 & 3;
modrm.useAddress = modrm.mod != 3;
if(modrm.mod == 3) return;
if(modrm.mod == 0 && modrm.mem == 6) {
modrm.segment = segment(DS0);
modrm.address = fetch<Word>();
} else if (modrm.mod == 3) {
if (!forceAddress) return;
// This is used when LEA/LDS/LES is called with register addressing mode,
// which is normally undefined behaviour.
//
// TODO: Does this incur a 1-clock penalty? When?
modrm.useAddress = true;
wait(1);
switch(modrm.mem) {
case 0: modrm.segment = segment(DS0); modrm.address = BW + AW; break;
case 1: modrm.segment = segment(DS0); modrm.address = BW + CW; break;
case 2: modrm.segment = segment(SS ); modrm.address = BP + DW; break;
case 3: modrm.segment = segment(SS ); modrm.address = BP + BW; break;
case 4: modrm.segment = segment(DS0); modrm.address = IX + SP; break;
case 5: modrm.segment = segment(DS0); modrm.address = IY + BP; break;
case 6: modrm.segment = segment(SS ); modrm.address = BP + IX; break;
case 7: modrm.segment = segment(DS0); modrm.address = BW + IY; break;
}
} else {
switch(modrm.mem) {
case 0: modrm.segment = segment(DS0); modrm.address = BW + IX; wait(1); break;
@@ -35,21 +53,21 @@ template<> auto V30MZ::setRegister<Byte>(u16 data) -> void { *RB[modrm.reg] = da
template<> auto V30MZ::setRegister<Word>(u16 data) -> void { *RW[modrm.reg] = data; }
template<> auto V30MZ::getMemory<Byte>(u32 offset) -> u16 {
if(modrm.mod == 3) return *RB[modrm.mem];
if(!modrm.useAddress) return *RB[modrm.mem];
return read<Byte>(modrm.segment, modrm.address + offset);
}
template<> auto V30MZ::getMemory<Word>(u32 offset) -> u16 {
if(modrm.mod == 3) return *RW[modrm.mem];
if(!modrm.useAddress) return *RW[modrm.mem];
return read<Word>(modrm.segment, modrm.address + offset);
}
template<> auto V30MZ::setMemory<Byte>(u16 data) -> void {
if(modrm.mod == 3) return (void)(*RB[modrm.mem] = data);
if(!modrm.useAddress) return (void)(*RB[modrm.mem] = data);
return write<Byte>(modrm.segment, modrm.address, data);
}
template<> auto V30MZ::setMemory<Word>(u16 data) -> void {
if(modrm.mod == 3) return (void)(*RW[modrm.mem] = data);
if(!modrm.useAddress) return (void)(*RW[modrm.mem] = data);
return write<Word>(modrm.segment, modrm.address, data);
}
+4 -14
View File
@@ -1,18 +1,8 @@
auto V30MZ::repeat() -> u8 {
for(auto prefix : prefixes) {
if(prefix == RepeatWhileZeroLo) return prefix;
if(prefix == RepeatWhileZeroHi) return prefix;
}
return 0;
}
auto V30MZ::segment(u16 segment) -> u16 {
for(auto prefix : prefixes) {
if(prefix == SegmentOverrideDS1) return DS1;
if(prefix == SegmentOverridePS ) return PS;
if(prefix == SegmentOverrideSS ) return SS;
if(prefix == SegmentOverrideDS0) return DS0;
}
if(prefix.segment == SegmentOverrideDS1) return DS1;
if(prefix.segment == SegmentOverridePS ) return PS;
if(prefix.segment == SegmentOverrideSS ) return SS;
if(prefix.segment == SegmentOverrideDS0) return DS0;
return segment;
}
@@ -4,13 +4,18 @@ auto V30MZ::serialize(serializer& s) -> void {
s(state.prefix);
s(opcode);
s(prefixes);
s(prefix.count);
s(prefix.lock);
s(prefix.repeat);
s(prefix.segment);
s(modrm.mod);
s(modrm.reg);
s(modrm.mem);
s(modrm.segment);
s(modrm.address);
s(modrm.useAddress);
s(AW);
s(CW);
+1 -1
View File
@@ -28,7 +28,7 @@ auto V30MZ::power() -> void {
state.prefix = 0;
opcode = 0;
prefixes.flush();
prefixFlush();
modrm.mod = 0;
modrm.reg = 0;
modrm.mem = 0;
+10 -2
View File
@@ -39,6 +39,7 @@ struct V30MZ {
auto power() -> void;
//instruction.cpp
auto prefixFlush() -> void;
auto interrupt(u8 vector) -> bool;
auto nonMaskableInterrupt() -> bool;
auto instruction() -> void;
@@ -51,7 +52,7 @@ struct V30MZ {
template<u32> auto setAccumulator(u32) -> void;
//modrm.cpp
auto modRM() -> void;
auto modRM(bool forceAddress = false) -> void;
auto getSegment() -> u16;
auto setSegment(u16) -> void;
@@ -242,7 +243,12 @@ struct V30MZ {
} state;
u8 opcode;
queue<u8[7]> prefixes;
struct Prefix {
u16 count;
u8 lock;
u8 repeat;
u8 segment;
} prefix;
struct ModRM {
u2 mod;
@@ -251,6 +257,8 @@ struct V30MZ {
u16 segment;
u16 address;
bool useAddress;
} modrm;
union { u16 AW; struct { u8 order_lsb2(AL, AH); }; }; //AX
@@ -113,8 +113,8 @@ auto WDC65816::instructionIndexedIndirectRead8(alu8 op) -> void {
U.l = fetch();
idle2();
idle();
V.l = readDirect(U.l + X.w + 0);
V.h = readDirect(U.l + X.w + 1);
V.l = readDirectX(U.l + X.w, 0);
V.h = readDirectX(U.l + X.w, 1);
L W.l = readBank(V.w + 0);
alu(W.l);
}
@@ -123,8 +123,8 @@ auto WDC65816::instructionIndexedIndirectRead16(alu16 op) -> void {
U.l = fetch();
idle2();
idle();
V.l = readDirect(U.l + X.w + 0);
V.h = readDirect(U.l + X.w + 1);
V.l = readDirectX(U.l + X.w, 0);
V.h = readDirectX(U.l + X.w, 1);
W.l = readBank(V.w + 0);
L W.h = readBank(V.w + 1);
alu(W.w);
@@ -90,8 +90,8 @@ auto WDC65816::instructionIndexedIndirectWrite8() -> void {
U.l = fetch();
idle2();
idle();
V.l = readDirect(U.l + X.w + 0);
V.h = readDirect(U.l + X.w + 1);
V.l = readDirectX(U.l + X.w, 0);
V.h = readDirectX(U.l + X.w, 1);
L writeBank(V.w + 0, A.l);
}
@@ -99,8 +99,8 @@ auto WDC65816::instructionIndexedIndirectWrite16() -> void {
U.l = fetch();
idle2();
idle();
V.l = readDirect(U.l + X.w + 0);
V.h = readDirect(U.l + X.w + 1);
V.l = readDirectX(U.l + X.w, 0);
V.h = readDirectX(U.l + X.w, 1);
writeBank(V.w + 0, A.l);
L writeBank(V.w + 1, A.h);
}
@@ -59,6 +59,13 @@ inline auto WDC65816::writeDirect(u32 address, n8 data) -> void {
write(n16(D.w + address), data);
}
inline auto WDC65816::readDirectX(u32 address, u32 offset) -> n8 {
// The (direct,X) addressing mode has a bug in which the high byte is
// wrapped within the page if E = 1 and D&0xFF != 0.
if(EF && D.l) return read(((D.w + address) & 0xffff00) | n8(D.w + address + offset));
else return readDirect(address + offset);
}
inline auto WDC65816::readDirectN(u32 address) -> n8 {
return read(n16(D.w + address));
}
@@ -64,6 +64,7 @@ struct WDC65816 {
auto pullN() -> n8;
auto pushN(n8 data) -> void;
auto readDirect(u32 address) -> n8;
auto readDirectX(u32 address, u32 offset) -> n8;
auto writeDirect(u32 address, n8 data) -> void;
auto readDirectN(u32 address) -> n8;
auto readBank(u32 address) -> n8;
@@ -234,9 +235,9 @@ struct WDC65816 {
auto serialize(serializer&) -> void;
//disassembler.cpp
noinline auto disassembleInstruction(n24 address, bool e, bool m, bool x) -> string;
noinline auto disassembleInstruction() -> string;
noinline auto disassembleContext(maybe<bool> e = {}) -> string;
NALL_NOINLINE auto disassembleInstruction(n24 address, bool e, bool m, bool x) -> string;
NALL_NOINLINE auto disassembleInstruction() -> string;
NALL_NOINLINE auto disassembleContext(maybe<bool> e = {}) -> string;
struct f8 {
bool c = 0; //carry
+2 -2
View File
@@ -211,8 +211,8 @@ struct Z80 {
auto serialize(serializer&) -> void;
//disassembler.cpp
noinline auto disassembleInstruction(maybe<n16> pc = {}) -> string;
noinline auto disassembleContext() -> string;
NALL_NOINLINE auto disassembleInstruction(maybe<n16> pc = {}) -> string;
NALL_NOINLINE auto disassembleContext() -> string;
auto disassemble(n16 pc, n8 prefix, n8 code) -> string;
auto disassembleCB(n16 pc, n8 prefix, n8 code) -> string;
+1
View File
@@ -17,6 +17,7 @@ auto VDP::load(Node::Object parent) -> void {
screen->setScale(1.0, 1.0);
screen->setAspect(8.0, 7.0);
screen->setViewport(0, 0, 284, 243);
screen->refreshRateHint(system.colorburst(), 228, 262);
TMS9918::load(screen);
}
+51 -82
View File
@@ -3,12 +3,14 @@
namespace ares::Famicom {
APU apu;
#include "length.cpp"
#include "envelope.cpp"
#include "sweep.cpp"
#include "pulse.cpp"
#include "triangle.cpp"
#include "noise.cpp"
#include "dmc.cpp"
#include "framecounter.cpp"
#include "serialization.cpp"
auto APU::load(Node::Object parent) -> void {
@@ -54,13 +56,20 @@ auto APU::main() -> void {
u32 triangleOutput = triangle.clock();
u32 noiseOutput = noise.clock();
u32 dmcOutput = dmc.clock();
clockFrameCounterDivider();
frame.main();
s32 output = 0;
output += pulseDAC[pulseOutput];
output += dmcTriangleNoiseDAC[dmcOutput][triangleOutput][noiseOutput];
stream->frame(sclamp<16>(output) / 32768.0);
tick();
}
auto APU::tick() -> void {
Thread::step(rate());
Thread::synchronize(cpu);
}
auto APU::setIRQ() -> void {
@@ -68,28 +77,28 @@ auto APU::setIRQ() -> void {
}
auto APU::power(bool reset) -> void {
pulse1 = {};
pulse2 = {};
triangle = {};
noise = {};
dmc = {};
dmc.periodCounter = Region::PAL() ? dmcPeriodTablePAL[0] : dmcPeriodTableNTSC[0];
frame = {};
enabledChannels = 0;
Thread::create(system.frequency(), {&APU::main, this});
pulse1.power(reset);
pulse2.power(reset);
triangle.power(reset);
noise.power(reset);
dmc.power(reset);
frame.power(reset);
setIRQ();
}
auto APU::readIO(n16 address) -> n8 {
n8 data = cpu.MDR;
n8 data = cpu.io.openBus;
switch(address) {
case 0x4015: {
data.bit(0) = (bool)pulse1.lengthCounter;
data.bit(1) = (bool)pulse2.lengthCounter;
data.bit(2) = (bool)triangle.lengthCounter;
data.bit(3) = (bool)noise.lengthCounter;
data.bit(0) = (bool)pulse1.length.counter;
data.bit(1) = (bool)pulse2.length.counter;
data.bit(2) = (bool)triangle.length.counter;
data.bit(3) = (bool)noise.length.counter;
data.bit(4) = (bool)dmc.lengthCounter;
data.bit(5) = 0;
data.bit(6) = frame.irqPending;
@@ -111,6 +120,7 @@ auto APU::writeIO(n16 address, n8 data) -> void {
pulse1.envelope.speed = data.bit(0,3);
pulse1.envelope.useSpeedAsVolume = data.bit(4);
pulse1.envelope.loopMode = data.bit(5);
pulse1.length.setHalt(frame.lengthClocking(), data.bit(5));
pulse1.duty = data.bit(6,7);
return;
}
@@ -137,9 +147,7 @@ auto APU::writeIO(n16 address, n8 data) -> void {
pulse1.dutyCounter = 0;
pulse1.envelope.reloadDecay = true;
if(enabledChannels.bit(0)) {
pulse1.lengthCounter = lengthCounterTable[data.bit(3,7)];
}
pulse1.length.setCounter(frame.lengthClocking(), data.bit(3,7));
return;
}
@@ -147,6 +155,7 @@ auto APU::writeIO(n16 address, n8 data) -> void {
pulse2.envelope.speed = data.bit(0,3);
pulse2.envelope.useSpeedAsVolume = data.bit(4);
pulse2.envelope.loopMode = data.bit(5);
pulse2.length.setHalt(frame.lengthClocking(), data.bit(5));
pulse2.duty = data.bit(6,7);
return;
}
@@ -173,15 +182,13 @@ auto APU::writeIO(n16 address, n8 data) -> void {
pulse2.dutyCounter = 0;
pulse2.envelope.reloadDecay = true;
if(enabledChannels.bit(1)) {
pulse2.lengthCounter = lengthCounterTable[data.bit(3,7)];
}
pulse2.length.setCounter(frame.lengthClocking(), data.bit(3,7));
return;
}
case 0x4008: {
triangle.linearLength = data.bit(0,6);
triangle.haltLengthCounter = data.bit(7);
triangle.length.setHalt(frame.lengthClocking(), data.bit(7));
return;
}
@@ -195,15 +202,14 @@ auto APU::writeIO(n16 address, n8 data) -> void {
triangle.reloadLinear = true;
if(enabledChannels.bit(2)) {
triangle.lengthCounter = lengthCounterTable[data.bit(3,7)];
}
triangle.length.setCounter(frame.lengthClocking(), data.bit(3,7));
return;
}
case 0x400c: {
noise.envelope.speed = data.bit(0,3);
noise.envelope.useSpeedAsVolume = data.bit(4);
noise.length.setHalt(frame.lengthClocking(), data.bit(5));
noise.envelope.loopMode = data.bit(5);
return;
}
@@ -217,9 +223,7 @@ auto APU::writeIO(n16 address, n8 data) -> void {
case 0x400f: {
noise.envelope.reloadDecay = true;
if(enabledChannels.bit(3)) {
noise.lengthCounter = lengthCounterTable[data.bit(3,7)];
}
noise.length.setCounter(frame.lengthClocking(), data.bit(3, 7));
return;
}
@@ -249,78 +253,43 @@ auto APU::writeIO(n16 address, n8 data) -> void {
}
case 0x4015: {
if(data.bit(0) == 0) pulse1.lengthCounter = 0;
if(data.bit(1) == 0) pulse2.lengthCounter = 0;
if(data.bit(2) == 0) triangle.lengthCounter = 0;
if(data.bit(3) == 0) noise.lengthCounter = 0;
if(data.bit(4) == 0) dmc.stop();
if(data.bit(4) == 1) dmc.start();
pulse1.length.setEnable(data.bit(0));
pulse2.length.setEnable(data.bit(1));
triangle.length.setEnable(data.bit(2));
noise.length.setEnable(data.bit(3));
if (data.bit(4) == 0) dmc.stop();
if (data.bit(4) == 1) dmc.start();
dmc.irqPending = false;
setIRQ();
enabledChannels = data.bit(0,4);
return;
}
case 0x4017: {
frame.mode = data.bit(6,7);
frame.counter = 0;
if(frame.mode.bit(1)) {
clockFrameCounter();
}
if(frame.mode.bit(0)) {
frame.irqPending = false;
setIRQ();
}
frame.divider = FrameCounter::NtscPeriod;
return;
}
case 0x4017: return frame.write(data);
}
}
auto APU::clockFrameCounter() -> void {
frame.counter++;
auto APU::clockQuarterFrame() -> void {
pulse1.envelope.clock();
pulse2.envelope.clock();
triangle.clockLinearLength();
noise.envelope.clock();
}
if(frame.counter.bit(0)) {
pulse1.clockLength();
pulse1.sweep.clock(0);
pulse2.clockLength();
pulse2.sweep.clock(1);
triangle.clockLength();
noise.clockLength();
}
auto APU::clockHalfFrame() -> void {
pulse1.length.main();
pulse1.sweep.clock(0);
pulse2.length.main();
pulse2.sweep.clock(1);
triangle.length.main();
noise.length.main();
pulse1.envelope.clock();
pulse2.envelope.clock();
triangle.clockLinearLength();
noise.envelope.clock();
if(frame.counter == 0) {
if(frame.mode.bit(1)) {
frame.divider += FrameCounter::NtscPeriod;
}
if(frame.mode == 0) {
frame.irqPending = true;
setIRQ();
}
}
}
auto APU::clockFrameCounterDivider() -> void {
frame.divider -= 2;
if(frame.divider <= 0) {
clockFrameCounter();
frame.divider += FrameCounter::NtscPeriod;
}
}
const n8 APU::lengthCounterTable[32] = {
0x0a,0xfe,0x14,0x02,0x28,0x04,0x50,0x06,0xa0,0x08,0x3c,0x0a,0x0e,0x0c,0x1a,0x0e,
0x0c,0x10,0x18,0x12,0x30,0x14,0x60,0x16,0xc0,0x18,0x48,0x1a,0x10,0x1c,0x20,0x1e,
};
const n16 APU::noisePeriodTableNTSC[16] = {
4, 8, 16, 32, 64, 96, 128, 160, 202, 254, 380, 508, 762, 1016, 2034, 4068,
};
+89 -24
View File
@@ -1,4 +1,4 @@
struct APU {
struct APU : Thread {
Node::Object node;
Node::Audio::Stream stream;
@@ -9,6 +9,7 @@ struct APU {
auto unload() -> void;
auto main() -> void;
auto tick() -> void;
auto setIRQ() -> void;
auto power(bool reset) -> void;
@@ -19,6 +20,37 @@ struct APU {
//serialization.cpp
auto serialize(serializer&) -> void;
struct Length {
//length.cpp
auto main() -> void;
auto power(bool reset, bool isTriangle) -> void;
auto setEnable(n1 value) -> void;
auto setHalt(bool lengthClocking, n1 value) -> void;
auto setCounter(bool lengthClocking, n5 index) -> void;
//serialization.cpp
auto serialize(serializer&) -> void;
n8 counter;
n1 halt;
n1 enable;
bool delayHalt;
n1 newHalt;
bool delayCounter;
n5 counterIndex;
constexpr static u8 table[32] = {
0x0a, 0xfe, 0x14, 0x02, 0x28, 0x04, 0x50, 0x06,
0xa0, 0x08, 0x3c, 0x0a, 0x0e, 0x0c, 0x1a, 0x0e,
0x0c, 0x10, 0x18, 0x12, 0x30, 0x14, 0x60, 0x16,
0xc0, 0x18, 0x48, 0x1a, 0x10, 0x1c, 0x20, 0x1e,
};
};
struct Envelope {
//envelope.cpp
auto volume() const -> u32;
@@ -54,18 +86,18 @@ struct APU {
struct Pulse {
//pulse.cpp
auto clockLength() -> void;
auto checkPeriod() -> bool;
auto clock() -> n8;
auto power(bool reset) -> void;
//serialization.cpp
auto serialize(serializer&) -> void;
Length length;
Envelope envelope;
Sweep sweep;
n16 lengthCounter;
n16 periodCounter = 1;
n16 periodCounter;
n2 duty;
n3 dutyCounter;
n11 period;
@@ -73,38 +105,40 @@ struct APU {
struct Triangle {
//triangle.cpp
auto clockLength() -> void;
auto clockLinearLength() -> void;
auto clock() -> n8;
auto power(bool reset) -> void;
//serialization.cpp
auto serialize(serializer&) -> void;
n16 lengthCounter;
n16 periodCounter = 1;
Length length;
n16 periodCounter;
n8 linearLength;
n1 haltLengthCounter;
n11 period;
n5 stepCounter = 16;
n5 stepCounter;
n8 linearLengthCounter;
n1 reloadLinear;
} triangle;
struct Noise {
//noise.cpp
auto clockLength() -> void;
auto clock() -> n8;
auto power(bool reset) -> void;
//serialization.cpp
auto serialize(serializer&) -> void;
Length length;
Envelope envelope;
n16 lengthCounter;
n16 periodCounter = 1;
n16 periodCounter;
n4 period;
n1 shortMode;
n15 lfsr = 1;
n15 lfsr;
} noise;
struct DMC {
@@ -113,12 +147,15 @@ struct APU {
auto stop() -> void;
auto clock() -> n8;
auto power(bool reset) -> void;
auto setDMABuffer(n8 data) -> void;
auto dmaAddress() -> n16 const { return 0x8000 | readAddress; }
//serialization.cpp
auto serialize(serializer&) -> void;
n16 lengthCounter;
n16 periodCounter;
n16 dmaDelayCounter;
n1 irqPending;
n4 period;
n1 irqEnable;
@@ -132,31 +169,59 @@ struct APU {
n8 dmaBuffer;
n1 sampleValid;
n8 sample;
n8 dmaDelayCounter;
} dmc;
struct FrameCounter {
static constexpr u16 NtscPeriod = 14915; //~(21.477MHz / 6 / 240hz)
enum mode: u8 { Freq60Hz = 0, Freq48Hz = 1 };
auto getPeriod() const -> u16 {
return Region::PAL() ? periodPAL[mode][step] : periodNTSC[mode][step];
}
auto lengthClocking() const -> bool {
// Because the CPU writes before the APU clock,
// the counter must be 1
return counter == 1 && (step == 1 || step == 4);
}
auto main() -> void;
auto power(bool reset) -> void;
auto write(n8 data) -> void;
//serialization.cpp
auto serialize(serializer&) -> void;
n1 irqInhibit;
n1 mode;
n1 irqPending;
n2 mode;
n2 counter;
i32 divider = 1;
} frame;
n3 step;
n16 counter;
bool odd;
bool delay;
n3 delayCounter;
constexpr static u16 periodNTSC[2][6] = {
{ 7457, 7456, 7458, 7457, 1, 1, },
{ 7457, 7456, 7458, 7458, 7452, 1, },
};
constexpr static u16 periodPAL[2][6] = {
{ 8313, 8314, 8312, 8313, 1, 1, },
{ 8313, 8314, 8312, 8320, 8312, 1,},
};
};
//apu.cpp
auto clockFrameCounter() -> void;
auto clockFrameCounterDivider() -> void;
auto clockQuarterFrame() -> void;
auto clockHalfFrame() -> void;
n5 enabledChannels;
FrameCounter frame;
//unserialized:
u16 pulseDAC[32];
u16 dmcTriangleNoiseDAC[128][16][16];
static const n8 lengthCounterTable[32];
static const n16 dmcPeriodTableNTSC[16];
static const n16 dmcPeriodTablePAL[16];
static const n16 noisePeriodTableNTSC[16];
+43 -32
View File
@@ -2,44 +2,19 @@ auto APU::DMC::start() -> void {
if(lengthCounter == 0) {
readAddress = 0x4000 + (addressLatch << 6);
lengthCounter = (lengthLatch << 4) + 1;
if (!dmaBufferValid)
dmaDelayCounter = periodCounter & 1 ? 2 : 3;
}
}
auto APU::DMC::stop() -> void {
lengthCounter = 0;
dmaDelayCounter = 0;
cpu.rdyLine(1);
cpu.rdyAddress(false);
}
auto APU::DMC::clock() -> n8 {
n8 result = dacLatch;
if(dmaDelayCounter > 0) {
dmaDelayCounter--;
if(dmaDelayCounter == 1) {
cpu.rdyAddress(true, 0x8000 | readAddress);
} else if(dmaDelayCounter == 0) {
cpu.rdyLine(1);
cpu.rdyAddress(false);
dmaBuffer = cpu.MDR;
dmaBufferValid = true;
lengthCounter--;
readAddress++;
if(lengthCounter == 0) {
if(loopMode) {
start();
} else if(irqEnable) {
irqPending = true;
apu.setIRQ();
}
}
}
}
if(--periodCounter == 0) {
if(sampleValid) {
s32 delta = (((sample >> bitCounter) & 1) << 2) - 2;
@@ -52,6 +27,9 @@ auto APU::DMC::clock() -> n8 {
sampleValid = true;
sample = dmaBuffer;
dmaBufferValid = false;
if (lengthCounter > 0)
cpu.dmcDMAPending();
} else {
sampleValid = false;
}
@@ -60,10 +38,43 @@ auto APU::DMC::clock() -> n8 {
periodCounter = Region::PAL() ? dmcPeriodTablePAL[period] : dmcPeriodTableNTSC[period];
}
if(lengthCounter > 0 && !dmaBufferValid && dmaDelayCounter == 0) {
cpu.rdyLine(0);
dmaDelayCounter = 4;
}
if (dmaDelayCounter > 0 && --dmaDelayCounter == 0)
cpu.dmcDMAPending();
return result;
}
auto APU::DMC::power(bool reset) -> void {
lengthCounter = 0;
periodCounter = Region::PAL() ? dmcPeriodTablePAL[0] : dmcPeriodTableNTSC[0];
irqPending = false;
period = 0;
irqEnable = 0;
loopMode = 0;
dacLatch = 0;
addressLatch = 0;
lengthLatch = 0;
readAddress = 0;
bitCounter = 0;
dmaBufferValid = 0;
dmaBuffer = 0;
sampleValid = 0;
sample = 0;
}
auto APU::DMC::setDMABuffer(n8 data) -> void {
dmaBuffer = data;
dmaBufferValid = true;
lengthCounter--;
readAddress++;
if (lengthCounter == 0) {
if (loopMode) {
readAddress = 0x4000 + (addressLatch << 6);
lengthCounter = (lengthLatch << 4) + 1;
} else if (irqEnable) {
irqPending = true;
apu.setIRQ();
}
}
}
+82
View File
@@ -0,0 +1,82 @@
auto APU::FrameCounter::main() -> void {
--counter;
odd = !odd;
if (delay && --delayCounter == 0) {
delay = false;
step = 0;
counter = getPeriod() + 2;
if (mode == Freq48Hz) {
apu.clockHalfFrame();
}
}
if (counter != 0)
return;
switch(step) {
case 0:
step = 1;
apu.clockQuarterFrame();
break;
case 1:
step = 2;
apu.clockHalfFrame();
break;
case 2:
step = 3;
apu.clockQuarterFrame();
break;
case 3:
step = 4;
if (mode == Freq60Hz && irqInhibit == 0)
irqPending = 1;
break;
case 4:
step = 5;
apu.clockHalfFrame();
if (mode == Freq60Hz && irqInhibit == 0) {
irqPending = 1;
apu.setIRQ();
}
break;
case 5:
step = 0;
if (mode == Freq60Hz && irqInhibit == 0)
irqPending = 1;
break;
}
counter = getPeriod();
}
auto APU::FrameCounter::power(bool reset) -> void {
irqInhibit = 0;
if (!reset) mode = Freq60Hz;
irqPending = 0;
step = 0;
counter = getPeriod();
odd = true;
delay = false;
delayCounter = 0;
}
auto APU::FrameCounter::write(n8 data) -> void {
mode = data.bit(7);
delay = true;
// If the write occurs during an APU cycle,
// the effects occur 3 CPU cycles after the
// $4017 write cycle, and if the write occurs
// between APU cycles, the effects occurs 4 CPU
// cycles after the write cycle.
delayCounter = odd ? 1 : 2;
irqInhibit = data.bit(6);
if (irqInhibit) {
irqPending = 0;
apu.setIRQ();
}
}
+56
View File
@@ -0,0 +1,56 @@
auto APU::Length::main() -> void {
if (halt == 0 && counter)
counter--;
if (delayHalt) {
delayHalt = false;
halt = newHalt;
}
if (delayCounter) {
delayCounter = false;
if (counter == 0)
counter = table[counterIndex];
}
}
auto APU::Length::power(bool reset, bool isTriangle) -> void {
enable = 0;
if (!reset || !isTriangle) {
counter = 0;
halt = 0;
delayHalt = false;
newHalt = 0;
delayCounter = false;
counterIndex = 0;
}
}
auto APU::Length::setEnable(n1 value) -> void {
enable = value;
if (!enable)
counter = 0;
}
auto APU::Length::setHalt(bool lengthClocking, n1 value) -> void {
if (!lengthClocking) {
halt = value;
} else {
delayHalt = true;
newHalt = value;
}
}
auto APU::Length::setCounter(bool lengthClocking, n5 index) -> void {
if (enable) {
if (!lengthClocking)
counter = table[index];
else {
delayCounter = true;
counterIndex = index;
}
}
}
+11 -7
View File
@@ -1,11 +1,5 @@
auto APU::Noise::clockLength() -> void {
if(envelope.loopMode == 0) {
if(lengthCounter > 0) lengthCounter--;
}
}
auto APU::Noise::clock() -> n8 {
if(lengthCounter == 0) return 0;
if(length.counter == 0) return 0;
n8 result = (lfsr & 1) ? envelope.volume() : 0;
@@ -24,3 +18,13 @@ auto APU::Noise::clock() -> n8 {
return result;
}
auto APU::Noise::power(bool reset) -> void {
length.power(reset, false);
envelope = {};
periodCounter = 1;
period = 0;
shortMode = 0;
lfsr = 1;
}
+12 -7
View File
@@ -1,12 +1,6 @@
auto APU::Pulse::clockLength() -> void {
if(envelope.loopMode == 0) {
if(lengthCounter) lengthCounter--;
}
}
auto APU::Pulse::clock() -> n8 {
if(!sweep.checkPeriod()) return 0;
if(lengthCounter == 0) return 0;
if(length.counter == 0) return 0;
static constexpr u32 dutyTable[4][8] = {
{0, 0, 0, 0, 0, 0, 0, 1}, //12.5%
@@ -24,3 +18,14 @@ auto APU::Pulse::clock() -> n8 {
return result;
}
auto APU::Pulse::power(bool reset) -> void {
length.power(reset, false);
envelope = {};
sweep = {};
periodCounter = 1;
duty = 0;
dutyCounter = 0;
period = 0;
}
Loaded 100 of 5549 files, more files were not shown because too many files have changed in this diff. Show more