eirexe

Untitled

Jul 4th, 2013
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 45.62 KB | None | 0 0
  1. /*
  2. === Howto: run ===
  3.  
  4. Run it using a sh file and launch it in gmenu2x.
  5. or use telnet/ssh
  6. Parameters:
  7. nesemu romname.nes inputspeedrun.fmv
  8.  
  9. ==================
  10. */
  11.  
  12. #include <stdint.h>
  13. #include <signal.h>
  14. #include <assert.h>
  15. #include <cmath>
  16.  
  17. #include <SDL.h>
  18. #include <vector>
  19.  
  20. /* NESEMU1 : EMULATOR FOR THE NINTENDO ENTERTAINMENT SYSTEM (R) ARCHITECTURE */
  21. /* originally written by and copyright (C) 2011 Joel Yliluoma - http://iki.fi/bisqwit/ */
  22. /* Ported to gcw0 by #[email protected] */
  23. /* Trademarks are owned by their respective owners. Lawyers love tautologies. */
  24.  
  25. static const char* inputfn = "input.fmv";
  26.  
  27. // Integer types
  28. typedef uint_least32_t u32;
  29. typedef uint_least16_t u16;
  30. typedef uint_least8_t u8;
  31. typedef int_least8_t s8;
  32.  
  33. // Bitfield utilities
  34. template<unsigned bitno, unsigned nbits=1, typename T=u8>
  35. struct RegBit
  36. {
  37. T data;
  38. enum { mask = (1u << nbits) - 1u };
  39. template<typename T2>
  40. RegBit& operator=(T2 val)
  41. {
  42. data = (data & ~(mask << bitno)) | ((nbits > 1 ? val & mask : !!val) << bitno);
  43. return *this;
  44. }
  45. operator unsigned() const { return (data >> bitno) & mask; }
  46. RegBit& operator++ () { return *this = *this + 1; }
  47. unsigned operator++ (int) { unsigned r = *this; ++*this; return r; }
  48. };
  49.  
  50. namespace IO
  51. {
  52. SDL_Surface *s;
  53. void Init()
  54. {
  55. SDL_Init(SDL_INIT_VIDEO);
  56. SDL_InitSubSystem(SDL_INIT_VIDEO);
  57. s = SDL_SetVideoMode(256, 240, 32,0);
  58. signal(SIGINT, SIG_DFL);
  59. }
  60.  
  61. void PutPixel(unsigned px,unsigned py, unsigned pixel, int offset)
  62. {
  63. // The input value is a NES color index (with de-emphasis bits).
  64. // We need RGB values. To produce a RGB value, we emulate the NTSC circuitry.
  65. // For most part, this process is described at:
  66. // http://wiki.nesdev.com/w/index.php/NTSC_video
  67. // Incidentally, this code is shorter than a table of 64*8 RGB values.
  68. static unsigned palette[3][64][512] = {}, prev=~0u;
  69. // Caching the generated colors
  70. if(prev == ~0u)
  71. for(int o=0; o<3; ++o)
  72. for(int u=0; u<3; ++u)
  73. for(int p0=0; p0<512; ++p0)
  74. for(int p1=0; p1<64; ++p1)
  75. {
  76. // Calculate the luma and chroma by emulating the relevant circuits:
  77. auto s = "\372\273\32\305\35\311I\330D\357}\13D!}N";
  78. int y=0, i=0, q=0;
  79. for(int p=0; p<12; ++p) // 12 samples of NTSC signal constitute a color.
  80. {
  81. // Sample either the previous or the current pixel.
  82. int r = (p+o*4)%12, pixel = r < 8-u*2 ? p0 : p1; // Use pixel=p0 to disable artifacts.
  83. // Decode the color index.
  84. int c = pixel%16, l = c<0xE ? pixel/4 & 12 : 4, e=p0/64;
  85. // NES NTSC modulator (square wave between up to four voltage levels):
  86. int b = 40 + s[(c > 12*((c+8+p)%12 < 6)) + 2*!(0451326 >> p/2*3 & e) + l];
  87. // Ideal TV NTSC demodulator:
  88. y += b;
  89. i += b * int(std::cos(M_PI * p / 6) * 5909);
  90. q += b * int(std::sin(M_PI * p / 6) * 5909);
  91. }
  92. // Convert the YIQ color into RGB
  93. auto gammafix = [=](float f) { return f <= 0.f ? 0.f : std::pow(f, 2.2f / 1.8f); };
  94. auto clamp = [](int v) { return v>255 ? 255 : v; };
  95. // Store color at subpixel precision
  96. if(u==2) palette[o][p1][p0] += 0x10000*clamp(255 * gammafix(y/1980.f + i* 0.947f/9e6f + q* 0.624f/9e6f));
  97. if(u==1) palette[o][p1][p0] += 0x00100*clamp(255 * gammafix(y/1980.f + i*-0.275f/9e6f + q*-0.636f/9e6f));
  98. if(u==0) palette[o][p1][p0] += 0x00001*clamp(255 * gammafix(y/1980.f + i*-1.109f/9e6f + q* 1.709f/9e6f));
  99. }
  100. // Store the RGB color into the frame buffer.
  101. ((u32*) s->pixels) [py * 256 + px] = palette[offset][prev%64][pixel];
  102. prev = pixel;
  103. }
  104. void FlushScanline(unsigned py)
  105. {
  106. if(py == 239) SDL_Flip(s);
  107. }
  108.  
  109. int joy_current[2]={0,0}, joy_next[2]={0,0}, joypos[2]={0,0};
  110. void JoyStrobe(unsigned v)
  111. {
  112. if(v) { joy_current[0] = joy_next[0]; joypos[0]=0; }
  113. if(v) { joy_current[1] = joy_next[1]; joypos[1]=0; }
  114. }
  115. u8 JoyRead(unsigned idx)
  116. {
  117. static const u8 masks[8] = {0x20,0x10,0x40,0x80,0x04,0x08,0x02,0x01};
  118. return ((joy_current[idx] & masks[joypos[idx]++ & 7]) ? 1 : 0);
  119. }
  120. }
  121.  
  122. namespace GamePak
  123. {
  124. std::vector<u8> ROM, VRAM(0x2000);
  125. unsigned mappernum;
  126. const unsigned VROM_Granularity = 0x0400, VROM_Pages = 0x2000 / VROM_Granularity;
  127. const unsigned ROM_Granularity = 0x2000, ROM_Pages = 0x10000 / ROM_Granularity;
  128. unsigned char NRAM[0x1000], PRAM[0x2000];
  129. unsigned char* banks[ROM_Pages] = {};
  130. unsigned char* Vbanks[VROM_Pages] = {};
  131. unsigned char *Nta[4] = { NRAM+0x0000, NRAM+0x0400, NRAM+0x0000, NRAM+0x0400 };
  132.  
  133. template<unsigned npages,unsigned char*(&b)[npages], std::vector<u8>& r, unsigned granu>
  134. static void SetPages(unsigned size, unsigned baseaddr, unsigned index)
  135. {
  136. for(unsigned v = r.size() + index * size,
  137. p = baseaddr / granu;
  138. p < (baseaddr + size) / granu && p < npages;
  139. ++p, v += granu)
  140. b[p] = &r[v % r.size()];
  141. }
  142. auto& SetROM = SetPages< ROM_Pages, banks, ROM, ROM_Granularity>;
  143. auto& SetVROM = SetPages<VROM_Pages,Vbanks,VRAM,VROM_Granularity>;
  144.  
  145. u8 Access(unsigned addr, u8 value, bool write)
  146. {
  147. if(write && addr >= 0x8000 && mappernum == 7) // e.g. Rare games
  148. {
  149. SetROM(0x8000, 0x8000, (value&7));
  150. Nta[0] = Nta[1] = Nta[2] = Nta[3] = &NRAM[0x400 * ((value>>4)&1)];
  151. }
  152. if(write && addr >= 0x8000 && mappernum == 2) // e.g. Rockman, Castlevania
  153. {
  154. SetROM(0x4000, 0x8000, value);
  155. }
  156. if(write && addr >= 0x8000 && mappernum == 3) // e.g. Kage, Solomon's Key
  157. {
  158. value &= Access(addr,0,false); // Simulate bus conflict
  159. SetVROM(0x2000, 0x0000, (value&3));
  160. }
  161. if(write && addr >= 0x8000 && mappernum == 1) // e.g. Rockman 2, Simon's Quest
  162. {
  163. static u8 regs[4]={0x0C,0,0,0}, counter=0, cache=0;
  164. if(value & 0x80) { regs[0]=0x0C; goto configure; }
  165. cache |= (value&1) << counter;
  166. if(++counter == 5)
  167. {
  168. regs[ (addr>>13) & 3 ] = value = cache;
  169. configure:
  170. cache = counter = 0;
  171. static const u8 sel[4][4] = { {0,0,0,0}, {1,1,1,1}, {0,1,0,1}, {0,0,1,1} };
  172. for(unsigned m=0; m<4; ++m) Nta[m] = &NRAM[0x400 * sel[regs[0]&3][m]];
  173. SetVROM(0x1000, 0x0000, ((regs[0]&16) ? regs[1] : ((regs[1]&~1)+0)));
  174. SetVROM(0x1000, 0x1000, ((regs[0]&16) ? regs[2] : ((regs[1]&~1)+1)));
  175. switch( (regs[0]>>2)&3 )
  176. {
  177. case 0: case 1:
  178. SetROM(0x8000, 0x8000, (regs[3] & 0xE) / 2);
  179. break;
  180. case 2:
  181. SetROM(0x4000, 0x8000, 0);
  182. SetROM(0x4000, 0xC000, (regs[3] & 0xF));
  183. break;
  184. case 3:
  185. SetROM(0x4000, 0x8000, (regs[3] & 0xF));
  186. SetROM(0x4000, 0xC000, ~0);
  187. break;
  188. }
  189. }
  190. }
  191. if( (addr >> 13) == 3 ) return PRAM[addr & 0x1FFF ];
  192. return banks[ (addr / ROM_Granularity) % ROM_Pages] [addr % ROM_Granularity];
  193. }
  194. void Init()
  195. {
  196. SetVROM(0x2000, 0x0000, 0);
  197. for(unsigned v=0; v<4; ++v) SetROM(0x4000, v*0x4000, v==3 ? -1 : 0);
  198. }
  199. }
  200.  
  201. namespace CPU /* CPU: Ricoh RP2A03 (based on MOS6502, almost the same as in Commodore 64) */
  202. {
  203. u8 RAM[0x800];
  204. bool reset=true, nmi=false, nmi_edge_detected=false, intr=false;
  205.  
  206. template<bool write> u8 MemAccess(u16 addr, u8 v=0);
  207. u8 RB(u16 addr) { return MemAccess<0>(addr); }
  208. u8 WB(u16 addr,u8 v) { return MemAccess<1>(addr, v); }
  209. void tick();
  210. }
  211.  
  212. namespace PPU /* Picture Processing Unit */
  213. {
  214. union regtype // PPU register file
  215. {
  216. u32 value;
  217. // Reg0 (write) // Reg1 (write) // Reg2 (read)
  218. RegBit<0,8,u32> sysctrl; RegBit< 8,8,u32> dispctrl; RegBit<16,8,u32> status;
  219. RegBit<0,2,u32> BaseNTA; RegBit< 8,1,u32> Grayscale; RegBit<21,1,u32> SPoverflow;
  220. RegBit<2,1,u32> Inc; RegBit< 9,1,u32> ShowBG8; RegBit<22,1,u32> SP0hit;
  221. RegBit<3,1,u32> SPaddr; RegBit<10,1,u32> ShowSP8; RegBit<23,1,u32> InVBlank;
  222. RegBit<4,1,u32> BGaddr; RegBit<11,1,u32> ShowBG; // Reg3 (write)
  223. RegBit<5,1,u32> SPsize; RegBit<12,1,u32> ShowSP; RegBit<24,8,u32> OAMaddr;
  224. RegBit<6,1,u32> SlaveFlag; RegBit<11,2,u32> ShowBGSP; RegBit<24,2,u32> OAMdata;
  225. RegBit<7,1,u32> NMIenabled; RegBit<13,3,u32> EmpRGB; RegBit<26,6,u32> OAMindex;
  226. } reg;
  227. // Raw memory data as read&written by the game
  228. u8 palette[32], OAM[256];
  229. // Decoded sprite information, used & changed during each scanline
  230. struct { u8 sprindex, y, index, attr, x; u16 pattern; } OAM2[8], OAM3[8];
  231.  
  232. union scrolltype
  233. {
  234. RegBit<3,16,u32> raw; // raw VRAM address (16-bit)
  235. RegBit<0, 8,u32> xscroll; // low 8 bits of first write to 2005
  236. RegBit<0, 3,u32> xfine; // low 3 bits of first write to 2005
  237. RegBit<3, 5,u32> xcoarse; // high 5 bits of first write to 2005
  238. RegBit<8, 5,u32> ycoarse; // high 5 bits of second write to 2005
  239. RegBit<13,2,u32> basenta; // nametable index (copied from 2000)
  240. RegBit<13,1,u32> basenta_h; // horizontal nametable index
  241. RegBit<14,1,u32> basenta_v; // vertical nametable index
  242. RegBit<15,3,u32> yfine; // low 3 bits of second write to 2005
  243. RegBit<11,8,u32> vaddrhi; // first write to 2006 (with high 2 bits set to zero)
  244. RegBit<3, 8,u32> vaddrlo; // second write to 2006
  245. } scroll, vaddr;
  246.  
  247. unsigned pat_addr, sprinpos, sproutpos, sprrenpos, sprtmp;
  248. u16 tileattr, tilepat, ioaddr;
  249. u32 bg_shift_pat, bg_shift_attr;
  250.  
  251. int scanline=241, x=0, scanline_end=341, VBlankState=0, cycle_counter=0;
  252. int read_buffer=0, open_bus=0, open_bus_decay_timer=0;
  253. bool even_odd_toggle=false, offset_toggle=false;
  254.  
  255. /* Memory mapping: Convert PPU memory address into a reference to relevant data */
  256. u8& mmap(int i)
  257. {
  258. i &= 0x3FFF;
  259. if(i >= 0x3F00) { if(i%4==0) i &= 0x0F; return palette[i & 0x1F]; }
  260. if(i < 0x2000) return GamePak::Vbanks[(i / GamePak::VROM_Granularity) % GamePak::VROM_Pages]
  261. [ i % GamePak::VROM_Granularity];
  262. return GamePak::Nta[ (i>>10)&3][i&0x3FF];
  263. }
  264. // External I/O: read or write
  265. u8 Access(u16 index, u8 v, bool write)
  266. {
  267. auto RefreshOpenBus = [&](u8 v) { return open_bus_decay_timer = 77777, open_bus = v; };
  268. u8 res = open_bus;
  269. if(write) RefreshOpenBus(v);
  270. switch(index) // Which port from $200x?
  271. {
  272. case 0: if(write) { reg.sysctrl = v; scroll.basenta = reg.BaseNTA; } break;
  273. case 1: if(write) { reg.dispctrl = v; } break;
  274. case 2: if(write) break;
  275. res = reg.status | (open_bus & 0x1F);
  276. reg.InVBlank = false; // Reading $2002 clears the vblank flag.
  277. offset_toggle = false; // Also resets the toggle for address updates.
  278. if(VBlankState != -5)
  279. VBlankState = 0; // This also may cancel the setting of InVBlank.
  280. break;
  281. case 3: if(write) reg.OAMaddr = v; break; // Index into Object Attribute Memory
  282. case 4: if(write) OAM[reg.OAMaddr++] = v; // Write or read the OAM (sprites).
  283. else res = RefreshOpenBus(OAM[reg.OAMaddr] & (reg.OAMdata==2 ? 0xE3 : 0xFF));
  284. break;
  285. case 5: if(!write) break; // Set background scrolling offset
  286. if(offset_toggle) { scroll.yfine = v & 7; scroll.ycoarse = v >> 3; }
  287. else { scroll.xscroll = v; }
  288. offset_toggle = !offset_toggle;
  289. break;
  290. case 6: if(!write) break; // Set video memory position for reads/writes
  291. if(offset_toggle) { scroll.vaddrlo = v; vaddr.raw = (unsigned) scroll.raw; }
  292. else { scroll.vaddrhi = v & 0x3F; }
  293. offset_toggle = !offset_toggle;
  294. break;
  295. case 7:
  296. res = read_buffer;
  297. u8& t = mmap(vaddr.raw); // Access the video memory.
  298. if(write) res = t = v;
  299. else { if((vaddr.raw & 0x3F00) == 0x3F00) // palette?
  300. res = read_buffer = (open_bus & 0xC0) | (t & 0x3F);
  301. read_buffer = t; }
  302. RefreshOpenBus(res);
  303. vaddr.raw = vaddr.raw + (reg.Inc ? 32 : 1); // The address is automatically updated.
  304. break;
  305. }
  306. return res;
  307. }
  308. void rendering_tick()
  309. {
  310. bool tile_decode_mode = 0x10FFFF & (1u << (x/16)); // When x is 0..255, 320..335
  311.  
  312. // Each action happens in two steps: 1) select memory address; 2) receive data and react on it.
  313. switch(x % 8)
  314. {
  315. case 2: // Point to attribute table
  316. ioaddr = 0x23C0 + 0x400*vaddr.basenta + 8*(vaddr.ycoarse/4) + (vaddr.xcoarse/4);
  317. if(tile_decode_mode) break; // Or nametable, with sprites.
  318. case 0: // Point to nametable
  319. ioaddr = 0x2000 + (vaddr.raw & 0xFFF);
  320. // Reset sprite data
  321. if(x == 0) { sprinpos = sproutpos = 0; if(reg.ShowSP) reg.OAMaddr = 0; }
  322. if(!reg.ShowBG) break;
  323. // Reset scrolling (vertical once, horizontal each scanline)
  324. if(x == 304 && scanline == -1) vaddr.raw = (unsigned) scroll.raw;
  325. if(x == 256) { vaddr.xcoarse = (unsigned)scroll.xcoarse;
  326. vaddr.basenta_h = (unsigned)scroll.basenta_h;
  327. sprrenpos = 0; }
  328. break;
  329. case 1:
  330. if(x == 337 && scanline == -1 && even_odd_toggle && reg.ShowBG) scanline_end = 340;
  331. // Name table access
  332. pat_addr = 0x1000*reg.BGaddr + 16*mmap(ioaddr) + vaddr.yfine;
  333. if(!tile_decode_mode) break;
  334. // Push the current tile into shift registers.
  335. // The bitmap pattern is 16 bits, while the attribute is 2 bits, repeated 8 times.
  336. bg_shift_pat = (bg_shift_pat >> 16) + 0x00010000 * tilepat;
  337. bg_shift_attr = (bg_shift_attr >> 16) + 0x55550000 * tileattr;
  338. break;
  339. case 3:
  340. // Attribute table access
  341. if(tile_decode_mode)
  342. {
  343. tileattr = (mmap(ioaddr) >> ((vaddr.xcoarse&2) + 2*(vaddr.ycoarse&2))) & 3;
  344. // Go to the next tile horizontally (and switch nametable if it wraps)
  345. if(!++vaddr.xcoarse) { vaddr.basenta_h = 1-vaddr.basenta_h; }
  346. // At the edge of the screen, do the same but vertically
  347. if(x==251 && !++vaddr.yfine && ++vaddr.ycoarse == 30)
  348. { vaddr.ycoarse = 0; vaddr.basenta_v = 1-vaddr.basenta_v; }
  349. }
  350. else if(sprrenpos < sproutpos)
  351. {
  352. // Select sprite pattern instead of background pattern
  353. auto& o = OAM3[sprrenpos]; // Sprite to render on next scanline
  354. memcpy(&o, &OAM2[sprrenpos], sizeof(o));
  355. unsigned y = (scanline) - o.y;
  356. if(o.attr & 0x80) y ^= (reg.SPsize ? 15 : 7);
  357. pat_addr = 0x1000 * (reg.SPsize ? (o.index & 0x01) : reg.SPaddr);
  358. pat_addr += 0x10 * (reg.SPsize ? (o.index & 0xFE) : (o.index & 0xFF));
  359. pat_addr += (y&7) + (y&8)*2;
  360. }
  361. break;
  362. // Pattern table bytes
  363. case 5:
  364. tilepat = mmap(pat_addr|0);
  365. break;
  366. case 7: // Interleave the bits of the two pattern bytes
  367. unsigned p = tilepat | (mmap(pat_addr|8) << 8);
  368. p = (p&0xF00F) | ((p&0x0F00)>>4) | ((p&0x00F0)<<4);
  369. p = (p&0xC3C3) | ((p&0x3030)>>2) | ((p&0x0C0C)<<2);
  370. p = (p&0x9999) | ((p&0x4444)>>1) | ((p&0x2222)<<1);
  371. tilepat = p;
  372. // When decoding sprites, save the sprite graphics and move to next sprite
  373. if(!tile_decode_mode && sprrenpos < sproutpos)
  374. OAM3[sprrenpos++].pattern = tilepat;
  375. break;
  376. }
  377. // Find which sprites are visible on next scanline (TODO: implement crazy 9-sprite malfunction)
  378. switch(x>=64 && x<256 && x%2 ? (reg.OAMaddr++ & 3) : 4)
  379. {
  380. default:
  381. // Access OAM (object attribute memory)
  382. sprtmp = OAM[reg.OAMaddr];
  383. break;
  384. case 0:
  385. if(sprinpos >= 64) { reg.OAMaddr=0; break; }
  386. ++sprinpos; // next sprite
  387. if(sproutpos<8) OAM2[sproutpos].y = sprtmp;
  388. if(sproutpos<8) OAM2[sproutpos].sprindex = reg.OAMindex;
  389. {int y1 = sprtmp, y2 = sprtmp + (reg.SPsize?16:8);
  390. if(!( scanline >= y1 && scanline < y2 ))
  391. reg.OAMaddr = sprinpos != 2 ? reg.OAMaddr+3 : 8;}
  392. break;
  393. case 1:
  394. if(sproutpos<8) OAM2[sproutpos].index = sprtmp;
  395. break;
  396. case 2:
  397. if(sproutpos<8) OAM2[sproutpos].attr = sprtmp;
  398. break;
  399. case 3:
  400. if(sproutpos<8) OAM2[sproutpos].x = sprtmp;
  401. if(sproutpos<8) ++sproutpos; else reg.SPoverflow = true;
  402. if(sprinpos == 2) reg.OAMaddr = 8;
  403. break;
  404. }
  405. }
  406. void render_pixel()
  407. {
  408. bool edge = u8(x+8) < 16; // 0..7, 248..255
  409. bool showbg = reg.ShowBG && (!edge || reg.ShowBG8);
  410. bool showsp = reg.ShowSP && (!edge || reg.ShowSP8);
  411.  
  412. // Render the background
  413. unsigned fx = scroll.xfine, xpos = 15 - (( (x&7) + fx + 8*!!(x&7) ) & 15);
  414.  
  415. unsigned pixel = 0, attr = 0;
  416. if(showbg) // Pick a pixel from the shift registers
  417. {
  418. pixel = (bg_shift_pat >> (xpos*2)) & 3;
  419. attr = (bg_shift_attr >> (xpos*2)) & (pixel ? 3 : 0);
  420. }
  421. else if( (vaddr.raw & 0x3F00) == 0x3F00 && !reg.ShowBGSP )
  422. pixel = vaddr.raw;
  423.  
  424. // Overlay the sprites
  425. if(showsp)
  426. for(unsigned sno=0; sno<sprrenpos; ++sno)
  427. {
  428. auto& s = OAM3[sno];
  429. // Check if this sprite is horizontally in range
  430. unsigned xdiff = x - s.x;
  431. if(xdiff >= 8) continue; // Also matches negative values
  432. // Determine which pixel to display; skip transparent pixels
  433. if(!(s.attr & 0x40)) xdiff = 7-xdiff;
  434. u8 spritepixel = (s.pattern >> (xdiff*2)) & 3;
  435. if(!spritepixel) continue;
  436. // Register sprite-0 hit if applicable
  437. if(x < 255 && pixel && s.sprindex == 0) reg.SP0hit = true;
  438. // Render the pixel unless behind-background placement wanted
  439. if(!(s.attr & 0x20) || !pixel)
  440. {
  441. attr = (s.attr & 3) + 4;
  442. pixel = spritepixel;
  443. }
  444. // Only process the first non-transparent sprite pixel.
  445. break;
  446. }
  447. pixel = palette[ (attr*4 + pixel) & 0x1F ] & (reg.Grayscale ? 0x30 : 0x3F);
  448. IO::PutPixel(x, scanline, pixel | (reg.EmpRGB << 6), cycle_counter);
  449. }
  450.  
  451. // PPU::tick() -- This function is called 3 times per each CPU cycle.
  452. // Each call iterates through one pixel of the screen.
  453. // The screen is divided into 262 scanlines, each having 341 columns, as such:
  454. //
  455. // x=0 x=256 x=340
  456. // ___|____________________|__________|
  457. // y=-1 | pre-render scanline| prepare | >
  458. // ___|____________________| sprites _| > Graphics
  459. // y=0 | visible area | for the | > processing
  460. // | - this is rendered | next | > scanlines
  461. // y=239 | on the screen. | scanline | >
  462. // ___|____________________|______
  463. // y=240 | idle
  464. // ___|_______________________________
  465. // y=241 | vertical blanking (idle)
  466. // | 20 scanlines long
  467. // y=260___|____________________|__________|
  468. //
  469. // On actual PPU, the scanline begins actually before x=0, with
  470. // sync/colorburst/black/background color being rendered, and
  471. // ends after x=256 with background/black being rendered first,
  472. // but in this emulator we only care about the visible area.
  473. //
  474. // When background rendering is enabled, scanline -1 is
  475. // 340 or 341 pixels long, alternating each frame.
  476. // In all other situations the scanline is 341 pixels long.
  477. // Thus, it takes 89341 or 89342 PPU::tick() calls to render 1 frame.
  478. void tick()
  479. {
  480. // Set/clear vblank where needed
  481. switch(VBlankState)
  482. {
  483. case -5: reg.status = 0; break;
  484. case 2: reg.InVBlank = true; break;
  485. case 0: CPU::nmi = reg.InVBlank && reg.NMIenabled; break;
  486. }
  487. if(VBlankState != 0) VBlankState += (VBlankState < 0 ? 1 : -1);
  488. if(open_bus_decay_timer) if(!--open_bus_decay_timer) open_bus = 0;
  489.  
  490. // Graphics processing scanline?
  491. if(scanline < 240)
  492. {
  493. /* Process graphics for this cycle */
  494. if(reg.ShowBGSP) rendering_tick();
  495. if(scanline >= 0 && x < 256) render_pixel();
  496. }
  497.  
  498. // Done with the cycle. Check for end of scanline.
  499. if(++cycle_counter == 3) cycle_counter = 0; // For NTSC pixel shifting
  500. if(++x >= scanline_end)
  501. {
  502. // Begin new scanline
  503. IO::FlushScanline(scanline);
  504. scanline_end = 341;
  505. x = 0;
  506. // Does something special happen on the new scanline?
  507. switch(scanline += 1)
  508. {
  509. case 261: // Begin of rendering
  510. scanline = -1; // pre-render line
  511. even_odd_toggle = !even_odd_toggle;
  512. // Clear vblank flag
  513. VBlankState = -5;
  514. break;
  515. case 241: // Begin of vertical blanking
  516. // I cheat here: I did not bother to learn how to use SDL events,
  517. // so I simply read button presses from a movie file, which happens
  518. // to be a TAS, rather than from the keyboard or from a joystick.
  519. static FILE* fp = fopen(inputfn, "rb");
  520. if(fp)
  521. {
  522. static unsigned ctrlmask = 0;
  523. if(!ftell(fp))
  524. {
  525. fseek(fp, 0x05, SEEK_SET);
  526. ctrlmask = fgetc(fp);
  527. fseek(fp, 0x90, SEEK_SET); // Famtasia Movie format.
  528. }
  529. if(ctrlmask & 0x80) { IO::joy_next[0] = fgetc(fp); if(feof(fp)) IO::joy_next[0] = 0; }
  530. if(ctrlmask & 0x40) { IO::joy_next[1] = fgetc(fp); if(feof(fp)) IO::joy_next[1] = 0; }
  531. }
  532. // Set vblank flag
  533. VBlankState = 2;
  534. }
  535. }
  536. }
  537. }
  538.  
  539. namespace APU /* Audio Processing Unit */
  540. {
  541. static const u8 LengthCounters[32] = { 10,254,20, 2,40, 4,80, 6,160, 8,60,10,14,12,26,14,
  542. 12, 16,24,18,48,20,96,22,192,24,72,26,16,28,32,30 };
  543. static const u16 NoisePeriods[16] = { 2,4,8,16,32,48,64,80,101,127,190,254,381,508,1017,2034 };
  544. static const u16 DMCperiods[16] = { 428,380,340,320,286,254,226,214,190,160,142,128,106,84,72,54 };
  545.  
  546. bool FiveCycleDivider = false, IRQdisable = true, ChannelsEnabled[5] = { false };
  547. bool PeriodicIRQ = false, DMC_IRQ = false;
  548. bool count(int& v, int reset) { return --v < 0 ? (v=reset),true : false; }
  549.  
  550. struct channel
  551. {
  552. int length_counter, linear_counter, address, envelope;
  553. int sweep_delay, env_delay, wave_counter, hold, phase, level;
  554. union // Per-channel register file
  555. {
  556. // 4000, 4004, 400C, 4012: // 4001, 4005, 4013: // 4002, 4006, 400A, 400E:
  557. RegBit<0,8,u32> reg0; RegBit< 8,8,u32> reg1; RegBit<16,8,u32> reg2;
  558. RegBit<6,2,u32> DutyCycle; RegBit< 8,3,u32> SweepShift; RegBit<16,4,u32> NoiseFreq;
  559. RegBit<4,1,u32> EnvDecayDisable; RegBit<11,1,u32> SweepDecrease; RegBit<23,1,u32> NoiseType;
  560. RegBit<0,4,u32> EnvDecayRate; RegBit<12,3,u32> SweepRate; RegBit<16,11,u32> WaveLength;
  561. RegBit<5,1,u32> EnvDecayLoopEnable; RegBit<15,1,u32> SweepEnable; // 4003, 4007, 400B, 400F, 4010:
  562. RegBit<0,4,u32> FixedVolume; RegBit< 8,8,u32> PCMlength; RegBit<24,8,u32> reg3;
  563. RegBit<5,1,u32> LengthCounterDisable; RegBit<27,5,u32> LengthCounterInit;
  564. RegBit<0,7,u32> LinearCounterInit; RegBit<30,1,u32> LoopEnabled;
  565. RegBit<7,1,u32> LinearCounterDisable; RegBit<31,1,u32> IRQenable;
  566. } reg;
  567.  
  568. // Function for updating the wave generators and taking the sample for each channel.
  569. template<unsigned c>
  570. int tick()
  571. {
  572. channel& ch = *this;
  573. if(!ChannelsEnabled[c]) return c==4 ? 64 : 8;
  574. int wl = (ch.reg.WaveLength+1) * (c >= 2 ? 1 : 2);
  575. if(c == 3) wl = NoisePeriods[ ch.reg.NoiseFreq ];
  576. int volume = ch.length_counter ? ch.reg.EnvDecayDisable ? ch.reg.FixedVolume : ch.envelope : 0;
  577. // Sample may change at wavelen intervals.
  578. auto& S = ch.level;
  579. if(!count(ch.wave_counter, wl)) return S;
  580. switch(c)
  581. {
  582. default:// Square wave. With four different 8-step binary waveforms (32 bits of data total).
  583. if(wl < 8) return S = 8;
  584. return S = (0xF33C0C04u & (1u << (++ch.phase % 8 + ch.reg.DutyCycle * 8))) ? volume : 0;
  585.  
  586. case 2: // Triangle wave
  587. if(ch.length_counter && ch.linear_counter && wl >= 3) ++ch.phase;
  588. return S = (ch.phase & 15) ^ ((ch.phase & 16) ? 15 : 0);
  589.  
  590. case 3: // Noise: Linear feedback shift register
  591. if(!ch.hold) ch.hold = 1;
  592. ch.hold = (ch.hold >> 1)
  593. | (((ch.hold ^ (ch.hold >> (ch.reg.NoiseType ? 6 : 1))) & 1) << 14);
  594. return S = (ch.hold & 1) ? 0 : volume;
  595.  
  596. case 4: // Delta modulation channel (DMC)
  597. // hold = 8 bit value, phase = number of bits buffered
  598. if(ch.phase == 0) // Nothing in sample buffer?
  599. {
  600. if(!ch.length_counter && ch.reg.LoopEnabled) // Loop?
  601. {
  602. ch.length_counter = ch.reg.PCMlength*16 + 1;
  603. ch.address = (ch.reg.reg0 | 0x300) << 6;
  604. }
  605. if(ch.length_counter > 0) // Load next 8 bits if available
  606. {
  607. // Note: Re-entrant! But not recursive, because even
  608. // the shortest wave length is greater than the read time.
  609. // TODO: proper clock
  610. if(ch.reg.WaveLength>20)
  611. for(unsigned t=0; t<3; ++t) CPU::RB(u16(ch.address) | 0x8000); // timing
  612. ch.hold = CPU::RB(u16(ch.address++) | 0x8000); // Fetch byte
  613. ch.phase = 8;
  614. --ch.length_counter;
  615. }
  616. else // Otherwise, disable channel or issue IRQ
  617. ChannelsEnabled[4] = ch.reg.IRQenable && (CPU::intr = DMC_IRQ = true);
  618. }
  619. if(ch.phase != 0) // Update the signal if sample buffer nonempty
  620. {
  621. int v = ch.linear_counter;
  622. if(ch.hold & (0x80 >> --ch.phase)) v += 2; else v -= 2;
  623. if(v >= 0 && v <= 0x7F) ch.linear_counter = v;
  624. }
  625. return S = ch.linear_counter;
  626. }
  627. }
  628. } channels[5] = { };
  629.  
  630. struct { short lo, hi; } hz240counter = { 0,0 };
  631.  
  632. void Write(u8 index, u8 value)
  633. {
  634. channel& ch = channels[(index/4) % 5];
  635. switch(index<0x10 ? index%4 : index)
  636. {
  637. case 0: if(ch.reg.LinearCounterDisable) ch.linear_counter=value&0x7F; ch.reg.reg0 = value; break;
  638. case 1: ch.reg.reg1 = value; ch.sweep_delay = ch.reg.SweepRate; break;
  639. case 2: ch.reg.reg2 = value; break;
  640. case 3:
  641. ch.reg.reg3 = value;
  642. if(ChannelsEnabled[index/4])
  643. ch.length_counter = LengthCounters[ch.reg.LengthCounterInit];
  644. ch.linear_counter = ch.reg.LinearCounterInit;
  645. ch.env_delay = ch.reg.EnvDecayRate;
  646. ch.envelope = 15;
  647. if(index < 8) ch.phase = 0;
  648. break;
  649. case 0x10: ch.reg.reg3 = value; ch.reg.WaveLength = DMCperiods[value&0x0F]; break;
  650. case 0x12: ch.reg.reg0 = value; ch.address = (ch.reg.reg0 | 0x300) << 6; break;
  651. case 0x13: ch.reg.reg1 = value; ch.length_counter = ch.reg.PCMlength*16 + 1; break; // sample length
  652. case 0x11: ch.linear_counter = value & 0x7F; break; // dac value
  653. case 0x15:
  654. for(unsigned c=0; c<5; ++c)
  655. ChannelsEnabled[c] = value & (1 << c);
  656. for(unsigned c=0; c<5; ++c)
  657. if(!ChannelsEnabled[c])
  658. channels[c].length_counter = 0;
  659. else if(c == 4 && channels[c].length_counter == 0)
  660. channels[c].length_counter = ch.reg.PCMlength*16 + 1;
  661. break;
  662. case 0x17:
  663. IRQdisable = value & 0x40;
  664. FiveCycleDivider = value & 0x80;
  665. hz240counter = { 0,0 };
  666. if(IRQdisable) PeriodicIRQ = DMC_IRQ = false;
  667. }
  668. }
  669. u8 Read()
  670. {
  671. u8 res = 0;
  672. for(unsigned c=0; c<5; ++c) res |= (channels[c].length_counter ? 1 << c : 0);
  673. if(PeriodicIRQ) res |= 0x40; PeriodicIRQ = false;
  674. if(DMC_IRQ) res |= 0x80; DMC_IRQ = false;
  675. CPU::intr = false;
  676. return res;
  677. }
  678.  
  679. void tick() // Invoked at CPU's rate.
  680. {
  681. // Divide CPU clock by 7457.5 to get a 240 Hz, which controls certain events.
  682. if((hz240counter.lo += 2) >= 14915)
  683. {
  684. hz240counter.lo -= 14915;
  685. if(++hz240counter.hi >= 4+FiveCycleDivider) hz240counter.hi = 0;
  686.  
  687. // 60 Hz interval: IRQ. IRQ is not invoked in five-cycle mode (48 Hz).
  688. if(!IRQdisable && !FiveCycleDivider && hz240counter.hi==0)
  689. CPU::intr = PeriodicIRQ = true;
  690.  
  691. // Some events are invoked at 96 Hz or 120 Hz rate. Others, 192 Hz or 240 Hz.
  692. bool HalfTick = (hz240counter.hi&5)==1, FullTick = hz240counter.hi < 4;
  693. for(unsigned c=0; c<4; ++c)
  694. {
  695. channel& ch = channels[c];
  696. int wl = ch.reg.WaveLength;
  697.  
  698. // Length tick (all channels except DMC, but different disable bit for triangle wave)
  699. if(HalfTick && ch.length_counter
  700. && !(c==2 ? ch.reg.LinearCounterDisable : ch.reg.LengthCounterDisable))
  701. ch.length_counter -= 1;
  702.  
  703. // Sweep tick (square waves only)
  704. if(HalfTick && c < 2 && count(ch.sweep_delay, ch.reg.SweepRate))
  705. if(wl >= 8 && ch.reg.SweepEnable && ch.reg.SweepShift)
  706. {
  707. int s = wl >> ch.reg.SweepShift, d[4] = {s, s, ~s, -s};
  708. wl += d[ch.reg.SweepDecrease*2 + c];
  709. if(wl < 0x800) ch.reg.WaveLength = wl;
  710. }
  711.  
  712. // Linear tick (triangle wave only)
  713. if(FullTick && c == 2)
  714. ch.linear_counter = ch.reg.LinearCounterDisable
  715. ? ch.reg.LinearCounterInit
  716. : (ch.linear_counter > 0 ? ch.linear_counter - 1 : 0);
  717.  
  718. // Envelope tick (square and noise channels)
  719. if(FullTick && c != 2 && count(ch.env_delay, ch.reg.EnvDecayRate))
  720. if(ch.envelope > 0 || ch.reg.EnvDecayLoopEnable)
  721. ch.envelope = (ch.envelope-1) & 15;
  722. }
  723. }
  724.  
  725. // Mix the audio: Get the momentary sample from each channel and mix them.
  726. #define s(c) channels[c].tick<c==1 ? 0 : c>()
  727. auto v = [](float m,float n, float d) { return n!=0.f ? m/n : d; };
  728. short sample = 30000 *
  729. (v(95.88f, (100.f + v(8128.f, s(0) + s(1), -100.f)), 0.f)
  730. + v(159.79f, (100.f + v(1.0, s(2)/8227.f + s(3)/12241.f + s(4)/22638.f, -100.f)), 0.f)
  731. - 0.5f
  732. );
  733. #undef s
  734. // I cheat here: I did not bother to learn how to use SDL mixer, let alone use it in <5 lines of code,
  735. // so I simply use a combination of external programs for outputting the audio.
  736. // Hooray for Unix principles! A/V sync will be ensured in post-process.
  737. //return; // Disable sound because already device is in use
  738.  
  739. }
  740. }
  741.  
  742. namespace CPU
  743. {
  744. void tick()
  745. {
  746. // PPU clock: 3 times the CPU rate
  747. for(unsigned n=0; n<3; ++n) PPU::tick();
  748. // APU clock: 1 times the CPU rate
  749. for(unsigned n=0; n<1; ++n) APU::tick();
  750. }
  751.  
  752. template<bool write> u8 MemAccess(u16 addr, u8 v)
  753. {
  754. // Memory writes are turned into reads while reset is being signalled
  755. if(reset && write) return MemAccess<0>(addr);
  756.  
  757. tick();
  758. // Map the memory from CPU's viewpoint.
  759. /**/ if(addr < 0x2000) { u8& r = RAM[addr & 0x7FF]; if(!write)return r; r=v; }
  760. else if(addr < 0x4000) return PPU::Access(addr&7, v, write);
  761. else if(addr < 0x4018)
  762. switch(addr & 0x1F)
  763. {
  764. case 0x14: // OAM DMA: Copy 256 bytes from RAM into PPU's sprite memory
  765. if(write) for(unsigned b=0; b<256; ++b) WB(0x2004, RB((v&7)*0x0100+b));
  766. return 0;
  767. case 0x15: if(!write) return APU::Read(); APU::Write(0x15,v); break;
  768. case 0x16: if(!write) return IO::JoyRead(0); IO::JoyStrobe(v); break;
  769. case 0x17: if(!write) return IO::JoyRead(1); // write:passthru
  770. default: if(!write) break;
  771. APU::Write(addr&0x1F, v);
  772. }
  773. else return GamePak::Access(addr, v, write);
  774. return 0;
  775. }
  776.  
  777. // CPU registers:
  778. u16 PC=0xC000;
  779. u8 A=0,X=0,Y=0,S=0;
  780. union /* Status flags: */
  781. {
  782. u8 raw;
  783. RegBit<0> C; // carry
  784. RegBit<1> Z; // zero
  785. RegBit<2> I; // interrupt enable/disable
  786. RegBit<3> D; // decimal mode (unsupported on NES, but flag exists)
  787. // 4,5 (0x10,0x20) don't exist
  788. RegBit<6> V; // overflow
  789. RegBit<7> N; // negative
  790. } P;
  791.  
  792. u16 wrap(u16 oldaddr, u16 newaddr) { return (oldaddr & 0xFF00) + u8(newaddr); }
  793. void Misfire(u16 old, u16 addr) { u16 q = wrap(old, addr); if(q != addr) RB(q); }
  794. u8 Pop() { return RB(0x100 | u8(++S)); }
  795. void Push(u8 v) { WB(0x100 | u8(S--), v); }
  796.  
  797. template<u16 op> // Execute a single CPU instruction, defined by opcode "op".
  798. void Ins() // With template magic, the compiler will literally synthesize >256 different functions.
  799. {
  800. // Note: op 0x100 means "NMI", 0x101 means "Reset", 0x102 means "IRQ". They are implemented in terms of "BRK".
  801. // User is responsible for ensuring that WB() will not store into memory while Reset is being processed.
  802. unsigned addr=0, d=0, t=0xFF, c=0, sb=0, pbits = op<0x100 ? 0x30 : 0x20;
  803.  
  804. // Define the opcode decoding matrix, which decides which micro-operations constitute
  805. // any particular opcode. (Note: The PLA of 6502 works on a slightly different principle.)
  806. enum { o8 = op/8, o8m = 1 << (op%8) };
  807. // Fetch op'th item from a bitstring encoded in a data-specific variant of base64,
  808. // where each character transmits 8 bits of information rather than 6.
  809. // This peculiar encoding was chosen to reduce the source code size.
  810. // Enum temporaries are used in order to ensure compile-time evaluation.
  811. #define t(s,code) { enum { \
  812. i=o8m & (s[o8]>90 ? (130+" (),-089<>?BCFGHJLSVWZ[^hlmnxy|}"[s[o8]-94]) \
  813. : (s[o8]-" (("[s[o8]/39])) }; if(i) { code; } }
  814.  
  815. /* Decode address operand */
  816. t(" !", addr = 0xFFFA) // NMI vector location
  817. t(" *", addr = 0xFFFC) // Reset vector location
  818. t("! ,", addr = 0xFFFE) // Interrupt vector location
  819. t("zy}z{y}zzy}zzy}zzy}zzy}zzy}zzy}z ", addr = RB(PC++))
  820. t("2 yy2 yy2 yy2 yy2 XX2 XX2 yy2 yy ", d = X) // register index
  821. t(" 62 62 62 62 om om 62 62 ", d = Y)
  822. t("2 y 2 y 2 y 2 y 2 y 2 y 2 y 2 y ", addr=u8(addr+d); d=0; tick()) // add zeropage-index
  823. t(" y z!y z y z y z y z y z y z y z ", addr=u8(addr); addr+=256*RB(PC++)) // absolute address
  824. t("3 6 2 6 2 6 286 2 6 2 6 2 6 2 6 /", addr=RB(c=addr); addr+=256*RB(wrap(c,c+1)))// indirect w/ page wrap
  825. t(" *Z *Z *Z *Z 6z *Z *Z ", Misfire(addr, addr+d)) // abs. load: extra misread when cross-page
  826. t(" 4k 4k 4k 4k 6z 4k 4k ", RB(wrap(addr, addr+d)))// abs. store: always issue a misread
  827. /* Load source operand */
  828. t("aa__ff__ab__,4 ____ - ____ ", t &= A) // Many operations take A or X as operand. Some try in
  829. t(" knnn 4 99 ", t &= X) // error to take both; the outcome is an AND operation.
  830. t(" 9989 99 ", t &= Y) // sty,dey,iny,tya,cpy
  831. t(" 4 ", t &= S) // tsx, las
  832. t("!!!! !! !! !! ! !! !! !!/", t &= P.raw|pbits; c = t)// php, flag test/set/clear, interrupts
  833. t("_^__dc___^__ ed__98 ", c = t; t = 0xFF) // save as second operand
  834. t("vuwvzywvvuwvvuwv zy|zzywvzywv ", t &= RB(addr+d)) // memory operand
  835. t(",2 ,2 ,2 ,2 -2 -2 -2 -2 ", t &= RB(PC++)) // immediate operand
  836. /* Operations that mogrify memory operands directly */
  837. t(" 88 ", P.V = t & 0x40; P.N = t & 0x80) // bit
  838. t(" nink nnnk ", sb = P.C) // rol,rla, ror,rra,arr
  839. t("nnnknnnk 0 ", P.C = t & 0x80) // rol,rla, asl,slo,[arr,anc]
  840. t(" nnnknink ", P.C = t & 0x01) // lsr,sre, ror,rra,asr
  841. t("ninknink ", t = (t << 1) | (sb * 0x01))
  842. t(" nnnknnnk ", t = (t >> 1) | (sb * 0x80))
  843. t(" ! kink ", t = u8(t - 1)) // dec,dex,dey,dcp
  844. t(" ! khnk ", t = u8(t + 1)) // inc,inx,iny,isb
  845. /* Store modified value (memory) */
  846. t("kgnkkgnkkgnkkgnkzy|J kgnkkgnk ", WB(addr+d, t))
  847. t(" q ", WB(wrap(addr, addr+d), t &= ((addr+d) >> 8))) // [shx,shy,shs,sha?]
  848. /* Some operations used up one clock cycle that we did not account for yet */
  849. t("rpstljstqjstrjst - - - -kjstkjst/", tick()) // nop,flag ops,inc,dec,shifts,stack,transregister,interrupts
  850. /* Stack operations and unconditional jumps */
  851. t(" ! ! ! ", tick(); t = Pop()) // pla,plp,rti
  852. t(" ! ! ", RB(PC++); PC = Pop(); PC |= (Pop() << 8)) // rti,rts
  853. t(" ! ", RB(PC++)) // rts
  854. t("! ! /", d=PC+(op?-1:1); Push(d>>8); Push(d)) // jsr, interrupts
  855. t("! ! 8 8 /", PC = addr) // jmp, jsr, interrupts
  856. t("!! ! /", Push(t)) // pha, php, interrupts
  857. /* Bitmasks */
  858. t("! !! !! !! !! ! !! !! !!/", t = 1)
  859. t(" ! ! !! !! ", t <<= 1)
  860. t("! ! ! !! !! ! ! !/", t <<= 2)
  861. t(" ! ! ! ! ! ", t <<= 4)
  862. t(" ! ! ! !____ ", t = u8(~t)) // sbc, isb, clear flag
  863. t("`^__ ! ! !/", t = c | t) // ora, slo, set flag
  864. t(" !!dc`_ !! ! ! !! !! ! ", t = c & t) // and, bit, rla, clear/test flag
  865. t(" _^__ ", t = c ^ t) // eor, sre
  866. /* Conditional branches */
  867. t(" ! ! ! ! ", if(t) { tick(); Misfire(PC, addr = s8(addr) + PC); PC=addr; })
  868. t(" ! ! ! ! ", if(!t) { tick(); Misfire(PC, addr = s8(addr) + PC); PC=addr; })
  869. /* Addition and subtraction */
  870. t(" _^__ ____ ", c = t; t += A + P.C; P.V = (c^t) & (A^t) & 0x80; P.C = t & 0x100)
  871. t(" ed__98 ", t = c - t; P.C = ~t & 0x100) // cmp,cpx,cpy, dcp, sbx
  872. /* Store modified value (register) */
  873. t("aa__aa__aa__ab__ 4 !____ ____ ", A = t)
  874. t(" nnnn 4 ! ", X = t) // ldx, dex, tax, inx, tsx,lax,las,sbx
  875. t(" ! 9988 ! ", Y = t) // ldy, dey, tay, iny
  876. t(" 4 0 ", S = t) // txs, las, shs
  877. t("! ! ! !! ! ! ! ! !/", P.raw = t & ~0x30) // plp, rti, flag set/clear
  878. /* Generic status flag updates */
  879. t("wwwvwwwvwwwvwxwv 5 !}}||{}wv{{wv ", P.N = t & 0x80)
  880. t("wwwv||wvwwwvwxwv 5 !}}||{}wv{{wv ", P.Z = u8(t) == 0)
  881. t(" 0 ", P.V = (((t >> 5)+1)&2)) // [arr]
  882. /* All implemented opcodes are cycle-accurate and memory-access-accurate.
  883. * [] means that this particular separate rule exists only to provide the indicated unofficial opcode(s).
  884. */
  885. }
  886.  
  887. void Op()
  888. {
  889. /* Check the state of NMI flag */
  890. bool nmi_now = nmi;
  891.  
  892. unsigned op = RB(PC++);
  893.  
  894. if(reset) { op=0x101; }
  895. else if(nmi_now && !nmi_edge_detected) { op=0x100; nmi_edge_detected = true; }
  896. else if(intr && !P.I) { op=0x102; }
  897. if(!nmi_now) nmi_edge_detected=false;
  898.  
  899. // Define function pointers for each opcode (00..FF) and each interrupt (100,101,102)
  900. #define c(n) Ins<0x##n>,Ins<0x##n+1>,
  901. #define o(n) c(n)c(n+2)c(n+4)c(n+6)
  902. static void(*const i[0x108])() =
  903. {
  904. o(00)o(08)o(10)o(18)o(20)o(28)o(30)o(38)
  905. o(40)o(48)o(50)o(58)o(60)o(68)o(70)o(78)
  906. o(80)o(88)o(90)o(98)o(A0)o(A8)o(B0)o(B8)
  907. o(C0)o(C8)o(D0)o(D8)o(E0)o(E8)o(F0)o(F8) o(100)
  908. };
  909. #undef o
  910. #undef c
  911. i[op]();
  912.  
  913. reset = false;
  914. }
  915. }
  916.  
  917. int main(int/*argc*/, char** argv)
  918. {
  919. // Open the ROM file specified on commandline
  920. FILE* fp = fopen(argv[1], "rb");
  921. inputfn = argv[2];
  922.  
  923. if (!fp) {
  924. puts("ROM doesn't exist");
  925. exit(1);
  926. }
  927.  
  928. // Read the ROM file header
  929. assert(fgetc(fp)=='N' && fgetc(fp)=='E' && fgetc(fp)=='S' && fgetc(fp)=='\32');
  930. u8 rom16count = fgetc(fp);
  931. u8 vrom8count = fgetc(fp);
  932. u8 ctrlbyte = fgetc(fp);
  933. u8 mappernum = fgetc(fp) | (ctrlbyte>>4);
  934. fgetc(fp);fgetc(fp);fgetc(fp);fgetc(fp);fgetc(fp);fgetc(fp);fgetc(fp);fgetc(fp);
  935. if(mappernum >= 0x40) mappernum &= 15;
  936. GamePak::mappernum = mappernum;
  937.  
  938. // Read the ROM data
  939. if(rom16count) GamePak::ROM.resize(rom16count * 0x4000);
  940. if(vrom8count) GamePak::VRAM.resize(vrom8count * 0x2000);
  941. fread(&GamePak::ROM[0], rom16count, 0x4000, fp);
  942. fread(&GamePak::VRAM[0], vrom8count, 0x2000, fp);
  943.  
  944. fclose(fp);
  945. printf("%u * 16kB ROM, %u * 8kB VROM, mapper %u, ctrlbyte %02X\n", rom16count, vrom8count, mappernum, ctrlbyte);
  946.  
  947. // Start emulation
  948. GamePak::Init();
  949. IO::Init();
  950. PPU::reg.value = 0;
  951.  
  952. // Pre-initialize RAM the same way as FCEUX does, to improve TAS sync.
  953. for(unsigned a=0; a<0x800; ++a)
  954. CPU::RAM[a] = (a&4) ? 0xFF : 0x00;
  955.  
  956. // Run the CPU until the program is killed.
  957. for(;;) CPU::Op();
  958. }
Advertisement
Add Comment
Please, Sign In to add comment