Compare commits

...
101 Commits
Author SHA1 Message Date
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 1bd36fb2cc Merge commit 'ad70fadc8edfcded08fd3f9a326d4760fe23958d' 2024-03-28 11:37:46 +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 69daac5356 Merge commit 'f7d6650c2622df1195b7103fc49d3d967cacc01b' 2024-03-28 11:37:40 +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 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 33a00d4da0 Merge commit '8b88e3093edf5f067ada42156d796bf785238726' 2024-02-25 12:22:29 +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 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
4074 changed files with 445323 additions and 12345 deletions

No files matched your search

+46 -13
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
@@ -87,6 +91,24 @@ jobs:
keychain-password: ${{ secrets.MACOS_KEYCHAIN_PASSWORD }}
- name: Checkout source code
uses: actions/checkout@v2
- 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
@@ -95,19 +117,22 @@ jobs:
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
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
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 +140,9 @@ jobs:
pushd thirdparty/MoltenVK
./build-moltenvk.sh
popd
pushd thirdparty/librashader
./build-librashader.sh
popd
- name: Set up MSVC environment
if: matrix.platform.msvc-arch != ''
uses: ilammy/msvc-dev-cmd@v1
@@ -185,9 +213,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 +316,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
@@ -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);
+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];
}
}
+10 -8
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;
}
+21 -10
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);
+68 -135
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 = {};
+41 -16
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 {
+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 = "138";
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; }
@@ -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;
}
}
+121 -69
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,80 +32,125 @@ 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;
@@ -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);
}
+1 -1
View File
@@ -36,6 +36,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 +44,6 @@ auto SH2::instruction() -> void {
step(CCR);
CCR = 0;
ID = 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);
}
@@ -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);
}
+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);
}
@@ -11,6 +11,7 @@ auto V30MZ::serialize(serializer& s) -> void {
s(modrm.mem);
s(modrm.segment);
s(modrm.address);
s(modrm.useAddress);
s(AW);
s(CW);
+3 -1
View File
@@ -51,7 +51,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;
@@ -251,6 +251,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;
+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,
};
+86 -23
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,6 +147,8 @@ struct APU {
auto stop() -> void;
auto clock() -> n8;
auto power(bool reset) -> void;
//serialization.cpp
auto serialize(serializer&) -> void;
@@ -135,28 +171,55 @@ struct APU {
} 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];
+20 -1
View File
@@ -24,7 +24,7 @@ auto APU::DMC::clock() -> n8 {
cpu.rdyLine(1);
cpu.rdyAddress(false);
dmaBuffer = cpu.MDR;
dmaBuffer = cpu.io.openBus;
dmaBufferValid = true;
lengthCounter--;
readAddress++;
@@ -67,3 +67,22 @@ auto APU::DMC::clock() -> n8 {
return result;
}
auto APU::DMC::power(bool reset) -> void {
lengthCounter = 0;
periodCounter = Region::PAL() ? dmcPeriodTablePAL[0] : dmcPeriodTableNTSC[0];
dmaDelayCounter = 0;
irqPending = 0;
period = 0;
irqEnable = 0;
loopMode = 0;
dacLatch = 0;
addressLatch = 0;
lengthLatch = 0;
readAddress = 0;
bitCounter = 0;
dmaBufferValid = 0;
dmaBuffer = 0;
sampleValid = 0;
sample = 0;
}
+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 = true;
delayCounter = 1;
}
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;
}
+24 -7
View File
@@ -1,10 +1,22 @@
auto APU::serialize(serializer& s) -> void {
Thread::serialize(s);
s(pulse1);
s(pulse2);
s(triangle);
s(dmc);
s(frame);
s(enabledChannels);
}
auto APU::Length::serialize(serializer& s) -> void {
s(counter);
s(halt);
s(enable);
s(delayHalt);
s(newHalt);
s(delayCounter);
s(counterIndex);
}
auto APU::Envelope::serialize(serializer& s) -> void {
@@ -29,7 +41,7 @@ auto APU::Sweep::serialize(serializer& s) -> void {
auto APU::Pulse::serialize(serializer& s) -> void {
s(envelope);
s(sweep);
s(lengthCounter);
s(length);
s(periodCounter);
s(duty);
s(dutyCounter);
@@ -37,10 +49,9 @@ auto APU::Pulse::serialize(serializer& s) -> void {
}
auto APU::Triangle::serialize(serializer& s) -> void {
s(lengthCounter);
s(length);
s(periodCounter);
s(linearLength);
s(haltLengthCounter);
s(period);
s(stepCounter);
s(linearLengthCounter);
@@ -49,7 +60,7 @@ auto APU::Triangle::serialize(serializer& s) -> void {
auto APU::Noise::serialize(serializer& s) -> void {
s(envelope);
s(lengthCounter);
s(length);
s(periodCounter);
s(period);
s(shortMode);
@@ -76,8 +87,14 @@ auto APU::DMC::serialize(serializer& s) -> void {
}
auto APU::FrameCounter::serialize(serializer& s) -> void {
s(irqPending);
s(irqInhibit);
s(mode);
s(irqPending);
s(step);
s(counter);
s(divider);
s(odd);
s(delay);
s(delayCounter);
}
+13 -8
View File
@@ -1,9 +1,3 @@
auto APU::Triangle::clockLength() -> void {
if(haltLengthCounter == 0) {
if(lengthCounter > 0) lengthCounter--;
}
}
auto APU::Triangle::clockLinearLength() -> void {
if(reloadLinear) {
linearLengthCounter = linearLength;
@@ -11,13 +5,13 @@ auto APU::Triangle::clockLinearLength() -> void {
linearLengthCounter--;
}
if(haltLengthCounter == 0) reloadLinear = false;
if(length.halt == 0) reloadLinear = false;
}
auto APU::Triangle::clock() -> n8 {
n8 result = stepCounter & 0x0f;
if((stepCounter & 0x10) == 0) result ^= 0x0f;
if(lengthCounter == 0 || linearLengthCounter == 0) return result;
if(length.counter == 0 || linearLengthCounter == 0) return result;
if(--periodCounter == 0) {
stepCounter++;
@@ -26,3 +20,14 @@ auto APU::Triangle::clock() -> n8 {
return result;
}
auto APU::Triangle::power(bool reset) -> void {
length.power(reset, true);
periodCounter = 1;
linearLength = 0;
period = 0;
stepCounter = 16;
linearLengthCounter = 0;
reloadLinear = 0;
}
+1
View File
@@ -19,6 +19,7 @@ struct BandaiFCG : Interface {
irqEnable = false;
}
}
tick();
}
auto readPRG(n32 address, n8 data) -> n8 override {
@@ -37,6 +37,7 @@ struct BandaiLZ93D50 : Interface {
irqEnable = false;
}
}
tick();
}
auto readPRG(n32 address, n8 data) -> n8 override {
+10
View File
@@ -117,6 +117,16 @@ auto Interface::create(string board) -> Interface* {
return p;
}
auto Interface::main() -> void {
cartridge.step(cartridge.rate() * 4095);
tick();
}
auto Interface::tick() -> void {
cartridge.step(cartridge.rate());
cartridge.synchronize(cpu);
}
auto Interface::load(Memory::Readable<n8>& memory, string name) -> bool {
if(auto fp = pak->read(name)) {
memory.allocate(fp->size(), 0xff);
+2 -1
View File
@@ -11,7 +11,8 @@ struct Interface {
virtual auto save() -> void {}
virtual auto unload() -> void {}
virtual auto main() -> void {}
virtual auto main() -> void;
virtual auto tick() -> void;
virtual auto readPRG(n32 address, n8 data) -> n8 { return data; }
virtual auto writePRG(n32 address, n8 data) -> void {}
+5 -3
View File
@@ -163,7 +163,7 @@ struct HVC_ExROM : Interface { //MMC5
pulse1.envelope.clock();
pulse2.clockLength();
pulse2.envelope.clock();
frameDivider += APU::FrameCounter::NtscPeriod;
frameDivider += 14915; // ~(21.477MHz / 6 / 240hz)
}
i32 output = 0;
@@ -172,6 +172,8 @@ struct HVC_ExROM : Interface { //MMC5
stream->frame(sclamp<16>(-output) / 32768.0);
cpu.irqLine((irqLine & irqEnable) || (pcm.irqLine & pcm.irqEnable) || timerLine);
tick();
}
auto scanline() -> void {
@@ -354,7 +356,7 @@ struct HVC_ExROM : Interface { //MMC5
pulse1.period.bit(8,10) = data.bit(0,2);
pulse1.dutyCounter = 0;
pulse1.envelope.reloadDecay = 1;
pulse1.lengthCounter = apu.lengthCounterTable[data.bit(3,7)];
pulse1.lengthCounter = APU::Length::table[data.bit(3,7)];
break;
case 0x5004:
@@ -375,7 +377,7 @@ struct HVC_ExROM : Interface { //MMC5
pulse2.period.bit(8,10) = data.bit(0,2);
pulse2.dutyCounter = 0;
pulse2.envelope.reloadDecay = 1;
pulse2.lengthCounter = apu.lengthCounterTable[data.bit(3,7)];
pulse2.lengthCounter = APU::Length::table[data.bit(3,7)];
break;
case 0x5010:
+1
View File
@@ -22,6 +22,7 @@ struct HVC_FMR : Interface {
auto main() -> void override {
fds.main();
tick();
}
auto readPRG(n32 address, n8 data) -> n8 override {
+1
View File
@@ -24,6 +24,7 @@ struct HVC_HKROM : Interface { //MMC6
auto main() -> void override {
if(irqDelay) irqDelay--;
cpu.irqLine(irqLine);
tick();
}
auto irqTest(n32 address) -> void {
+1
View File
@@ -90,6 +90,7 @@ struct HVC_SxROM : Interface { //MMC1
auto main() -> void override {
if(writeDelay) writeDelay--;
tick();
}
auto addressProgramROM(n32 address) -> n32 {
+1
View File
@@ -62,6 +62,7 @@ struct HVC_TxROM : Interface { //MMC3
auto main() -> void override {
if(irqDelay) irqDelay--;
cpu.irqLine(irqLine);
tick();
}
auto irqTest(n16 address) -> void {
+1
View File
@@ -17,6 +17,7 @@ struct IremH3001 : Interface {
if(irqCounter && --irqCounter == 0) irqLine = 1;
}
cpu.irqLine(irqLine);
tick();
}
auto readPRG(n32 address, n8 data) -> n8 override {
+1
View File
@@ -39,6 +39,7 @@ struct JalecoJF23 : Interface {
}
}
cpu.irqLine(irqLine);
tick();
}
auto readPRG(n32 address, n8 data) -> n8 override {
+1
View File
@@ -38,6 +38,7 @@ struct KonamiVRC3 : Interface {
}
}
cpu.irqLine(irqLine);
tick();
}
auto readPRG(n32 address, n8 data) -> n8 override {
+1
View File
@@ -47,6 +47,7 @@ struct KonamiVRC4 : Interface {
}
}
cpu.irqLine(irqLine);
tick();
}
auto readPRG(n32 address, n8 data) -> n8 override {
+1
View File
@@ -38,6 +38,7 @@ struct KonamiVRC5 : Interface {
cpu.irqLine(1);
}
}
tick();
}
//converts JIS X 0208 codepoint to CIRAM tile# + QTRAM bank#
+2
View File
@@ -134,6 +134,8 @@ struct KonamiVRC6 : Interface {
sawtooth.clock();
f64 output = (pulse1.output + pulse2.output + sawtooth.output) / 61.0 * 0.5;
stream->frame(-output);
tick();
}
auto addressPRG(n32 address) const -> n32 {
+2
View File
@@ -66,6 +66,8 @@ struct KonamiVRC7 : Interface {
if(!disableFM) sample = ym2413.clock();
stream->frame(sample);
}
tick();
}
auto readPRG(n32 address, n8 data) -> n8 override {
+2
View File
@@ -41,6 +41,8 @@ struct Namco163 : Interface {
double output = clockSound();
stream->frame(output / 255.0 * 0.5);
}
tick();
}
auto clockSound() -> double {
+1
View File
@@ -26,6 +26,7 @@ struct Sunsoft3 : Interface {
irqEnable = 0;
cpu.irqLine(1);
}
tick();
}
auto readPRG(n32 address, n8 data) -> n8 override {
+1
View File
@@ -28,6 +28,7 @@ struct Sunsoft4 : Interface {
auto main() -> void override {
if(optionTimer) optionTimer--;
tick();
}
auto readPRG(n32 address, n8 data) -> n8 override {
+2
View File
@@ -47,6 +47,8 @@ struct Sunsoft5B : Interface {
output += volume[channels[2]];
stream->frame(sclamp<16>(output * 1.5 * 32768.0) / 32768.0);
}
tick();
}
auto readPRG(n32 address, n8 data) -> n8 override {
+1
View File
@@ -16,6 +16,7 @@ struct TaitoTC0690 : Interface {
if(irqDelay) irqDelay--;
if(irqLineDelay && --irqLineDelay == 0) irqLine = 1;
cpu.irqLine(irqLine);
tick();
}
auto irqTest(n16 address) -> void {
+1
View File
@@ -47,6 +47,7 @@ auto Cartridge::save() -> void {
}
auto Cartridge::power() -> void {
Thread::create(system.frequency(), {&Cartridge::main, this});
board->power();
}
+1
View File
@@ -1,3 +1,4 @@
auto Cartridge::serialize(serializer& s) -> void {
Thread::serialize(s);
if(board) s(*board);
}
+1 -6
View File
@@ -25,7 +25,7 @@ auto CPU::unload() -> void {
auto CPU::main() -> void {
if(io.interruptPending) {
debugger.interrupt("IRQ");
return interrupt();
interrupt();
}
debugger.instruction();
@@ -34,8 +34,6 @@ auto CPU::main() -> void {
auto CPU::step(u32 clocks) -> void {
assert(clocks == rate());
apu.main();
cartridge.main();
Thread::step(clocks);
Thread::synchronize();
}
@@ -49,9 +47,6 @@ auto CPU::power(bool reset) -> void {
ram.fill(0xff);
}
PC.byte(0) = readBus(0xfffc);
PC.byte(1) = readBus(0xfffd);
io = {};
}
+4
View File
@@ -44,6 +44,9 @@ struct CPU : MOS6502, Thread {
auto read(n16 address) -> n8 override;
auto write(n16 address, n8 data) -> void override;
auto lastCycle() -> void override;
auto cancelNmi() -> void override;
auto delayIrq() -> void override;
auto irqPending() -> bool override;
auto nmi(n16& vector) -> void override;
auto oamDMA() -> void;
@@ -67,6 +70,7 @@ struct CPU : MOS6502, Thread {
n16 rdyAddressValue;
n1 oamDMAPending;
n8 oamDMAPage;
n8 openBus;
} io;
};
+2 -2
View File
@@ -8,7 +8,7 @@
inline auto CPU::readBus(n16 address) -> n8 {
if(auto result = platform->cheat(address)) return *result;
n8 data = cartridge.readPRG(address, MDR);
n8 data = cartridge.readPRG(address, io.openBus);
if(address <= 0x1fff) return ram.read(address);
if(address <= 0x3fff) return ppu.readIO(address);
if(address <= 0x4017) return cpu.readIO(address);
@@ -28,7 +28,7 @@ inline auto CPU::writeBus(n16 address, n8 data) -> void {
}
auto CPU::readIO(n16 address) -> n8 {
n8 data = MDR;
n8 data = io.openBus;
switch(address) {
Loaded 100 of 4074 files, more files were not shown because too many files have changed in this diff. Show more