35d720987835572d053e4edf1ee158abf4a9a69a
[fceu.git] / fce.c
1 /* FCE Ultra - NES/Famicom Emulator
2  *
3  * Copyright notice for this file:
4  *  Copyright (C) 1998 BERO
5  *  Copyright (C) 2002 Ben Parnell
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 #include        <string.h>
23 #include        <stdio.h>
24 #include        <stdlib.h>
25
26 #include        "types.h"
27 #include        "x6502.h"
28 #include        "fce.h"
29 #include        "sound.h"
30 #include        "svga.h"
31 #include        "netplay.h"
32 #include        "general.h"
33 #include        "endian.h"
34 #include        "version.h"
35 #include        "memory.h"
36
37 #include        "cart.h"
38 #include        "nsf.h"
39 #include        "fds.h"
40 #include        "ines.h"
41 #include        "unif.h"
42 #include        "cheat.h"
43
44 #include        "state.h"
45 #include        "video.h"
46 #include        "input.h"
47 #include        "file.h"
48 #include        "crc32.h"
49 #include        "ppu.h"
50
51 #include        "palette.h"
52 #include        "movie.h"
53
54 #include        "dprintf.h"
55
56 #ifdef GP2X
57 #include        "drivers/gp2x/asmutils.h"
58 #endif
59
60 #define Pal     (PALRAM)
61
62
63 static void (*RefreshLine)(uint8 *P, uint32 vofs) = NULL;
64 static void PRefreshLine(void);
65
66 static void ResetPPU(void);
67 static void PowerPPU(void);
68
69 uint64 timestampbase=0;
70
71 static int ppudead=1;
72 static int kook=0;
73
74 int MMC5Hack;
75 uint32 MMC5HackVROMMask;
76 uint8 *MMC5HackExNTARAMPtr;
77 uint8 *MMC5HackVROMPTR;
78 uint8 MMC5HackCHRMode=0;
79 uint8 MMC5HackSPMode;
80 uint8 MMC5HackSPScroll;
81 uint8 MMC5HackSPPage;
82
83 uint8 *MMC5SPRVPage[8];
84 uint8 *MMC5BGVPage[8];
85
86
87 uint8 VRAMBuffer,PPUGenLatch;
88
89 uint8 *vnapage[4];
90 uint8 PPUNTARAM;
91 uint8 PPUCHRRAM;
92
93 /* Color deemphasis emulation.  Joy... */
94 static uint8 deemp=0;
95 static int deempcnt[8];
96
97 int tosprite=256;
98
99 FCEUGI FCEUGameInfo;
100 void (*GameInterface)(int h);
101
102 void FP_FASTAPASS(1) (*PPU_hook)(uint32 A);
103
104 void (*GameStateRestore)(int version);
105 void (*GameHBIRQHook)(void), (*GameHBIRQHook2)(void);
106
107 readfunc ARead[0x10000];
108 writefunc BWrite[0x10000];
109 static readfunc *AReadG;
110 static writefunc *BWriteG;
111 static int RWWrap=0;
112
113 #ifdef ASM_6502
114 static void asmcpu_update(int32 cycles)
115 {
116  // some code from x6502.c
117  fhcnt-=cycles;
118  if(fhcnt<=0)
119  {
120   FrameSoundUpdate();
121   fhcnt+=fhinc;
122  }
123
124  if(PCMIRQCount>0)
125  {
126   PCMIRQCount-=cycles;
127   if(PCMIRQCount<=0)
128   {
129    vdis=1;
130    if((PSG[0x10]&0x80) && !(PSG[0x10]&0x40))
131    {
132     extern uint8 SIRQStat;
133     SIRQStat|=0x80;
134     X6502_IRQBegin(FCEU_IQDPCM);
135    }
136   }
137  }
138 }
139
140 void asmcpu_unpack(void)
141 {
142         nes_registers[0] = X.A << 24;
143         nes_registers[1] = X.X;
144         nes_registers[2] = X.Y;
145         pc_base = 0;
146         nes_registers[3] = X.PC;
147         X6502_Rebase_a();
148         nes_registers[4] = X.S << 24;
149         nes_registers[4]|= X.IRQlow << 8;
150         nes_registers[7] = (uint32)X.count << 16;
151
152         // NVUB DIZC
153         nes_registers[4]|= X.P & 0x5d;
154         nes_registers[5] = X.P << 24; // N
155         if (!(X.P&0x02)) nes_registers[5] |= 1; // Z
156 }
157
158 void asmcpu_pack(void)
159 {
160         X.A = nes_registers[0] >> 24;
161         X.X = nes_registers[1];
162         X.Y = nes_registers[2];
163         X.PC= nes_registers[3] - pc_base;
164         X.S = nes_registers[4] >> 24;
165         X.IRQlow = nes_registers[4] >> 8;
166         X.count = (int32) nes_registers[7] >> 16;
167
168         // NVUB DIZC
169         X.P = nes_registers[4] & 0x5d;
170         if (  nes_registers[5]&0x80000000)  X.P |= 0x80; // N
171         if (!(nes_registers[5]&0x000000ff)) X.P |= 0x02; // Z
172 }
173 #endif
174
175 DECLFW(BNull)
176 {
177
178 }
179
180 DECLFR(ANull)
181 {
182  return(X.DB);
183 }
184
185 int AllocGenieRW(void)
186 {
187  if(!(AReadG=FCEU_malloc(0x8000*sizeof(readfunc))))
188   return 0;
189  if(!(BWriteG=FCEU_malloc(0x8000*sizeof(writefunc))))
190   return 0;
191  RWWrap=1;
192  return 1;
193 }
194
195 void FlushGenieRW(void)
196 {
197  int32 x;
198
199  if(RWWrap)
200  {
201   for(x=0;x<0x8000;x++)
202   {
203    ARead[x+0x8000]=AReadG[x];
204    BWrite[x+0x8000]=BWriteG[x];
205   }
206 #ifdef ASM_6502
207   GenieSetPages(1);
208 #endif
209   free(AReadG);
210   free(BWriteG);
211   AReadG=0;
212   BWriteG=0;
213   RWWrap=0;
214  }
215 }
216
217 readfunc FASTAPASS(1) GetReadHandler(int32 a)
218 {
219   if(a>=0x8000 && RWWrap)
220    return AReadG[a-0x8000];
221   else
222    return ARead[a];
223 }
224
225 void FASTAPASS(3) SetReadHandler(int32 start, int32 end, readfunc func)
226 {
227   int32 x;
228
229   if(!func)
230    func=ANull;
231
232   if(RWWrap)
233    for(x=end;x>=start;x--)
234    {
235     if(x>=0x8000)
236      AReadG[x-0x8000]=func;
237     else
238      ARead[x]=func;
239    }
240   else
241
242    for(x=end;x>=start;x--)
243     ARead[x]=func;
244 }
245
246 writefunc FASTAPASS(1) GetWriteHandler(int32 a)
247 {
248   if(RWWrap && a>=0x8000)
249    return BWriteG[a-0x8000];
250   else
251    return BWrite[a];
252 }
253
254 void FASTAPASS(3) SetWriteHandler(int32 start, int32 end, writefunc func)
255 {
256   int32 x;
257
258   if(!func)
259    func=BNull;
260
261   if(RWWrap)
262    for(x=end;x>=start;x--)
263    {
264     if(x>=0x8000)
265      BWriteG[x-0x8000]=func;
266     else
267      BWrite[x]=func;
268    }
269   else
270    for(x=end;x>=start;x--)
271     BWrite[x]=func;
272 }
273
274 uint8 vtoggle=0;
275 uint8 XOffset=0;
276
277 uint32 TempAddr,RefreshAddr;
278
279
280 /* scanline is equal to the current visible scanline we're on. */
281
282 int scanline;
283
284 uint8 GameMemBlock[131072] __attribute__ ((aligned (4)));
285 uint8 NTARAM[0x800] __attribute__ ((aligned (4)));
286 uint8 PALRAM[0x20] __attribute__ ((aligned (4)));
287 #if !defined(ASM_6502) || defined(DEBUG_ASM_6502)
288 uint8 RAM[0x800] __attribute__ ((aligned (4)));
289 #endif
290
291 uint8 PPU[4];
292 uint8 PPUSPL;
293
294 uint8 PAL=0;
295
296
297 #define MMC5BGVRAMADR(V)      &MMC5BGVPage[(V)>>10][(V)]
298 #define VRAMADR(V)      &VPage[(V)>>10][(V)]
299
300 static int linestartts;
301 static int tofix=0;
302
303 static void ResetRL(void)
304 {
305  linestartts=timestamp*48+X6502_GetCycleCount();
306  tofix=1;
307 }
308
309 static INLINE void Fixit1(void);
310
311 static void TryFixit1(void)
312 {
313  #define TOFIXNUM (272-0x4)
314  int lastpixel;
315
316  if (scanline < 240 && tofix)
317  {
318   lastpixel = (timestamp*48-linestartts)>>4;
319   if (PAL) lastpixel += lastpixel>>4;
320
321   //printf("lastpixel: %i\n", lastpixel);
322
323   if(lastpixel>=TOFIXNUM)
324   {
325    Fixit1();
326    tofix=0;
327   }
328  }
329 }
330
331
332 static DECLFW(BRAML)
333 {
334         RAM[A]=V;
335 }
336
337 static DECLFW(BRAMH)
338 {
339         RAM[A&0x7FF]=V;
340 }
341
342 static DECLFR(ARAML)
343 {
344         return RAM[A];
345 }
346
347 static DECLFR(ARAMH)
348 {
349         return RAM[A&0x7FF];
350 }
351
352
353 static DECLFR(A2002)
354 {
355         /* merged */
356                         uint8 ret;
357
358                         TryFixit1();
359                         ret = PPU_status;
360                         ret|=PPUGenLatch&0x1F;
361                         vtoggle=0;
362                         PPU_status&=0x7F;
363                          PPUGenLatch=ret;
364                         //dprintf("r [2002] %02x",ret);
365                         return ret;
366 }
367
368 static DECLFR(A200x)
369 {
370         /* merged */
371                         TryFixit1();
372                         return PPUGenLatch;
373 }
374
375 static DECLFR(A2007)
376 {
377         /* merged */
378                         uint8 ret;
379                         uint32 tmp=RefreshAddr&0x3FFF;
380
381                         TryFixit1();
382
383                         ret=VRAMBuffer;
384
385                         if(PPU_hook) PPU_hook(tmp);
386                         PPUGenLatch=VRAMBuffer;
387                         if(tmp<0x2000)
388                         {
389                          VRAMBuffer=VPage[tmp>>10][tmp];
390                         }
391                         else
392                         {
393                          VRAMBuffer=vnapage[(tmp>>10)&0x3][tmp&0x3FF];
394                         }
395
396                         if (INC32) RefreshAddr+=32;
397                         else RefreshAddr++;
398                         if(PPU_hook) PPU_hook(RefreshAddr&0x3fff);
399                         dprintf("r [2007] %02x",ret);
400                         return ret;
401 }
402
403 static DECLFW(B2000)
404 {
405         /* NMI2? */
406                 TryFixit1();
407                 PPUGenLatch=V;
408                 PPU[0]=V;
409                 TempAddr&=0xF3FF;
410                 TempAddr|=(V&3)<<10;
411 }
412
413 static DECLFW(B2001)
414 {
415         /* merged */
416                   TryFixit1();
417                   PPUGenLatch=V;
418                   PPU[1]=V;
419                   if(V&0xE0)
420                    deemp=V>>5;
421                   //printf("$%04x:$%02x, %d\n",X.PC,V,scanline);
422 }
423
424 static DECLFW(B2002)
425 {
426         /* merged */
427                  PPUGenLatch=V;
428 }
429
430 static DECLFW(B2003)
431 {
432         /* merged */
433                 PPUGenLatch=V;
434                 PPU[3]=V;
435                 PPUSPL=V&0x7;
436 }
437
438 static DECLFW(B2004)
439 {
440         /* merged */
441                 PPUGenLatch=V;
442                 if(PPUSPL>=8)
443                 {
444                  if(PPU[3]>=8)
445                   SPRAM[PPU[3]]=V;
446                 }
447                 else
448                 {
449                  //printf("$%02x:$%02x\n",PPUSPL,V);
450                  SPRAM[PPUSPL]=V;
451                 }
452                 PPU[3]++;
453                 PPUSPL++;
454
455 }
456
457 static DECLFW(B2005)
458 {
459         /* merged */
460                 uint32 tmp=TempAddr;
461                 TryFixit1();
462                 PPUGenLatch=V;
463                 if (!vtoggle)
464                 {
465                  tmp&=0xFFE0;
466                  tmp|=V>>3;
467                  XOffset=V&7;
468                 }
469                 else
470                 {
471                  tmp&=0x8C1F;
472                  tmp|=((V&~0x7)<<2);
473                  tmp|=(V&7)<<12;
474                 }
475
476                 TempAddr=tmp;
477                 vtoggle^=1;
478 }
479
480 static DECLFW(B2006)
481 {
482         /* merged */
483                        TryFixit1();
484
485                        PPUGenLatch=V;
486                        if(!vtoggle)
487                        {
488                         TempAddr&=0x00FF;
489                         TempAddr|=(V&0x3f)<<8;
490                        }
491                        else
492                        {
493                         TempAddr&=0xFF00;
494                         TempAddr|=V;
495
496                         RefreshAddr=TempAddr;
497                         if(PPU_hook)
498                          PPU_hook(RefreshAddr);
499                        }
500                       vtoggle^=1;
501 }
502
503 static DECLFW(B2007)
504 {
505         /* merged */
506                         uint32 tmp=RefreshAddr&0x3FFF;
507                         PPUGenLatch=V;
508                         if(tmp>=0x3F00)
509                         {
510                          // hmmm....
511                          if(!(tmp&0xf))
512                           PALRAM[0x00]=PALRAM[0x04]=PALRAM[0x08]=PALRAM[0x0C]=V&0x3f;
513                          else if(tmp&3) PALRAM[(tmp&0x1f)]=V&0x3f;
514                         }
515                         else if(tmp<0x2000)
516                         {
517                           if(PPUCHRRAM&(1<<(tmp>>10)))
518                             VPage[tmp>>10][tmp]=V;
519                         }
520                         else
521                         {
522                          if(PPUNTARAM&(1<<((tmp&0xF00)>>10)))
523                           vnapage[((tmp&0xF00)>>10)][tmp&0x3FF]=V;
524                         }
525                         if (INC32) RefreshAddr+=32;
526                         else RefreshAddr++;
527                         if(PPU_hook) PPU_hook(RefreshAddr&0x3fff);
528 }
529
530 static DECLFW(B4014)
531 {
532         uint32 t=V<<8;
533         int x;
534
535         for(x=0;x<256;x++)
536          B2004(0x2004,X.DB=ARead[t+x](t+x));
537         X6502_AddCycles(512);
538 }
539
540 void BGRender(uint8 *target)
541 {
542         uint32 tem, vofs;
543         vofs=((PPU[0]&0x10)<<8) | ((RefreshAddr>>12)&7);
544
545         Pal[0]|=64;
546         Pal[4]|=64;
547         Pal[8]|=64;
548         Pal[0xC]|=64;
549         RefreshLine(target-XOffset, vofs);
550         Pal[0]&=63;
551         Pal[4]&=63;
552         Pal[8]&=63;
553         Pal[0xC]&=63;
554
555         if(!(PPU[1]&2))
556         {
557          tem=Pal[0]|0x40;
558          tem|=tem<<8;
559          tem|=tem<<16;
560          *(uint32 *)target=*(uint32 *)(target+4)=tem;
561         }
562 }
563
564 #ifdef FRAMESKIP
565 int FSkip_setting=-1; // auto
566 int FSkip=0;
567 void FCEUI_FrameSkip(int x)
568 {
569  FSkip=x;
570 }
571 #endif
572
573 /*      This is called at the beginning of each visible scanline */
574 static void Loop6502(void)
575 {
576         uint32 tem;
577         int x;
578         uint8 *target=XBuf+scanline*320+32;
579
580         if(ScreenON || SpriteON)
581         {
582          /* PRefreshLine() will not get called on skipped frames.  This
583             could cause a problem, but the solution would be rather complex,
584             due to the current sprite 0 hit code.
585          */
586          #ifdef FRAMESKIP
587          if(!FSkip)
588          {
589          #endif
590           if(ScreenON)
591           {
592            if(scanline>=FSettings.FirstSLine && scanline<=FSettings.LastSLine)
593             BGRender(target);
594            else
595            {
596             if(PPU_hook)
597              PRefreshLine();
598            }
599           }
600           else
601           {
602            tem=Pal[0]|(Pal[0]<<8)|(Pal[0]<<16)|(Pal[0]<<24);
603            tem|=0x40404040;
604            FCEU_dwmemset(target,tem,264);
605           }
606          #ifdef FRAMESKIP
607          }
608          #endif
609          if (SpriteON && scanline)
610           RefreshSprite(target);
611          #ifdef FRAMESKIP
612          if(!FSkip)
613          {
614          #endif
615           if(PPU[1]&0x01)
616           {
617            for(x=63;x>=0;x--)
618             ((uint32 *)target)[x]=((uint32*)target)[x]&0xF0F0F0F0;
619           }
620 #ifdef GP2X
621            if((PPU[1]>>5)==0x7) block_or(target, 256, 0xc0);
622            else if(PPU[1]&0xE0) block_andor(target, 256, 0x3f, 0x40);
623            else                 block_andor(target, 256, 0x3f, 0x80);
624 #else
625            if((PPU[1]>>5)==0x7)
626             for(x=63;x>=0;x--)
627              ((uint32 *)target)[x]=(((uint32*)target)[x])|0xc0c0c0c0;
628            else if(PPU[1]&0xE0)
629             for(x=63;x>=0;x--)
630              ((uint32 *)target)[x]=(((uint32*)target)[x]&0x3f3f3f3f)|0x40404040;
631            else
632             for(x=63;x>=0;x--)
633              ((uint32 *)target)[x]=(((uint32*)target)[x]&0x3f3f3f3f)|0x80808080;
634 #endif
635           // black borders
636           ((uint32 *)target)[-2]=((uint32 *)target)[-1]=0;
637           ((uint32 *)target)[64]=((uint32 *)target)[65]=0;
638          #ifdef FRAMESKIP
639          }
640          #endif
641         }
642         else
643         {
644          tem=Pal[0]|(Pal[0]<<8)|(Pal[0]<<16)|(Pal[0]<<24);
645          FCEU_dwmemset(target,tem,256);
646         }
647         if(InputScanlineHook)
648          InputScanlineHook(target, scanline);
649 }
650
651 #define PAL(c)  ((c)+cc)
652
653
654 static void PRefreshLine(void)
655 {
656         uint32 vofs;
657         uint8 X1;
658
659         vofs = 0;
660         if (BGAdrHI) vofs = 0x1000;
661
662         vofs+=(RefreshAddr>>12)&7;
663
664         for(X1=33;X1;X1--)
665         {
666                 register uint8 no;
667                 register uint8 zz2;
668                 zz2=(uint8)((RefreshAddr>>10)&3);
669                 PPU_hook(0x2000|(RefreshAddr&0xFFF));
670                 no  = vnapage[zz2][(RefreshAddr&0x3ff)];
671                 PPU_hook((no<<4)+vofs);
672                 if((RefreshAddr&0x1f)==0x1f)
673                  RefreshAddr^=0x41F;
674                 else
675                  RefreshAddr++;
676         }
677 }
678
679 /* This high-level graphics MMC5 emulation code was written
680    for MMC5 carts in "CL" mode.  It's probably not totally
681    correct for carts in "SL" mode.
682    */
683 static void RefreshLine_MMC5Hack1(uint8 *P, uint32 vofs)
684 {
685           int8 tochange, X1;
686
687           tochange=MMC5HackSPMode&0x1F;
688
689           for(X1=33;X1;X1--,P+=8)
690           {
691                 uint8 *C;
692                 uint8 cc,zz,zz2;
693                 uint32 vadr;
694
695                 if((tochange<=0 && MMC5HackSPMode&0x40) ||
696                    (tochange>0 && !(MMC5HackSPMode&0x40)))
697                 {
698                  uint8 xs,ys;
699
700                  xs=33-X1;
701                  ys=((scanline>>3)+MMC5HackSPScroll)&0x1F;
702                  if(ys>=0x1E) ys-=0x1E;
703                  vadr=(MMC5HackExNTARAMPtr[xs|(ys<<5)]<<4)+(vofs&7);
704
705                  C = MMC5HackVROMPTR+vadr;
706                  C += ((MMC5HackSPPage & 0x3f & MMC5HackVROMMask) << 12);
707
708                  cc=MMC5HackExNTARAMPtr[0x3c0+(xs>>2)+((ys&0x1C)<<1)];
709                  cc=((cc >> ((xs&2) + ((ys&0x2)<<1))) &3) <<2;
710                 }
711                 else
712                 {
713                  zz=RefreshAddr&0x1F;
714                  zz2=(RefreshAddr>>10)&3;
715                  vadr=(vnapage[zz2][RefreshAddr&0x3ff]<<4)+vofs;
716                  C = MMC5BGVRAMADR(vadr);
717                  cc=vnapage[zz2][0x3c0+(zz>>2)+((RefreshAddr&0x380)>>4)];
718                  cc=((cc >> ((zz&2) + ((RefreshAddr&0x40)>>4))) &3) <<2;
719                 }
720                 #include "fceline.h"
721
722                 if((RefreshAddr&0x1f)==0x1f)
723                  RefreshAddr^=0x41F;
724                 else
725                  RefreshAddr++;
726                 tochange--;
727           }
728 }
729
730 static void RefreshLine_MMC5Hack2(uint8 *P, uint32 vofs)
731 {
732           int8 tochange, X1;
733
734           tochange=MMC5HackSPMode&0x1F;
735
736           for(X1=33;X1;X1--,P+=8)
737           {
738                 uint8 *C;
739                 uint8 cc;
740                 uint8 zz2;
741                 uint32 vadr;
742
743                 if((tochange<=0 && MMC5HackSPMode&0x40) ||
744                    (tochange>0 && !(MMC5HackSPMode&0x40)))
745                 {
746                  uint8 xs,ys;
747
748                  xs=33-X1;
749                  ys=((scanline>>3)+MMC5HackSPScroll)&0x1F;
750                  if(ys>=0x1E) ys-=0x1E;
751                  vadr=(MMC5HackExNTARAMPtr[xs|(ys<<5)]<<4)+(vofs&7);
752
753                  C = MMC5HackVROMPTR+vadr;
754                  C += ((MMC5HackSPPage & 0x3f & MMC5HackVROMMask) << 12);
755
756                  cc=MMC5HackExNTARAMPtr[0x3c0+(xs>>2)+((ys&0x1C)<<1)];
757                  cc=((cc >> ((xs&2) + ((ys&0x2)<<1))) &3) <<2;
758                 }
759                 else
760                 {
761                  C=MMC5HackVROMPTR;
762                  zz2=(RefreshAddr>>10)&3;
763                  vadr = (vnapage[zz2][RefreshAddr & 0x3ff] << 4) + vofs;
764                  C += (((MMC5HackExNTARAMPtr[RefreshAddr & 0x3ff]) & 0x3f &
765                          MMC5HackVROMMask) << 12) + (vadr & 0xfff);
766                  vadr = (MMC5HackExNTARAMPtr[RefreshAddr & 0x3ff] & 0xC0)>> 4;
767                  cc = vadr;
768                 }
769                 #include "fceline.h"
770                 if((RefreshAddr&0x1f)==0x1f)
771                  RefreshAddr^=0x41F;
772                 else
773                  RefreshAddr++;
774                 tochange--;
775           }
776 }
777
778 static void RefreshLine_MMC5Hack3(uint8 *P, uint32 vofs)
779 {
780           int8 X1;
781
782           for(X1=33;X1;X1--,P+=8)
783           {
784                 uint8 *C;
785                 uint8 cc;
786                 uint8 zz2;
787                 uint32 vadr;
788
789                 C=MMC5HackVROMPTR;
790                 zz2=(RefreshAddr>>10)&3;
791                 vadr = (vnapage[zz2][RefreshAddr & 0x3ff] << 4) + vofs;
792                 C += (((MMC5HackExNTARAMPtr[RefreshAddr & 0x3ff]) & 0x3f &
793                         MMC5HackVROMMask) << 12) + (vadr & 0xfff);
794                 vadr = (MMC5HackExNTARAMPtr[RefreshAddr & 0x3ff] & 0xC0)>> 4;
795                 cc = vadr;
796
797                 #include "fceline.h"
798                 if((RefreshAddr&0x1f)==0x1f)
799                  RefreshAddr^=0x41F;
800                 else
801                  RefreshAddr++;
802           }
803 }
804
805 static void RefreshLine_MMC5Hack4(uint8 *P, uint32 vofs)
806 {
807           int8 X1;
808
809           for(X1=33;X1;X1--,P+=8)
810           {
811                 uint8 *C;
812                 uint8 cc,zz,zz2;
813                 uint32 vadr;
814
815                 zz=RefreshAddr&0x1F;
816                 zz2=(RefreshAddr>>10)&3;
817                 vadr=(vnapage[zz2][RefreshAddr&0x3ff]<<4)+vofs;
818                 C = MMC5BGVRAMADR(vadr);
819                 cc=vnapage[zz2][0x3c0+(zz>>2)+((RefreshAddr&0x380)>>4)];
820                 cc=((cc >> ((zz&2) + ((RefreshAddr&0x40)>>4))) &3) <<2;
821
822                 #include "fceline.h"
823
824                 if((RefreshAddr&0x1f)==0x1f)
825                  RefreshAddr^=0x41F;
826                 else
827                  RefreshAddr++;
828           }
829 }
830
831 static void RefreshLine_PPU_hook(uint8 *P, uint32 vofs)
832 {
833          int8 X1;
834
835          for(X1=33;X1;X1--,P+=8)
836          {
837                 uint8 *C;
838                 uint8 cc,zz,zz2;
839                 uint32 vadr;
840
841                 zz=RefreshAddr&0x1F;
842                 zz2=(RefreshAddr>>10)&3;
843                 PPU_hook(0x2000|(RefreshAddr&0xFFF));
844                 cc=vnapage[zz2][0x3c0+(zz>>2)+((RefreshAddr&0x380)>>4)];
845                 cc=((cc >> ((zz&2) + ((RefreshAddr&0x40)>>4))) &3) <<2;
846                 vadr=(vnapage[zz2][RefreshAddr&0x3ff]<<4)+vofs;
847                 C = VRAMADR(vadr);
848
849                 #include "fceline.h"
850
851                 PPU_hook(vadr);
852
853                 if((RefreshAddr&0x1f)==0x1f)
854                  RefreshAddr^=0x41F;
855                 else
856                  RefreshAddr++;
857          }
858 }
859
860 static void RefreshLine_normal(uint8 *P, uint32 vofs) // vofs is 0x107 max
861 {
862          int8 X1;
863          uint32 rfraddr = RefreshAddr;
864          uint8 *page = vnapage[(rfraddr>>10)&3];
865          uint32 cc2=0;
866
867          if ((rfraddr&0xc)!=0)
868           cc2=*(uint32 *) (page + ((rfraddr&0x380)>>4) + ((rfraddr&0x10)>>2) + 0x3c0);
869
870          for (X1=33;X1;X1--,P+=8)
871          {
872                 uint8 cc,*C;
873                 uint32 vadr;
874
875                 vadr=(page[rfraddr&0x3ff]<<4)+vofs;
876                 C = VRAMADR(vadr);
877                 if ((rfraddr&0xc)==0)
878                  cc2=*(uint32 *) (page + ((rfraddr&0x380)>>4) + ((rfraddr&0x10)>>2) + 0x3c0);
879                 cc=((cc2 >> ((rfraddr&2) + ((rfraddr&0x40)>>4) + ((rfraddr&0xc)<<1))) & 3) << 2;
880
881                 #include "fceline.h"
882
883                 if((rfraddr&0x1f)==0x1f) {
884                  rfraddr^=0x41F;
885                  page = vnapage[(rfraddr>>10)&3];
886                 } else
887                  rfraddr++;
888          }
889          RefreshAddr = rfraddr;
890 }
891
892 static void SetRefreshLine(void)
893 {
894         if(MMC5Hack && geniestage!=1)
895         {
896          if(MMC5HackCHRMode==0 && (MMC5HackSPMode&0x80))
897          {
898                  if (RefreshLine != RefreshLine_MMC5Hack1) printf("set refr RefreshLine_MMC5Hack1\n");
899                  RefreshLine = RefreshLine_MMC5Hack1;
900          }
901          else if(MMC5HackCHRMode==1 && (MMC5HackSPMode&0x80))
902          {
903                 if (RefreshLine != RefreshLine_MMC5Hack2) printf("set refr RefreshLine_MMC5Hack2\n");
904                  RefreshLine = RefreshLine_MMC5Hack2;
905          }
906          else if(MMC5HackCHRMode==1)
907          {
908                 if (RefreshLine != RefreshLine_MMC5Hack3) printf("set refr RefreshLine_MMC5Hack3\n");
909                  RefreshLine = RefreshLine_MMC5Hack3;
910          }
911          else
912          {
913                 if (RefreshLine != RefreshLine_MMC5Hack4) printf("set refr RefreshLine_MMC5Hack4\n");
914                  RefreshLine = RefreshLine_MMC5Hack4;
915          }
916         }       // End if(MMC5Hack)
917         else if(PPU_hook)
918         {
919                 if (RefreshLine != RefreshLine_PPU_hook) printf("set refr RefreshLine_PPU_hook\n");
920                 RefreshLine = RefreshLine_PPU_hook;
921         }
922         else
923         {
924                 if (RefreshLine != RefreshLine_normal) printf("set refr RefreshLine_normal\n");
925                 RefreshLine = RefreshLine_normal;
926         }
927 }
928
929 static INLINE
930 void Fixit2(void)
931 {
932    if(ScreenON || SpriteON)
933    {
934     uint32 rad=RefreshAddr;
935     rad&=0xFBE0;
936     rad|=TempAddr&0x041f;
937     RefreshAddr=rad;
938     //PPU_hook(RefreshAddr,-1);
939    }
940 }
941
942 static INLINE
943 void Fixit1(void)
944 {
945    if(ScreenON || SpriteON)
946    {
947     uint32 rad=RefreshAddr;
948
949     if((rad&0x7000)==0x7000)
950     {
951      rad^=0x7000;
952      if((rad&0x3E0)==0x3A0)
953      {
954       rad^=0x3A0;
955       rad^=0x800;
956      }
957      else
958      {
959       if((rad&0x3E0)==0x3e0)
960        rad^=0x3e0;
961       else rad+=0x20;
962      }
963     }
964     else
965      rad+=0x1000;
966     RefreshAddr=rad;
967     //PPU_hook(RefreshAddr,-1);
968    }
969 }
970
971
972 /*      This is called at the beginning of all h-blanks on visible lines. */
973 static void DoHBlank(void)
974 {
975  if(ScreenON || SpriteON)
976   FetchSpriteData();
977  if(GameHBIRQHook && (ScreenON || SpriteON) && ((PPU[0]&0x38)!=0x18))
978  {
979   X6502_Run(6);
980   Fixit2();
981   X6502_Run(4);
982   GameHBIRQHook();
983   X6502_Run(85-16-10);
984  }
985  else
986  {
987   X6502_Run(6);  // Tried 65, caused problems with Slalom(maybe others)
988   Fixit2();
989   X6502_Run(85-6-16);
990  }
991  if(GameHBIRQHook2 && (ScreenON || SpriteON))
992   GameHBIRQHook2();
993  //PPU_hook(0,-1);
994  //fprintf(stderr,"%3d: $%04x\n",scanline,RefreshAddr);
995  scanline++;
996  if (scanline<240)
997   ResetRL();
998  X6502_Run(16);
999 }
1000
1001
1002 // ============================//
1003 // end of new code
1004 // ===========================//
1005
1006 void ResetMapping(void)
1007 {
1008         int x;
1009
1010         SetReadHandler(0x0000,0xFFFF,ANull);
1011         SetWriteHandler(0x0000,0xFFFF,BNull);
1012
1013         SetReadHandler(0,0x7FF,ARAML);
1014         SetWriteHandler(0,0x7FF,BRAML);
1015
1016         SetReadHandler(0x800,0x1FFF,ARAMH);  /* Part of a little */
1017         SetWriteHandler(0x800,0x1FFF,BRAMH); /* hack for a small speed boost. */
1018
1019         for(x=0x2000;x<0x4000;x+=8)
1020         {
1021          ARead[x]=A200x;
1022          BWrite[x]=B2000;
1023          ARead[x+1]=A200x;
1024          BWrite[x+1]=B2001;
1025          ARead[x+2]=A2002;
1026          BWrite[x+2]=B2002;
1027          ARead[x+3]=A200x;
1028          BWrite[x+3]=B2003;
1029          ARead[x+4]=A200x;
1030          BWrite[x+4]=B2004;
1031          ARead[x+5]=A200x;
1032          BWrite[x+5]=B2005;
1033          ARead[x+6]=A200x;
1034          BWrite[x+6]=B2006;
1035          ARead[x+7]=A2007;
1036          BWrite[x+7]=B2007;
1037         }
1038
1039         BWrite[0x4014]=B4014;
1040         SetNESSoundMap();
1041         InitializeInput();
1042 }
1043
1044 int GameLoaded=0;
1045 void CloseGame(void)
1046 {
1047  if(GameLoaded)
1048  {
1049   if(FCEUGameInfo.type!=GIT_NSF)
1050    FCEU_FlushGameCheats(0,0);
1051   #ifdef NETWORK
1052   if(FSettings.NetworkPlay) KillNetplay();
1053   #endif
1054   GameInterface(GI_CLOSE);
1055   CloseGenie();
1056   GameLoaded=0;
1057  }
1058 }
1059
1060 void ResetGameLoaded(void)
1061 {
1062         if(GameLoaded) CloseGame();
1063         GameStateRestore=0;
1064         PPU_hook=0;
1065         GameHBIRQHook=GameHBIRQHook2=0;
1066         GameExpSound.Fill=0;
1067         GameExpSound.RChange=0;
1068         if(GameExpSound.Kill)
1069          GameExpSound.Kill();
1070         GameExpSound.Kill=0;
1071         MapIRQHook=0;
1072         MMC5Hack=0;
1073         PAL&=1;
1074         pale=0;
1075
1076         FCEUGameInfo.name=0;
1077         FCEUGameInfo.type=GIT_CART;
1078         FCEUGameInfo.vidsys=GIV_USER;
1079         FCEUGameInfo.input[0]=FCEUGameInfo.input[1]=-1;
1080         FCEUGameInfo.inputfc=-1;
1081 }
1082
1083 char lastLoadedGameName [2048];
1084 int UNIFLoad(const char *name, int fp);
1085 int iNESLoad(const char *name, int fp);
1086 int FDSLoad(const char *name, int fp);
1087 int NSFLoad(int fp);
1088
1089 FCEUGI *FCEUI_LoadGame(char *name)
1090 {
1091         char name2[512];
1092         int have_movie = 0;
1093         int fp;
1094
1095         Exit=1;
1096         ResetGameLoaded();
1097
1098         strncpy(name2, name, sizeof(name2));
1099         name2[sizeof(name2)-1] = 0;
1100
1101         fp=FCEU_fopen(name2,"rb");
1102         if(!fp)
1103         {
1104          FCEU_PrintError("Error opening \"%s\"!",name);
1105          return 0;
1106         }
1107
1108         {
1109          char *p = name2 + strlen(name2) - 4;
1110          if (strcmp(p, ".fcm") == 0)
1111          {
1112           // movie detected
1113           printf("movie detected\n");
1114           FCEU_fclose(fp);
1115           *p = 0;
1116           fp=FCEU_fopen(name2,"rb");
1117           if (!fp) {
1118            printf("no ROM for movie\n");
1119            return 0;
1120           }
1121           have_movie = 1;
1122          }
1123         }
1124
1125         strcpy(lastLoadedGameName, name2);
1126
1127         GetFileBase(name2);
1128         if(iNESLoad(name2,fp))
1129          goto endlseq;
1130         if(NSFLoad(fp))
1131          goto endlseq;
1132         if(FDSLoad(name2,fp))
1133          goto endlseq;
1134         if(UNIFLoad(name2,fp))
1135          goto endlseq;
1136
1137         FCEU_PrintError("An error occurred while loading the file.");
1138         FCEU_fclose(fp);
1139         return 0;
1140
1141         endlseq:
1142         FCEU_fclose(fp);
1143         GameLoaded=1;
1144
1145         FCEU_ResetVidSys();
1146         if(FCEUGameInfo.type!=GIT_NSF)
1147          if(FSettings.GameGenie)
1148           OpenGenie();
1149
1150         PowerNES();
1151         #ifdef NETWORK
1152         if(FSettings.NetworkPlay) InitNetplay();
1153         #endif
1154         SaveStateRefresh();
1155         if(FCEUGameInfo.type!=GIT_NSF)
1156         {
1157          FCEU_LoadGamePalette();
1158          FCEU_LoadGameCheats(0);
1159         }
1160
1161         FCEU_ResetPalette();
1162         Exit=0;
1163
1164         if (have_movie)
1165                 FCEUI_LoadMovie(name, 1);
1166         return(&FCEUGameInfo);
1167 }
1168
1169
1170 void FCEU_ResetVidSys(void)
1171 {
1172  int w;
1173
1174  if(FCEUGameInfo.vidsys==GIV_NTSC)
1175   w=0;
1176  else if(FCEUGameInfo.vidsys==GIV_PAL)
1177   w=1;
1178  else
1179   w=FSettings.PAL;
1180
1181  if(w)
1182  {
1183   PAL=1;
1184   FSettings.FirstSLine=FSettings.UsrFirstSLine[1];
1185   FSettings.LastSLine=FSettings.UsrLastSLine[1];
1186  }
1187  else
1188  {
1189   PAL=0;
1190   FSettings.FirstSLine=FSettings.UsrFirstSLine[0];
1191   FSettings.LastSLine=FSettings.UsrLastSLine[0];
1192  }
1193  printf("ResetVidSys: PAL = %i\n", PAL);
1194  SetSoundVariables();
1195 }
1196
1197 int FCEUI_Initialize(void)
1198 {
1199         if(!InitVirtualVideo())
1200          return 0;
1201         memset(&FSettings,0,sizeof(FSettings));
1202         FSettings.UsrFirstSLine[0]=8;
1203         FSettings.UsrFirstSLine[1]=0;
1204         FSettings.UsrLastSLine[0]=FSettings.UsrLastSLine[1]=239;
1205         FSettings.SoundVolume=100;
1206         return 1;
1207 }
1208
1209 void MMC5_hb(int);     /* Ugh ugh ugh. */
1210 static INLINE void Thingo(void)
1211 {
1212    Loop6502();
1213
1214    if(MMC5Hack && (ScreenON || SpriteON)) MMC5_hb(scanline);
1215
1216    // check: Battletoads & Double Dragon
1217    if(tosprite>=256)
1218    {
1219     X6502_Run(256);
1220    }
1221    else
1222    {
1223      // sky glitches in SMB1 if done wrong
1224      X6502_Run(tosprite);
1225      PPU[2]|=0x40;
1226      X6502_Run(256-tosprite);
1227      tosprite = 256;
1228    }
1229    TryFixit1();
1230    DoHBlank();
1231 }
1232
1233 void EmLoop(void)
1234 {
1235  for(;;)
1236  {
1237   int x;
1238   uint32 scanlines_per_frame = PAL ? 312 : 262;
1239   UpdateInput();
1240   FCEU_ApplyPeriodicCheats();
1241
1242   // FCEUPPU_Loop:
1243   if(ppudead) /* Needed for Knight Rider, possibly others. */
1244   {
1245    //memset(XBuf, 0, 320*240);
1246    X6502_Run(scanlines_per_frame*(256+85));
1247    ppudead--;
1248    goto update;
1249   }
1250
1251   X6502_Run(256+85);
1252
1253   PPU[2]|=0x80;
1254   PPU[3]=PPUSPL=0;             /* Not sure if this is correct.  According
1255                                   to Matt Conte and my own tests, it is.  Timing is probably
1256                                   off, though.  NOTE:  Not having this here
1257                                   breaks a Super Donkey Kong game. */
1258
1259   X6502_Run(12);                /* I need to figure out the true nature and length
1260                                    of this delay.
1261                                 */
1262   if(FCEUGameInfo.type==GIT_NSF)
1263    DoNSFFrame();
1264   else if(VBlankON)
1265    TriggerNMI();
1266
1267   // Note: this is needed for asm core
1268   // Warning: using 'scanline' var here breaks Castlevania III
1269   {
1270    int lines;
1271    X6502_Run(256+85-12);
1272    for (lines=scanlines_per_frame-242-1;lines;lines--)
1273      X6502_Run(256+85);
1274   }
1275   // X6502_Run((scanlines_per_frame-242)*(256+85)-12);
1276   PPU_status&=0x1f;
1277   X6502_Run(256);
1278
1279   {
1280    if(ScreenON || SpriteON)
1281    {
1282     if(GameHBIRQHook)
1283      GameHBIRQHook();
1284      if(PPU_hook)
1285       for(x=0;x<42;x++) {PPU_hook(0x2000); PPU_hook(0);} // ugh
1286     if(GameHBIRQHook2)
1287      GameHBIRQHook2();
1288    }
1289
1290    X6502_Run(85-16);
1291
1292    if(ScreenON || SpriteON)
1293    {
1294     RefreshAddr=TempAddr;
1295     if(PPU_hook) PPU_hook(RefreshAddr&0x3fff);
1296    }
1297    ResetRL();
1298
1299    X6502_Run(16-kook);
1300    kook ^= 1;
1301   }
1302
1303   if(FCEUGameInfo.type==GIT_NSF)
1304   {
1305    // run scanlines for asm core to fuction
1306    for(scanline=0;scanline<240;scanline++)
1307     X6502_Run(256+85);
1308   }
1309   else
1310   {
1311    int x,max,maxref;
1312
1313    deemp=PPU[1]>>5;
1314    SetRefreshLine();
1315    for(scanline=0;scanline<240;)       // scanline is incremented in  DoLine.  Evil. :/
1316    {
1317     deempcnt[deemp]++;
1318     Thingo();
1319    }
1320    if(MMC5Hack && (ScreenON || SpriteON)) MMC5_hb(scanline);
1321    for(x=1,max=0,maxref=0;x<7;x++)
1322    {
1323     if(deempcnt[x]>max)
1324     {
1325      max=deempcnt[x];
1326      maxref=x;
1327     }
1328     deempcnt[x]=0;
1329    }
1330    SetNESDeemph(maxref,0);
1331   }
1332
1333 update:
1334   {
1335    int ssize;
1336
1337    ssize=FlushEmulateSound();
1338
1339    timestampbase += timestamp;
1340    timestamp = 0;
1341
1342    #ifdef FRAMESKIP
1343    if(FSkip)
1344    {
1345     FCEU_PutImageDummy();
1346     FSkip--;
1347     FCEUD_Update(0,WaveFinalMono,ssize);
1348    }
1349    else
1350    #endif
1351    {
1352     FCEU_PutImage();
1353     FCEUD_Update(XBuf+8,WaveFinalMono,ssize);
1354    }
1355   }
1356
1357   if(Exit)
1358   {
1359    CloseGame();
1360    break;
1361   }
1362
1363  } // for
1364 }
1365
1366 #ifdef FPS
1367 #include <sys/time.h>
1368 uint64 frcount;
1369 #endif
1370 void FCEUI_Emulate(void)
1371 {
1372         #ifdef FPS
1373         uint64 starttime,end;
1374         struct timeval tv;
1375         frcount=0;
1376         gettimeofday(&tv,0);
1377         starttime=((uint64)tv.tv_sec*1000000)+tv.tv_usec;
1378         #endif
1379         EmLoop();
1380
1381         #ifdef FPS
1382         // Probably won't work well on Windows port; for
1383         // debugging/speed testing.
1384         {
1385          uint64 w;
1386          int i,frac;
1387          gettimeofday(&tv,0);
1388          end=((uint64)tv.tv_sec*1000000)+tv.tv_usec;
1389          w=frcount*10000000000LL/(end-starttime);
1390          i=w/10000;
1391          frac=w-i*10000;
1392          printf("Average FPS: %d.%04d\n",i,frac);
1393         }
1394         #endif
1395
1396 }
1397
1398 void FCEUI_CloseGame(void)
1399 {
1400         Exit=1;
1401 }
1402
1403 static void ResetPPU(void)
1404 {
1405         VRAMBuffer=PPU[0]=PPU[1]=PPU[2]=PPU[3]=0;
1406         PPUSPL=0;
1407         PPUGenLatch=0;
1408         RefreshAddr=TempAddr=0;
1409         vtoggle = 0;
1410         ppudead = 2;
1411         kook = 0;
1412 }
1413
1414 static void PowerPPU(void)
1415 {
1416         memset(NTARAM,0x00,0x800);
1417         memset(PALRAM,0x00,0x20);
1418         memset(SPRAM,0x00,0x100);
1419         ResetPPU();
1420 }
1421
1422 void ResetNES(void)
1423 {
1424         if(!GameLoaded) return;
1425         GameInterface(GI_RESETM2);
1426         ResetSound();
1427         ResetPPU();
1428         X6502_Reset();
1429 }
1430
1431 static void FCEU_MemoryRand(uint8 *ptr, uint32 size)
1432 {
1433  int x=0;
1434  while(size)
1435  {
1436   *ptr=(x&4)?0xFF:0x00;
1437   x++;
1438   size--;
1439   ptr++;
1440  }
1441 }
1442
1443 void PowerNES(void)
1444 {
1445         if(!GameLoaded) return;
1446
1447         FCEU_CheatResetRAM();
1448         FCEU_CheatAddRAM(2,0,RAM);
1449
1450         GeniePower();
1451
1452 #ifndef DEBUG_ASM_6502
1453         FCEU_MemoryRand(RAM,0x800);
1454 #else
1455         memset(RAM,0x00,0x800);
1456 #endif
1457         ResetMapping();
1458         GameInterface(GI_POWER);
1459         PowerSound();
1460         PowerPPU();
1461         timestampbase=0;
1462 #ifdef ASM_6502
1463         if (geniestage)
1464          GenieSetPages(0);
1465 #endif
1466         X6502_Power();
1467 }
1468
1469
1470 /* savestate stuff */
1471 uint16 TempAddrT,RefreshAddrT;
1472
1473 SFORMAT FCEUPPU_STATEINFO[]={
1474  { NTARAM, 0x800, "NTAR"},
1475  { PALRAM, 0x20, "PRAM"},
1476  { SPRAM, 0x100, "SPRA"},
1477  { PPU, 0x4, "PPUR"},
1478  { &XOffset, 1, "XOFF"},
1479  { &vtoggle, 1, "VTOG"},
1480  { &RefreshAddrT, 2|RLSB, "RADD"},
1481  { &TempAddrT, 2|RLSB, "TADD"},
1482  { &VRAMBuffer, 1, "VBUF"},
1483  { &PPUGenLatch, 1, "PGEN"},
1484  // from 0.98.15
1485  { &kook, 1, "KOOK"},
1486  { &ppudead, 1, "DEAD"},
1487  { &PPUSPL, 1, "PSPL"},
1488  { 0 }
1489  };
1490
1491