1d5b4937e3c58f54089919e7550e35abc7983d68
[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        "movie.h"
52
53 #define Pal     (PALRAM)
54
55
56 #ifdef DEBUG_ASM_6502
57 extern int cpu_repeat;
58 extern int cpu_lastval;
59 #endif
60
61 static void (*RefreshLine)(uint8 *P, uint32 vofs) = NULL;
62 static void PRefreshLine(void);
63
64 static void ResetPPU(void);
65 static void PowerPPU(void);
66
67 uint64 timestampbase=0;
68
69 int MMC5Hack;
70 uint32 MMC5HackVROMMask;
71 uint8 *MMC5HackExNTARAMPtr;
72 uint8 *MMC5HackVROMPTR;
73 uint8 MMC5HackCHRMode=0;
74 uint8 MMC5HackSPMode;
75 uint8 MMC5HackSPScroll;
76 uint8 MMC5HackSPPage;
77
78 uint8 *MMC5SPRVPage[8];
79 uint8 *MMC5BGVPage[8];
80
81
82 uint8 VRAMBuffer,PPUGenLatch;
83
84 uint8 *vnapage[4];
85 uint8 PPUNTARAM;
86 uint8 PPUCHRRAM;
87
88 /* Color deemphasis emulation.  Joy... */
89 static uint8 deemp=0;
90 static int deempcnt[8];
91
92 int tosprite=256;
93
94 FCEUGI FCEUGameInfo;
95 void (*GameInterface)(int h);
96
97 void FP_FASTAPASS(1) (*PPU_hook)(uint32 A);
98
99 void (*GameStateRestore)(int version);
100 void (*GameHBIRQHook)(void);
101
102 readfunc ARead[0x10000];
103 writefunc BWrite[0x10000];
104 static readfunc *AReadG;
105 static writefunc *BWriteG;
106 static int RWWrap=0;
107
108 #ifdef ASM_6502
109 static void asmcpu_update(int32 cycles)
110 {
111  // timestamp..
112  timestamp += ((cycles >> 4) * 43) >> 7; // aproximating /= 48
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;
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];
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   free(AReadG);
205   free(BWriteG);
206   AReadG=0;
207   BWriteG=0;
208   RWWrap=0;
209  }
210 }
211
212 readfunc FASTAPASS(1) GetReadHandler(int32 a)
213 {
214   if(a>=0x8000 && RWWrap)
215    return AReadG[a-0x8000];
216   else
217    return ARead[a];
218 }
219
220 void FASTAPASS(3) SetReadHandler(int32 start, int32 end, readfunc func)
221 {
222   int32 x;
223
224   if(!func)
225    func=ANull;
226
227   if(RWWrap)
228    for(x=end;x>=start;x--)
229    {
230     if(x>=0x8000)
231      AReadG[x-0x8000]=func;
232     else
233      ARead[x]=func;
234    }
235   else
236
237    for(x=end;x>=start;x--)
238     ARead[x]=func;
239 }
240
241 writefunc FASTAPASS(1) GetWriteHandler(int32 a)
242 {
243   if(RWWrap && a>=0x8000)
244    return BWriteG[a-0x8000];
245   else
246    return BWrite[a];
247 }
248
249 void FASTAPASS(3) SetWriteHandler(int32 start, int32 end, writefunc func)
250 {
251   int32 x;
252
253   if(!func)
254    func=BNull;
255
256   if(RWWrap)
257    for(x=end;x>=start;x--)
258    {
259     if(x>=0x8000)
260      BWriteG[x-0x8000]=func;
261     else
262      BWrite[x]=func;
263    }
264   else
265    for(x=end;x>=start;x--)
266     BWrite[x]=func;
267 }
268
269 uint8 vtoggle=0;
270 uint8 XOffset=0;
271
272 uint32 TempAddr,RefreshAddr;
273
274
275 /* scanline is equal to the current visible scanline we're on. */
276
277 int scanline;
278
279 uint8 GameMemBlock[131072] __attribute__ ((aligned (4)));
280 uint8 NTARAM[0x800] __attribute__ ((aligned (4)));
281 uint8 PALRAM[0x20] __attribute__ ((aligned (4)));
282 #if !defined(ASM_6502) || defined(DEBUG_ASM_6502)
283 uint8 RAM[0x800] __attribute__ ((aligned (4)));
284 #endif
285
286 uint8 PPU[4];
287 uint8 PPUSPL;
288
289 uint8 PAL=0;
290
291
292 #define MMC5BGVRAMADR(V)      &MMC5BGVPage[(V)>>10][(V)]
293 #define VRAMADR(V)      &VPage[(V)>>10][(V)]
294
295 static DECLFW(BRAML)
296 {
297         RAM[A]=V;
298 }
299
300 static DECLFW(BRAMH)
301 {
302         RAM[A&0x7FF]=V;
303 }
304
305 static DECLFR(ARAML)
306 {
307         return RAM[A];
308 }
309
310 static DECLFR(ARAMH)
311 {
312         return RAM[A&0x7FF];
313 }
314
315
316 static DECLFR(A2002)
317 {
318                         uint8 ret;
319 #ifdef DEBUG_ASM_6502
320         if (cpu_repeat) return cpu_lastval;
321 #endif
322                         ret = PPU_status;
323                         vtoggle=0;
324                         PPU_status&=0x7F;
325 #ifdef DEBUG_ASM_6502
326 //      cpu_lastval=ret|(PPUGenLatch&0x1F);
327 #endif
328                         return ret|(PPUGenLatch&0x1F);
329 }
330
331 static DECLFR(A200x)
332 {
333                         return PPUGenLatch;
334 }
335
336 static DECLFR(A2007)
337 {
338                         uint8 ret;
339                         uint32 tmp=RefreshAddr&0x3FFF;
340 #ifdef DEBUG_ASM_6502
341         if (cpu_repeat) return cpu_lastval;
342 #endif
343
344                         PPUGenLatch=ret=VRAMBuffer;
345                         if(PPU_hook) PPU_hook(tmp);
346                         if(tmp<0x2000)
347                         {
348                          VRAMBuffer=VPage[tmp>>10][tmp];
349                         }
350                         else
351                         {
352                          VRAMBuffer=vnapage[(tmp>>10)&0x3][tmp&0x3FF];
353                         }
354
355                         if (INC32) RefreshAddr+=32;
356                         else RefreshAddr++;
357                         if(PPU_hook) PPU_hook(RefreshAddr&0x3fff);
358 #ifdef DEBUG_ASM_6502
359 //      cpu_lastval=ret;
360 #endif
361                         return ret;
362 }
363
364 static DECLFW(B2000)
365 {
366                 PPUGenLatch=V;
367                 PPU[0]=V;
368                 TempAddr&=0xF3FF;
369                 TempAddr|=(V&3)<<10;
370 }
371
372 static DECLFW(B2001)
373 {
374                   PPUGenLatch=V;
375                   PPU[1]=V;
376                   if(V&0xE0)
377                    deemp=V>>5;
378                   //printf("$%04x:$%02x, %d\n",X.PC,V,scanline);
379 }
380
381 static DECLFW(B2002)
382 {
383                  PPUGenLatch=V;
384 }
385
386 static DECLFW(B2003)
387 {
388                 PPUGenLatch=V;
389                 PPU[3]=V;
390                 PPUSPL=V&0x7;
391 }
392
393 static DECLFW(B2004)
394 {
395                 PPUGenLatch=V;
396                 //SPRAM[PPU[3]++]=V;
397                 if(PPUSPL&8)
398                 {
399                  if(PPU[3]>=8)
400                   SPRAM[PPU[3]]=V;
401                 }
402                 else
403                 {
404                  //printf("$%02x:$%02x\n",PPUSPL,V);
405                  SPRAM[PPUSPL]=V;
406                  PPUSPL++;
407                 }
408                 PPU[3]++;
409
410 }
411
412 static DECLFW(B2005)
413 {
414                 uint32 tmp=TempAddr;
415
416                 PPUGenLatch=V;
417                 if (!vtoggle)
418                 {
419                  tmp&=0xFFE0;
420                  tmp|=V>>3;
421                  XOffset=V&7;
422                 }
423                 else
424                 {
425                  tmp&=0x8C1F;
426                  tmp|=((V&~0x7)<<2);
427                  tmp|=(V&7)<<12;
428                 }
429
430                 TempAddr=tmp;
431                 vtoggle^=1;
432 }
433
434 static DECLFW(B2006)
435 {
436                        PPUGenLatch=V;
437                        if(!vtoggle)
438                        {
439                         TempAddr&=0x00FF;
440                         TempAddr|=(V&0x3f)<<8;
441                        }
442                        else
443                        {
444                         TempAddr&=0xFF00;
445                         TempAddr|=V;
446                         RefreshAddr=TempAddr;
447
448                         if(PPU_hook)
449                          PPU_hook(RefreshAddr);
450                        }
451                       vtoggle^=1;
452 }
453
454 static DECLFW(B2007)
455 {
456                         uint32 tmp=RefreshAddr&0x3FFF;
457
458                         PPUGenLatch=V;
459                         if(tmp>=0x3F00)
460                         {
461                         // hmmm....
462                         if(!(tmp&0xf))
463                          PALRAM[0x00]=PALRAM[0x04]=PALRAM[0x08]=PALRAM[0x0C]=
464                          PALRAM[0x10]=PALRAM[0x14]=PALRAM[0x18]=PALRAM[0x1c]=V&0x3f;
465                         else if(tmp&3) PALRAM[(tmp&0x1f)]=V&0x3f;
466                         }
467                         else if(tmp<0x2000)
468                         {
469                           if(PPUCHRRAM&(1<<(tmp>>10)))
470                             VPage[tmp>>10][tmp]=V;
471                         }
472                         else
473                         {
474                          if(PPUNTARAM&(1<<((tmp&0xF00)>>10)))
475                           vnapage[((tmp&0xF00)>>10)][tmp&0x3FF]=V;
476                         }
477                         if (INC32) RefreshAddr+=32;
478                         else RefreshAddr++;
479                         if(PPU_hook) PPU_hook(RefreshAddr&0x3fff);
480 }
481
482 static DECLFW(B4014)
483 {
484         uint32 t=V<<8;
485         int x;
486         for(x=0;x<256;x++)
487          B2004(0x2004,X.DB=ARead[t+x](t+x));
488         X6502_AddCycles(512);
489 }
490
491 void BGRender(uint8 *target)
492 {
493         uint32 tem, vofs;
494         vofs=((PPU[0]&0x10)<<8) | ((RefreshAddr>>12)&7);
495
496         Pal[0]|=64;
497         Pal[4]|=64;
498         Pal[8]|=64;
499         Pal[0xC]|=64;
500         RefreshLine(target-XOffset, vofs);
501         Pal[0]&=63;
502         Pal[4]&=63;
503         Pal[8]&=63;
504         Pal[0xC]&=63;
505
506         if(!(PPU[1]&2))
507         {
508          tem=Pal[0]|0x40;
509          tem|=tem<<8;
510          tem|=tem<<16;
511          *(uint32 *)target=*(uint32 *)(target+4)=tem;
512         }
513 }
514
515 #ifdef FRAMESKIP
516 int FSkip_setting=-1; // auto
517 int FSkip=0;
518 void FCEUI_FrameSkip(int x)
519 {
520  FSkip=x;
521 }
522 #endif
523
524 /*      This is called at the beginning of each visible scanline */
525 static void Loop6502(void)
526 {
527         uint32 tem;
528         int x;
529         uint8 *target=XBuf+scanline*320+32;
530
531         if(ScreenON || SpriteON)
532         {
533          /* PRefreshLine() will not get called on skipped frames.  This
534             could cause a problem, but the solution would be rather complex,
535             due to the current sprite 0 hit code.
536          */
537          #ifdef FRAMESKIP
538          if(!FSkip)
539          {
540          #endif
541           if(ScreenON)
542           {
543            if(scanline>=FSettings.FirstSLine && scanline<=FSettings.LastSLine)
544             BGRender(target);
545            else
546            {
547             if(PPU_hook)
548              PRefreshLine();
549            }
550           }
551           else
552           {
553            tem=Pal[0]|(Pal[0]<<8)|(Pal[0]<<16)|(Pal[0]<<24);
554            tem|=0x40404040;
555            FCEU_dwmemset(target,tem,264);
556           }
557          #ifdef FRAMESKIP
558          }
559          #endif
560          if (SpriteON && scanline)
561           RefreshSprite(target);
562          #ifdef FRAMESKIP
563          if(!FSkip)
564          {
565          #endif
566           if(PPU[1]&0x01)
567           {
568            for(x=63;x>=0;x--)
569             ((uint32 *)target)[x]=((uint32*)target)[x]&0xF0F0F0F0;
570           }
571            if((PPU[1]>>5)==0x7)
572             for(x=63;x>=0;x--)
573              ((uint32 *)target)[x]=(((uint32*)target)[x]&0x3f3f3f3f)|0x40404040;
574            else if(PPU[1]&0xE0)
575             for(x=63;x>=0;x--)
576              ((uint32 *)target)[x]=((uint32*)target)[x]|0xC0C0C0C0;
577            else
578             for(x=63;x>=0;x--)
579              ((uint32 *)target)[x]=((uint32*)target)[x]&0x3f3f3f3f;
580           FCEU_dwmemset(target-  8,0x3f3f3f3f,8);
581           FCEU_dwmemset(target+256,0x3f3f3f3f,8);
582          #ifdef FRAMESKIP
583          }
584          #endif
585         }
586         else
587         {
588          tem=Pal[0]|(Pal[0]<<8)|(Pal[0]<<16)|(Pal[0]<<24);
589          FCEU_dwmemset(target,tem,256);
590         }
591         if(InputScanlineHook)
592          InputScanlineHook(target, scanline);
593 }
594
595 #define PAL(c)  ((c)+cc)
596
597
598 static void PRefreshLine(void)
599 {
600         uint32 vofs;
601         uint8 X1;
602
603         vofs = 0;
604         if (BGAdrHI) vofs = 0x1000;
605
606         vofs+=(RefreshAddr>>12)&7;
607
608         for(X1=33;X1;X1--)
609         {
610                 register uint8 no;
611                 register uint8 zz2;
612                 zz2=(uint8)((RefreshAddr>>10)&3);
613                 PPU_hook(0x2000|(RefreshAddr&0xFFF));
614                 no  = vnapage[zz2][(RefreshAddr&0x3ff)];
615                 PPU_hook((no<<4)+vofs);
616                 if((RefreshAddr&0x1f)==0x1f)
617                  RefreshAddr^=0x41F;
618                 else
619                  RefreshAddr++;
620         }
621 }
622
623 /* This high-level graphics MMC5 emulation code was written
624    for MMC5 carts in "CL" mode.  It's probably not totally
625    correct for carts in "SL" mode.
626    */
627 static void RefreshLine_MMC5Hack1(uint8 *P, uint32 vofs)
628 {
629           int8 tochange, X1;
630
631           tochange=MMC5HackSPMode&0x1F;
632
633           for(X1=33;X1;X1--,P+=8)
634           {
635                 uint8 *C;
636                 uint8 cc,zz,zz2;
637                 uint32 vadr;
638
639                 if((tochange<=0 && MMC5HackSPMode&0x40) ||
640                    (tochange>0 && !(MMC5HackSPMode&0x40)))
641                 {
642                  uint8 xs,ys;
643
644                  xs=33-X1;
645                  ys=((scanline>>3)+MMC5HackSPScroll)&0x1F;
646                  if(ys>=0x1E) ys-=0x1E;
647                  vadr=(MMC5HackExNTARAMPtr[xs|(ys<<5)]<<4)+(vofs&7);
648
649                  C = MMC5HackVROMPTR+vadr;
650                  C += ((MMC5HackSPPage & 0x3f & MMC5HackVROMMask) << 12);
651
652                  cc=MMC5HackExNTARAMPtr[0x3c0+(xs>>2)+((ys&0x1C)<<1)];
653                  cc=((cc >> ((xs&2) + ((ys&0x2)<<1))) &3) <<2;
654                 }
655                 else
656                 {
657                  zz=RefreshAddr&0x1F;
658                  zz2=(RefreshAddr>>10)&3;
659                  vadr=(vnapage[zz2][RefreshAddr&0x3ff]<<4)+vofs;
660                  C = MMC5BGVRAMADR(vadr);
661                  cc=vnapage[zz2][0x3c0+(zz>>2)+((RefreshAddr&0x380)>>4)];
662                  cc=((cc >> ((zz&2) + ((RefreshAddr&0x40)>>4))) &3) <<2;
663                 }
664                 #include "fceline.h"
665
666                 if((RefreshAddr&0x1f)==0x1f)
667                  RefreshAddr^=0x41F;
668                 else
669                  RefreshAddr++;
670                 tochange--;
671           }
672 }
673
674 static void RefreshLine_MMC5Hack2(uint8 *P, uint32 vofs)
675 {
676           int8 tochange, X1;
677
678           tochange=MMC5HackSPMode&0x1F;
679
680           for(X1=33;X1;X1--,P+=8)
681           {
682                 uint8 *C;
683                 uint8 cc;
684                 uint8 zz2;
685                 uint32 vadr;
686
687                 if((tochange<=0 && MMC5HackSPMode&0x40) ||
688                    (tochange>0 && !(MMC5HackSPMode&0x40)))
689                 {
690                  uint8 xs,ys;
691
692                  xs=33-X1;
693                  ys=((scanline>>3)+MMC5HackSPScroll)&0x1F;
694                  if(ys>=0x1E) ys-=0x1E;
695                  vadr=(MMC5HackExNTARAMPtr[xs|(ys<<5)]<<4)+(vofs&7);
696
697                  C = MMC5HackVROMPTR+vadr;
698                  C += ((MMC5HackSPPage & 0x3f & MMC5HackVROMMask) << 12);
699
700                  cc=MMC5HackExNTARAMPtr[0x3c0+(xs>>2)+((ys&0x1C)<<1)];
701                  cc=((cc >> ((xs&2) + ((ys&0x2)<<1))) &3) <<2;
702                 }
703                 else
704                 {
705                  C=MMC5HackVROMPTR;
706                  zz2=(RefreshAddr>>10)&3;
707                  vadr = (vnapage[zz2][RefreshAddr & 0x3ff] << 4) + vofs;
708                  C += (((MMC5HackExNTARAMPtr[RefreshAddr & 0x3ff]) & 0x3f &
709                          MMC5HackVROMMask) << 12) + (vadr & 0xfff);
710                  vadr = (MMC5HackExNTARAMPtr[RefreshAddr & 0x3ff] & 0xC0)>> 4;
711                  cc = vadr;
712                 }
713                 #include "fceline.h"
714                 if((RefreshAddr&0x1f)==0x1f)
715                  RefreshAddr^=0x41F;
716                 else
717                  RefreshAddr++;
718                 tochange--;
719           }
720 }
721
722 static void RefreshLine_MMC5Hack3(uint8 *P, uint32 vofs)
723 {
724           int8 X1;
725
726           for(X1=33;X1;X1--,P+=8)
727           {
728                 uint8 *C;
729                 uint8 cc;
730                 uint8 zz2;
731                 uint32 vadr;
732
733                 C=MMC5HackVROMPTR;
734                 zz2=(RefreshAddr>>10)&3;
735                 vadr = (vnapage[zz2][RefreshAddr & 0x3ff] << 4) + vofs;
736                 C += (((MMC5HackExNTARAMPtr[RefreshAddr & 0x3ff]) & 0x3f &
737                         MMC5HackVROMMask) << 12) + (vadr & 0xfff);
738                 vadr = (MMC5HackExNTARAMPtr[RefreshAddr & 0x3ff] & 0xC0)>> 4;
739                 cc = vadr;
740
741                 #include "fceline.h"
742                 if((RefreshAddr&0x1f)==0x1f)
743                  RefreshAddr^=0x41F;
744                 else
745                  RefreshAddr++;
746           }
747 }
748
749 static void RefreshLine_MMC5Hack4(uint8 *P, uint32 vofs)
750 {
751           int8 X1;
752
753           for(X1=33;X1;X1--,P+=8)
754           {
755                 uint8 *C;
756                 uint8 cc,zz,zz2;
757                 uint32 vadr;
758
759                 zz=RefreshAddr&0x1F;
760                 zz2=(RefreshAddr>>10)&3;
761                 vadr=(vnapage[zz2][RefreshAddr&0x3ff]<<4)+vofs;
762                 C = MMC5BGVRAMADR(vadr);
763                 cc=vnapage[zz2][0x3c0+(zz>>2)+((RefreshAddr&0x380)>>4)];
764                 cc=((cc >> ((zz&2) + ((RefreshAddr&0x40)>>4))) &3) <<2;
765
766                 #include "fceline.h"
767
768                 if((RefreshAddr&0x1f)==0x1f)
769                  RefreshAddr^=0x41F;
770                 else
771                  RefreshAddr++;
772           }
773 }
774
775 static void RefreshLine_PPU_hook(uint8 *P, uint32 vofs)
776 {
777          int8 X1;
778
779          for(X1=33;X1;X1--,P+=8)
780          {
781                 uint8 *C;
782                 uint8 cc,zz,zz2;
783                 uint32 vadr;
784
785                 zz=RefreshAddr&0x1F;
786                 zz2=(RefreshAddr>>10)&3;
787                 PPU_hook(0x2000|(RefreshAddr&0xFFF));
788                 cc=vnapage[zz2][0x3c0+(zz>>2)+((RefreshAddr&0x380)>>4)];
789                 cc=((cc >> ((zz&2) + ((RefreshAddr&0x40)>>4))) &3) <<2;
790                 vadr=(vnapage[zz2][RefreshAddr&0x3ff]<<4)+vofs;
791                 C = VRAMADR(vadr);
792
793                 #include "fceline.h"
794
795                 PPU_hook(vadr);
796
797                 if((RefreshAddr&0x1f)==0x1f)
798                  RefreshAddr^=0x41F;
799                 else
800                  RefreshAddr++;
801          }
802 }
803
804 static void RefreshLine_normal(uint8 *P, uint32 vofs) // vofs is 0x107 max
805 {
806          int8 X1;
807          uint32 rfraddr = RefreshAddr;
808          uint8 *page = vnapage[(rfraddr>>10)&3];
809          uint32 cc2=0;
810
811          if ((rfraddr&0xc)!=0)
812           cc2=*(uint32 *) (page + ((rfraddr&0x380)>>4) + ((rfraddr&0x10)>>2) + 0x3c0);
813
814          for (X1=33;X1;X1--,P+=8)
815          {
816                 uint8 cc,*C;
817                 uint32 vadr;
818
819                 vadr=(page[rfraddr&0x3ff]<<4)+vofs;
820                 C = VRAMADR(vadr);
821                 if ((rfraddr&0xc)==0)
822                  cc2=*(uint32 *) (page + ((rfraddr&0x380)>>4) + ((rfraddr&0x10)>>2) + 0x3c0);
823                 cc=((cc2 >> ((rfraddr&2) + ((rfraddr&0x40)>>4) + ((rfraddr&0xc)<<1))) & 3) << 2;
824
825                 #include "fceline.h"
826
827                 if((rfraddr&0x1f)==0x1f) {
828                  rfraddr^=0x41F;
829                  page = vnapage[(rfraddr>>10)&3];
830                 } else
831                  rfraddr++;
832          }
833          RefreshAddr = rfraddr;
834 }
835
836 static void SetRefreshLine(void)
837 {
838         if(MMC5Hack && geniestage!=1)
839         {
840          if(MMC5HackCHRMode==0 && (MMC5HackSPMode&0x80))
841          {
842                  if (RefreshLine != RefreshLine_MMC5Hack1) printf("set refr RefreshLine_MMC5Hack1\n");
843                  RefreshLine = RefreshLine_MMC5Hack1;
844          }
845          else if(MMC5HackCHRMode==1 && (MMC5HackSPMode&0x80))
846          {
847                 if (RefreshLine != RefreshLine_MMC5Hack2) printf("set refr RefreshLine_MMC5Hack2\n");
848                  RefreshLine = RefreshLine_MMC5Hack2;
849          }
850          else if(MMC5HackCHRMode==1)
851          {
852                 if (RefreshLine != RefreshLine_MMC5Hack3) printf("set refr RefreshLine_MMC5Hack3\n");
853                  RefreshLine = RefreshLine_MMC5Hack3;
854          }
855          else
856          {
857                 if (RefreshLine != RefreshLine_MMC5Hack4) printf("set refr RefreshLine_MMC5Hack4\n");
858                  RefreshLine = RefreshLine_MMC5Hack4;
859          }
860         }       // End if(MMC5Hack)
861         else if(PPU_hook)
862         {
863                 if (RefreshLine != RefreshLine_PPU_hook) printf("set refr RefreshLine_PPU_hook\n");
864                 RefreshLine = RefreshLine_PPU_hook;
865         }
866         else
867         {
868                 if (RefreshLine != RefreshLine_normal) printf("set refr RefreshLine_normal\n");
869                 RefreshLine = RefreshLine_normal;
870         }
871 }
872
873 //static INLINE
874 void Fixit2(void)
875 {
876    if(ScreenON || SpriteON)
877    {
878     uint32 rad=RefreshAddr;
879     rad&=0xFBE0;
880     rad|=TempAddr&0x041f;
881     RefreshAddr=rad;
882     //PPU_hook(RefreshAddr,-1);
883    }
884 }
885
886 //static INLINE
887 void Fixit1(void)
888 {
889    if(ScreenON || SpriteON)
890    {
891     uint32 rad=RefreshAddr;
892
893     if((rad&0x7000)==0x7000)
894     {
895      rad^=0x7000;
896      if((rad&0x3E0)==0x3A0)
897      {
898       rad^=0x3A0;
899       rad^=0x800;
900      }
901      else
902      {
903       if((rad&0x3E0)==0x3e0)
904        rad^=0x3e0;
905       else rad+=0x20;
906      }
907     }
908     else
909      rad+=0x1000;
910     RefreshAddr=rad;
911     //PPU_hook(RefreshAddr,-1);
912    }
913 }
914
915 //#define NEW_TRY
916
917 /*      This is called at the beginning of all h-blanks on visible lines. */
918 #ifndef NEW_TRY
919 static void DoHBlank(void)
920 {
921  if(ScreenON || SpriteON)
922   FetchSpriteData();
923  if(GameHBIRQHook && (ScreenON || SpriteON))
924  {
925   X6502_Run(12);
926   GameHBIRQHook();
927   X6502_Run(25-12);
928   Fixit2();
929   X6502_Run(85-25);
930  }
931  else
932  {
933   X6502_Run(25);        // Tried 65, caused problems with Slalom(maybe others)
934   Fixit2();
935   X6502_Run(85-25);
936  }
937  //PPU_hook(0,-1);
938  //fprintf(stderr,"%3d: $%04x\n",scanline,RefreshAddr);
939 }
940 #endif
941
942
943 // ============================//
944 // end of new code
945 // ===========================//
946
947 void ResetMapping(void)
948 {
949         int x;
950
951         SetReadHandler(0x0000,0xFFFF,ANull);
952         SetWriteHandler(0x0000,0xFFFF,BNull);
953
954         SetReadHandler(0,0x7FF,ARAML);
955         SetWriteHandler(0,0x7FF,BRAML);
956
957         SetReadHandler(0x800,0x1FFF,ARAMH);  /* Part of a little */
958         SetWriteHandler(0x800,0x1FFF,BRAMH); /* hack for a small speed boost. */
959
960         for(x=0x2000;x<0x4000;x+=8)
961         {
962          ARead[x]=A200x;
963          BWrite[x]=B2000;
964          ARead[x+1]=A200x;
965          BWrite[x+1]=B2001;
966          ARead[x+2]=A2002;
967          BWrite[x+2]=B2002;
968          ARead[x+3]=A200x;
969          BWrite[x+3]=B2003;
970          ARead[x+4]=A200x;
971          BWrite[x+4]=B2004;
972          ARead[x+5]=A200x;
973          BWrite[x+5]=B2005;
974          ARead[x+6]=A200x;
975          BWrite[x+6]=B2006;
976          ARead[x+7]=A2007;
977          BWrite[x+7]=B2007;
978         }
979
980         BWrite[0x4014]=B4014;
981         SetNESSoundMap();
982         InitializeInput();
983 }
984
985 int GameLoaded=0;
986 void CloseGame(void)
987 {
988  if(GameLoaded)
989  {
990   if(FCEUGameInfo.type!=GIT_NSF)
991    FlushGameCheats();
992   #ifdef NETWORK
993   if(FSettings.NetworkPlay) KillNetplay();
994   #endif
995   GameInterface(GI_CLOSE);
996   CloseGenie();
997   GameLoaded=0;
998  }
999 }
1000
1001 void ResetGameLoaded(void)
1002 {
1003         if(GameLoaded) CloseGame();
1004         GameStateRestore=0;
1005         PPU_hook=0;
1006         GameHBIRQHook=0;
1007         GameExpSound.Fill=0;
1008         GameExpSound.RChange=0;
1009         if(GameExpSound.Kill)
1010          GameExpSound.Kill();
1011         GameExpSound.Kill=0;
1012         MapIRQHook=0;
1013         MMC5Hack=0;
1014         PAL&=1;
1015         pale=0;
1016
1017         FCEUGameInfo.name=0;
1018         FCEUGameInfo.type=GIT_CART;
1019         FCEUGameInfo.vidsys=GIV_USER;
1020         FCEUGameInfo.input[0]=FCEUGameInfo.input[1]=-1;
1021         FCEUGameInfo.inputfc=-1;
1022 }
1023
1024 char lastLoadedGameName [2048];
1025
1026 FCEUGI *FCEUI_LoadGame(char *name)
1027 {
1028         char name2[512];
1029         int have_movie = 0;
1030         int fp;
1031
1032         Exit=1;
1033         ResetGameLoaded();
1034
1035         strncpy(name2, name, sizeof(name2));
1036         name2[sizeof(name2)-1] = 0;
1037
1038         fp=FCEU_fopen(name2,"rb");
1039         if(!fp)
1040         {
1041          FCEU_PrintError("Error opening \"%s\"!",name);
1042          return 0;
1043         }
1044
1045         {
1046          char *p = name2 + strlen(name2) - 4;
1047          if (strcmp(p, ".fcm") == 0)
1048          {
1049           // movie detected
1050           printf("movie detected\n");
1051           FCEU_fclose(fp);
1052           *p = 0;
1053           fp=FCEU_fopen(name2,"rb");
1054           if (!fp) {
1055            printf("no ROM for movie\n");
1056            return 0;
1057           }
1058           have_movie = 1;
1059          }
1060         }
1061
1062         strcpy(lastLoadedGameName, name2);
1063
1064         GetFileBase(name2);
1065         if(iNESLoad(name2,fp))
1066          goto endlseq;
1067         if(NSFLoad(fp))
1068          goto endlseq;
1069         if(FDSLoad(name2,fp))
1070          goto endlseq;
1071         if(UNIFLoad(name2,fp))
1072          goto endlseq;
1073
1074         FCEU_PrintError("An error occurred while loading the file.");
1075         FCEU_fclose(fp);
1076         return 0;
1077
1078         endlseq:
1079         FCEU_fclose(fp);
1080         GameLoaded=1;
1081
1082         FCEU_ResetVidSys();
1083         if(FCEUGameInfo.type!=GIT_NSF)
1084          if(FSettings.GameGenie)
1085           OpenGenie();
1086
1087         PowerNES();
1088         #ifdef NETWORK
1089         if(FSettings.NetworkPlay) InitNetplay();
1090         #endif
1091         SaveStateRefresh();
1092         if(FCEUGameInfo.type!=GIT_NSF)
1093         {
1094          LoadGamePalette();
1095          LoadGameCheats();
1096         }
1097
1098         FCEU_ResetPalette();
1099         Exit=0;
1100
1101         if (have_movie)
1102                 FCEUI_LoadMovie(name, 1);
1103         return(&FCEUGameInfo);
1104 }
1105
1106
1107 void FCEU_ResetVidSys(void)
1108 {
1109  int w;
1110
1111  if(FCEUGameInfo.vidsys==GIV_NTSC)
1112   w=0;
1113  else if(FCEUGameInfo.vidsys==GIV_PAL)
1114   w=1;
1115  else
1116   w=FSettings.PAL;
1117
1118  if(w)
1119  {
1120   PAL=1;
1121   FSettings.FirstSLine=FSettings.UsrFirstSLine[1];
1122   FSettings.LastSLine=FSettings.UsrLastSLine[1];
1123  }
1124  else
1125  {
1126   PAL=0;
1127   FSettings.FirstSLine=FSettings.UsrFirstSLine[0];
1128   FSettings.LastSLine=FSettings.UsrLastSLine[0];
1129  }
1130  printf("PAL = %i\n", PAL);
1131  SetSoundVariables();
1132 }
1133
1134 int FCEUI_Initialize(void)
1135 {
1136         if(!InitVirtualVideo())
1137          return 0;
1138         memset(&FSettings,0,sizeof(FSettings));
1139         FSettings.UsrFirstSLine[0]=8;
1140         FSettings.UsrFirstSLine[1]=0;
1141         FSettings.UsrLastSLine[0]=FSettings.UsrLastSLine[1]=239;
1142         FSettings.SoundVolume=65535;    // 100%
1143         return 1;
1144 }
1145
1146 #define harko 0xe //0x9
1147 static INLINE void Thingo(void)
1148 {
1149    Loop6502();
1150 #ifndef NEW_TRY
1151
1152    if(tosprite>=256)
1153    {
1154     X6502_Run(256-harko);
1155     Fixit1();
1156     X6502_Run(harko);
1157    }
1158    else
1159    {
1160     if(tosprite<=240)
1161     {
1162      X6502_Run(tosprite);
1163      PPU[2]|=0x40;
1164      X6502_Run(256-tosprite-harko);
1165      Fixit1();
1166      X6502_Run(harko);
1167     }
1168     else
1169     {
1170      X6502_Run(256-harko);
1171      Fixit1();
1172      X6502_Run(tosprite-(256-harko));
1173      PPU[2]|=0x40;
1174      X6502_Run(256-tosprite);
1175     }
1176     tosprite=256;
1177    }
1178    DoHBlank();
1179 #else
1180    X6502_Run_scanline();
1181 #endif
1182 }
1183 #undef harko
1184
1185 void EmLoop(void)
1186 {
1187  for(;;)
1188  {
1189   uint32 scanlines_per_frame = PAL ? 312 : 262;
1190         //extern int asdc;
1191         //printf("asdc: %i\n", asdc);
1192         //asdc=0;
1193   ApplyPeriodicCheats();
1194   X6502_Run(256+85);
1195
1196   PPU[2]|=0x80;
1197   PPU[3]=PPUSPL=0;             /* Not sure if this is correct.  According
1198                                   to Matt Conte and my own tests, it is.  Timing is probably
1199                                   off, though.  NOTE:  Not having this here
1200                                   breaks a Super Donkey Kong game. */
1201
1202   X6502_Run(12);                /* I need to figure out the true nature and length
1203                                    of this delay.
1204                                 */
1205   if(FCEUGameInfo.type==GIT_NSF)
1206    TriggerNMINSF();
1207   else if(VBlankON)
1208    TriggerNMI();
1209
1210   X6502_Run(256+85-12);
1211   for(scanline=242+1;scanline<scanlines_per_frame;scanline++)
1212     X6502_Run(256+85);
1213
1214   PPU_status&=0x1f;
1215
1216   X6502_Run(256);
1217   {
1218    static int kook=0;
1219    if(ScreenON || SpriteON)
1220     if(GameHBIRQHook)
1221      GameHBIRQHook();
1222
1223    X6502_Run(85-kook);
1224    kook=(kook+1)&1;
1225   }
1226
1227   if(ScreenON || SpriteON)
1228   {
1229    RefreshAddr=TempAddr;
1230    if(PPU_hook) PPU_hook(RefreshAddr&0x3fff);
1231   }
1232   if(FCEUGameInfo.type==GIT_NSF)
1233   {
1234    X6502_Run((256+85)*240);
1235   }
1236   else
1237   {
1238    int x,max,maxref;
1239
1240    deemp=PPU[1]>>5;
1241    SetRefreshLine();
1242    for(scanline=0;scanline<240;scanline++)
1243    {
1244     deempcnt[deemp]++;
1245     Thingo();
1246    }
1247    for(x=1,max=0,maxref=0;x<7;x++)
1248    {
1249     if(deempcnt[x]>max)
1250     {
1251      max=deempcnt[x];
1252      maxref=x;
1253     }
1254     deempcnt[x]=0;
1255    }
1256    //FCEU_DispMessage("%2x:%2x:%2x:%2x:%2x:%2x:%2x:%2x %d",deempcnt[0],deempcnt[1],deempcnt[2],deempcnt[3],deempcnt[4],deempcnt[5],deempcnt[6],deempcnt[7],maxref);
1257    //memset(deempcnt,0,sizeof(deempcnt));
1258    SetNESDeemph(maxref,0);
1259   }
1260
1261   {
1262    int ssize;
1263
1264    ssize=FlushEmulateSound();
1265
1266    #ifdef FRAMESKIP
1267    if(FSkip)
1268    {
1269     FCEU_PutImageDummy();
1270     FSkip--;
1271     FCEUD_Update(0,WaveFinalMono,ssize);
1272    }
1273    else
1274    #endif
1275    {
1276     FCEU_PutImage();
1277     FCEUD_Update(XBuf+8,WaveFinalMono,ssize);
1278    }
1279    UpdateInput();
1280   }
1281
1282   if(Exit)
1283   {
1284    CloseGame();
1285    break;
1286   }
1287
1288  }
1289 }
1290
1291 #ifdef FPS
1292 #include <sys/time.h>
1293 uint64 frcount;
1294 #endif
1295 void FCEUI_Emulate(void)
1296 {
1297         #ifdef FPS
1298         uint64 starttime,end;
1299         struct timeval tv;
1300         frcount=0;
1301         gettimeofday(&tv,0);
1302         starttime=((uint64)tv.tv_sec*1000000)+tv.tv_usec;
1303         #endif
1304         EmLoop();
1305
1306         #ifdef FPS
1307         // Probably won't work well on Windows port; for
1308         // debugging/speed testing.
1309         {
1310          uint64 w;
1311          int i,frac;
1312          gettimeofday(&tv,0);
1313          end=((uint64)tv.tv_sec*1000000)+tv.tv_usec;
1314          w=frcount*10000000000LL/(end-starttime);
1315          i=w/10000;
1316          frac=w-i*10000;
1317          printf("Average FPS: %d.%04d\n",i,frac);
1318         }
1319         #endif
1320
1321 }
1322
1323 void FCEUI_CloseGame(void)
1324 {
1325         Exit=1;
1326 }
1327
1328 static void ResetPPU(void)
1329 {
1330         VRAMBuffer=PPU[0]=PPU[1]=PPU[2]=PPU[3]=0;
1331         PPUSPL=0;
1332         PPUGenLatch=0;
1333         RefreshAddr=TempAddr=0;
1334         vtoggle = 0;
1335 }
1336
1337 static void PowerPPU(void)
1338 {
1339         memset(NTARAM,0x00,0x800);
1340         memset(PALRAM,0x00,0x20);
1341         memset(SPRAM,0x00,0x100);
1342         ResetPPU();
1343 }
1344
1345 void ResetNES(void)
1346 {
1347         if(!GameLoaded || (FCEUGameInfo.type==GIT_NSF)) return;
1348         GameInterface(GI_RESETM2);
1349         ResetSound();
1350         ResetPPU();
1351         X6502_Reset();
1352 }
1353
1354 void PowerNES(void)
1355 {
1356         if(!GameLoaded) return;
1357
1358         FCEU_CheatResetRAM();
1359         FCEU_CheatAddRAM(2,0,RAM);
1360
1361         GeniePower();
1362
1363         memset(RAM,0x00,0x800);
1364         ResetMapping();
1365         GameInterface(GI_POWER);
1366         PowerSound();
1367         PowerPPU();
1368         timestampbase=0;
1369         X6502_Power();
1370 }
1371