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