NESEmulator/NES Emulator/bus.c

84 lines
1.6 KiB
C
Raw Normal View History

2021-10-20 20:39:29 +00:00
#include "bus.h"
#include <stdlib.h>
#include <stdio.h>
#include "cpu.h"
#include "cartridge.h"
struct Bus* createBus()
{
struct Bus* bus = (struct Bus*)malloc(sizeof(struct Bus));
if (bus == NULL)
{
fprintf(stderr, "Failed to create Bus object, aborting.");
exit(1);
}
// 2KB of memory, equates to 2048 Bytes (0x800)
bus->ram = (Byte*)malloc(0x800);
if (bus->ram == NULL)
{
fprintf(stderr, "Failed to allocate memory for NES RAM, aborting.");
exit(1);
}
// Create CPU and attach it
bus->cpu = createCPU(bus);
// Create and insert cartridge
2021-10-20 21:11:08 +00:00
bus->cartridge = createCartridge(bus, "roms/nestest.nes");
2021-10-20 20:39:29 +00:00
2021-10-20 21:23:16 +00:00
printf("Reset vector: $%x\n", ((Word)readCartridge(bus->cartridge, 0xFFFD) << 8) | (readCartridge(bus->cartridge, 0xFFFC)));
2021-10-20 20:39:29 +00:00
return bus;
}
void destroyBus(struct Bus* bus)
{
destroyCartridge(bus->cartridge);
destroyCPU(bus->cpu);
free(bus->ram);
free(bus);
}
2021-10-20 21:23:16 +00:00
Byte readBus(struct Bus* bus, Word addr)
2021-10-20 20:39:29 +00:00
{
2021-10-20 21:11:08 +00:00
Byte val = 0;
2021-10-20 20:39:29 +00:00
// Return from the appropriate device depending on the address
if (addr <= 0x1FFF) // RAM (or one of the mirrored addresses)
{
2021-10-20 21:11:08 +00:00
val = bus->ram[addr & 0x7FF];
2021-10-20 20:39:29 +00:00
}
else if (0x4020 <= addr && addr <= 0xFFFF) // Cartridge space
{
// rom->read()
}
else
{
fprintf(stderr, "Access violation at $%x", addr);
exit(1);
}
2021-10-20 21:11:08 +00:00
return val;
2021-10-20 20:39:29 +00:00
}
2021-10-20 21:23:16 +00:00
void writeBus(struct Bus* bus, Word addr, Byte val)
2021-10-20 20:39:29 +00:00
{
2021-10-20 21:23:16 +00:00
// writeCartridge to the appropriate memory or device
2021-10-20 20:39:29 +00:00
if (addr <= 0x1FFF) // RAM (or one of the mirrored addresses)
{
bus->ram[addr & 0x7FF] = val;
}
else if (0x4020 <= addr && addr <= 0xFFFF) // Cartridge space
{
// rom->write()
}
else
{
fprintf(stderr, "Access violation at $%x", addr);
exit(1);
}
}