menu and controls wip..
[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=0;
566 void FCEUI_FrameSkip(int x)
567 {
568  FSkip=x;
569 }
570 #endif
571
572 /*      This is called at the beginning of each visible scanline */
573 static void Loop6502(void)
574 {
575         uint32 tem;
576         int x;
577         uint8 *target=XBuf+scanline*320+32;
578
579         if(ScreenON || SpriteON)
580         {
581          /* PRefreshLine() will not get called on skipped frames.  This
582             could cause a problem, but the solution would be rather complex,
583             due to the current sprite 0 hit code.
584          */
585          #ifdef FRAMESKIP
586          if(!FSkip)
587          {
588          #endif
589           if(ScreenON)
590           {
591            if(scanline>=FSettings.FirstSLine && scanline<=FSettings.LastSLine)
592             BGRender(target);
593            else
594            {
595             if(PPU_hook)
596              PRefreshLine();
597            }
598           }
599           else
600           {
601            tem=Pal[0]|(Pal[0]<<8)|(Pal[0]<<16)|(Pal[0]<<24);
602            tem|=0x40404040;
603            FCEU_dwmemset(target,tem,264);
604           }
605          #ifdef FRAMESKIP
606          }
607          #endif
608          if (SpriteON && scanline)
609           RefreshSprite(target);
610          #ifdef FRAMESKIP
611          if(!FSkip)
612          {
613          #endif
614           if(PPU[1]&0x01)
615           {
616            for(x=63;x>=0;x--)
617             ((uint32 *)target)[x]=((uint32*)target)[x]&0xF0F0F0F0;
618           }
619 #ifdef GP2X
620            if((PPU[1]>>5)==0x7) block_or(target, 256, 0xc0);
621            else if(PPU[1]&0xE0) block_andor(target, 256, 0x3f, 0x40);
622            else                 block_andor(target, 256, 0x3f, 0x80);
623 #else
624            if((PPU[1]>>5)==0x7)
625             for(x=63;x>=0;x--)
626              ((uint32 *)target)[x]=(((uint32*)target)[x])|0xc0c0c0c0;
627            else if(PPU[1]&0xE0)
628             for(x=63;x>=0;x--)
629              ((uint32 *)target)[x]=(((uint32*)target)[x]&0x3f3f3f3f)|0x40404040;
630            else
631             for(x=63;x>=0;x--)
632              ((uint32 *)target)[x]=(((uint32*)target)[x]&0x3f3f3f3f)|0x80808080;
633 #endif
634           // black borders
635           ((uint32 *)target)[-2]=((uint32 *)target)[-1]=0;
636           ((uint32 *)target)[64]=((uint32 *)target)[65]=0;
637          #ifdef FRAMESKIP
638          }
639          #endif
640         }
641         else
642         {
643          tem=Pal[0]|(Pal[0]<<8)|(Pal[0]<<16)|(Pal[0]<<24);
644          FCEU_dwmemset(target,tem,256);
645         }
646         if(InputScanlineHook)
647          InputScanlineHook(target, scanline);
648 }
649
650 #define PAL(c)  ((c)+cc)
651
652
653 static void PRefreshLine(void)
654 {
655         uint32 vofs;
656         uint8 X1;
657
658         vofs = 0;
659         if (BGAdrHI) vofs = 0x1000;
660
661         vofs+=(RefreshAddr>>12)&7;
662
663         for(X1=33;X1;X1--)
664         {
665                 register uint8 no;
666                 register uint8 zz2;
667                 zz2=(uint8)((RefreshAddr>>10)&3);
668                 PPU_hook(0x2000|(RefreshAddr&0xFFF));
669                 no  = vnapage[zz2][(RefreshAddr&0x3ff)];
670                 PPU_hook((no<<4)+vofs);
671                 if((RefreshAddr&0x1f)==0x1f)
672                  RefreshAddr^=0x41F;
673                 else
674                  RefreshAddr++;
675         }
676 }
677
678 /* This high-level graphics MMC5 emulation code was written
679    for MMC5 carts in "CL" mode.  It's probably not totally
680    correct for carts in "SL" mode.
681    */
682 static void RefreshLine_MMC5Hack1(uint8 *P, uint32 vofs)
683 {
684           int8 tochange, X1;
685
686           tochange=MMC5HackSPMode&0x1F;
687
688           for(X1=33;X1;X1--,P+=8)
689           {
690                 uint8 *C;
691                 uint8 cc,zz,zz2;
692                 uint32 vadr;
693
694                 if((tochange<=0 && MMC5HackSPMode&0x40) ||
695                    (tochange>0 && !(MMC5HackSPMode&0x40)))
696                 {
697                  uint8 xs,ys;
698
699                  xs=33-X1;
700                  ys=((scanline>>3)+MMC5HackSPScroll)&0x1F;
701                  if(ys>=0x1E) ys-=0x1E;
702                  vadr=(MMC5HackExNTARAMPtr[xs|(ys<<5)]<<4)+(vofs&7);
703
704                  C = MMC5HackVROMPTR+vadr;
705                  C += ((MMC5HackSPPage & 0x3f & MMC5HackVROMMask) << 12);
706
707                  cc=MMC5HackExNTARAMPtr[0x3c0+(xs>>2)+((ys&0x1C)<<1)];
708                  cc=((cc >> ((xs&2) + ((ys&0x2)<<1))) &3) <<2;
709                 }
710                 else
711                 {
712                  zz=RefreshAddr&0x1F;
713                  zz2=(RefreshAddr>>10)&3;
714                  vadr=(vnapage[zz2][RefreshAddr&0x3ff]<<4)+vofs;
715                  C = MMC5BGVRAMADR(vadr);
716                  cc=vnapage[zz2][0x3c0+(zz>>2)+((RefreshAddr&0x380)>>4)];
717                  cc=((cc >> ((zz&2) + ((RefreshAddr&0x40)>>4))) &3) <<2;
718                 }
719                 #include "fceline.h"
720
721                 if((RefreshAddr&0x1f)==0x1f)
722                  RefreshAddr^=0x41F;
723                 else
724                  RefreshAddr++;
725                 tochange--;
726           }
727 }
728
729 static void RefreshLine_MMC5Hack2(uint8 *P, uint32 vofs)
730 {
731           int8 tochange, X1;
732
733           tochange=MMC5HackSPMode&0x1F;
734
735           for(X1=33;X1;X1--,P+=8)
736           {
737                 uint8 *C;
738                 uint8 cc;
739                 uint8 zz2;
740                 uint32 vadr;
741
742                 if((tochange<=0 && MMC5HackSPMode&0x40) ||
743                    (tochange>0 && !(MMC5HackSPMode&0x40)))
744                 {
745                  uint8 xs,ys;
746
747                  xs=33-X1;
748                  ys=((scanline>>3)+MMC5HackSPScroll)&0x1F;
749                  if(ys>=0x1E) ys-=0x1E;
750                  vadr=(MMC5HackExNTARAMPtr[xs|(ys<<5)]<<4)+(vofs&7);
751
752                  C = MMC5HackVROMPTR+vadr;
753                  C += ((MMC5HackSPPage & 0x3f & MMC5HackVROMMask) << 12);
754
755                  cc=MMC5HackExNTARAMPtr[0x3c0+(xs>>2)+((ys&0x1C)<<1)];
756                  cc=((cc >> ((xs&2) + ((ys&0x2)<<1))) &3) <<2;
757                 }
758                 else
759                 {
760                  C=MMC5HackVROMPTR;
761                  zz2=(RefreshAddr>>10)&3;
762                  vadr = (vnapage[zz2][RefreshAddr & 0x3ff] << 4) + vofs;
763                  C += (((MMC5HackExNTARAMPtr[RefreshAddr & 0x3ff]) & 0x3f &
764                          MMC5HackVROMMask) << 12) + (vadr & 0xfff);
765                  vadr = (MMC5HackExNTARAMPtr[RefreshAddr & 0x3ff] & 0xC0)>> 4;
766                  cc = vadr;
767                 }
768                 #include "fceline.h"
769                 if((RefreshAddr&0x1f)==0x1f)
770                  RefreshAddr^=0x41F;
771                 else
772                  RefreshAddr++;
773                 tochange--;
774           }
775 }
776
777 static void RefreshLine_MMC5Hack3(uint8 *P, uint32 vofs)
778 {
779           int8 X1;
780
781           for(X1=33;X1;X1--,P+=8)
782           {
783                 uint8 *C;
784                 uint8 cc;
785                 uint8 zz2;
786                 uint32 vadr;
787
788                 C=MMC5HackVROMPTR;
789                 zz2=(RefreshAddr>>10)&3;
790                 vadr = (vnapage[zz2][RefreshAddr & 0x3ff] << 4) + vofs;
791                 C += (((MMC5HackExNTARAMPtr[RefreshAddr & 0x3ff]) & 0x3f &
792                         MMC5HackVROMMask) << 12) + (vadr & 0xfff);
793                 vadr = (MMC5HackExNTARAMPtr[RefreshAddr & 0x3ff] & 0xC0)>> 4;
794                 cc = vadr;
795
796                 #include "fceline.h"
797                 if((RefreshAddr&0x1f)==0x1f)
798                  RefreshAddr^=0x41F;
799                 else
800                  RefreshAddr++;
801           }
802 }
803
804 static void RefreshLine_MMC5Hack4(uint8 *P, uint32 vofs)
805 {
806           int8 X1;
807
808           for(X1=33;X1;X1--,P+=8)
809           {
810                 uint8 *C;
811                 uint8 cc,zz,zz2;
812                 uint32 vadr;
813
814                 zz=RefreshAddr&0x1F;
815                 zz2=(RefreshAddr>>10)&3;
816                 vadr=(vnapage[zz2][RefreshAddr&0x3ff]<<4)+vofs;
817                 C = MMC5BGVRAMADR(vadr);
818                 cc=vnapage[zz2][0x3c0+(zz>>2)+((RefreshAddr&0x380)>>4)];
819                 cc=((cc >> ((zz&2) + ((RefreshAddr&0x40)>>4))) &3) <<2;
820
821                 #include "fceline.h"
822
823                 if((RefreshAddr&0x1f)==0x1f)
824                  RefreshAddr^=0x41F;
825                 else
826                  RefreshAddr++;
827           }
828 }
829
830 static void RefreshLine_PPU_hook(uint8 *P, uint32 vofs)
831 {
832          int8 X1;
833
834          for(X1=33;X1;X1--,P+=8)
835          {
836                 uint8 *C;
837                 uint8 cc,zz,zz2;
838                 uint32 vadr;
839
840                 zz=RefreshAddr&0x1F;
841                 zz2=(RefreshAddr>>10)&3;
842                 PPU_hook(0x2000|(RefreshAddr&0xFFF));
843                 cc=vnapage[zz2][0x3c0+(zz>>2)+((RefreshAddr&0x380)>>4)];
844                 cc=((cc >> ((zz&2) + ((RefreshAddr&0x40)>>4))) &3) <<2;
845                 vadr=(vnapage[zz2][RefreshAddr&0x3ff]<<4)+vofs;
846                 C = VRAMADR(vadr);
847
848                 #include "fceline.h"
849
850                 PPU_hook(vadr);
851
852                 if((RefreshAddr&0x1f)==0x1f)
853                  RefreshAddr^=0x41F;
854                 else
855                  RefreshAddr++;
856          }
857 }
858
859 static void RefreshLine_normal(uint8 *P, uint32 vofs) // vofs is 0x107 max
860 {
861          int8 X1;
862          uint32 rfraddr = RefreshAddr;
863          uint8 *page = vnapage[(rfraddr>>10)&3];
864          uint32 cc2=0;
865
866          if ((rfraddr&0xc)!=0)
867           cc2=*(uint32 *) (page + ((rfraddr&0x380)>>4) + ((rfraddr&0x10)>>2) + 0x3c0);
868
869          for (X1=33;X1;X1--,P+=8)
870          {
871                 uint8 cc,*C;
872                 uint32 vadr;
873
874                 vadr=(page[rfraddr&0x3ff]<<4)+vofs;
875                 C = VRAMADR(vadr);
876                 if ((rfraddr&0xc)==0)
877                  cc2=*(uint32 *) (page + ((rfraddr&0x380)>>4) + ((rfraddr&0x10)>>2) + 0x3c0);
878                 cc=((cc2 >> ((rfraddr&2) + ((rfraddr&0x40)>>4) + ((rfraddr&0xc)<<1))) & 3) << 2;
879
880                 #include "fceline.h"
881
882                 if((rfraddr&0x1f)==0x1f) {
883                  rfraddr^=0x41F;
884                  page = vnapage[(rfraddr>>10)&3];
885                 } else
886                  rfraddr++;
887          }
888          RefreshAddr = rfraddr;
889 }
890
891 static void SetRefreshLine(void)
892 {
893         if(MMC5Hack && geniestage!=1)
894         {
895          if(MMC5HackCHRMode==0 && (MMC5HackSPMode&0x80))
896          {
897                  if (RefreshLine != RefreshLine_MMC5Hack1) printf("set refr RefreshLine_MMC5Hack1\n");
898                  RefreshLine = RefreshLine_MMC5Hack1;
899          }
900          else if(MMC5HackCHRMode==1 && (MMC5HackSPMode&0x80))
901          {
902                 if (RefreshLine != RefreshLine_MMC5Hack2) printf("set refr RefreshLine_MMC5Hack2\n");
903                  RefreshLine = RefreshLine_MMC5Hack2;
904          }
905          else if(MMC5HackCHRMode==1)
906          {
907                 if (RefreshLine != RefreshLine_MMC5Hack3) printf("set refr RefreshLine_MMC5Hack3\n");
908                  RefreshLine = RefreshLine_MMC5Hack3;
909          }
910          else
911          {
912                 if (RefreshLine != RefreshLine_MMC5Hack4) printf("set refr RefreshLine_MMC5Hack4\n");
913                  RefreshLine = RefreshLine_MMC5Hack4;
914          }
915         }       // End if(MMC5Hack)
916         else if(PPU_hook)
917         {
918                 if (RefreshLine != RefreshLine_PPU_hook) printf("set refr RefreshLine_PPU_hook\n");
919                 RefreshLine = RefreshLine_PPU_hook;
920         }
921         else
922         {
923                 if (RefreshLine != RefreshLine_normal) printf("set refr RefreshLine_normal\n");
924                 RefreshLine = RefreshLine_normal;
925         }
926 }
927
928 static INLINE
929 void Fixit2(void)
930 {
931    if(ScreenON || SpriteON)
932    {
933     uint32 rad=RefreshAddr;
934     rad&=0xFBE0;
935     rad|=TempAddr&0x041f;
936     RefreshAddr=rad;
937     //PPU_hook(RefreshAddr,-1);
938    }
939 }
940
941 static INLINE
942 void Fixit1(void)
943 {
944    if(ScreenON || SpriteON)
945    {
946     uint32 rad=RefreshAddr;
947
948     if((rad&0x7000)==0x7000)
949     {
950      rad^=0x7000;
951      if((rad&0x3E0)==0x3A0)
952      {
953       rad^=0x3A0;
954       rad^=0x800;
955      }
956      else
957      {
958       if((rad&0x3E0)==0x3e0)
959        rad^=0x3e0;
960       else rad+=0x20;
961      }
962     }
963     else
964      rad+=0x1000;
965     RefreshAddr=rad;
966     //PPU_hook(RefreshAddr,-1);
967    }
968 }
969
970
971 /*      This is called at the beginning of all h-blanks on visible lines. */
972 static void DoHBlank(void)
973 {
974  if(ScreenON || SpriteON)
975   FetchSpriteData();
976  if(GameHBIRQHook && (ScreenON || SpriteON) && ((PPU[0]&0x38)!=0x18))
977  {
978   X6502_Run(6);
979   Fixit2();
980   X6502_Run(4);
981   GameHBIRQHook();
982   X6502_Run(85-16-10);
983  }
984  else
985  {
986   X6502_Run(6);  // Tried 65, caused problems with Slalom(maybe others)
987   Fixit2();
988   X6502_Run(85-6-16);
989  }
990  if(GameHBIRQHook2 && (ScreenON || SpriteON))
991   GameHBIRQHook2();
992  //PPU_hook(0,-1);
993  //fprintf(stderr,"%3d: $%04x\n",scanline,RefreshAddr);
994  scanline++;
995  if (scanline<240)
996   ResetRL();
997  X6502_Run(16);
998 }
999
1000
1001 // ============================//
1002 // end of new code
1003 // ===========================//
1004
1005 void ResetMapping(void)
1006 {
1007         int x;
1008
1009         SetReadHandler(0x0000,0xFFFF,ANull);
1010         SetWriteHandler(0x0000,0xFFFF,BNull);
1011
1012         SetReadHandler(0,0x7FF,ARAML);
1013         SetWriteHandler(0,0x7FF,BRAML);
1014
1015         SetReadHandler(0x800,0x1FFF,ARAMH);  /* Part of a little */
1016         SetWriteHandler(0x800,0x1FFF,BRAMH); /* hack for a small speed boost. */
1017
1018         for(x=0x2000;x<0x4000;x+=8)
1019         {
1020          ARead[x]=A200x;
1021          BWrite[x]=B2000;
1022          ARead[x+1]=A200x;
1023          BWrite[x+1]=B2001;
1024          ARead[x+2]=A2002;
1025          BWrite[x+2]=B2002;
1026          ARead[x+3]=A200x;
1027          BWrite[x+3]=B2003;
1028          ARead[x+4]=A200x;
1029          BWrite[x+4]=B2004;
1030          ARead[x+5]=A200x;
1031          BWrite[x+5]=B2005;
1032          ARead[x+6]=A200x;
1033          BWrite[x+6]=B2006;
1034          ARead[x+7]=A2007;
1035          BWrite[x+7]=B2007;
1036         }
1037
1038         BWrite[0x4014]=B4014;
1039         SetNESSoundMap();
1040         InitializeInput();
1041 }
1042
1043 int GameLoaded=0;
1044 void CloseGame(void)
1045 {
1046  if(GameLoaded)
1047  {
1048   if(FCEUGameInfo.type!=GIT_NSF)
1049    FCEU_FlushGameCheats(0,0);
1050   #ifdef NETWORK
1051   if(FSettings.NetworkPlay) KillNetplay();
1052   #endif
1053   GameInterface(GI_CLOSE);
1054   CloseGenie();
1055   GameLoaded=0;
1056  }
1057 }
1058
1059 void ResetGameLoaded(void)
1060 {
1061         if(GameLoaded) CloseGame();
1062         GameStateRestore=0;
1063         PPU_hook=0;
1064         GameHBIRQHook=GameHBIRQHook2=0;
1065         GameExpSound.Fill=0;
1066         GameExpSound.RChange=0;
1067         if(GameExpSound.Kill)
1068          GameExpSound.Kill();
1069         GameExpSound.Kill=0;
1070         MapIRQHook=0;
1071         MMC5Hack=0;
1072         PAL&=1;
1073         pale=0;
1074
1075         FCEUGameInfo.name=0;
1076         FCEUGameInfo.type=GIT_CART;
1077         FCEUGameInfo.vidsys=GIV_USER;
1078         FCEUGameInfo.input[0]=FCEUGameInfo.input[1]=-1;
1079         FCEUGameInfo.inputfc=-1;
1080 }
1081
1082 char lastLoadedGameName [2048];
1083 int UNIFLoad(const char *name, int fp);
1084 int iNESLoad(const char *name, int fp);
1085 int FDSLoad(const char *name, int fp);
1086 int NSFLoad(int fp);
1087
1088 FCEUGI *FCEUI_LoadGame(char *name)
1089 {
1090         char name2[512];
1091         int have_movie = 0;
1092         int fp;
1093
1094         //Exit=1;
1095         ResetGameLoaded();
1096
1097         strncpy(name2, name, sizeof(name2));
1098         name2[sizeof(name2)-1] = 0;
1099
1100         fp=FCEU_fopen(name2,"rb");
1101         if(!fp)
1102         {
1103          FCEU_PrintError("Error opening \"%s\"!",name);
1104          return 0;
1105         }
1106
1107         {
1108          char *p = name2 + strlen(name2) - 4;
1109          if (strcmp(p, ".fcm") == 0)
1110          {
1111           // movie detected
1112           printf("movie detected\n");
1113           FCEU_fclose(fp);
1114           *p = 0;
1115           fp=FCEU_fopen(name2,"rb");
1116           if (!fp && p - name2 > 2)  p[-2] = 0;
1117           fp=FCEU_fopen(name2,"rb");
1118           if (!fp) {
1119            printf("no ROM for movie\n");
1120            return 0;
1121           }
1122           have_movie = 1;
1123          }
1124         }
1125
1126         strcpy(lastLoadedGameName, name2);
1127
1128         GetFileBase(name2);
1129         if(iNESLoad(name2,fp))
1130          goto endlseq;
1131         if(NSFLoad(fp))
1132          goto endlseq;
1133         if(FDSLoad(name2,fp))
1134          goto endlseq;
1135         if(UNIFLoad(name2,fp))
1136          goto endlseq;
1137
1138         FCEU_PrintError("An error occurred while loading the file.");
1139         FCEU_fclose(fp);
1140         return 0;
1141
1142         endlseq:
1143         FCEU_fclose(fp);
1144         GameLoaded=1;
1145
1146         FCEU_ResetVidSys();
1147         if(FCEUGameInfo.type!=GIT_NSF)
1148          if(FSettings.GameGenie)
1149           OpenGenie();
1150
1151         PowerNES();
1152         #ifdef NETWORK
1153         if(FSettings.NetworkPlay) InitNetplay();
1154         #endif
1155         SaveStateRefresh();
1156         if(FCEUGameInfo.type!=GIT_NSF)
1157         {
1158          FCEU_LoadGamePalette();
1159          FCEU_LoadGameCheats(0);
1160         }
1161
1162         FCEU_ResetPalette();
1163         Exit=0;
1164
1165         if (have_movie)
1166                 FCEUI_LoadMovie(name, 1);
1167         return(&FCEUGameInfo);
1168 }
1169
1170
1171 void FCEU_ResetVidSys(void)
1172 {
1173  int w;
1174
1175  if(FCEUGameInfo.vidsys==GIV_NTSC)
1176   w=0;
1177  else if(FCEUGameInfo.vidsys==GIV_PAL)
1178   w=1;
1179  else
1180   w=FSettings.PAL;
1181
1182  if(w)
1183  {
1184   PAL=1;
1185   FSettings.FirstSLine=FSettings.UsrFirstSLine[1];
1186   FSettings.LastSLine=FSettings.UsrLastSLine[1];
1187  }
1188  else
1189  {
1190   PAL=0;
1191   FSettings.FirstSLine=FSettings.UsrFirstSLine[0];
1192   FSettings.LastSLine=FSettings.UsrLastSLine[0];
1193  }
1194  printf("ResetVidSys: PAL = %i\n", PAL);
1195  SetSoundVariables();
1196 }
1197
1198 int FCEUI_Initialize(void)
1199 {
1200         if(!InitVirtualVideo())
1201          return 0;
1202         memset(&FSettings,0,sizeof(FSettings));
1203         FSettings.UsrFirstSLine[0]=8;
1204         FSettings.UsrFirstSLine[1]=0;
1205         FSettings.UsrLastSLine[0]=FSettings.UsrLastSLine[1]=239;
1206         FSettings.SoundVolume=100;
1207         return 1;
1208 }
1209
1210 void MMC5_hb(int);     /* Ugh ugh ugh. */
1211 static INLINE void Thingo(void)
1212 {
1213    Loop6502();
1214
1215    if(MMC5Hack && (ScreenON || SpriteON)) MMC5_hb(scanline);
1216
1217    // check: Battletoads & Double Dragon
1218    if(tosprite>=256)
1219    {
1220     X6502_Run(256);
1221    }
1222    else
1223    {
1224      // sky glitches in SMB1 if done wrong
1225      X6502_Run(tosprite);
1226      PPU[2]|=0x40;
1227      X6502_Run(256-tosprite);
1228      tosprite = 256;
1229    }
1230    TryFixit1();
1231    DoHBlank();
1232 }
1233
1234 void EmLoop(void)
1235 {
1236  for(;;)
1237  {
1238   int x;
1239   uint32 scanlines_per_frame = PAL ? 312 : 262;
1240   UpdateInput();
1241   FCEU_ApplyPeriodicCheats();
1242
1243   // FCEUPPU_Loop:
1244   if(ppudead) /* Needed for Knight Rider, possibly others. */
1245   {
1246    //memset(XBuf, 0, 320*240);
1247    X6502_Run(scanlines_per_frame*(256+85));
1248    ppudead--;
1249    goto update;
1250   }
1251
1252   X6502_Run(256+85);
1253
1254   PPU[2]|=0x80;
1255   PPU[3]=PPUSPL=0;             /* Not sure if this is correct.  According
1256                                   to Matt Conte and my own tests, it is.  Timing is probably
1257                                   off, though.  NOTE:  Not having this here
1258                                   breaks a Super Donkey Kong game. */
1259
1260   X6502_Run(12);                /* I need to figure out the true nature and length
1261                                    of this delay.
1262                                 */
1263   if(FCEUGameInfo.type==GIT_NSF)
1264    DoNSFFrame();
1265   else if(VBlankON)
1266    TriggerNMI();
1267
1268   // Note: this is needed for asm core
1269   // Warning: using 'scanline' var here breaks Castlevania III
1270   {
1271    int lines;
1272    X6502_Run(256+85-12);
1273    for (lines=scanlines_per_frame-242-1;lines;lines--)
1274      X6502_Run(256+85);
1275   }
1276   // X6502_Run((scanlines_per_frame-242)*(256+85)-12);
1277   PPU_status&=0x1f;
1278   X6502_Run(256);
1279
1280   {
1281    if(ScreenON || SpriteON)
1282    {
1283     if(GameHBIRQHook)
1284      GameHBIRQHook();
1285      if(PPU_hook)
1286       for(x=0;x<42;x++) {PPU_hook(0x2000); PPU_hook(0);} // ugh
1287     if(GameHBIRQHook2)
1288      GameHBIRQHook2();
1289    }
1290
1291    X6502_Run(85-16);
1292
1293    if(ScreenON || SpriteON)
1294    {
1295     RefreshAddr=TempAddr;
1296     if(PPU_hook) PPU_hook(RefreshAddr&0x3fff);
1297    }
1298    ResetRL();
1299
1300    X6502_Run(16-kook);
1301    kook ^= 1;
1302   }
1303
1304   if(FCEUGameInfo.type==GIT_NSF)
1305   {
1306    // run scanlines for asm core to fuction
1307    for(scanline=0;scanline<240;scanline++)
1308     X6502_Run(256+85);
1309   }
1310   else
1311   {
1312    int x,max,maxref;
1313
1314    deemp=PPU[1]>>5;
1315    SetRefreshLine();
1316    for(scanline=0;scanline<240;)       // scanline is incremented in  DoLine.  Evil. :/
1317    {
1318     deempcnt[deemp]++;
1319     Thingo();
1320    }
1321    if(MMC5Hack && (ScreenON || SpriteON)) MMC5_hb(scanline);
1322    for(x=1,max=0,maxref=0;x<7;x++)
1323    {
1324     if(deempcnt[x]>max)
1325     {
1326      max=deempcnt[x];
1327      maxref=x;
1328     }
1329     deempcnt[x]=0;
1330    }
1331    SetNESDeemph(maxref,0);
1332   }
1333
1334 update:
1335   {
1336    int ssize;
1337
1338    ssize=FlushEmulateSound();
1339
1340    timestampbase += timestamp;
1341    timestamp = 0;
1342
1343    #ifdef FRAMESKIP
1344    if(FSkip)
1345    {
1346     FCEU_PutImageDummy();
1347     FSkip--;
1348     FCEUD_Update(0,WaveFinalMono,ssize);
1349    }
1350    else
1351    #endif
1352    {
1353     FCEU_PutImage();
1354     FCEUD_Update(XBuf+8,WaveFinalMono,ssize);
1355    }
1356   }
1357
1358   if(Exit)
1359   {
1360    //CloseGame();
1361    break;
1362   }
1363
1364  } // for
1365 }
1366
1367 #ifdef FPS
1368 #include <sys/time.h>
1369 uint64 frcount;
1370 #endif
1371 void FCEUI_Emulate(void)
1372 {
1373         #ifdef FPS
1374         uint64 starttime,end;
1375         struct timeval tv;
1376         frcount=0;
1377         gettimeofday(&tv,0);
1378         starttime=((uint64)tv.tv_sec*1000000)+tv.tv_usec;
1379         #endif
1380         EmLoop();
1381
1382         #ifdef FPS
1383         // Probably won't work well on Windows port; for
1384         // debugging/speed testing.
1385         {
1386          uint64 w;
1387          int i,frac;
1388          gettimeofday(&tv,0);
1389          end=((uint64)tv.tv_sec*1000000)+tv.tv_usec;
1390          w=frcount*10000000000LL/(end-starttime);
1391          i=w/10000;
1392          frac=w-i*10000;
1393          printf("Average FPS: %d.%04d\n",i,frac);
1394         }
1395         #endif
1396
1397 }
1398
1399 void FCEUI_CloseGame(void)
1400 {
1401         Exit=1;
1402 }
1403
1404 static void ResetPPU(void)
1405 {
1406         VRAMBuffer=PPU[0]=PPU[1]=PPU[2]=PPU[3]=0;
1407         PPUSPL=0;
1408         PPUGenLatch=0;
1409         RefreshAddr=TempAddr=0;
1410         vtoggle = 0;
1411         ppudead = 2;
1412         kook = 0;
1413 }
1414
1415 static void PowerPPU(void)
1416 {
1417         memset(NTARAM,0x00,0x800);
1418         memset(PALRAM,0x00,0x20);
1419         memset(SPRAM,0x00,0x100);
1420         ResetPPU();
1421 }
1422
1423 void ResetNES(void)
1424 {
1425         if(!GameLoaded) return;
1426         GameInterface(GI_RESETM2);
1427         ResetSound();
1428         ResetPPU();
1429         X6502_Reset();
1430 }
1431
1432 static void FCEU_MemoryRand(uint8 *ptr, uint32 size)
1433 {
1434  int x=0;
1435  while(size)
1436  {
1437   *ptr=(x&4)?0xFF:0x00;
1438   x++;
1439   size--;
1440   ptr++;
1441  }
1442 }
1443
1444 void PowerNES(void)
1445 {
1446         if(!GameLoaded) return;
1447
1448         FCEU_CheatResetRAM();
1449         FCEU_CheatAddRAM(2,0,RAM);
1450
1451         GeniePower();
1452
1453 #ifndef DEBUG_ASM_6502
1454         FCEU_MemoryRand(RAM,0x800);
1455 #else
1456         memset(RAM,0x00,0x800);
1457 #endif
1458         ResetMapping();
1459         GameInterface(GI_POWER);
1460         PowerSound();
1461         PowerPPU();
1462         timestampbase=0;
1463 #ifdef ASM_6502
1464         if (geniestage)
1465          GenieSetPages(0);
1466 #endif
1467         X6502_Power();
1468 }
1469
1470
1471 /* savestate stuff */
1472 uint16 TempAddrT,RefreshAddrT;
1473
1474 SFORMAT FCEUPPU_STATEINFO[]={
1475  { NTARAM, 0x800, "NTAR"},
1476  { PALRAM, 0x20, "PRAM"},
1477  { SPRAM, 0x100, "SPRA"},
1478  { PPU, 0x4, "PPUR"},
1479  { &XOffset, 1, "XOFF"},
1480  { &vtoggle, 1, "VTOG"},
1481  { &RefreshAddrT, 2|RLSB, "RADD"},
1482  { &TempAddrT, 2|RLSB, "TADD"},
1483  { &VRAMBuffer, 1, "VBUF"},
1484  { &PPUGenLatch, 1, "PGEN"},
1485  // from 0.98.15
1486  { &kook, 1, "KOOK"},
1487  { &ppudead, 1, "DEAD"},
1488  { &PPUSPL, 1, "PSPL"},
1489  { 0 }
1490  };
1491
1492