Previous 15994 Revisions Next

r8416 Wednesday 7th July, 2010 at 05:12:20 UTC by Miodrag Milanović
Files removed from MAME
[src/emu]cpuexec.c cpuexec.h cpuintrf.h
[src/mame/drivers]janshi.c mirderby.c
[src/mame/machine]daikaiju.c
[src/mame/video]n64_bup.c

src/mame/machine/daikaiju.c
r8415r8416
1/***************************************************************************
2
3Daikaijuu no Gyakushuu protection sim
4
5Tomasz Slanina 20060529
6
7
8Communciation from CPU to MCU is encrypted - every byte
9is xored with data taken from cyclic , 22 bytes long buffer.
10
11MCU commands:
12=============
13
14 0x19 - unknown
15----------------
16 - no args
17 - no results
18Few writes at the end of level (level summary screen).
19
20
21 0x1d - watchdog?
22------------------
23 - no args
24 - no results
25
26
27  0x31 - VRAM address 1
28-----------------------
29 - args = row
30          column
31 - result = 0xd000 + column*2 + row*64
32 Address in text layer.
33
34
35 0x32 - VRAM address 2
36-----------------------
37 - args = row
38          column
39 - result = 0xc000 + column*2 + row*64
40 Address in BG layer.
41
42
43 0x36 - Controls 1
44------------------
45 - args = data from input port
46          previous result
47 - result - bits 0-2 = direction ,
48   encoded as:
49    0
50   7 1
51  6   2
52   5 3
53    4
54 - result - bit 3 = 0 -> no movement (bits 0-2 = bits 0-2 of previous result
55                    1 -> movement
56 - result - bit 4 = 0/1 -> button A pressed/released
57 - result - bit 5 = previous status of button A
58 - result - bit 6 = 0/1 -> button B pressed/released
59 - result - bit 7 = previous status of button B
60
61 0x40 - Player message(s) status (not working ?)
62-------------------------------------------------
63 - args = unk (0/9/d/f (stored at $a020))
64          unk (0/1/2 (stored at $a023))
65          unk (0/1/2 (stored at $a024)) (2nd and 3rd args are ident.)
66 - result = 0/1/2/ (same as 2nd/3rd arg)
67Result is discarded due to bug (or patch?) in the code - missing "cp 0"/"or a"/"and a"/etc instruction
68to set CPU flags before conditional jump at addr. 0x256 (previous flags are tested, Z is _always_ set
69(it's result of testing MCU "data ready to send" flag).
70Thic mcu command is used to determine if player message(READY/PLAYER1/PLAYER2) should be
71displayed (game) or not (attract mode). Due to above bug message is always displayed
72(confirmed on real hw).
73
74 0x44 -  Controls 2
75--------------------
76- args = result of command 0x36
77         previous result of command 44
78         step (1 or 2)
79- result  - bits 0-3 = direction encoded like in result of command 0x36, but
80                       16 steps instead 8. This command calculates all steps between
81                       new direction (1st arg) and old one with given step.
82                       Example:
83                       w (2,0,1)  r (1)
84                       w (2,1,1)  r (2)
85                       w (2,2,1)  r (3)
86                       w (2,3,1)  r (4)
87                       w (2,4,1)  r (4)
88                       ...
89                       w (2,4,1)  r (4)
90          - bit 4 = 1 -> result bits 0-3 == prev result bits 0-3, otherwise 0
91          - bits 5-7 = unknown , always 0 ?
92
93 0x60 - MCU ID
94---------------
95 - no args
96 - result = 0x5a
97
98
99***************************************************************************/
100#include "emu.h"
101#include "cpu/z80/z80.h"
102#include "includes/lsasquad.h"
103
104#define ID_DAIKAIJU 0x5a
105
106#define MCU_UNKNOWN   0x19
107#define MCU_WATCHDOG  0x1d
108#define MCU_ADDRESS1  0x31
109#define MCU_ADDRESS2  0x32
110#define MCU_CONTROLS1 0x36
111#define MCU_MESSAGE   0x40
112#define MCU_CONTROLS2 0x44
113#define MCU_ID        0x60
114
115#define MCU_ADDRESS1_LENGTH  2
116#define MCU_ADDRESS2_LENGTH  2
117#define MCU_CONTROLS1_LENGTH 2
118#define MCU_MESSAGE_LENGTH   3
119#define MCU_CONTROLS2_LENGTH 3
120#define MCU_ID_LENGTH        0
121
122#define SET_COMMAND(n)   state->daikaiju_command = data; \
123         state->daikaiju_length = n;\
124         state->daikaiju_cnt = 0;\
125         state->daikaiju_cntr = 0;
126
127
128static const int xortable[]=
129{
130 0xF5, 0xD5, 0x6A, 0x26, 0x00, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x16, 0x00, 0xCB, 0x23, 0x19,
131 0x11, 0x00, 0xC0, 0x19, 0xD1, 0xF1, 0xC9, -1
132};
133
134WRITE8_HANDLER( daikaiju_mcu_w )
135{
136   lsasquad_state *state = (lsasquad_state *)space->machine->driver_data;
137
138   if (state->daikaiju_xor < 0)
139   {
140      //reset
141      state->daikaiju_xor = 0;
142      data ^= 0xc3;
143   }
144   else
145   {
146      data ^= xortable[state->daikaiju_xor];
147      //check for end of table
148      if (xortable[++state->daikaiju_xor] < 0)
149      {
150         state->daikaiju_xor = 0;
151      }
152   }
153   state->daikaiju_prev = data;
154
155   if (state->daikaiju_length == 0) //new command
156   {
157      switch(data)
158      {
159         case MCU_UNKNOWN:
160         case MCU_WATCHDOG: break;
161         case MCU_ADDRESS1:  SET_COMMAND(MCU_ADDRESS1_LENGTH); break;
162         case MCU_ADDRESS2:  SET_COMMAND(MCU_ADDRESS2_LENGTH); break;
163         case MCU_CONTROLS1: SET_COMMAND(MCU_CONTROLS1_LENGTH); break;
164         case MCU_MESSAGE:   SET_COMMAND(MCU_MESSAGE_LENGTH); break;
165         case MCU_CONTROLS2: SET_COMMAND(MCU_CONTROLS2_LENGTH); break;
166         case MCU_ID:         SET_COMMAND(MCU_ID_LENGTH); break;
167         default:
168            state->daikaiju_command = data;
169            logerror("Unknown MCU command W %x %x \n",data,cpu_get_pc(space->cpu));
170      }
171   }
172   else
173   {
174      --state->daikaiju_length;
175      state->daikaiju_buffer[state->daikaiju_cnt++] = data;
176   }
177}
178
179READ8_HANDLER( daikaiju_mcu_r )
180{
181   lsasquad_state *state = (lsasquad_state *)space->machine->driver_data;
182
183   switch (state->daikaiju_command)
184   {
185      case MCU_ID:
186         return ID_DAIKAIJU;
187
188      case MCU_CONTROLS1:
189      {
190         int n;
191         switch ((state->daikaiju_buffer[0] & 0xf) ^ 0xf)
192         {
193            case 0x00:   n = (state->daikaiju_buffer[1] & (~8)) & 0xf; break;
194            case 0x08:   n = 0 | 8; break;
195            case 0x0a:   n = 1 | 8; break;
196            case 0x02:   n = 2 | 8; break;
197            case 0x06:   n = 3 | 8; break;
198            case 0x04:   n = 4 | 8; break;
199            case 0x05:   n = 5 | 8; break;
200            case 0x01:   n = 6 | 8; break;
201            case 0x09:   n = 7 | 8; break;
202
203            default:      n = 0; break;
204         }
205
206         if (!(state->daikaiju_buffer[0] & 0x10)) //button 1 pressed
207         {
208            if (state->daikaiju_buffer[1] & 0x10) //previous status
209            {
210               n |= 0x40;   // button 0->1
211            }
212            else
213            {
214               n |= 0; //button 1->1
215            }
216         }
217         else
218         {
219            if (state->daikaiju_buffer[1] & 0x10) //previous status
220            {
221               n |= 0x40 + 0x10;   // button 0->0
222            }
223            else
224            {
225               n |= 0x10; //button 1->0
226            }
227         }
228
229         if (!(state->daikaiju_buffer[0] & 0x20)) //button 2 pressed
230         {
231            if (state->daikaiju_buffer[1] & 0x20) //previous status
232            {
233               n |= 0x80;   // button 0->1
234            }
235            else
236            {
237               n |= 0; //button 1->1
238            }
239         }
240         else
241         {
242            if (state->daikaiju_buffer[1] & 0x20) //previous status
243            {
244               n |= 0x80 + 0x20;   // button 0->0
245            }
246            else
247            {
248               n |= 0x20; //button 1->0
249            }
250         }
251         return n;
252      }
253
254      case MCU_ADDRESS1:
255      {
256         int address = state->daikaiju_buffer[1] * 2 + 64 * state->daikaiju_buffer[0];
257
258         address &= 0x0fff; // ?
259         address += 0xd000;
260
261         if (state->daikaiju_cntr == 0)
262         {
263            state->daikaiju_cntr++;
264            return address & 0xff;
265         }
266         else
267         {
268            return address >> 8;
269         }
270      }
271
272      case MCU_ADDRESS2:
273      {
274         int address = state->daikaiju_buffer[1] * 2 + 64 * state->daikaiju_buffer[0];
275
276         address &= 0x1fff; // ?
277         address += 0xc000;
278
279         if (state->daikaiju_cntr == 0)
280         {
281            state->daikaiju_cntr++;
282            return address & 0xff;
283         }
284         else
285         {
286            return address >> 8;
287         }
288      }
289
290      case MCU_MESSAGE:
291         return state->daikaiju_buffer[1];
292
293      case MCU_CONTROLS2:
294      {
295         int n;
296         int dest = (state->daikaiju_buffer[0] & 0x7) << 1;
297         int prev = (state->daikaiju_buffer[1] & 0xf);
298
299         if (state->daikaiju_buffer[2] == 2)
300         {
301            prev &= 0xfe;
302         }
303
304         if (prev != dest)
305         {
306            int diff = (dest - prev);
307
308            if ((diff > 8)|| (diff < 0 && diff > -8))
309            {
310               n = (prev - state->daikaiju_buffer[2]) & 0xf;
311            }
312            else
313            {
314               n = (prev + state->daikaiju_buffer[2]) & 0xf;
315            }
316         }
317         else
318         {
319            n = prev;
320         }
321         prev &= 0xf;
322
323         if (prev != n)
324         {
325            n |= 0x10;
326         }
327         return n;
328      }
329   }
330   logerror("Unknown MCU R %x %x %x %x\n", cpu_get_pc(space->cpu), state->daikaiju_command, state->daikaiju_length, state->daikaiju_prev);
331   return 0xff;
332}
333
334READ8_HANDLER( daikaiju_mcu_status_r )
335{
336   lsasquad_state *state = (lsasquad_state *)space->machine->driver_data;
337   int res = input_port_read(space->machine, "MCU?");
338
339   res ^= mame_rand(space->machine) & 3;
340   res |= ((state->sound_pending & 0x02) ^ 2) << 3; //inverted flag
341   state->sound_pending &= ~0x02;
342   return res;
343}
src/mame/video/n64_bup.c
r8415r8416
1/*
2    Nintendo 64 Video Hardware
3
4    Initial version by Ville Linde
5    Many improvements by Harmony
6    Many improvements by angrylion, Ziggy, Gonetz, Orkin
7*/
8
9#include <math.h>
10#include "driver.h"
11#include "includes/n64.h"
12
13#define LOG_RDP_EXECUTION       0
14
15#define STRICT_ERROR (0)
16
17#if STRICT_ERROR
18#define stricterror fatalerror
19#else
20#define stricterror(...)
21#endif
22
23static FILE *rdp_exec;
24
25static UINT32 rdp_cmd_data[0x1000];
26static int rdp_cmd_ptr = 0;
27static int rdp_cmd_cur = 0;
28
29static UINT32 curpixel_cvg=0;
30static UINT32 curpixel_overlap = 0;
31
32//sign-extension macros
33#define SIGN17(x)   (((x) & 0x10000) ? ((x) | ~0x1ffff) : ((x) & 0x1ffff))
34#define SIGN16(x)   (((x) & 0x8000) ? ((x) | ~0xffff) : ((x) & 0xffff))
35#define SIGN11(x)   (((x) & 0x400) ? ((x) | ~0x7ff) : ((x) & 0x7ff))
36
37#define RDP_CVG_SPAN_MAX    1024
38
39#define COMMANDS_PER_BUCKET            16
40#define CACHE_LINE_SIZE               64         /* this is a general guess */
41#define TOTAL_BUCKETS               (512 / COMMANDS_PER_BUCKET)
42#define UNITS_PER_COMMAND            (128 / COMMANDS_PER_BUCKET)
43
44typedef struct
45{
46   int lx, rx;
47   int dymax;
48   int s, ds;
49   int t, dt;
50   int w, dw;
51   int r, dr;
52   int g, dg;
53   int b, db;
54   int a, da;
55   int z, dz;
56    UINT8 cvg[RDP_CVG_SPAN_MAX];
57    int dzpix;
58} SPAN;
59
60//UINT8 cvg_mem[8*1048576];
61
62static SPAN span[4096];
63
64/*****************************************************************************/
65
66#define BYTE_ADDR_XOR      BYTE4_XOR_BE(0)
67#define WORD_ADDR_XOR      (WORD_XOR_BE(0) >> 1)
68
69typedef struct
70{
71   UINT8 r, g, b, a;
72} COLOR;
73
74typedef struct
75{
76   UINT16 xl, yl, xh, yh;      // 10.2 fixed-point
77} RECTANGLE;
78
79typedef struct
80{
81   int tilenum;
82   UINT16 xl, yl, xh, yh;      // 10.2 fixed-point
83   INT16 s, t;               // 10.5 fixed-point
84   INT16 dsdx, dtdy;         // 5.10 fixed-point
85   int flip;
86} TEX_RECTANGLE;
87
88typedef struct
89{
90   int format;   // Image data format: RGBA, YUV, CI, IA, I
91   int size; // Size of texel element: 4b, 8b, 16b, 32b
92   UINT32 line; // Size of tile line in bytes
93   UINT32 tmem; // Starting tmem address for this tile in bytes
94   int palette; // Palette number for 4b CI texels
95   int ct, mt, cs, ms; // Clamp / mirror enable bits for S / T direction
96   int mask_t, shift_t, mask_s, shift_s; // Mask values / LOD shifts
97   UINT16 sl, tl, sh, th;      // 10.2 fixed-point, starting and ending texel row / column
98} TILE;
99
100typedef struct
101{
102   int sub_a_rgb0;
103   int sub_b_rgb0;
104   int mul_rgb0;
105   int add_rgb0;
106   int sub_a_a0;
107   int sub_b_a0;
108   int mul_a0;
109   int add_a0;
110
111   int sub_a_rgb1;
112   int sub_b_rgb1;
113   int mul_rgb1;
114   int add_rgb1;
115   int sub_a_a1;
116   int sub_b_a1;
117   int mul_a1;
118   int add_a1;
119} COMBINE_MODES;
120
121typedef struct
122{
123   int cycle_type;
124   int persp_tex_en;
125   int detail_tex_en;
126   int sharpen_tex_en;
127   int tex_lod_en;
128   int en_tlut;
129   int tlut_type;
130   int sample_type;
131   int mid_texel;
132   int bi_lerp0;
133   int bi_lerp1;
134   int convert_one;
135   int key_en;
136   int rgb_dither_sel;
137   int alpha_dither_sel;
138   int blend_m1a_0;
139   int blend_m1a_1;
140   int blend_m1b_0;
141   int blend_m1b_1;
142   int blend_m2a_0;
143   int blend_m2a_1;
144   int blend_m2b_0;
145   int blend_m2b_1;
146    int tex_edge;
147   int force_blend;
148   int alpha_cvg_select;
149   int cvg_times_alpha;
150   int z_mode;
151   int cvg_dest;
152   int color_on_cvg;
153   int image_read_en;
154   int z_update_en;
155   int z_compare_en;
156   int antialias_en;
157   int z_source_sel;
158   int dither_alpha_en;
159   int alpha_compare_en;
160} OTHER_MODES;
161
162/*****************************************************************************/
163
164#define PIXEL_SIZE_4BIT         0
165#define PIXEL_SIZE_8BIT         1
166#define PIXEL_SIZE_16BIT      2
167#define PIXEL_SIZE_32BIT      3
168
169#define CYCLE_TYPE_1         0
170#define CYCLE_TYPE_2         1
171#define CYCLE_TYPE_COPY         2
172#define CYCLE_TYPE_FILL         3
173
174#define SAMPLE_TYPE_1x1         0
175#define SAMPLE_TYPE_2x2         1
176
177static COMBINE_MODES combine;
178static OTHER_MODES other_modes;
179
180static COLOR blend_color;
181static COLOR prim_color;
182static COLOR env_color;
183static COLOR fog_color;
184static COLOR combined_color;
185static COLOR texel0_color;
186static COLOR texel1_color;
187static COLOR shade_color;
188static COLOR key_scale; // Used in NASCAR 2000
189static COLOR noise_color; // Used in Super Smash Bros.
190
191static COLOR one_color      = { 0xff, 0xff, 0xff, 0xff };
192static COLOR zero_color      = { 0x00, 0x00, 0x00, 0x00 };
193
194// combiner inputs
195static UINT8 *combiner_rgbsub_a_r[2];
196static UINT8 *combiner_rgbsub_a_g[2];
197static UINT8 *combiner_rgbsub_a_b[2];
198static UINT8 *combiner_rgbsub_b_r[2];
199static UINT8 *combiner_rgbsub_b_g[2];
200static UINT8 *combiner_rgbsub_b_b[2];
201static UINT8 *combiner_rgbmul_r[2];
202static UINT8 *combiner_rgbmul_g[2];
203static UINT8 *combiner_rgbmul_b[2];
204static UINT8 *combiner_rgbadd_r[2];
205static UINT8 *combiner_rgbadd_g[2];
206static UINT8 *combiner_rgbadd_b[2];
207
208static UINT8 *combiner_alphasub_a[2];
209static UINT8 *combiner_alphasub_b[2];
210static UINT8 *combiner_alphamul[2];
211static UINT8 *combiner_alphaadd[2];
212
213// blender input
214static UINT8 *blender1a_r[2];
215static UINT8 *blender1a_g[2];
216static UINT8 *blender1a_b[2];
217static UINT8 *blender1b_a[2];
218static UINT8 *blender2a_r[2];
219static UINT8 *blender2a_g[2];
220static UINT8 *blender2a_b[2];
221static UINT8 *blender2b_a[2];
222
223static COLOR pixel_color;
224static COLOR inv_pixel_color;
225static COLOR blended_pixel_color;
226static COLOR memory_color;
227
228static UINT32 fill_color;      // packed 16-bit or 32-bit, depending on framebuffer format
229
230static UINT16 primitive_z;
231static UINT16 primitive_delta_z;
232
233static int fb_format;
234static int fb_size;
235int fb_width;
236int fb_height;
237static UINT32 fb_address;
238
239static UINT32 zb_address;
240
241static int ti_format;
242static int ti_size;
243static int ti_width;
244static UINT32 ti_address;
245
246static TILE tile[8];
247
248static RECTANGLE clip;
249
250static UINT8 *TMEM;
251#define tlut ((UINT16*)(TMEM + 0x800))
252
253static INT32 k0, k1, k2, k3, k4, k5;
254static UINT8 primitive_lod_frac = 0;
255static UINT8 lod_frac = 0;
256static UINT8 hidden_bits[0x800000];
257
258static INT32 NormPointRom[64];
259static INT32 NormSlopeRom[64];
260
261#define zmode other_modes.z_mode
262static struct
263{
264   UINT32 shift;
265   UINT32 add;
266} z_dec_table[8] =
267{
268   { 6, 0x00000 },
269   { 5, 0x20000 },
270   { 4, 0x30000 },
271   { 3, 0x38000 },
272   { 2, 0x3c000 },
273   { 1, 0x3e000 },
274   { 0, 0x3f000 },
275   { 0, 0x3f800 },
276};
277
278static INT32 gamma_table[256];
279static INT32 gamma_dither_table[0x4000];
280static UINT16 z_com_table[0x40000]; // Pre-calculated table of compressed z values
281static UINT32 max_level = 0;
282static UINT32 min_level = 0;
283static COLOR ViBuffer[640][480]; // Used by divot filter
284static INT32 maskbits_table[16]; // Pre-calculated
285static INT32 clamp_t_diff[8];
286static INT32 clamp_s_diff[8];
287
288/* queue management */
289static osd_work_queue *   queue;         /* work queue */
290
291typedef struct _command_work_unit command_work_unit;
292struct _command_work_unit
293{
294   running_machine    *machine;
295   volatile UINT32      count_next;            /* number of scanlines and index of next item to process */
296   UINT16            previtem;            /* index of previous item in the same bucket */
297   INT16            dummy0;               /* pad to 16 bytes */
298#ifndef PTR64
299   UINT32            dummy1;               /* pad to 16 bytes */
300#endif
301   UINT32   command[44];   // Command data
302};
303
304/* command work units */
305static command_work_unit **   units;         /* array of work unit pointers */
306static UINT32            unit_next;      /* index of next unit to allocate */
307static UINT32            unit_count;      /* number of work units available */
308static size_t            unit_size;      /* size of each work unit, in bytes */
309
310/* buckets */
311static UINT16            unit_bucket[TOTAL_BUCKETS]; /* buckets for tracking unit usage */
312
313/*-------------------------------------------------
314    allocate_array - allocate an array of pointers
315-------------------------------------------------*/
316
317static void **allocate_array(size_t *itemsize, UINT32 itemcount)
318{
319   void **ptrarray;
320   int itemnum;
321
322   /* fail if 0 */
323   if (itemcount == 0)
324      return NULL;
325
326   /* round to a cache line boundary */
327   *itemsize = ((*itemsize + CACHE_LINE_SIZE - 1) / CACHE_LINE_SIZE) * CACHE_LINE_SIZE;
328
329   /* allocate the array */
330   ptrarray = alloc_array_clear_or_die(void *, itemcount);
331
332   /* allocate the actual items */
333   ptrarray[0] = alloc_array_clear_or_die(UINT8, *itemsize * itemcount);
334
335   /* initialize the pointer array */
336   for (itemnum = 1; itemnum < itemcount; itemnum++)
337      ptrarray[itemnum] = (UINT8 *)ptrarray[0] + *itemsize * itemnum;
338   return ptrarray;
339}
340
341static void rdp_work_alloc(running_machine *machine, int max_commands)
342{
343   /* allocate command work units */
344   int command_count = MAX(max_commands, 1);
345   unit_size = sizeof(command_work_unit);
346   unit_count = MIN(command_count * UNITS_PER_COMMAND, 65535);
347   unit_next = 0;
348   units = (command_work_unit **)allocate_array(&unit_size, unit_count);
349   queue = osd_work_queue_alloc(WORK_QUEUE_FLAG_MULTI | WORK_QUEUE_FLAG_HIGH_FREQ);
350}
351
352//static void rdp_poly_wait(running_machine *machine)
353//{
354   /* wait for all pending work items to complete */
355//   if (queue)
356//   {
357//      osd_work_queue_wait(queue, osd_ticks_per_second() * 100);
358//   }
359
360//   memset(unit_bucket, 0xff, sizeof(unit_bucket));
361//}
362
363INLINE int alpha_compare(running_machine *machine, UINT8 comb_alpha);
364INLINE UINT8 alpha_cvg_get(UINT8 comb_alpha);
365INLINE UINT8 COMBINER_EQUATION(UINT8 A, UINT8 B, UINT8 C, UINT8 D);
366INLINE void BLENDER_EQUATION(INT32* r, INT32* g, INT32* b, int cycle, int bsel_special);
367INLINE UINT32 addrightcvg(UINT32 x, UINT32 k);
368INLINE UINT32 addleftcvg(UINT32 x, UINT32 k);
369INLINE UINT32 FBWRITE_16(UINT16 *fb, UINT8* hb, UINT32 r, UINT32 g, UINT32 b);
370INLINE UINT32 FBWRITE_32(UINT32 *fb, UINT32 r, UINT32 g, UINT32 b);
371//INLINE UINT32 FBWRITE_8(UINT8* fb, UINT8 c);
372INLINE UINT32 z_decompress(UINT16* zb);
373INLINE UINT16 dz_decompress(UINT16* zb, UINT8* zhb);
374INLINE void z_build_com_table(void);
375INLINE void z_store(UINT16* zb, UINT8* zhb, UINT32 z, UINT32 deltaz);
376INLINE UINT32 z_compare(void* fb, UINT8* hb, UINT16* zb, UINT8* zhb, UINT32 sz, UINT16 dzpix);
377INLINE INT32 normalize_dzpix(INT32 sum);
378INLINE INT32 CLIP(INT32 value,INT32 min,INT32 max);
379INLINE COLOR video_filter16(UINT16* vbuff, UINT8* hbuff, UINT32 hres);
380INLINE void divot_filter16(INT32* r, INT32* g, INT32* b, UINT16* fbuff, UINT32 fbuff_index);
381INLINE void restore_filter16(INT32* r, INT32* g, INT32* b, UINT16* fbuff, UINT32 fbuff_index, UINT32 hres);
382INLINE UINT32 getlog2(UINT32 lod_clamp);
383INLINE void set_shade_for_rects(void);
384INLINE void set_shade_for_tris(UINT32 shade);
385INLINE void copy_colors(COLOR* dst, COLOR* src);
386INLINE void BILERP_AND_WRITE(UINT32* src0, UINT32* src1, UINT32* dest);
387INLINE void tcdiv(INT32 ss, INT32 st, INT32 sw, INT32* sss, INT32* sst);
388INLINE void divot_filter16_buffer(INT32* r, INT32* g, INT32* b, COLOR* vibuffer);
389INLINE void restore_filter16_buffer(INT32* r, INT32* g, INT32* b, COLOR* vibuff, UINT32 hres);
390INLINE void restore_two(COLOR* filtered, COLOR* neighbour);
391INLINE void video_max(UINT32* Pixels, UINT8* max, UINT32* enb);
392INLINE UINT32 ge_two(UINT32 enb);
393INLINE void calculate_clamp_diffs(UINT32 prim_tile);
394INLINE void rgb_dither(INT32* r, INT32* g, INT32* b, int dith);
395
396INLINE void MASK(INT32* S, INT32* T, INT32 cycle)
397{
398   INT32 swrap, twrap;
399
400   if (tile[cycle].mask_s) // Select clamp if mask == 0
401   {
402      swrap = *S >> (tile[cycle].mask_s > 10 ? 10 : tile[cycle].mask_s);
403      swrap &= 1;
404      if (tile[cycle].ms && swrap)
405      {
406         *S = (~(*S)) & maskbits_table[tile[cycle].mask_s]; // Mirroring and masking
407      }
408      else if (tile[cycle].mask_s)
409      {
410         *S &= maskbits_table[tile[cycle].mask_s]; // Masking
411      }
412   }
413
414   if (tile[cycle].mask_t)
415   {
416      twrap = *T >> (tile[cycle].mask_t > 10 ? 10 : tile[cycle].mask_t);
417      twrap &= 1;
418      if (tile[cycle].mt && twrap)
419      {
420         *T = (~(*T)) & maskbits_table[tile[cycle].mask_t]; // Mirroring and masking
421      }
422      else if (tile[cycle].mask_t)
423      {
424         *T &= maskbits_table[tile[cycle].mask_t];
425      }
426   }
427}
428
429INLINE void texshift(INT32* S, INT32* T, INT32* maxs, INT32* maxt, UINT32 num)
430{
431   *S = SIGN16(*S);
432   *T = SIGN16(*T);
433   if (tile[num].shift_s)
434   {
435      if (tile[num].shift_s < 11)
436      {
437         *S >>= tile[num].shift_s;
438      }
439      else
440      {
441         *S <<= (16 - tile[num].shift_s);
442      }
443      *S = SIGN16(*S);
444   }
445   if (tile[num].shift_s)
446   {
447      if (tile[num].shift_t < 11)
448      {
449         *T >>= tile[num].shift_t;
450      }
451       else
452       {
453         *T <<= (16 - tile[num].shift_t);
454      }
455      *T = SIGN16(*T);
456   }
457   *maxs = ((*S >> 3) >= tile[num].sh);
458   *maxt = ((*T >> 3) >= tile[num].th);
459}
460
461INLINE void CLAMP(INT32* S, INT32* T, INT32* SFRAC, INT32* TFRAC, INT32 maxs, INT32 maxt, INT32 num)
462{
463   int notcopy = (other_modes.cycle_type != CYCLE_TYPE_COPY);
464   int dosfrac = (tile[num].cs || !tile[num].mask_s);
465   int dos = dosfrac && notcopy;
466   int dotfrac = (tile[num].ct || !tile[num].mask_t);
467   int dot = dotfrac && notcopy;
468   int overunders = 0;
469   int overundert = 0;
470   if (*S & 0x10000 && dos)
471   {
472      *S = 0;
473      overunders = 1;
474   }
475   else if (maxs && dos)
476   {
477      *S = clamp_s_diff[num];
478      overunders = 1;
479
480   }
481   else
482   {
483      *S = (SIGN17(*S) >> 5) & 0x1fff;
484   }
485   if (overunders && dosfrac)
486   {
487      *SFRAC = 0;
488   }
489
490   if (*T & 0x10000 && dot)
491   {
492      *T = 0;
493      overundert = 1;
494   }
495   else if (maxt && dot)
496   {
497      *T = clamp_t_diff[num];
498      overundert = 1;
499   }
500   else
501   {
502      *T = (SIGN17(*T) >> 5) & 0x1fff;
503   }
504   if (overundert && dotfrac)
505   {
506      *TFRAC = 0;
507   }
508}
509
510INLINE void CLAMP_LIGHT(INT32* S, INT32* T, INT32 maxs, INT32 maxt, INT32 num)
511{
512   int notcopy = (other_modes.cycle_type != CYCLE_TYPE_COPY);
513   int dos = (tile[num].cs || !tile[num].mask_s) && notcopy;
514   int dot = (tile[num].ct || !tile[num].mask_t) && notcopy;
515
516   if (*S & 0x10000 && dos)
517   {
518      *S = 0;
519   }
520   else if (maxs && dos)
521   {
522      *S = clamp_s_diff[num];
523   }
524   else
525   {
526      *S = (SIGN17(*S) >> 5) & 0x1fff;
527   }
528
529   if (*T & 0x10000 && dot)
530   {
531      *T = 0;
532   }
533   else if (maxt && dot)
534   {
535      *T = clamp_t_diff[num];
536   }
537   else
538   {
539      *T = (SIGN17(*T) >> 5) & 0x1fff;
540   }
541}
542
543/*****************************************************************************/
544
545
546
547VIDEO_START(n64)
548{
549   int i = 0;
550   UINT8 *normpoint = memory_region(machine, "normpoint");
551   UINT8 *normslope = memory_region(machine, "normslope");
552
553   if (LOG_RDP_EXECUTION)
554      rdp_exec = fopen("rdp_execute.txt", "wt");
555
556   TMEM = auto_alloc_array(machine, UINT8, 0x1004); // 4 guard bytes
557   memset(TMEM, 0, 0x1000);
558   TMEM[0x1000] = TMEM[0x1001] = 25;
559
560   combiner_rgbsub_a_r[0] = combiner_rgbsub_a_r[1] = &one_color.r;
561   combiner_rgbsub_a_g[0] = combiner_rgbsub_a_g[1] = &one_color.g;
562   combiner_rgbsub_a_b[0] = combiner_rgbsub_a_b[1] = &one_color.b;
563   combiner_rgbsub_b_r[0] = combiner_rgbsub_b_r[1] = &one_color.r;
564   combiner_rgbsub_b_g[0] = combiner_rgbsub_b_g[1] = &one_color.g;
565   combiner_rgbsub_b_b[0] = combiner_rgbsub_b_b[1] = &one_color.b;
566   combiner_rgbmul_r[0] = combiner_rgbmul_r[1] = &one_color.r;
567   combiner_rgbmul_g[0] = combiner_rgbmul_g[1] = &one_color.g;
568   combiner_rgbmul_b[0] = combiner_rgbmul_b[1] = &one_color.b;
569   combiner_rgbadd_r[0] = combiner_rgbadd_r[1] = &one_color.r;
570   combiner_rgbadd_g[0] = combiner_rgbadd_g[1] = &one_color.g;
571   combiner_rgbadd_b[0] = combiner_rgbadd_b[1] = &one_color.b;
572
573   combiner_alphasub_a[0] = combiner_alphasub_a[1] = &one_color.a;
574   combiner_alphasub_b[0] = combiner_alphasub_b[1] = &one_color.a;
575   combiner_alphamul[0] = combiner_alphamul[1] = &one_color.a;
576   combiner_alphaadd[0] = combiner_alphaadd[1] = &one_color.a;
577
578   blender1a_r[0] = blender1a_r[1] = &pixel_color.r;
579   blender1a_g[0] = blender1a_g[1] = &pixel_color.r;
580   blender1a_b[0] = blender1a_b[1] = &pixel_color.r;
581   blender1b_a[0] = blender1b_a[1] = &pixel_color.r;
582   blender2a_r[0] = blender2a_r[1] = &pixel_color.r;
583   blender2a_g[0] = blender2a_g[1] = &pixel_color.r;
584   blender2a_b[0] = blender2a_b[1] = &pixel_color.r;
585   blender2b_a[0] = blender2b_a[1] = &pixel_color.r;
586
587   memset(hidden_bits, 3, 4194304); // Hack / fix for letters in Rayman 2
588
589   for (i = 0; i < 256; i++)
590   {
591      gamma_table[i] = sqrt((float)(i << 6));
592      gamma_table[i] <<= 1;
593   }
594
595   for (i = 0; i < 0x4000; i++)
596   {
597      gamma_dither_table[i] = sqrt(i);
598      gamma_dither_table[i] <<= 1;
599   }
600
601   z_build_com_table();
602
603   maskbits_table[0] = 0x3ff;
604   for(i = 1; i < 16; i++)
605   {
606      maskbits_table[i] = ((UINT16)(0xffff) >> (16 - i)) & 0x3ff;
607   }
608
609   for(i = 0; i < 64; i++)
610   {
611      NormPointRom[i] = (normpoint[(i << 1) + 1] << 8) | normpoint[i << 1];
612      NormSlopeRom[i] = (normslope[(i << 1) + 1] << 8) | normslope[i << 1];
613   }
614
615   rdp_work_alloc(machine, 16384);
616}
617
618VIDEO_UPDATE(n64)
619{
620   int i, j;
621   UINT32 final = 0;
622   UINT32 prev_cvg = 0, next_cvg = 0;
623    int height = fb_height;
624    int dither_filter = (n64_vi_control >> 16) & 1;
625    int fsaa = (((n64_vi_control >> 8) & 3) < 2);
626    int divot = (n64_vi_control >> 4) & 1;
627    int gamma = (n64_vi_control >> 3) & 1;
628    int gamma_dither = (n64_vi_control >> 2) & 1;
629    int vibuffering = ((n64_vi_control & 2) && fsaa && divot);
630
631    UINT32 *frame_buffer32;
632   UINT16 *frame_buffer;
633   UINT32 hb;
634   UINT8* hidden_buffer;
635   COLOR newc;
636
637   UINT32 pixels = 0;
638   UINT16 pix = 0;
639   int r, g, b;
640   int dith = 0;
641
642   INT32 hdiff = (n64_vi_hstart & 0x3ff) - ((n64_vi_hstart >> 16) & 0x3ff);
643   float hcoeff = ((float)(n64_vi_xscale & 0xfff) / (1 << 10));
644   UINT32 hres = ((float)hdiff * hcoeff);
645   INT32 invisiblewidth = n64_vi_width - hres;
646
647   INT32 vdiff = ((n64_vi_vstart & 0x3ff) - ((n64_vi_vstart >> 16) & 0x3ff)) >> 1;
648   float vcoeff = ((float)(n64_vi_yscale & 0xfff) / (1 << 10));
649   UINT32 vres = ((float)vdiff * vcoeff);
650
651   if (vdiff <= 0 || hdiff <= 0)
652   {
653      return 0;
654   }
655
656   frame_buffer = (UINT16*)&rdram[(n64_vi_origin & 0xffffff) >> 2];
657   hb = ((n64_vi_origin & 0xffffff) >> 2) >> 1;
658   hidden_buffer = &hidden_bits[hb];
659
660   vibuffering = 0; // Disabled for now
661
662
663   if (hres > 640) // Needed by Top Gear Overdrive (E)
664   {
665      invisiblewidth += (hres - 640);
666      hres = 640;
667   }
668
669   if (vibuffering && ((n64_vi_control & 3) == 2))
670   {
671      if (frame_buffer)
672      {
673         for (j=0; j < vres; j++)
674         {
675            for (i=0; i < hres; i++)
676            {
677               UINT16 pix;
678               pix = frame_buffer[pixels ^ WORD_ADDR_XOR];
679               curpixel_cvg = ((pix & 1) << 2) | (hidden_buffer[pixels ^ BYTE_ADDR_XOR] & 3); // Reuse of this variable
680               if (curpixel_cvg < 7 && i > 1 && j > 1 && i < (hres - 2) && j < (vres - 2) && fsaa)
681               {
682                  newc = video_filter16(&frame_buffer[pixels ^ WORD_ADDR_XOR], &hidden_buffer[pixels ^ BYTE_ADDR_XOR], n64_vi_width);
683                  ViBuffer[i][j] = newc;
684               }
685               else
686               {
687                  newc.r = (((pix >> 11) & 0x1f) << 3) | (((pix >> 11) & 0x1f) >> 2);
688                  newc.g = (((pix >> 6) & 0x1f) << 3) | (((pix >> 6) & 0x1f) >> 2);
689                  newc.b = (((pix >> 1) & 0x1f) << 3) | (((pix >> 1) & 0x1f) >> 2);
690                  ViBuffer[i][j] = newc;
691               }
692               pixels++;
693            }
694            pixels += invisiblewidth;
695         }
696      }
697   }
698
699    if (n64_vi_blank)
700    {
701        for (j=0; j <height; j++)
702        {
703            UINT32 *d = BITMAP_ADDR32(bitmap, j, 0);
704            for (i=0; i < fb_width; i++)
705            {
706                d[BYTE_XOR_BE(i)] = 0;
707            }
708        }
709        return 0;
710    }
711
712    switch (n64_vi_control & 0x3)
713   {
714      case 0:      // blank/no signal
715      {
716         break;
717      }
718
719      case 2:      // RGBA5551
720      {
721         pixels = 0;
722
723         if (frame_buffer)
724         {
725            for (j=0; j < vres; j++)
726            {
727               UINT32 *d = BITMAP_ADDR32(bitmap, j, 0);
728
729               for (i=0; i < hres; i++)
730               {
731                  int r, g, b;
732
733                  pix = frame_buffer[pixels ^ WORD_ADDR_XOR];
734                  curpixel_cvg = ((pix & 1) << 2) | (hidden_buffer[pixels ^ BYTE_ADDR_XOR] & 3);
735
736                  if (i > 0 && i < (hres - 1) && divot)
737                  {
738                     prev_cvg = ((frame_buffer[(pixels - 1)^WORD_ADDR_XOR] & 1) << 2) | (hidden_buffer[(pixels - 1)^BYTE_ADDR_XOR] & 3);
739                     next_cvg = ((frame_buffer[(pixels + 1)^WORD_ADDR_XOR] & 1) << 2) | (hidden_buffer[(pixels + 1)^BYTE_ADDR_XOR] & 3);
740                  }
741                  r = (((pix >> 11) & 0x1f) << 3) | (((pix >> 11) & 0x1f) >> 2);
742                  g = (((pix >> 6) & 0x1f) << 3) | (((pix >> 6) & 0x1f) >> 2);
743                  b = (((pix >> 1) & 0x1f) << 3) | (((pix >> 1) & 0x1f) >> 2);
744
745                  if (!vibuffering && curpixel_cvg < 7 && i > 1 && j > 1 && i < (hres - 2) && j < (vres - 2) && fsaa)
746                  {
747                     newc = video_filter16(&frame_buffer[pixels ^ WORD_ADDR_XOR],&hidden_buffer[pixels ^ BYTE_ADDR_XOR], n64_vi_width);
748                     r = newc.r; g = newc.g; b = newc.b;
749                  }
750                  else if (dither_filter && curpixel_cvg == 7 && i > 0 && j > 0 && i < (hres - 1) && j < (vres - 1))
751                  {
752                     if (vibuffering)
753                     {
754                        restore_filter16_buffer(&r, &g, &b, &ViBuffer[i][j], n64_vi_width);
755                     }
756                     else
757                     {
758                        restore_filter16(&r, &g, &b, &frame_buffer[pixels ^ WORD_ADDR_XOR], pixels ^ WORD_ADDR_XOR, n64_vi_width);
759                     }
760                  }
761                  if (i > 0 && i < (hres - 1) && divot && (curpixel_cvg != 7 || prev_cvg != 7 || next_cvg != 7))
762                  {
763                     if (vibuffering)
764                     {
765                        divot_filter16_buffer(&r, &g, &b, &ViBuffer[i][j]);
766                     }
767                     else
768                     {
769                        divot_filter16(&r, &g, &b, &frame_buffer[pixels ^ WORD_ADDR_XOR], pixels ^ WORD_ADDR_XOR);
770                     }
771                  }
772
773                  if (gamma_dither)
774                  {
775                     dith = mame_rand(screen->machine) & 0x3f;
776                  }
777                  if (gamma)
778                  {
779                     if (gamma_dither)
780                     {
781                        r = gamma_dither_table[(r << 6)|dith];
782                        g = gamma_dither_table[(g << 6)|dith];
783                        b = gamma_dither_table[(b << 6)|dith];
784                     }
785                     else
786                     {
787                        r = gamma_table[r];
788                        g = gamma_table[g];
789                        b = gamma_table[b];
790                     }
791                  }
792                  else if (gamma_dither)
793                  {
794                     if (r < 255)
795                        r += (dith & 1);
796                     if (g < 255)
797                        g += (dith & 1);
798                     if (b < 255)
799                        b += (dith & 1);
800                  }
801                  pixels++;
802
803                  final = (r << 16) | (g << 8) | b;
804                  d[i] = final; // Fix me for endianness
805               }
806               pixels +=invisiblewidth;
807            }
808         }
809         break;
810      }
811
812      case 3:      // RGBA8888
813      {
814            frame_buffer32 = (UINT32*)&rdram[(n64_vi_origin & 0xffffff) >> 2];
815         if (frame_buffer32)
816         {
817            for (j=0; j < vres; j++)
818            {
819               UINT32 *d = BITMAP_ADDR32(bitmap, j, 0);
820               for (i=0; i < hres; i++)
821               {
822                  UINT32 pix = *frame_buffer32++;
823                  if (gamma || gamma_dither)
824                  {
825                     r = (pix >> 24) & 0xff;
826                     g = (pix >> 16) & 0xff;
827                     b = (pix >> 8) & 0xff;
828                     if (gamma_dither)
829                     {
830                        dith = mame_rand(screen->machine) & 0x3f;
831                     }
832                     if (gamma)
833                     {
834                        if (gamma_dither)
835                        {
836                           r = gamma_dither_table[(r << 6)| dith];
837                           g = gamma_dither_table[(g << 6)| dith];
838                           b = gamma_dither_table[(b << 6)| dith];
839                        }
840                        else
841                        {
842                           r = gamma_table[r];
843                           g = gamma_table[g];
844                           b = gamma_table[b];
845                        }
846                     }
847                     else if (gamma_dither)
848                     {
849                        if (r < 255)
850                           r += (dith & 1);
851                        if (g < 255)
852                           g += (dith & 1);
853                        if (b < 255)
854                           b += (dith & 1);
855                     }
856                     pix = (r << 24) | (g << 16) | (b << 8);
857                  }
858
859
860                  d[i] = (pix >> 8);
861               }
862               frame_buffer32 += invisiblewidth;
863            }
864         }
865         break;
866      }
867
868        default:    fatalerror("Unknown framebuffer format %d\n", n64_vi_control & 0x3);
869   }
870   return 0;
871}
872
873/*****************************************************************************/
874
875INLINE void SET_SUBA_RGB_INPUT(UINT8 **input_r, UINT8 **input_g, UINT8 **input_b, int code)
876{
877   switch (code & 0xf)
878   {
879      case 0:      *input_r = &combined_color.r;   *input_g = &combined_color.g;   *input_b = &combined_color.b;   break;
880      case 1:      *input_r = &texel0_color.r;      *input_g = &texel0_color.g;      *input_b = &texel0_color.b;      break;
881      case 2:      *input_r = &texel1_color.r;      *input_g = &texel1_color.g;      *input_b = &texel1_color.b;      break;
882      case 3:      *input_r = &prim_color.r;      *input_g = &prim_color.g;      *input_b = &prim_color.b;      break;
883      case 4:      *input_r = &shade_color.r;      *input_g = &shade_color.g;      *input_b = &shade_color.b;      break;
884      case 5:      *input_r = &env_color.r;      *input_g = &env_color.g;      *input_b = &env_color.b;      break;
885      case 6:      *input_r = &one_color.r;      *input_g = &one_color.g;      *input_b = &one_color.b;      break;
886      case 7:      *input_r = &noise_color.r;      *input_g = &noise_color.g;      *input_b = &noise_color.b;      break;
887      case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15:
888      {
889         *input_r = &zero_color.r;      *input_g = &zero_color.g;      *input_b = &zero_color.b;      break;
890      }
891   }
892}
893
894INLINE void SET_SUBB_RGB_INPUT(UINT8 **input_r, UINT8 **input_g, UINT8 **input_b, int code)
895{
896   switch (code & 0xf)
897   {
898      case 0:      *input_r = &combined_color.r;   *input_g = &combined_color.g;   *input_b = &combined_color.b;   break;
899      case 1:      *input_r = &texel0_color.r;      *input_g = &texel0_color.g;      *input_b = &texel0_color.b;      break;
900      case 2:      *input_r = &texel1_color.r;      *input_g = &texel1_color.g;      *input_b = &texel1_color.b;      break;
901      case 3:      *input_r = &prim_color.r;      *input_g = &prim_color.g;      *input_b = &prim_color.b;      break;
902      case 4:      *input_r = &shade_color.r;      *input_g = &shade_color.g;      *input_b = &shade_color.b;      break;
903      case 5:      *input_r = &env_color.r;      *input_g = &env_color.g;      *input_b = &env_color.b;      break;
904      case 6:      fatalerror("SET_SUBB_RGB_INPUT: key_center\n"); break;
905      case 7:      *input_r = (UINT8*)&k4;         *input_g = (UINT8*)&k4;         *input_b = (UINT8*)&k4;         break;
906      case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15:
907      {
908         *input_r = &zero_color.r;      *input_g = &zero_color.g;      *input_b = &zero_color.b;      break;
909      }
910   }
911}
912
913INLINE void SET_MUL_RGB_INPUT(UINT8 **input_r, UINT8 **input_g, UINT8 **input_b, int code)
914{
915   switch (code & 0x1f)
916   {
917      case 0:      *input_r = &combined_color.r;   *input_g = &combined_color.g;   *input_b = &combined_color.b;   break;
918      case 1:      *input_r = &texel0_color.r;      *input_g = &texel0_color.g;      *input_b = &texel0_color.b;      break;
919      case 2:      *input_r = &texel1_color.r;      *input_g = &texel1_color.g;      *input_b = &texel1_color.b;      break;
920      case 3:      *input_r = &prim_color.r;      *input_g = &prim_color.g;      *input_b = &prim_color.b;      break;
921      case 4:      *input_r = &shade_color.r;      *input_g = &shade_color.g;      *input_b = &shade_color.b;      break;
922      case 5:      *input_r = &env_color.r;      *input_g = &env_color.g;      *input_b = &env_color.b;      break;
923      case 6:      *input_r = &key_scale.r;      *input_g = &key_scale.g;      *input_b = &key_scale.b;      break;
924      case 7:      *input_r = &combined_color.a;   *input_g = &combined_color.a;   *input_b = &combined_color.a;   break;
925      case 8:      *input_r = &texel0_color.a;      *input_g = &texel0_color.a;      *input_b = &texel0_color.a;      break;
926      case 9:      *input_r = &texel1_color.a;      *input_g = &texel1_color.a;      *input_b = &texel1_color.a;      break;
927      case 10:   *input_r = &prim_color.a;      *input_g = &prim_color.a;      *input_b = &prim_color.a;      break;
928      case 11:   *input_r = &shade_color.a;      *input_g = &shade_color.a;      *input_b = &shade_color.a;      break;
929      case 12:   *input_r = &env_color.a;      *input_g = &env_color.a;      *input_b = &env_color.a;      break;
930      case 13:   *input_r = &lod_frac;         *input_g = &lod_frac;         *input_b = &lod_frac;         break;
931      case 14:   *input_r = &primitive_lod_frac;   *input_g = &primitive_lod_frac;   *input_b = &primitive_lod_frac; break;
932      case 15:   *input_r = (UINT8*)&k5;         *input_g = (UINT8*)&k5;         *input_b = (UINT8*)&k5;         break;
933      case 16: case 17: case 18: case 19: case 20: case 21: case 22: case 23:
934      case 24: case 25: case 26: case 27: case 28: case 29: case 30: case 31:
935      {
936         *input_r = &zero_color.r;      *input_g = &zero_color.g;      *input_b = &zero_color.b;      break;
937      }
938   }
939}
940
941INLINE void SET_ADD_RGB_INPUT(UINT8 **input_r, UINT8 **input_g, UINT8 **input_b, int code)
942{
943   switch (code & 0x7)
944   {
945      case 0:      *input_r = &combined_color.r;   *input_g = &combined_color.g;   *input_b = &combined_color.b;   break;
946      case 1:      *input_r = &texel0_color.r;      *input_g = &texel0_color.g;      *input_b = &texel0_color.b;      break;
947      case 2:      *input_r = &texel1_color.r;      *input_g = &texel1_color.g;      *input_b = &texel1_color.b;      break;
948      case 3:      *input_r = &prim_color.r;      *input_g = &prim_color.g;      *input_b = &prim_color.b;      break;
949      case 4:      *input_r = &shade_color.r;      *input_g = &shade_color.g;      *input_b = &shade_color.b;      break;
950      case 5:      *input_r = &env_color.r;      *input_g = &env_color.g;      *input_b = &env_color.b;      break;
951      case 6:      *input_r = &one_color.r;      *input_g = &one_color.g;      *input_b = &one_color.b;      break;
952      case 7:      *input_r = &zero_color.r;      *input_g = &zero_color.g;      *input_b = &zero_color.b;      break;
953   }
954}
955
956INLINE void SET_SUB_ALPHA_INPUT(UINT8 **input, int code)
957{
958   switch (code & 0x7)
959   {
960      case 0:      *input = &combined_color.a; break;
961      case 1:      *input = &texel0_color.a; break;
962      case 2:      *input = &texel1_color.a; break;
963      case 3:      *input = &prim_color.a; break;
964      case 4:      *input = &shade_color.a; break;
965      case 5:      *input = &env_color.a; break;
966      case 6:      *input = &one_color.a; break;
967      case 7:      *input = &zero_color.a; break;
968   }
969}
970
971INLINE void SET_MUL_ALPHA_INPUT(UINT8 **input, int code)
972{
973   switch (code & 0x7)
974   {
975      case 0:      *input = &lod_frac; break;//HACK
976      case 1:      *input = &texel0_color.a; break;
977      case 2:      *input = &texel1_color.a; break;
978      case 3:      *input = &prim_color.a; break;
979      case 4:      *input = &shade_color.a; break;
980      case 5:      *input = &env_color.a; break;
981      case 6:      *input = &primitive_lod_frac; break;//HACK
982      case 7:      *input = &zero_color.a; break;
983   }
984}
985
986
987
988INLINE COLOR COLOR_COMBINER(running_machine *machine, int cycle)
989{
990   COLOR c;
991   COLOR temp;
992   UINT32 r, g, b, a;
993
994   if (other_modes.cycle_type == CYCLE_TYPE_1) //http://moogle-tech.com/blog/?p=84
995   {
996      cycle=1; // Needed by F-1 Pole Position 64 menus
997   }
998
999   if (other_modes.cycle_type == CYCLE_TYPE_2 && cycle == 1)
1000   {
1001      copy_colors(&temp, &texel0_color);
1002      copy_colors(&texel0_color, &texel1_color);
1003      copy_colors(&texel1_color, &temp);
1004   }
1005
1006   if (combiner_rgbsub_a_r[cycle] == &noise_color.r)
1007   {
1008      noise_color.r = mame_rand(machine) & 0xff;
1009      noise_color.g = mame_rand(machine) & 0xff;
1010      noise_color.b = mame_rand(machine) & 0xff;
1011   }
1012
1013   r = COMBINER_EQUATION(*combiner_rgbsub_a_r[cycle],*combiner_rgbsub_b_r[cycle],*combiner_rgbmul_r[cycle],*combiner_rgbadd_r[cycle]);
1014   g = COMBINER_EQUATION(*combiner_rgbsub_a_g[cycle],*combiner_rgbsub_b_g[cycle],*combiner_rgbmul_g[cycle],*combiner_rgbadd_g[cycle]);
1015   b = COMBINER_EQUATION(*combiner_rgbsub_a_b[cycle],*combiner_rgbsub_b_b[cycle],*combiner_rgbmul_b[cycle],*combiner_rgbadd_b[cycle]);
1016   a = COMBINER_EQUATION(*combiner_alphasub_a[cycle],*combiner_alphasub_b[cycle],*combiner_alphamul[cycle],*combiner_alphaadd[cycle]);
1017
1018   if (other_modes.cycle_type == CYCLE_TYPE_2 && cycle == 0)
1019   {
1020      combined_color.r=r;
1021      combined_color.g=g;
1022      combined_color.b=b;
1023      combined_color.a=a;
1024   }
1025
1026   //Alpha coverage combiner
1027   if (other_modes.cycle_type == CYCLE_TYPE_1 || (other_modes.cycle_type == CYCLE_TYPE_2 && cycle == 1))
1028   {
1029      a = alpha_cvg_get(a);
1030   }
1031
1032   c.r = r; c.g = g; c.b = b; c.a = a;
1033   return c;
1034}
1035
1036INLINE void SET_BLENDER_INPUT(int cycle, int which, UINT8 **input_r, UINT8 **input_g, UINT8 **input_b, UINT8 **input_a, int a, int b)
1037{
1038   switch (a & 0x3)
1039   {
1040      case 0:
1041      {
1042         if (cycle == 0)
1043         {
1044            *input_r = &pixel_color.r;
1045            *input_g = &pixel_color.g;
1046            *input_b = &pixel_color.b;
1047         }
1048         else
1049         {
1050            *input_r = &blended_pixel_color.r;
1051            *input_g = &blended_pixel_color.g;
1052            *input_b = &blended_pixel_color.b;
1053         }
1054         break;
1055      }
1056
1057      case 1:
1058      {
1059         *input_r = &memory_color.r;
1060         *input_g = &memory_color.g;
1061         *input_b = &memory_color.b;
1062         break;
1063      }
1064
1065      case 2:
1066      {
1067         *input_r = &blend_color.r;      *input_g = &blend_color.g;      *input_b = &blend_color.b;
1068         break;
1069      }
1070
1071      case 3:
1072      {
1073         *input_r = &fog_color.r;      *input_g = &fog_color.g;      *input_b = &fog_color.b;
1074         break;
1075      }
1076   }
1077
1078   if (which == 0)
1079   {
1080      switch (b & 0x3)
1081      {
1082         case 0:      *input_a = &pixel_color.a; break;
1083         case 1:      *input_a = &fog_color.a; break;
1084         case 2:      *input_a = &shade_color.a; break;
1085         case 3:      *input_a = &zero_color.a; break;
1086      }
1087   }
1088   else
1089   {
1090      switch (b & 0x3)
1091      {
1092         case 0:      *input_a = &inv_pixel_color.a; break;
1093         case 1:      *input_a = &memory_color.a; break;
1094         case 2:      *input_a = &one_color.a; break;
1095         case 3:      *input_a = &zero_color.a; break;
1096      }
1097   }
1098}
1099
1100static const UINT8 bayer_matrix[16] =
1101{ /* Bayer matrix */
1102    0,  4,  1, 5,
1103    6,  2,  7, 3,
1104    1,    5,  0, 4,
1105    7,  3,  6, 2
1106};
1107
1108static const UINT8 magic_matrix[16] =
1109{ /* Magic square matrix */
1110    0,  6,  1, 7,
1111    4,  2,  5, 3,
1112    3,    5,  2, 4,
1113    7,  1,  6, 0
1114};
1115
1116INLINE int BLENDER1_16(running_machine *machine, UINT16 *fb, UINT8* hb, COLOR c, int dith)
1117{
1118   int r, g, b;
1119   int special_bsel = 0;
1120   UINT16 mem = *fb;
1121   UINT32 memory_cvg = ((mem & 1) << 2) + (*hb & 3);
1122
1123   // Alpha compare
1124   if (!alpha_compare(machine, c.a))
1125   {
1126      return 0;
1127   }
1128   if (!curpixel_cvg) // New coverage is zero, so abort
1129   {
1130      return 0;
1131   }
1132
1133   if (blender2b_a[0] == &memory_color.a)
1134   {
1135      special_bsel = 1;
1136   }
1137
1138   copy_colors(&pixel_color,&c);
1139
1140   if (!other_modes.z_compare_en)
1141   {
1142      curpixel_overlap = 0;
1143   }
1144
1145   memory_color.r = (((mem >> 11) & 0x1f) << 3) | (((mem >> 11) & 0x1f) >> 2);
1146   memory_color.g = (((mem >>  6) & 0x1f) << 3) | (((mem >>  6) & 0x1f) >> 2);
1147   memory_color.b = (((mem >>  1) & 0x1f) << 3) | (((mem >>  1) & 0x1f) >> 2);
1148
1149   if (other_modes.image_read_en)
1150   {
1151      memory_color.a = (memory_cvg << 5) & 0xe0;
1152   }
1153   else
1154   {
1155      memory_color.a = 0xe0;
1156   }
1157
1158   if (!curpixel_overlap && !other_modes.force_blend)
1159   {
1160      r = *blender1a_r[0];
1161      g = *blender1a_g[0];
1162      b = *blender1a_b[0];
1163   }
1164   else
1165   {
1166      inv_pixel_color.a = 0xff - *blender1b_a[0];
1167
1168      BLENDER_EQUATION(&r, &g, &b, 0, special_bsel);
1169   }
1170
1171   if (other_modes.rgb_dither_sel < 2)
1172   {
1173      // Hack to prevent "double-dithering" artifacts
1174      int dithhack = ((r & 0xf8)==(memory_color.r&0xf8) && (g & 0xf8) == (memory_color.g & 0xf8) &&(b&0xf8)==(memory_color.b&0xf8));
1175      if (!dithhack)
1176      {
1177         rgb_dither(&r, &g, &b, dith);
1178      }
1179   }
1180
1181    return (FBWRITE_16(fb, hb, r, g, b));
1182}
1183
1184INLINE int BLENDER2_16(running_machine *machine, UINT16 *fb, UINT8* hb, COLOR c1, COLOR c2, int dith)
1185{
1186   int r, g, b;
1187   int special_bsel = 0;
1188   UINT16 mem = *fb;
1189   UINT32 memory_cvg = ((mem & 1) << 2) + (*hb & 3);
1190
1191   // Alpha compare
1192   if (!alpha_compare(machine, c2.a))
1193   {
1194      return 0;
1195   }
1196   if (!curpixel_cvg)
1197   {
1198      return 0;
1199   }
1200
1201   if (blender2b_a[0] == &memory_color.a)
1202   {
1203      special_bsel = 1;
1204   }
1205
1206   copy_colors(&pixel_color, &c2);
1207   if (!other_modes.z_compare_en)
1208   {
1209      curpixel_overlap = 0;
1210   }
1211
1212   memory_color.r = (((mem >> 11) & 0x1f) << 3) | (((mem >> 11) & 0x1f) >> 2);
1213   memory_color.g = (((mem >>  6) & 0x1f) << 3) | (((mem >>  6) & 0x1f) >> 2);
1214   memory_color.b = (((mem >>  1) & 0x1f) << 3) | (((mem >>  1) & 0x1f) >> 2);
1215
1216   if (other_modes.image_read_en)
1217   {
1218      memory_color.a = (memory_cvg << 5) & 0xe0;
1219   }
1220   else
1221   {
1222      memory_color.a = 0xe0;
1223   }
1224
1225   inv_pixel_color.a = 0xff - *blender1b_a[0];
1226
1227   BLENDER_EQUATION(&r, &g, &b, 0, special_bsel);
1228
1229   blended_pixel_color.r = r;
1230   blended_pixel_color.g = g;
1231   blended_pixel_color.b = b;
1232   blended_pixel_color.a = pixel_color.a;
1233
1234   pixel_color.r = r;
1235   pixel_color.g = g;
1236   pixel_color.b = b;
1237
1238   inv_pixel_color.a = 0xff - *blender1b_a[1];
1239
1240   if (!curpixel_overlap && !other_modes.force_blend)
1241   {
1242      r = *blender1a_r[1];
1243      g = *blender1a_g[1];
1244      b = *blender1a_b[1];
1245   }
1246   else
1247   {
1248      if (blender2b_a[1] == &memory_color.a)
1249      {
1250         special_bsel = 1;
1251      }
1252      else
1253      {
1254         special_bsel = 0;
1255      }
1256
1257      BLENDER_EQUATION(&r, &g, &b, 1, special_bsel);
1258   }
1259
1260   if (other_modes.rgb_dither_sel < 2)
1261   {
1262      // Hack to prevent "double-dithering" artifacts
1263      int dithhack = ((r & 0xf8)==(memory_color.r&0xf8) && (g & 0xf8) == (memory_color.g & 0xf8) &&(b&0xf8)==(memory_color.b&0xf8));
1264      if (!dithhack)
1265      {
1266         rgb_dither(&r, &g, &b, dith);
1267      }
1268   }
1269
1270   return (FBWRITE_16(fb, hb, r, g, b));
1271}
1272
1273/*****************************************************************************/
1274
1275
1276static void fill_rectangle_16bit(running_machine *machine, RECTANGLE *rect)
1277{
1278   UINT16 *fb = (UINT16*)&rdram[(fb_address / 4)];
1279   UINT8* hb = &hidden_bits[fb_address >> 1];
1280
1281   int index, i, j;
1282   int x1 = rect->xh / 4;
1283   int x2 = rect->xl / 4;
1284   int y1 = rect->yh / 4;
1285   int y2 = rect->yl / 4;
1286   int clipx1, clipx2, clipy1, clipy2;
1287   UINT16 fill_color1, fill_color2;
1288   int fill_cvg1;
1289   int fill_cvg2;
1290
1291   if (x2 <= x1)
1292   {
1293      x2=x1+1; // SCARS (E)
1294   }
1295   if (y2 == y1)
1296   {
1297      y2=y1+1; // Goldeneye
1298   }
1299
1300
1301   fill_color1 = (fill_color >> 16) & 0xffff;
1302   fill_color2 = (fill_color >>  0) & 0xffff;
1303   fill_cvg1 = (fill_color1 & 1) ? 8 : 1;
1304   fill_cvg2 = (fill_color2 & 1) ? 8 : 1;
1305
1306   clipx1 = clip.xh / 4;
1307   clipx2 = clip.xl / 4;
1308   clipy1 = clip.yh / 4;
1309   clipy2 = clip.yl / 4;
1310
1311   // clip
1312   if (x1 < clipx1)
1313   {
1314      x1 = clipx1;
1315   }
1316   if (y1 < clipy1)
1317   {
1318      y1 = clipy1;
1319   }
1320   if (x2 >= clipx2)
1321   {
1322      x2 = clipx2-1;
1323   }
1324   if (y2 >= clipy2)
1325   {
1326      y2 = clipy2-1;
1327   }
1328
1329   set_shade_for_rects(); // Needed by Command & Conquer menus
1330
1331   if (other_modes.cycle_type == CYCLE_TYPE_FILL)
1332   {
1333      for (j=y1; j <= y2; j++)
1334      {
1335         index = j * fb_width;
1336         for (i=x1; i <= x2; i++)
1337         {
1338            int curpixel = index + i;
1339            fb[curpixel ^ WORD_ADDR_XOR] = (i & 1) ? fill_color1 : fill_color2;
1340            hb[curpixel ^ BYTE_ADDR_XOR] = (i & 1) ? ((fill_color1 & 1)? 3:0) : ((fill_color2 & 1) ? 3:0);
1341         }
1342      }
1343   }
1344   else if (other_modes.cycle_type == CYCLE_TYPE_1)
1345   {
1346      for (j = y1; j <= y2; j++)
1347      {
1348         COLOR c;
1349         int dith = 0;
1350         index = j * fb_width;
1351         for (i = x1; i <= x2; i++)
1352         {
1353            curpixel_cvg = (i & 1) ? fill_cvg1 : fill_cvg2;
1354            c = COLOR_COMBINER(machine, 0);
1355            if (!other_modes.rgb_dither_sel)
1356            {
1357               dith = magic_matrix[(((j) & 3) << 2) + ((i ^ WORD_ADDR_XOR) & 3)];
1358            }
1359            else if (other_modes.rgb_dither_sel == 1)
1360            {
1361               dith = bayer_matrix[(((j) & 3) << 2) + ((i ^ WORD_ADDR_XOR) & 3)];
1362            }
1363            BLENDER1_16(machine, &fb[(index + i) ^ WORD_ADDR_XOR], &hb[(index + i) ^ BYTE_ADDR_XOR], c, dith);
1364         }
1365      }
1366   }
1367   else if (other_modes.cycle_type == CYCLE_TYPE_2)
1368   {
1369      for (j=y1; j <= y2; j++)
1370      {
1371         COLOR c1, c2;
1372         int dith = 0;
1373         index = j * fb_width;
1374         for (i=x1; i <= x2; i++)
1375         {
1376            curpixel_cvg = (i & 1) ? fill_cvg1 : fill_cvg2;
1377            c1 = COLOR_COMBINER(machine, 0);
1378            c2 = COLOR_COMBINER(machine, 1);
1379            if (!other_modes.rgb_dither_sel)
1380            {
1381               dith = magic_matrix[(((j) & 3) << 2) + ((i ^ WORD_ADDR_XOR) & 3)];
1382            }
1383            else if (other_modes.rgb_dither_sel == 1)
1384            {
1385               dith = bayer_matrix[(((j) & 3) << 2) + ((i ^ WORD_ADDR_XOR) & 3)];
1386            }
1387            BLENDER2_16(machine, &fb[(index + i) ^ WORD_ADDR_XOR],  &hb[(index + i) ^ BYTE_ADDR_XOR], c1, c2, dith);
1388         }
1389      }
1390   }
1391   else
1392   {
1393      fatalerror("fill_rectangle_16bit: cycle type copy");
1394   }
1395}
1396
1397#define XOR_SWAP_BYTE   4
1398#define XOR_SWAP_WORD   2
1399#define XOR_SWAP_DWORD   1
1400
1401INLINE void FETCH_TEXEL(COLOR *color, int s, int t, UINT32 tilenum)
1402{
1403   UINT32 twidth   = tile[tilenum].line;
1404   UINT32   tformat = tile[tilenum].format;
1405   UINT32 tsize =   tile[tilenum].size;
1406   UINT32 tbase =   tile[tilenum].tmem;
1407   UINT32 tpal   = tile[tilenum].palette & 0xf;
1408
1409   if (t < 0) t = 0;
1410   if (s < 0) s = 0;
1411
1412   switch (tformat)
1413   {
1414      case 0:      // RGBA
1415      {
1416         switch (tsize)
1417         {
1418            case PIXEL_SIZE_4BIT:
1419            {
1420               UINT8 *tc = (UINT8*)TMEM;
1421                    int taddr = ((tbase + ((t) * twidth) + ((s) / 2)) ^ ((t & 1) ? XOR_SWAP_BYTE : 0)) & 0x7ff;
1422               UINT8 p = ((s) & 1) ? (tc[taddr ^ BYTE_ADDR_XOR] & 0xf) : (tc[taddr ^ BYTE_ADDR_XOR] >> 4);
1423               UINT16 c = tlut[(((tpal << 4) | p) ^ WORD_ADDR_XOR) << 2];
1424
1425               if (other_modes.en_tlut)
1426               {
1427                  if (other_modes.tlut_type == 0)
1428                  {
1429                     color->r = (((c >> 11) & 0x1f) << 3) | (((c >> 11) & 0x1f) >> 2);
1430                     color->g = (((c >>  6) & 0x1f) << 3) | (((c >>  6) & 0x1f) >> 2);
1431                     color->b = (((c >>  1) & 0x1f) << 3) | (((c >>  1) & 0x1f) >> 2);
1432                     color->a = (c & 1) ? 0xff : 0;
1433                  }
1434                  else
1435                  {
1436                     color->r = color->g = color->b = (c >> 8) & 0xff;
1437                     color->a = c & 0xff;
1438                  }
1439               }
1440               else
1441               {
1442                  color->r = color->g = color->b = color->a = (tpal << 4) | p;
1443               }
1444               break;
1445            }
1446            case PIXEL_SIZE_8BIT:
1447            {
1448               UINT8 *tc = (UINT8*)TMEM;
1449                    int taddr = ((tbase + ((t) * twidth) + ((s))) ^ ((t & 1) ? XOR_SWAP_BYTE : 0)) & 0x7ff;
1450               UINT8 p = tc[taddr ^ BYTE_ADDR_XOR];
1451               UINT16 c = tlut[(p ^ WORD_ADDR_XOR) << 2];
1452
1453               if (other_modes.en_tlut)
1454               {
1455                  if (other_modes.tlut_type == 0)
1456                  {
1457                     color->r = (((c >> 11) & 0x1f) << 3) | (((c >> 11) & 0x1f) >> 2);
1458                     color->g = (((c >>  6) & 0x1f) << 3) | (((c >>  6) & 0x1f) >> 2);
1459                     color->b = (((c >>  1) & 0x1f) << 3) | (((c >>  1) & 0x1f) >> 2);
1460                     color->a = (c & 1) ? 0xff : 0;
1461                  }
1462                  else
1463                  {
1464                     color->r = color->g = color->b = (c >> 8) & 0xff;
1465                     color->a = c & 0xff;
1466                  }
1467               }
1468               else
1469               {
1470                  color->r = color->g = color->b = color->a = p;
1471               }
1472               break;
1473            }
1474            case PIXEL_SIZE_16BIT:
1475            {
1476               UINT16 *tc = (UINT16*)TMEM;
1477                    int taddr = ((tbase>>1) + ((t) * (twidth>>1)) + (s))  ^ ((t & 1) ? XOR_SWAP_WORD : 0);
1478               UINT16 c = tc[(taddr & 0x7ff) ^ WORD_ADDR_XOR]; // PGA European Tour (U)
1479
1480               if (!other_modes.en_tlut)
1481               {
1482                  color->r = (((c >> 11) & 0x1f) << 3) | (((c >> 11) & 0x1f) >> 2);
1483                  color->g = (((c >>  6) & 0x1f) << 3) | (((c >>  6) & 0x1f) >> 2);
1484                  color->b = (((c >>  1) & 0x1f) << 3) | (((c >>  1) & 0x1f) >> 2);
1485                  color->a = (c & 1) ? 0xff : 0;
1486               }
1487               else
1488               {
1489                  c = tlut[(c >> 8) << 2];
1490                  if (other_modes.tlut_type == 0) //Golden Eye 007, sea, "frigate" level
1491                  {
1492                     color->r = (((c >> 11) & 0x1f) << 3) | (((c >> 11) & 0x1f) >> 2);
1493                     color->g = (((c >>  6) & 0x1f) << 3) | (((c >>  6) & 0x1f) >> 2);
1494                     color->b = (((c >>  1) & 0x1f) << 3) | (((c >>  1) & 0x1f) >> 2);
1495                     color->a = (c & 1) ? 0xff : 0;
1496                  }
1497                  else // Beetle Adventure Racing, Mount Mayhem
1498                  {
1499                     color->r = color->g = color->b = (c >> 8) & 0xff;
1500                     color->a = c & 0xff;
1501                  }
1502               }
1503               break;
1504            }
1505            case PIXEL_SIZE_32BIT:
1506            {
1507               UINT32 *tc = (UINT32*)TMEM;
1508               int xorval = (fb_size == PIXEL_SIZE_16BIT) ? XOR_SWAP_WORD : XOR_SWAP_DWORD; // Conker's Bad Fur Day, Jet Force Gemini, Super Smash Bros., Mickey's Speedway USA, Ogre Battle, Wave Race, Gex 3, South Park Rally
1509                    int taddr = (((tbase >> 2) + ((t) * (twidth >> 1)) + (s)) ^ ((t & 1) ? xorval : 0)) & 0x3ff;
1510               UINT32 c = tc[taddr];
1511
1512               if (!other_modes.en_tlut)
1513               {
1514                  color->r = ((c >> 24) & 0xff);
1515                  color->g = ((c >> 16) & 0xff);
1516                  color->b = ((c >>  8) & 0xff);
1517                  color->a = ((c >>  0) & 0xff);
1518               }
1519               else
1520               {
1521                  c = tlut[(c >> 24) << 2];
1522                  if (!other_modes.tlut_type)
1523                  {
1524                     color->r = (((c >> 11) & 0x1f) << 3) | (((c >> 11) & 0x1f) >> 2);
1525                     color->g = (((c >>  6) & 0x1f) << 3) | (((c >>  6) & 0x1f) >> 2);
1526                     color->b = (((c >>  1) & 0x1f) << 3) | (((c >>  1) & 0x1f) >> 2);
1527                     color->a = (c & 1) ? 0xff : 0;
1528                  }
1529                  else
1530                  {
1531                     color->r = color->g = color->b = (c >> 8) & 0xff;
1532                     color->a = c & 0xff;
1533                  }
1534               }
1535               break;
1536            }
1537            default:
1538               color->r = color->g = color->b = color->a = 0xff;
1539               fatalerror("FETCH_TEXEL: unknown RGBA texture size %d\n", tsize);
1540               break;
1541         }
1542         break;
1543      }
1544      case 1:      // YUV: Bottom of the 9th, Pokemon Stadium, Ogre Battle 64
1545      {
1546         switch (tsize)
1547         {
1548            case PIXEL_SIZE_16BIT:
1549            {
1550               INT32 newr = 0;
1551               INT32 newg = 0;
1552               INT32 newb = 0;
1553               UINT16 *tc = (UINT16*)TMEM;
1554               int taddr = ((tbase >> 1) + ((t) * (twidth)) + (s)) ^ ((t & 1) ? XOR_SWAP_WORD : 0);
1555               UINT16 c1, c2;
1556               INT32 y;
1557               INT32 u, v;
1558               c1 = tc[taddr ^ WORD_ADDR_XOR];
1559               c2 = tc[taddr]; // other word
1560
1561               if (!(taddr & 1))
1562               {
1563                  v = c2 >> 8;
1564                  u = c1 >> 8;
1565                  y = c1 & 0xff;
1566               }
1567               else
1568               {
1569                  v = c1 >> 8;
1570                  u = c2 >> 8;
1571                  y = c1 & 0xff;
1572               }
1573               v -= 128;
1574               u -= 128;
1575
1576               if (!other_modes.bi_lerp0)
1577               {
1578                  newr = y + ((k0 * v) >> 8);
1579                  newg = y + ((k1 * u) >> 8) + ((k2 * v) >> 8);
1580                  newb = y + ((k3 * u) >> 8);
1581               }
1582               color->r = (newr < 0) ? 0 : ((newr > 0xff) ? 0xff : newr);
1583               color->g = (newg < 0) ? 0 : ((newg > 0xff) ? 0xff : newg);
1584               color->b = (newb < 0) ? 0 : ((newb > 0xff) ? 0xff : newb);
1585               color->a = 0xff;
1586               break;
1587            }
1588         }
1589         break;
1590      }
1591      case 2:      // Color Index
1592      {
1593         switch (tsize)
1594         {
1595            case PIXEL_SIZE_4BIT:
1596            {
1597               UINT8 *tc = (UINT8*)TMEM;
1598                    int taddr = ((tbase + ((t) * twidth) + ((s) / 2)) ^ ((t & 1) ? XOR_SWAP_BYTE : 0)) & 0x7ff;
1599               UINT8 p = ((s) & 1) ? (tc[taddr ^ BYTE_ADDR_XOR] & 0xf) : (tc[taddr ^ BYTE_ADDR_XOR] >> 4);
1600               UINT16 c = tlut[((tpal << 4) | p) << 2];
1601
1602               if (other_modes.en_tlut)
1603               {
1604                  if (other_modes.tlut_type == 0)
1605                  {
1606                     color->r = (((c >> 11) & 0x1f) << 3) | (((c >> 11) & 0x1f) >> 2);
1607                     color->g = (((c >>  6) & 0x1f) << 3) | (((c >>  6) & 0x1f) >> 2);
1608                     color->b = (((c >>  1) & 0x1f) << 3) | (((c >>  1) & 0x1f) >> 2);
1609                     color->a = (c & 1) ? 0xff : 0;
1610                  }
1611                  else
1612                  {
1613                     color->r = color->g = color->b = (c >> 8) & 0xff;
1614                     color->a = c & 0xff;
1615                  }
1616               }
1617               else
1618               {
1619                  color->r = color->g = color->b = color->a = (tpal << 4) | p;
1620               }
1621               break;
1622            }
1623            case PIXEL_SIZE_8BIT:
1624            {
1625               UINT8 *tc = (UINT8*)TMEM;
1626                    int taddr = ((tbase + ((t) * twidth) + ((s))) ^ ((t & 1) ? XOR_SWAP_BYTE : 0)) & 0x7ff;
1627               UINT8 p = tc[taddr ^ BYTE_ADDR_XOR];
1628               UINT16 c = tlut[p << 2];
1629
1630               if (other_modes.en_tlut)
1631               {
1632                  if (other_modes.tlut_type == 0)
1633                  {
1634                     color->r = (((c >> 11) & 0x1f) << 3) | (((c >> 11) & 0x1f) >> 2);
1635                     color->g = (((c >>  6) & 0x1f) << 3) | (((c >>  6) & 0x1f) >> 2);
1636                     color->b = (((c >>  1) & 0x1f) << 3) | (((c >>  1) & 0x1f) >> 2);
1637                     color->a = (c & 1) ? 0xff : 0;
1638                  }
1639                  else
1640                  {
1641                     color->r = color->g = color->b = (c >> 8) & 0xff;
1642                     color->a = c & 0xff;
1643                  }
1644               }
1645               else
1646               {
1647                  color->r = color->g = color->b = color->a = p;
1648               }
1649               break;
1650            }
1651            case PIXEL_SIZE_16BIT:
1652            {
1653                    // 16-bit CI is a "valid" mode; some games use it, it behaves the same as 16-bit RGBA
1654               UINT16 *tc = (UINT16*)TMEM;
1655                    int taddr = ((tbase>>1) + ((t) * (twidth>>1)) + (s))  ^ ((t & 1) ? XOR_SWAP_WORD : 0);
1656               UINT16 c = tc[(taddr & 0x7ff) ^ WORD_ADDR_XOR]; // PGA European Tour (U)
1657
1658               if (!other_modes.en_tlut)
1659               {
1660                  color->r = (((c >> 11) & 0x1f) << 3) | (((c >> 11) & 0x1f) >> 2);
1661                  color->g = (((c >>  6) & 0x1f) << 3) | (((c >>  6) & 0x1f) >> 2);
1662                  color->b = (((c >>  1) & 0x1f) << 3) | (((c >>  1) & 0x1f) >> 2);
1663                  color->a = (c & 1) ? 0xff : 0;
1664               }
1665               else
1666               {
1667                  c = tlut[(c >> 8) << 2];
1668                  if (!other_modes.tlut_type) // GoldenEye 007, sea, "frigate" level
1669                  {
1670                     color->r = (((c >> 11) & 0x1f) << 3) | (((c >> 11) & 0x1f) >> 2);
1671                     color->g = (((c >>  6) & 0x1f) << 3) | (((c >>  6) & 0x1f) >> 2);
1672                     color->b = (((c >>  1) & 0x1f) << 3) | (((c >>  1) & 0x1f) >> 2);
1673                     color->a = (c & 1) ? 0xff : 0;
1674                  }
1675                  else // Beetle Adventure Racing, Mount Mayhem
1676                  {
1677                     color->r = color->g = color->b = (c >> 8) & 0xff;
1678                     color->a = c & 0xff;
1679                  }
1680               }
1681               break;
1682            }
1683            default:
1684               color->r = color->g = color->b = color->a = 0xff;
1685               fatalerror("FETCH_TEXEL: unknown CI texture size %d\n", tsize);
1686               break;
1687         }
1688         break;
1689      }
1690      case 3:      // Intensity + Alpha
1691      {
1692         switch (tsize)
1693         {
1694            case PIXEL_SIZE_4BIT:
1695            {
1696               UINT8 *tc = (UINT8*)TMEM;
1697                    int taddr = (tbase + ((t) * twidth) + (s >> 1)) ^ ((t & 1) ? XOR_SWAP_BYTE : 0);
1698               UINT8 p = ((s) & 1) ? (tc[taddr ^ BYTE_ADDR_XOR] & 0xf) : (tc[taddr ^ BYTE_ADDR_XOR] >> 4);
1699               UINT8 i = ((p & 0xe) << 4) | ((p & 0xe) << 1) | (p & 0xe >> 2);
1700
1701               if (!other_modes.en_tlut)
1702               {
1703                  color->r = i;
1704                  color->g = i;
1705                  color->b = i;
1706                  color->a = (p & 0x1) ? 0xff : 0;
1707               }
1708               else
1709               {
1710                  UINT16 c = tlut[((tpal << 4) | p) << 2];
1711                  if (!other_modes.tlut_type)
1712                  {
1713                          color->r = (((c >> 11) & 0x1f) << 3) | (((c >> 11) & 0x1f) >> 2);
1714                          color->g = (((c >>  6) & 0x1f) << 3) | (((c >>  6) & 0x1f) >> 2);
1715                          color->b = (((c >>  1) & 0x1f) << 3) | (((c >>  1) & 0x1f) >> 2);
1716                          color->a = (c & 1) ? 0xff : 0;
1717                  }
1718                  else
1719                  {
1720                     color->r = color->g = color->b = (c >> 8) & 0xff;
1721                     color->a = c & 0xff;
1722                  }
1723               }
1724               break;
1725            }
1726            case PIXEL_SIZE_8BIT:
1727            {
1728               UINT8 *tc = (UINT8*)TMEM;
1729                    int taddr = ((tbase + ((t) * twidth) + ((s))) ^ ((t & 1) ? XOR_SWAP_BYTE : 0)) & 0xfff;
1730               UINT8 p = tc[taddr ^ BYTE_ADDR_XOR];
1731               UINT8 i = 0;
1732
1733               if (!other_modes.en_tlut)
1734               {
1735                  i = (p >> 4) | (p & 0xf0);
1736                  color->r = i;
1737                  color->g = i;
1738                  color->b = i;
1739                  color->a = (p & 0xf) | ((p << 4) & 0xf0);
1740               }
1741               else
1742               {
1743                  UINT16 c = tlut[p << 2];
1744                  if (!other_modes.tlut_type)
1745                  {
1746                     color->r = (((c >> 11) & 0x1f) << 3) | (((c >> 11) & 0x1f) >> 2);
1747                     color->g = (((c >>  6) & 0x1f) << 3) | (((c >>  6) & 0x1f) >> 2);
1748                     color->b = (((c >>  1) & 0x1f) << 3) | (((c >>  1) & 0x1f) >> 2);
1749                          color->a = (c & 1) ? 0xff : 0;
1750                  }
1751                  else
1752                  {
1753                     color->r = color->g = color->b = (c >> 8) & 0xff;
1754                     color->a = c & 0xff;
1755                  }
1756               }
1757               break;
1758            }
1759            case PIXEL_SIZE_16BIT:
1760            {
1761               UINT16 *tc = (UINT16*)TMEM;
1762                    int taddr = ((tbase >> 1) + ((t) * (twidth >> 1)) + (s)) ^ ((t & 1) ? XOR_SWAP_WORD : 0);
1763               UINT16 c = tc[taddr ^ WORD_ADDR_XOR];
1764               UINT8 i = (c >> 8);
1765
1766               if (!other_modes.en_tlut)
1767               {
1768                  color->r = i;
1769                  color->g = i;
1770                  color->b = i;
1771                  color->a = c & 0xff;
1772               }
1773               else
1774               {
1775                  c = tlut[(c >> 8) << 2];
1776                  if (!other_modes.tlut_type)
1777                  {
1778                     color->r = (((c >> 11) & 0x1f) << 3) | (((c >> 11) & 0x1f) >> 2);
1779                     color->g = (((c >>  6) & 0x1f) << 3) | (((c >>  6) & 0x1f) >> 2);
1780                     color->b = (((c >>  1) & 0x1f) << 3) | (((c >>  1) & 0x1f) >> 2);
1781                          color->a = (c & 1) ? 0xff : 0;
1782                  }
1783                  else
1784                  {
1785                     color->r = c >> 8;
1786                     color->g = c >> 8;
1787                     color->b = c >> 8;
1788                          color->a = c & 0xff;
1789                  }
1790               }
1791               break;
1792            }
1793            default:
1794               color->r = color->g = color->b = color->a = 0xff;
1795               fatalerror("FETCH_TEXEL: unknown IA texture size %d\n", tsize);
1796               break;
1797         }
1798         break;
1799      }
1800      case 4:      // Intensity
1801      {
1802         switch (tsize)
1803         {
1804            case PIXEL_SIZE_4BIT:
1805            {
1806               UINT8 *tc = (UINT8*)TMEM;
1807                    int taddr = ((tbase + ((t) * twidth) + ((s) / 2)) ^ ((t & 1) ? XOR_SWAP_BYTE : 0)) & 0xfff;
1808               UINT8 c = ((s) & 1) ? (tc[taddr ^ BYTE_ADDR_XOR] & 0xf) : (tc[taddr ^ BYTE_ADDR_XOR] >> 4);
1809               c |= (c << 4);
1810
1811               if (!other_modes.en_tlut)
1812               {
1813                  color->r = c;
1814                  color->g = c;
1815                  color->b = c;
1816                  color->a = c;
1817               }
1818               else
1819               {
1820                  UINT16 k = tlut[((tpal << 4) | c) << 2];
1821                  if (!other_modes.tlut_type)
1822                  {
1823                     color->r = (((k >> 11) & 0x1f) << 3) | (((k >> 11) & 0x1f) >> 2);
1824                     color->g = (((k >>  6) & 0x1f) << 3) | (((k >>  6) & 0x1f) >> 2);
1825                     color->b = (((k >>  1) & 0x1f) << 3) | (((k >>  1) & 0x1f) >> 2);
1826                     color->a = (k & 1) ? 0xff : 0;
1827                  }
1828                  else
1829                  {
1830                     color->r = color->g = color->b = (k >> 8) & 0xff;
1831                     color->a = k & 0xff;
1832                  }
1833               }
1834               break;
1835            }
1836            case PIXEL_SIZE_8BIT:
1837            {
1838               UINT8 *tc = (UINT8*)TMEM;
1839                    int taddr = ((tbase + ((t) * twidth) + ((s))) ^ ((t & 1) ? XOR_SWAP_BYTE : 0)) & 0xfff;
1840               UINT8 c = tc[taddr ^ BYTE_ADDR_XOR];
1841
1842               if (!other_modes.en_tlut)
1843               {
1844                  color->r = c;
1845                  color->g = c;
1846                  color->b = c;
1847                  color->a = c;
1848               }
1849               else
1850               {
1851                  UINT16 k = tlut[ c << 2];
1852                  if (!other_modes.tlut_type)
1853                  {
1854                     color->r = (((k >> 11) & 0x1f) << 3) | (((k >> 11) & 0x1f) >> 2);
1855                     color->g = (((k >>  6) & 0x1f) << 3) | (((k >>  6) & 0x1f) >> 2);
1856                     color->b = (((k >>  1) & 0x1f) << 3) | (((k >>  1) & 0x1f) >> 2);
1857                     color->a = (k & 1) ? 0xff : 0;
1858                  }
1859                  else
1860                  {
1861                     color->r = color->g = color->b = (k >> 8) & 0xff;
1862                     color->a = k & 0xff;
1863                  }
1864               }
1865               break;
1866            }
1867            default:
1868               color->r = color->g = color->b = color->a = 0xff;
1869               //fatalerror("FETCH_TEXEL: unknown I texture size %d\n", tsize);
1870               break;
1871         }
1872         break;
1873      }
1874      default:
1875      {
1876         color->r = color->g = color->b = color->a = 0xff;
1877         fatalerror("FETCH_TEXEL: unknown texture format %d\n", tformat);
1878         break;
1879      }
1880   }
1881}
1882
1883INLINE void TEXTURE_PIPELINE(COLOR* TEX, INT32 SSS, INT32 SST, UINT32 NOBILINEAR, UINT32 tilenum)
1884{
1885#define RELATIVE(x, y)    ((((x) >> 3) - (y)) << 3) | (x & 7);
1886   INT32 maxs, maxt;
1887   if (other_modes.sample_type)
1888   {
1889      COLOR t0, t1, t2, t3;
1890      int sss1, sst1, sss2, sst2;
1891      INT32 rt0 = 0, rt1 = 0, rt2 = 0, rt3 = 0;
1892      INT32 gt0 = 0, gt1 = 0, gt2 = 0, gt3 = 0;
1893      INT32 bt0 = 0, bt1 = 0, bt2 = 0, bt3 = 0;
1894      INT32 at0 = 0, at1 = 0, at2 = 0, at3 = 0;
1895
1896      INT32 SFRAC = 0, TFRAC = 0, INVSF = 0, INVTF = 0;
1897      INT32 R32, G32, B32, A32;
1898      INT32 maxs2, maxt2;
1899      int upper = 0;
1900
1901      t0.r = t0.g = t0.b = t0.a = 0;
1902      t1.r = t1.g = t1.b = t1.a = 0;
1903      t2.r = t2.g = t2.b = t2.a = 0;
1904      t3.r = t3.g = t3.b = t3.a = 0;
1905
1906      sss1 = SSS;
1907      sst1 = SST;
1908
1909      texshift(&sss1, &sst1, &maxs, &maxt, tilenum);
1910
1911      sss2 = sss1 + 32; sst2 = sst1 + 32;
1912      maxs2 = ((sss2 >> 3) >= tile[tilenum].sh);
1913      maxt2 = ((sst2 >> 3) >= tile[tilenum].th);
1914
1915      sss1 = RELATIVE(sss1, tile[tilenum].sl);
1916      sst1 = RELATIVE(sst1, tile[tilenum].tl);
1917      sss2 = RELATIVE(sss2, tile[tilenum].sl);
1918      sst2 = RELATIVE(sst2, tile[tilenum].tl);
1919
1920      SFRAC = sss1 & 0x1f;
1921      TFRAC = sst1 & 0x1f;
1922
1923      CLAMP(&sss1, &sst1, &SFRAC, &TFRAC, maxs, maxt, tilenum);
1924      CLAMP_LIGHT(&sss2, &sst2, maxs2, maxt2, tilenum);
1925
1926      MASK(&sss1, &sst1, tilenum);
1927        MASK(&sss2, &sst2, tilenum);
1928
1929      upper = ((SFRAC + TFRAC) >= 0x20);
1930      if (upper)
1931      {
1932         INVSF = 0x20 - SFRAC;
1933         INVTF = 0x20 - TFRAC;
1934      }
1935
1936      if (other_modes.mid_texel || !upper)
1937      {
1938         FETCH_TEXEL(&t0, sss1, sst1, tilenum);
1939      }
1940      FETCH_TEXEL(&t1, sss2, sst1, tilenum);
1941      FETCH_TEXEL(&t2, sss1, sst2, tilenum);
1942      if (other_modes.mid_texel || upper)
1943      {
1944         FETCH_TEXEL(&t3, sss2, sst2, tilenum);
1945      }
1946      if (other_modes.mid_texel || !upper)
1947      {
1948         rt0 = t0.r; gt0 = t0.g; bt0 = t0.b; at0 = t0.a;
1949      }
1950      rt1 = t1.r; rt2 = t2.r; gt1 = t1.g; gt2 = t2.g; bt1 = t1.b; bt2 = t2.b; at1 = t1.a; at2 = t2.a;
1951      if (other_modes.mid_texel || upper)
1952      {
1953         rt3 = t3.r; gt3 = t3.g; bt3 = t3.b; at3 = t3.a;
1954      }
1955
1956      if (!other_modes.mid_texel || SFRAC!= 0x10 || TFRAC != 0x10)
1957      {
1958         if (upper)
1959         {
1960            R32 = rt3 + ((INVSF*(rt2 - rt3))>>5) + ((INVTF*(rt1 - rt3))>>5);
1961            TEX->r = (R32 < 0) ? 0 : R32;
1962            G32 = gt3 + ((INVSF*(gt2 - gt3))>>5) + ((INVTF*(gt1 - gt3))>>5);
1963            TEX->g = (G32 < 0) ? 0 : G32;
1964            B32 = bt3 + ((INVSF*(bt2 - bt3))>>5) + ((INVTF*(bt1 - bt3))>>5);
1965            TEX->b = (B32 < 0) ? 0 : B32;
1966            A32 = at3 + ((INVSF*(at2 - at3))>>5) + ((INVTF*(at1 - at3))>>5);
1967            TEX->a = (A32 < 0) ? 0 : A32;
1968         }
1969         else
1970         {
1971            R32 = rt0 + ((SFRAC*(rt1 - rt0))>>5) + ((TFRAC*(rt2 - rt0))>>5);
1972            TEX->r = (R32 < 0) ? 0 : R32;
1973            G32 = gt0 + ((SFRAC*(gt1 - gt0))>>5) + ((TFRAC*(gt2 - gt0))>>5);
1974            TEX->g = (G32 < 0) ? 0 : G32;
1975            B32 = bt0 + ((SFRAC*(bt1 - bt0))>>5) + ((TFRAC*(bt2 - bt0))>>5);
1976            TEX->b = (B32 < 0) ? 0 : B32;
1977            A32 = at0 + ((SFRAC*(at1 - at0))>>5) + ((TFRAC*(at2 - at0))>>5);
1978            TEX->a = (A32 < 0) ? 0 : A32;
1979         }
1980      }
1981      else // Is this accurate?
1982      {
1983         TEX->r = (rt0 + rt1 + rt2 + rt3) >> 2;
1984         TEX->g = (gt0 + gt1 + gt2 + gt3) >> 2;
1985         TEX->b = (bt0 + bt1 + bt2 + bt3) >> 2;
1986         TEX->a = (at0 + at1 + at2 + at3) >> 2;
1987      }
1988   }
1989   else
1990   {
1991      int sss1, sst1;
1992      INT32 SFRAC, TFRAC;
1993
1994      sss1 = SSS;
1995      sst1 = SST;
1996
1997      texshift(&sss1, &sst1, &maxs, &maxt, tilenum);
1998      sss1 = RELATIVE(sss1, tile[tilenum].sl);
1999      sst1 = RELATIVE(sst1, tile[tilenum].tl);
2000
2001      sss1 += 0x10;
2002      sst1 += 0x10;
2003
2004      SFRAC = sss1 & 0x1f;
2005      TFRAC = sst1 & 0x1f;
2006
2007      CLAMP(&sss1, &sst1, &SFRAC, &TFRAC, maxs, maxt, tilenum);
2008
2009        MASK(&sss1, &sst1, tilenum);
2010
2011      /* point sample */
2012      FETCH_TEXEL(TEX, sss1, sst1, tilenum);
2013   }
2014}
2015
2016INLINE UINT32 z_decompress(UINT16 *zb)
2017{
2018   UINT32 exponent = (*zb >> 13) & 7;
2019   UINT32 mantissa = (*zb >> 2) & 0x7ff;
2020   return ((mantissa << z_dec_table[exponent].shift) + z_dec_table[exponent].add);
2021}
2022
2023INLINE void z_build_com_table(void) // Thanks to angrylion, Gonetz and Orkin
2024{
2025   int j = 0;
2026   for(j = 0; j < 0x40000; j++)
2027   {
2028      UINT32 exponent = 0;
2029      UINT32 testbit = 0x20000;
2030      UINT32 mantissa = 0;
2031      while( (j & testbit) && (exponent < 7) )
2032      {
2033         exponent++;
2034         testbit = 1 << (17 - exponent);
2035      }
2036
2037      mantissa = (j >> (6 - (6 < exponent ? 6 : exponent))) & 0x7ff;
2038      z_com_table[j] = (UINT16)(((exponent << 11) | mantissa) << 2);
2039   }
2040}
2041
2042INLINE void z_store(UINT16* zb, UINT8* zhb, UINT32 z, UINT32 deltaz)
2043{
2044   UINT8 deltazmem = 15;
2045   int j = 0;
2046   z &= 0x3ffff;
2047   deltaz &= 0xffff;
2048   for(j = 15; j >= 0; j--)
2049   {
2050      if( (deltaz >> j) == 1 )
2051      {
2052         break;
2053      }
2054      else
2055      {
2056         deltazmem--;
2057      }
2058   }
2059   if (deltazmem>15)
2060   {
2061      deltazmem=0;
2062   }
2063   *zb = z_com_table[z]|(deltazmem>>2);
2064   *zhb = (deltazmem & 3);
2065}
2066
2067INLINE UINT16 dz_decompress(UINT16* zb, UINT8* zhb)
2068{
2069   UINT32 dz_compressed = (((*zb & 3) << 2)|(*zhb & 3));
2070   return (1 << dz_compressed);
2071}
2072
2073INLINE UINT32 z_compare(void* fb, UINT8* hb, UINT16* zb, UINT8* zhb, UINT32 sz, UINT16 dzpix)
2074{
2075   int force_coplanar = 0;
2076   UINT32 oz = z_decompress(zb);
2077   UINT32 dzmem = dz_decompress(zb, zhb);
2078   UINT32 dznew = 0;
2079   UINT32 farther = 0;
2080   UINT32 diff = 0;
2081   UINT32 nearer = 0;
2082   UINT32 infront = 0;
2083   UINT32 max = 0;
2084   int precision_factor = (oz >> 15) & 0xf;
2085   int overflow = 0;
2086   int cvgcoeff = 0;
2087   UINT32 mempixel, memory_cvg;
2088
2089   sz &= 0x3ffff;
2090   if (dzmem == 0x8000 && precision_factor < 3)
2091   {
2092      force_coplanar = 1;
2093   }
2094   if (!precision_factor)
2095   {
2096      dzmem = ((dzmem << 1) > 16) ? (dzmem << 1) : 16;
2097   }
2098   else if (precision_factor == 1)
2099   {
2100      dzmem = ((dzmem << 1) > 8) ? (dzmem << 1) : 8;
2101   }
2102   else if (precision_factor == 2)
2103   {
2104      dzmem = ((dzmem << 1) > 4) ? (dzmem << 1) : 4;
2105   }
2106   if (dzmem == 0 && precision_factor < 3)
2107   {
2108      dzmem = 0xffff;
2109   }
2110   if (dzmem > 0x8000)
2111   {
2112      dzmem = 0xffff;
2113   }
2114   dznew =((dzmem > dzpix) ? dzmem : (UINT32)dzpix) << 3;
2115   dznew &= 0x3ffff;
2116
2117   farther = ((sz + dznew) >= oz) ? 1 : 0;
2118   diff = (sz >= dznew) ? (sz - dznew) : 0;
2119   nearer = (diff <= oz) ? 1: 0;
2120   infront = (sz < oz) ? 1 : 0;
2121   max = (dzmem == 0x3ffff);
2122
2123   if (force_coplanar)
2124   {
2125      farther = nearer = 1;
2126   }
2127
2128   curpixel_overlap = 0;
2129
2130   switch(fb_size)
2131   {
2132      case 1: /* Banjo Tooie */
2133         memory_cvg = 0; //??
2134         break;
2135      case 2:
2136         mempixel = *(UINT16*)fb;
2137         memory_cvg = ((mempixel & 1) << 2) + (*hb & 3);
2138         break;
2139      case 3:
2140         mempixel = *(UINT32*)fb;
2141         memory_cvg = (mempixel >> 5) & 7;
2142         break;
2143      default:
2144         fatalerror("z_compare: fb_size = %d",fb_size);
2145         break;
2146   }
2147
2148   if (!other_modes.image_read_en)
2149   {
2150      memory_cvg = 7;
2151   }
2152
2153   overflow = ((memory_cvg + curpixel_cvg - 1) > 7) ? 1 : 0;
2154   curpixel_overlap = (other_modes.force_blend || (!overflow && other_modes.antialias_en && farther));
2155
2156   if (other_modes.z_mode == 1 && infront && farther && overflow)
2157   {
2158      cvgcoeff = ((dzmem >> dznew) - (sz >> dznew)) & 0xf;
2159      curpixel_cvg = ((cvgcoeff * (curpixel_cvg - 1)) >> 3) & 0xf;
2160   }
2161   if (curpixel_cvg > 8)
2162      curpixel_cvg = 8;
2163
2164   switch(other_modes.z_mode)
2165   {
2166      case 0: // Opaque
2167         return (max || (overflow ? infront : nearer))? 1 : 0;
2168         break;
2169      case 1: // Interpenetrating
2170         return (max || (overflow ? infront : nearer))? 1 : 0;
2171         break;
2172      case 2: // Transparent
2173         return (infront || max)? 1: 0;
2174         break;
2175      case 3: // Decal
2176         return (farther && nearer && !max) ? 1 : 0;
2177         break;
2178      default:
2179         fatalerror( "z_mode = %d", other_modes.z_mode);
2180         break;
2181   }
2182}
2183
2184INLINE INT32 normalize_dzpix(INT32 sum)
2185{
2186   int count = 0;
2187   if (sum & 0xc000)
2188   {
2189      return 0x8000;
2190   }
2191   if (!(sum & 0xffff))
2192   {
2193      return 1;
2194   }
2195   for(count = 0x2000; count > 0; count >>= 1)
2196    {
2197      if (sum & count)
2198      {
2199           return(count << 1);
2200      }
2201    }
2202    return 0;
2203}
2204
2205INLINE INT32 CLIP(INT32 value,INT32 min,INT32 max)
2206{
2207   if (value < min)
2208   {
2209      return min;
2210   }
2211   else if(value > max)
2212   {
2213      return max;
2214   }
2215   else
2216   {
2217      return value;
2218   }
2219}
2220
2221INLINE COLOR video_filter16(UINT16* vbuff, UINT8* hbuff, UINT32 hres)
2222{
2223   COLOR filtered, penumax, penumin, max, min;
2224   UINT16 pix = *vbuff;
2225   UINT32 centercvg = (*hbuff & 3) + ((pix & 1) << 2) + 1;
2226   UINT32 numoffull = 1;
2227   UINT32 cvg;
2228   UINT32 r = (((pix >> 11) & 0x1f) << 3) | (((pix >> 11) & 0x1f) >> 2);
2229   UINT32 g = (((pix >> 6) & 0x1f) << 3) | (((pix >> 6) & 0x1f) >> 2);
2230   UINT32 b = (((pix >> 1) & 0x1f) << 3) | (((pix >> 1) & 0x1f) >> 2);
2231   UINT32 backr[7], backg[7], backb[7];
2232   UINT32 invr[7], invg[7], invb[7];
2233   INT32 coeff;
2234   INT32 leftup = -hres - 2;
2235   INT32 leftdown = hres - 2;
2236   INT32 toleft = -2;
2237   UINT32 colr, colg, colb;
2238   UINT32 enb;
2239   int i = 0;
2240
2241   filtered.r = filtered.g = filtered.b = filtered.a = 0;
2242
2243   backr[0] = r;
2244   backg[0] = g;
2245   backb[0] = b;
2246   invr[0] = 255 - r;
2247   invg[0] = 255 - g;
2248   invb[0] = 255 - b;
2249
2250   if (centercvg == 8)
2251   {
2252      filtered.r = r; filtered.g = g; filtered.b = b;
2253      return filtered;
2254   }
2255
2256   for(i = 0; i < 5; i++)
2257   {
2258      pix = vbuff[leftup ^ WORD_ADDR_XOR];
2259      cvg = hbuff[leftup ^ BYTE_ADDR_XOR] & 3;
2260      if(i & 1)
2261      {
2262         if (cvg == 3 && (pix & 1))
2263         {
2264            backr[numoffull] = (((pix >> 11) & 0x1f) << 3) | (((pix >> 11) & 0x1f) >> 2);
2265            backg[numoffull] = (((pix >> 6) & 0x1f) << 3) | (((pix >> 6) & 0x1f) >> 2);
2266            backb[numoffull] = (((pix >> 1) & 0x1f) << 3) | (((pix >> 1) & 0x1f) >> 2);
2267            invr[numoffull] = 255 - backr[numoffull];
2268            invg[numoffull] = 255 - backg[numoffull];
2269            invb[numoffull] = 255 - backb[numoffull];
2270         }
2271         else
2272         {
2273                backr[numoffull] = invr[numoffull] = 0;
2274            backg[numoffull] = invg[numoffull] = 0;
2275            backb[numoffull] = invb[numoffull] = 0;
2276         }
2277         numoffull++;
2278      }
2279      leftup++;
2280   }
2281
2282   for(i = 0; i < 5; i++)
2283   {
2284      pix = vbuff[leftdown ^ WORD_ADDR_XOR];
2285      cvg = hbuff[leftdown ^ BYTE_ADDR_XOR] & 3;
2286      if (i&1)
2287      {
2288         if (cvg == 3 && (pix & 1))
2289         {
2290            backr[numoffull] = (((pix >> 11) & 0x1f) << 3) | (((pix >> 11) & 0x1f) >> 2);
2291            backg[numoffull] = (((pix >> 6) & 0x1f) << 3) | (((pix >> 6) & 0x1f) >> 2);
2292            backb[numoffull] = (((pix >> 1) & 0x1f) << 3) | (((pix >> 1) & 0x1f) >> 2);
2293            invr[numoffull] = 255 - backr[numoffull];
2294            invg[numoffull] = 255 - backg[numoffull];
2295            invb[numoffull] = 255 - backb[numoffull];
2296         }
2297         else
2298         {
2299                backr[numoffull] = invr[numoffull] = 0;
2300            backg[numoffull] = invg[numoffull] = 0;
2301            backb[numoffull] = invb[numoffull] = 0;
2302         }
2303         numoffull++;
2304      }
2305      leftdown++;
2306   }
2307
2308   for(i = 0; i < 5; i++)
2309   {
2310      pix = vbuff[toleft ^ WORD_ADDR_XOR];
2311      cvg = hbuff[toleft ^ BYTE_ADDR_XOR] & 3;
2312      if (!(i&3))
2313      {
2314         if (cvg == 3 && (pix & 1))
2315         {
2316            backr[numoffull] = (((pix >> 11) & 0x1f) << 3) | (((pix >> 11) & 0x1f) >> 2);
2317            backg[numoffull] = (((pix >> 6) & 0x1f) << 3) | (((pix >> 6) & 0x1f) >> 2);
2318            backb[numoffull] = (((pix >> 1) & 0x1f) << 3) | (((pix >> 1) & 0x1f) >> 2);
2319            invr[numoffull] = 255 - backr[numoffull];
2320            invg[numoffull] = 255 - backg[numoffull];
2321            invb[numoffull] = 255 - backb[numoffull];
2322         }
2323         else
2324         {
2325                backr[numoffull] = invr[numoffull] = 0;
2326            backg[numoffull] = invg[numoffull] = 0;
2327            backb[numoffull] = invb[numoffull] = 0;
2328         }
2329         numoffull++;
2330      }
2331      toleft++;
2332   }
2333
2334   if (numoffull != 7)
2335   {
2336      fatalerror("Something went wrong in vi_filter16");
2337   }
2338
2339   video_max(&backr[0], &max.r, &enb);
2340   for(i = 1; i < 7; i++)
2341   {
2342      if (!((enb >> i) & 1))
2343      {
2344         backr[i] = 0;
2345      }
2346   }
2347   video_max(&backg[0], &max.g, &enb);
2348   for (i = 1; i < 7; i++)
2349   {
2350      if (!((enb >> i) & 1))
2351      {
2352         backg[i] = 0;
2353      }
2354   }
2355   video_max(&backb[0], &max.b, &enb);
2356   for (i = 1; i < 7; i++)
2357   {
2358      if (!((enb >> i) & 1))
2359      {
2360         backb[i] = 0;
2361      }
2362   }
2363   video_max(&invr[0], &min.r, &enb);
2364   for (i = 1; i < 7; i++)
2365   {
2366      if (!((enb >> i) & 1))
2367      {
2368         backr[i] = 0;
2369      }
2370   }
2371   video_max(&invg[0], &min.g, &enb);
2372   for (i = 1; i < 7; i++)
2373   {
2374      if (!((enb >> i) & 1))
2375      {
2376         backg[i] = 0;
2377      }
2378   }
2379   video_max(&invb[0], &min.b, &enb);
2380   for (i = 1; i < 7; i++)
2381   {
2382      if (!((enb >> i) & 1))
2383      {
2384         backb[i] = 0;
2385      }
2386   }
2387
2388   video_max(&backr[0], &penumax.r, &enb);
2389   i = ge_two(enb);
2390   penumax.r = i ? max.r : penumax.r;
2391
2392   video_max(&backg[0], &penumax.g, &enb);
2393   i = ge_two(enb);
2394   penumax.g = i ? max.g : penumax.g;
2395
2396   video_max(&backb[0], &penumax.b, &enb);
2397   i = ge_two(enb);
2398   penumax.b = i ? max.b : penumax.b;
2399
2400   video_max(&invr[0], &penumin.r, &enb);
2401   i = ge_two(enb);
2402   penumin.r = i ? min.r : penumin.r;
2403
2404   video_max(&invg[0], &penumin.g, &enb);
2405   i = ge_two(enb);
2406   penumin.g = i ? min.g : penumin.g;
2407
2408   video_max(&invb[0], &penumin.b, &enb);
2409   i = ge_two(enb);
2410   penumin.b = i ? min.b : penumin.b;
2411
2412   penumin.r = 255 - penumin.r;
2413   penumin.g = 255 - penumin.g;
2414   penumin.b = 255 - penumin.b;
2415
2416   colr = (UINT32)penumin.r + (UINT32)penumax.r - (r << 1);
2417   colg = (UINT32)penumin.g + (UINT32)penumax.g - (g << 1);
2418   colb = (UINT32)penumin.b + (UINT32)penumax.b - (b << 1);
2419   coeff = 8 - (INT32)centercvg;
2420   colr = (((colr * coeff) + 4) >> 3) + r;
2421   colg = (((colg * coeff) + 4) >> 3) + g;
2422   colb = (((colb * coeff) + 4) >> 3) + b;
2423   colr &= 0xff;
2424   colg &= 0xff;
2425   colb &= 0xff;
2426
2427   filtered.r = colr;
2428   filtered.g = colg;
2429   filtered.b = colb;
2430   return filtered;
2431}
2432
2433// This needs to be fixed for endianness.
2434INLINE void divot_filter16(INT32* r, INT32* g, INT32* b, UINT16* fbuff, UINT32 fbuff_index)
2435{
2436   UINT32 leftr, leftg, leftb, rightr, rightg, rightb;
2437   UINT16 leftpix, rightpix;
2438   UINT16* next, *prev;
2439   UINT32 Lsw = fbuff_index & 1;
2440   next = (Lsw) ? (UINT16*)(fbuff - 1) : (UINT16*)(fbuff + 3);
2441   prev = (Lsw) ? (UINT16*)(fbuff - 3) : (UINT16*)(fbuff + 1);
2442   leftpix = *prev;
2443   rightpix = *next;
2444
2445   //leftpix = *(fbuff - 1); //for BE targets
2446   //rightpix = *(fbuff + 1);
2447
2448   leftr = (((leftpix >> 11) & 0x1f) << 3) | (((leftpix >> 11) & 0x1f) >> 2);
2449   leftg = (((leftpix >> 6) & 0x1f) << 3) | (((leftpix >> 6) & 0x1f) >> 2);
2450   leftb = (((leftpix >> 1) & 0x1f) << 3) | (((leftpix >> 1) & 0x1f) >> 2);
2451   rightr = (((rightpix >> 11) & 0x1f) << 3) | (((rightpix >> 11) & 0x1f) >> 2);
2452   rightg = (((rightpix >> 6) & 0x1f) << 3) | (((rightpix >> 6) & 0x1f) >> 2);
2453   rightb = (((rightpix >> 1) & 0x1f) << 3) |(((rightpix >> 1) & 0x1f) >> 2);
2454   if ((leftr >= *r && rightr >= leftr) || (leftr >= rightr && *r >= leftr))
2455   {
2456      *r = leftr; //left = median value
2457   }
2458   if ((rightr >= *r && leftr >= rightr) || (rightr >= leftr && *r >= rightr))
2459   {
2460      *r = rightr; //right = median, else *r itself is median
2461   }
2462   if ((leftg >= *g && rightg >= leftg) || (leftg >= rightg && *g >= leftg))
2463   {
2464      *g = leftg;
2465   }
2466   if ((rightg >= *g && leftg >= rightg) || (rightg >= leftg && *g >= rightg))
2467   {
2468      *g = rightg;
2469   }
2470   if ((leftb >= *b && rightb >= leftb) || (leftb >= rightb && *b >= leftb))
2471   {
2472      *b = leftb;
2473   }
2474   if ((rightb >= *b && leftb >= rightb) || (rightb >= leftb && *b >= rightb))
2475   {
2476      *b = rightb;
2477   }
2478}
2479
2480INLINE void divot_filter16_buffer(int* r, int* g, int* b, COLOR* vibuffer)
2481{
2482   UINT32 leftr, leftg, leftb, rightr, rightg, rightb;
2483   COLOR leftpix, rightpix, filtered;
2484   leftpix = vibuffer[-1];
2485   rightpix = vibuffer[1];
2486   filtered = *vibuffer;
2487
2488   *r = filtered.r;
2489   *g = filtered.g;
2490   *b = filtered.b;
2491   leftr = leftpix.r;
2492   leftg = leftpix.g;
2493   leftb = leftpix.b;
2494   rightr = rightpix.r;
2495   rightg = rightpix.g;
2496   rightb = rightpix.b;
2497   if ((leftr >= *r && rightr >= leftr) || (leftr >= rightr && *r >= leftr))
2498   {
2499      *r = leftr; //left = median value
2500   }
2501   if ((rightr >= *r && leftr >= rightr) || (rightr >= leftr && *r >= rightr))
2502   {
2503      *r = rightr; //right = median, else *r itself is median
2504   }
2505   if ((leftg >= *g && rightg >= leftg) || (leftg >= rightg && *g >= leftg))
2506   {
2507      *g = leftg;
2508   }
2509   if ((rightg >= *g && leftg >= rightg) || (rightg >= leftg && *g >= rightg))
2510   {
2511      *g = rightg;
2512   }
2513   if ((leftb >= *b && rightb >= leftb) || (leftb >= rightb && *b >= leftb))
2514   {
2515      *b = leftb;
2516   }
2517   if ((rightb >= *b && leftb >= rightb) || (rightb >= leftb && *b >= rightb))
2518   {
2519      *b = rightb;
2520   }
2521
2522   filtered.r = *r;
2523   filtered.g = *g;
2524   filtered.b = *b;
2525}
2526
2527// Fix me.
2528INLINE void restore_filter16(int* r, int* g, int* b, UINT16* fbuff, UINT32 fbuff_index, UINT32 hres)
2529{
2530   INT32 leftuppix = -hres - 1;
2531   INT32 leftdownpix = hres - 1;
2532   INT32 toleftpix = -1;
2533   UINT8 tempr, tempg, tempb;
2534   UINT16 pix;
2535   int i;
2536
2537   UINT8 r5 = *r;
2538   UINT8 g5 = *g;
2539   UINT8 b5 = *b;
2540   r5 &= ~7;
2541   g5 &= ~7;
2542   b5 &= ~7;
2543
2544   for (i = 0; i < 3; i++)
2545   {
2546      pix = fbuff[leftuppix ^ 1];
2547      tempr = (((pix >> 11) & 0x1f) << 3) | (((pix >> 11) & 0x1f) >> 2);
2548      tempg = (((pix >> 6) & 0x1f) << 3) | (((pix >> 6) & 0x1f) >> 2);
2549      tempb = (((pix >> 1) & 0x1f) << 3) | (((pix >> 1) & 0x1f) >> 2);
2550      tempr &= ~7;
2551      tempg &= ~7;
2552      tempb &= ~7;
2553      if (tempr > r5)
2554      {
2555         *r += 1;
2556      }
2557      if (tempr < r5)
2558      {
2559         *r -= 1;
2560      }
2561      if (tempg > g5)
2562      {
2563         *g += 1;
2564      }
2565      if (tempg < g5)
2566      {
2567         *g -= 1;
2568      }
2569      if (tempb > b5)
2570      {
2571         *b += 1;
2572      }
2573      if (tempb < b5)
2574      {
2575         *b -= 1;
2576      }
2577      leftuppix++;
2578   }
2579
2580   for (i = 0; i < 3; i++)
2581   {
2582      pix = fbuff[leftdownpix ^ 1];
2583      tempr = (((pix >> 11) & 0x1f) << 3) | (((pix >> 11) & 0x1f) >> 2);
2584      tempg = (((pix >> 6) & 0x1f) << 3) | (((pix >> 6) & 0x1f) >> 2);
2585      tempb = (((pix >> 1) & 0x1f) << 3) | (((pix >> 1) & 0x1f) >> 2);
2586      tempr &= ~7;
2587      tempg &= ~7;
2588      tempb &= ~7;
2589      if (tempr > r5)
2590      {
2591         *r += 1;
2592      }
2593      if (tempr < r5)
2594      {
2595         *r -= 1;
2596      }
2597      if (tempg > g5)
2598      {
2599         *g += 1;
2600      }
2601      if (tempg < g5)
2602      {
2603         *g -= 1;
2604      }
2605      if (tempb > b5)
2606      {
2607         *b += 1;
2608      }
2609      if (tempb < b5)
2610      {
2611         *b -= 1;
2612      }
2613      leftdownpix++;
2614   }
2615   for(i = 0; i < 3; i++)
2616   {
2617      if (!(i & 1))
2618      {
2619         pix = fbuff[toleftpix ^ 1];
2620         tempr = (((pix >> 11) & 0x1f) << 3) | (((pix >> 11) & 0x1f) >> 2);
2621         tempg = (((pix >> 6) & 0x1f) << 3) | (((pix >> 6) & 0x1f) >> 2);
2622         tempb = (((pix >> 1) & 0x1f) << 3) | (((pix >> 1) & 0x1f) >> 2);
2623         tempr &= ~7;
2624         tempg &= ~7;
2625         tempb &= ~7;
2626         if (tempr > r5)
2627         {
2628            *r += 1;
2629         }
2630         if (tempr < r5)
2631         {
2632            *r -= 1;
2633         }
2634         if (tempg > g5)
2635         {
2636            *g += 1;
2637         }
2638         if (tempg < g5)
2639         {
2640            *g -= 1;
2641         }
2642         if (tempb > b5)
2643         {
2644            *b += 1;
2645         }
2646         if (tempb < b5)
2647         {
2648            *b -= 1;
2649         }
2650      }
2651      toleftpix++;
2652   }
2653}
2654
2655INLINE void restore_filter16_buffer(INT32* r, INT32* g, INT32* b, COLOR* vibuff, UINT32 hres)
2656{
2657   COLOR filtered;
2658   COLOR leftuppix, leftdownpix, leftpix;
2659   COLOR rightuppix, rightdownpix, rightpix;
2660   COLOR uppix, downpix;
2661   INT32 ihres = (INT32)hres; //can't apply unary minus to unsigned
2662
2663   leftuppix = vibuff[-ihres - 1];
2664   leftdownpix = vibuff[ihres - 1];
2665   leftpix = vibuff[-1];
2666
2667   rightuppix = vibuff[-ihres + 1];
2668   rightdownpix = vibuff[ihres + 1];
2669   rightpix = vibuff[1];
2670
2671   uppix = vibuff[-ihres];
2672   downpix = vibuff[ihres];
2673   filtered = *vibuff;
2674
2675   restore_two(&filtered, &leftuppix);
2676   restore_two(&filtered, &uppix);
2677   restore_two(&filtered, &rightuppix);
2678
2679   restore_two(&filtered, &leftpix);
2680   restore_two(&filtered, &rightpix);
2681
2682   restore_two(&filtered, &leftdownpix);
2683   restore_two(&filtered, &downpix);
2684   restore_two(&filtered, &rightdownpix);
2685
2686   *r = filtered.r;
2687   *g = filtered.g;
2688   *b = filtered.b;
2689
2690   *r = CLIP(*r, 0, 0xff);
2691   *g = CLIP(*g, 0, 0xff);
2692   *b = CLIP(*b, 0, 0xff);
2693}
2694
2695// This is wrong, only the 5 upper bits are compared.
2696INLINE void restore_two(COLOR* filtered, COLOR* neighbour)
2697{
2698   if (neighbour->r > filtered->r)
2699   {
2700      filtered->r += 1;
2701   }
2702   if (neighbour->r < filtered->r)
2703   {
2704      filtered->r -= 1;
2705   }
2706   if (neighbour->g > filtered->g)
2707   {
2708      filtered->g += 1;
2709   }
2710   if (neighbour->g < filtered->g)
2711   {
2712      filtered->g -= 1;
2713   }
2714   if (neighbour->b > filtered->b)
2715   {
2716      filtered->b += 1;
2717   }
2718   if (neighbour->b < filtered->b)
2719   {
2720      filtered->b -= 1;
2721   }
2722}
2723
2724INLINE void video_max(UINT32* Pixels, UINT8* max, UINT32* enb)
2725{
2726   int i;
2727   int pos = 0;
2728   *enb = 0;
2729   for(i = 0; i < 7; i++)
2730   {
2731      if (Pixels[i] > Pixels[pos])
2732      {
2733          *enb += (1 << i);
2734         pos = i;
2735      }
2736      else if (Pixels[i] < Pixels[pos])
2737      {
2738          *enb += (1 << i);
2739      }
2740      else
2741      {
2742         pos = i;
2743      }
2744   }
2745   *max = Pixels[pos];
2746}
2747
2748INLINE UINT32 ge_two(UINT32 enb)
2749{
2750   int i;
2751   int j = 0;
2752   for(i = 0; i < 7; i++)
2753   {
2754      if (!((enb >> i) & 1))
2755      {
2756         j++;
2757      }
2758   }
2759   return (j > 1);
2760}
2761
2762INLINE void calculate_clamp_diffs(UINT32 prim_tile)
2763{
2764   int start, end;
2765   if (other_modes.tex_lod_en || prim_tile == 7)
2766   {
2767      start = 0;
2768      end = 7;
2769   }
2770   else
2771   {
2772      start = prim_tile;
2773      end = prim_tile + 1;
2774   }
2775   for (; start <= end; start++)
2776   {
2777      clamp_s_diff[start] = (tile[start].sh >> 2) - (tile[start].sl >> 2);
2778      clamp_t_diff[start] = (tile[start].th >> 2) - (tile[start].tl >> 2);
2779   }
2780}
2781
2782INLINE void rgb_dither(INT32* r, INT32* g, INT32* b, int dith)
2783{
2784   if ((*r & 7) > dith)
2785   {
2786      *r = (*r & 0xf8) + 8;
2787      if (*r > 247)
2788         *r = 255;
2789   }
2790   if ((*g & 7) > dith)
2791   {
2792      *g = (*g & 0xf8) + 8;
2793      if (*g > 247)
2794         *g = 255;
2795   }
2796   if ((*b & 7) > dith)
2797   {
2798      *b = (*b & 0xf8) + 8;
2799      if (*b > 247)
2800         *b = 255;
2801   }
2802}
2803
2804INLINE void set_shade_for_rects(void)
2805{
2806   shade_color.r = 0;
2807   shade_color.g = 0;
2808   shade_color.b = 0;
2809   shade_color.a = 0;
2810}
2811
2812INLINE void set_shade_for_tris(UINT32 shade)
2813{
2814   if (!shade) // Hack, needed for Top Gear Rally 2 sky
2815   {
2816      shade_color.r = prim_color.r;
2817      shade_color.g = prim_color.g;
2818      shade_color.b = prim_color.b;;
2819      shade_color.a = prim_color.a;
2820   }
2821}
2822
2823INLINE UINT32 getlog2(UINT32 lod_clamp)
2824{
2825   int i;
2826   if (lod_clamp < 2)
2827   {
2828      return 0;
2829   }
2830   else
2831   {
2832      for (i = 7; i > 0; i--)
2833      {
2834         if ((lod_clamp >> i) & 1)
2835         {
2836            return i;
2837         }
2838      }
2839   }
2840   return 0;
2841}
2842
2843INLINE void copy_colors(COLOR* dst, COLOR* src)
2844{
2845   dst->r = src->r;
2846   dst->g = src->g;
2847   dst->b = src->b;
2848   dst->a = src->a;
2849}
2850
2851INLINE void BILERP_AND_WRITE(UINT32* src0, UINT32* src1, UINT32* dest)
2852{
2853   UINT32 r1, g1, b1, col0, col1;
2854   col0 = *src0;
2855   col1 = *src1;
2856   r1 = (((col0 >> 16)&0xff) + ((col1 >> 16)&0xff))>>1;
2857   g1 = (((col0 >> 8)&0xff) + ((col1 >> 8)&0xff))>>1;
2858   b1 = (((col0 >> 0)&0xff) + ((col1 >> 0)&0xff))>>1;
2859   *dest = (r1 << 16) | (g1 << 8) | b1;
2860}
2861
2862INLINE void tcdiv(INT32 ss, INT32 st, INT32 sw, INT32* sss, INT32* sst)
2863{
2864   int w_carry;
2865   int shift;
2866   int normout;
2867   int wnorm;
2868   int temppoint, tempslope;
2869   int tlu_rcp;
2870   int tempmask;
2871   int shift_value;
2872
2873   if ((sw & 0x8000) || !(sw & 0x7fff))
2874   {
2875      w_carry = 1;
2876   }
2877   else
2878   {
2879      w_carry = 0;
2880   }
2881
2882   sw &= 0x7fff;
2883   for(shift = 1; shift <= 14 && !((sw << shift) & 0x8000); shift++);
2884   shift -= 1;
2885
2886   normout = ((sw << shift) & 0x3fff) >> 8;
2887   wnorm = ((sw << shift) & 0xff) << 2;
2888   temppoint = NormPointRom[normout];
2889   tempslope = NormSlopeRom[normout];
2890
2891   tlu_rcp = ((-(tempslope * wnorm)) >> 10);
2892   tlu_rcp = (tlu_rcp + temppoint);
2893
2894   *sss = SIGN16(ss) * tlu_rcp;
2895   *sst = SIGN16(st) * tlu_rcp;
2896   tempmask = ((1 << (shift+1)) - 1) << (29 - shift);
2897   shift_value = 13 - shift;
2898   if (shift_value < 0)
2899   {
2900      shift_value = 0;
2901   }
2902   *sss >>= shift_value;
2903   *sst >>= shift_value;
2904   if (shift == 0xe)
2905   {
2906      *sss <<= 1;
2907      *sst <<= 1;
2908   }
2909}
2910
2911#ifdef UNUSED_FUNCTION
2912void col_decode16(UINT16* addr, COLOR* col)
2913{
2914   col->r = (((*addr >> 11) & 0x1f) << 3) | (((*addr >> 11) & 0x1f) >> 2);
2915   col->g = (((*addr >> 6) & 0x1f) << 3) | (((*addr >> 6) & 0x1f) >> 2);
2916   col->b = (((*addr >> 1) & 0x1f) << 3) | (((*addr >> 6) & 0x1f) >> 2);
2917   col->a = (*addr & 1) ? 0xff : 0;
2918}
2919#endif
2920
2921static void texture_rectangle_16bit(running_machine *machine, TEX_RECTANGLE *rect)
2922{
2923   UINT16 *fb = (UINT16*)&rdram[(fb_address / 4)];
2924   UINT16 *zb = (UINT16*)&rdram[zb_address / 4];
2925   UINT8 *hb = &hidden_bits[fb_address >> 1];
2926   UINT8 *zhb = &hidden_bits[zb_address >> 1];
2927
2928   int i, j;
2929   int x1, x2, y1, y2;
2930   int s, t;
2931   int ss, st;
2932
2933   int clipx1, clipx2, clipy1, clipy2;
2934
2935   UINT32 tilenum = rect->tilenum;
2936   UINT32 tilenum2 = 0;
2937
2938   x1 = (rect->xh / 4);
2939   x2 = (rect->xl / 4);
2940   y1 = (rect->yh / 4);
2941   y2 = (rect->yl / 4);
2942
2943   if (x2<=x1)
2944   {
2945      x2 = x1 + 1;
2946   }
2947   if (y1==y2)
2948   {
2949      y2 = y1 + 1; // Needed by Goldeneye
2950   }
2951   if (other_modes.cycle_type == CYCLE_TYPE_FILL || other_modes.cycle_type == CYCLE_TYPE_COPY)
2952   {
2953      rect->dsdx /= 4;
2954      x2 += 1;
2955      y2 += 1;
2956   }
2957   else
2958   {
2959      if ((rect->xl & 3) == 3) // Needed by Mega Man 64
2960      {
2961         x2++;
2962      }
2963      if ((rect->yl & 3) == 3)
2964      {
2965         y2++;
2966      }
2967   }
2968
2969   clipx1 = clip.xh / 4;
2970   clipx2 = clip.xl / 4;
2971   clipy1 = clip.yh / 4;
2972   clipy2 = clip.yl / 4;
2973
2974   calculate_clamp_diffs(tilenum);
2975
2976   if (other_modes.cycle_type == CYCLE_TYPE_2)
2977   {
2978      if (!other_modes.tex_lod_en)
2979      {
2980         tilenum2 = (tilenum + 1) & 7;
2981      }
2982      else
2983      {
2984         tilenum2 = (tilenum + 1) & 7;
2985      }
2986   }
2987
2988
2989   set_shade_for_rects(); // Needed by Pilotwings 64
2990
2991   t = ((int)(rect->t)) << 5;
2992
2993   if (other_modes.cycle_type == CYCLE_TYPE_1)
2994   {
2995      for (j = y1; j < y2; j++)
2996      {
2997         int fb_index = j * fb_width;
2998         if (j >= clipy1 && j < clipy2)
2999         {
3000               s = ((int)(rect->s)) << 5;
3001
3002            for (i = x1; i < x2; i++)
3003            {
3004               if (i >= clipx1 && i < clipx2)
3005               {
3006                  COLOR c;
3007                  int rendered = 0;
3008                  int dith = 0;
3009                  int curpixel = fb_index + i;
3010                  UINT16* fbcur = &fb[curpixel ^ WORD_ADDR_XOR];
3011                  UINT16* zbcur = &zb[curpixel ^ WORD_ADDR_XOR];
3012                  UINT8* hbcur = &hb[curpixel ^ BYTE_ADDR_XOR];
3013                  UINT8* zhbcur = &zhb[curpixel ^ BYTE_ADDR_XOR];
3014
3015                  curpixel_cvg = 8;
3016
3017                  ss = s >> 5;
3018                  st = t >> 5;
3019                  if (rect->flip)
3020                  {
3021                     TEXTURE_PIPELINE(&texel0_color, st, ss, (rect->dsdx == (1 << 10)) && (rect->dtdy == (1 << 10)), tilenum);
3022                  }
3023                  else
3024                  {
3025                     TEXTURE_PIPELINE(&texel0_color, ss, st, (rect->dsdx == (1 << 10)) && (rect->dtdy == (1 << 10)), tilenum);
3026                  }
3027
3028                  c = COLOR_COMBINER(machine, 0);
3029
3030                  if (!other_modes.rgb_dither_sel)
3031                  {
3032                     dith = magic_matrix[(((j) & 3) << 2) + ((i ^ WORD_ADDR_XOR) & 3)];
3033                  }
3034                  else if (other_modes.rgb_dither_sel == 1)
3035                  {
3036                     dith = bayer_matrix[(((j) & 3) << 2) + ((i ^ WORD_ADDR_XOR) & 3)];
3037                  }
3038
3039
3040                  if (other_modes.z_compare_en && other_modes.z_source_sel)
3041                  {
3042                     if (z_compare(fbcur, hbcur, zbcur, zhbcur, ((UINT32)primitive_z)<<3,primitive_delta_z))
3043                     {
3044                        rendered = BLENDER1_16(machine, fbcur, hbcur, c, dith);
3045                     }
3046                  }
3047                  else
3048                  {
3049                     rendered = BLENDER1_16(machine, fbcur, hbcur, c, dith);
3050                  }
3051                  if (other_modes.z_update_en && other_modes.z_source_sel && rendered)
3052                  {
3053                     z_store(zbcur, zhbcur, ((UINT32)primitive_z) << 3,primitive_delta_z);
3054                  }
3055               }
3056
3057               s += (int)(rect->dsdx);
3058            }
3059         }
3060         t += (int)(rect->dtdy);
3061      }
3062   }
3063   else if (other_modes.cycle_type == CYCLE_TYPE_2)
3064   {
3065      for (j = y1; j < y2; j++)
3066      {
3067         int fb_index = j * fb_width;
3068
3069         if (j >= clipy1 && j < clipy2)
3070         {
3071            s = (int)(rect->s) << 5;
3072
3073            for (i = x1; i < x2; i++)
3074            {
3075               if (i >= clipx1 && i < clipx2)
3076               {
3077                  COLOR c1, c2;
3078                  int rendered=0;
3079                  int curpixel = fb_index + i;
3080                  UINT16* fbcur = &fb[curpixel ^ WORD_ADDR_XOR];
3081                  UINT16* zbcur = &zb[curpixel ^ WORD_ADDR_XOR];
3082                  UINT8* hbcur = &hb[curpixel ^ BYTE_ADDR_XOR];
3083                  UINT8* zhbcur = &zhb[curpixel ^ BYTE_ADDR_XOR];
3084                  int dith = 0;
3085
3086                  curpixel_cvg = 8;
3087
3088                  ss = s >> 5;
3089                  st = t >> 5;
3090
3091                  if (rect->flip)
3092                  {
3093                     TEXTURE_PIPELINE(&texel0_color, st, ss, (rect->dsdx == (1 << 10)) && (rect->dtdy == (1 << 10)),tilenum);
3094                     TEXTURE_PIPELINE(&texel1_color, st, ss, (rect->dsdx == (1 << 10)) && (rect->dtdy == (1 << 10)),tilenum2);
3095                  }
3096                  else
3097                  {
3098                     TEXTURE_PIPELINE(&texel0_color, ss, st, (rect->dsdx == (1 << 10)) && (rect->dtdy == (1 << 10)),tilenum);
3099                     TEXTURE_PIPELINE(&texel1_color, ss, st, (rect->dsdx == (1 << 10)) && (rect->dtdy == (1 << 10)),tilenum2);
3100                  }
3101                  c1 = COLOR_COMBINER(machine, 0);
3102                  c2 = COLOR_COMBINER(machine, 1);
3103
3104                  if (!other_modes.rgb_dither_sel)
3105                  {
3106                     dith = magic_matrix[(((j) & 3) << 2) + ((i ^ WORD_ADDR_XOR) & 3)];
3107                  }
3108                  else if (other_modes.rgb_dither_sel == 1)
3109                  {
3110                     dith = bayer_matrix[(((j) & 3) << 2) + ((i ^ WORD_ADDR_XOR) & 3)];
3111                  }
3112
3113                  if (other_modes.z_compare_en && other_modes.z_source_sel)
3114                  {
3115                     if (z_compare(fbcur, hbcur, zbcur, zhbcur, ((UINT32)primitive_z) << 3,primitive_delta_z))
3116                     {
3117                        rendered = BLENDER2_16(machine, fbcur, hbcur, c1, c2, dith);
3118                     }
3119                  }
3120                  else
3121                  {
3122                     rendered = BLENDER2_16(machine, fbcur, hbcur, c1, c2, dith);
3123                  }
3124                  if (other_modes.z_update_en && other_modes.z_source_sel && rendered)
3125                  {
3126                     z_store(zbcur, zhbcur, ((UINT32)primitive_z) << 3,primitive_delta_z);
3127                  }
3128               }
3129
3130               s += (rect->dsdx);
3131            }
3132         }
3133         t += (rect->dtdy);
3134      }
3135   }
3136   else if (other_modes.cycle_type == CYCLE_TYPE_COPY)
3137   {
3138      for (j = y1; j < y2; j++)
3139      {
3140         int fb_index = j * fb_width;
3141         if (j >= clipy1 && j < clipy2)
3142         {
3143            s = (int)(rect->s) << 5;
3144
3145            for (i = x1; i < x2; i++)
3146            {
3147                   if (i >= clipx1 && i < clipx2)
3148               {
3149                  ss = s >> 5;
3150                  st = t >> 5;
3151
3152                  if (rect->flip)
3153                  {
3154                     TEXTURE_PIPELINE(&texel0_color, st, ss, 1, tilenum);
3155                  }
3156                  else
3157                  {
3158                     TEXTURE_PIPELINE(&texel0_color, ss, st, 1, tilenum);
3159                  }
3160
3161                  curpixel_cvg = 8;
3162
3163                  if ((texel0_color.a != 0)||(!other_modes.alpha_compare_en))
3164                  {
3165                     fb[(fb_index + i) ^ WORD_ADDR_XOR] = ((texel0_color.r >> 3) << 11) | ((texel0_color.g >> 3) << 6) | ((texel0_color.b >> 3) << 1)|1;
3166                  }
3167               }
3168               s += rect->dsdx;
3169            }
3170         }
3171         t += rect->dtdy;
3172      }
3173   }
3174   else
3175   {
3176      fatalerror("texture_rectangle_16bit: unknown cycle type %d\n", other_modes.cycle_type);
3177   }
3178}
3179
3180/*****************************************************************************/
3181
3182INLINE int BLENDER1_32(running_machine *machine, UINT32 *fb, COLOR c)
3183{
3184   UINT32 mem = *fb;
3185   int r, g, b;
3186
3187   // Alpha compare
3188   if (!alpha_compare(machine, c.a))
3189   {
3190      return 0;
3191   }
3192   if (!curpixel_cvg)
3193   {
3194      return 0;
3195   }
3196
3197   copy_colors(&pixel_color, &c);
3198   if (!other_modes.z_compare_en)
3199   {
3200      curpixel_overlap = 0;
3201   }
3202
3203   memory_color.r = (mem >>24) & 0xff;
3204   memory_color.g = (mem >> 16) & 0xff;
3205   memory_color.b = (mem >> 8) & 0xff;
3206
3207   if (other_modes.image_read_en)
3208   {
3209      memory_color.a = mem & 0xe0;
3210   }
3211   else
3212   {
3213      memory_color.a = 0xe0;
3214   }
3215
3216   if (!curpixel_overlap && !other_modes.force_blend)
3217   {
3218      r = *blender1a_r[0];
3219      g = *blender1a_g[0];
3220      b = *blender1a_b[0];
3221   }
3222   else
3223   {
3224      int special_bsel = 0;
3225      if (blender2b_a[0] == &memory_color.a)
3226      {
3227         special_bsel = 1;
3228      }
3229
3230      inv_pixel_color.a = 0xff - *blender1b_a[0];
3231
3232      BLENDER_EQUATION(&r, &g, &b, 0, special_bsel);
3233   }
3234
3235   return  (FBWRITE_32(fb,r,g,b));
3236}
3237
3238INLINE int BLENDER2_32(running_machine *machine, UINT32 *fb, COLOR c1, COLOR c2)
3239{
3240   UINT32 mem = *fb;
3241   int r, g, b;
3242   int special_bsel = 0;
3243
3244   // Alpha compare
3245   if (!alpha_compare(machine, c2.a))
3246   {
3247      return 0;
3248   }
3249   if (!curpixel_cvg)
3250   {
3251      return 0;
3252   }
3253
3254   copy_colors(&pixel_color, &c2);
3255   if (!other_modes.z_compare_en)
3256   {
3257      curpixel_overlap = 0;
3258   }
3259
3260   memory_color.r = (mem >>24) & 0xff;
3261   memory_color.g = (mem >> 16) & 0xff;
3262   memory_color.b = (mem >> 8) & 0xff;
3263
3264   if (other_modes.image_read_en)
3265   {
3266      memory_color.a = (mem & 0xe0);
3267   }
3268   else
3269   {
3270      memory_color.a = 0xe0;
3271   }
3272
3273   if (blender2b_a[0] == &memory_color.a)
3274   {
3275      special_bsel = 1;
3276   }
3277
3278   inv_pixel_color.a = 0xff - *blender1b_a[0];
3279
3280   BLENDER_EQUATION(&r, &g, &b, 0, special_bsel);
3281
3282   blended_pixel_color.r = r;
3283   blended_pixel_color.g = g;
3284   blended_pixel_color.b = b;
3285
3286   pixel_color.r = r;
3287   pixel_color.g = g;
3288   pixel_color.b = b;
3289
3290   if (!curpixel_overlap && !other_modes.force_blend)
3291   {
3292      r = *blender1a_r[1];
3293      g = *blender1a_g[1];
3294      b = *blender1a_b[1];
3295   }
3296   else
3297   {
3298      if (blender2b_a[1] == &memory_color.a)
3299      {
3300         special_bsel = 1;
3301      }
3302      else
3303      {
3304         special_bsel = 0;
3305      }
3306
3307      inv_pixel_color.a = 0xff - *blender1b_a[1];
3308
3309      BLENDER_EQUATION(&r, &g, &b, 1, special_bsel);
3310   }
3311
3312   return  (FBWRITE_32(fb,r,g,b));
3313}
3314
3315static void fill_rectangle_32bit(running_machine *machine, RECTANGLE *rect)
3316{
3317   UINT32 *fb = (UINT32*)&rdram[(fb_address / 4)];
3318   int index, i, j;
3319   int x1 = rect->xh / 4;
3320   int x2 = rect->xl / 4;
3321   int y1 = rect->yh / 4;
3322   int y2 = rect->yl / 4;
3323   int clipx1, clipx2, clipy1, clipy2;
3324   int fill_cvg = 0;
3325
3326   if (x2 < x1)
3327   {
3328      stricterror ("SCARS (E) case: fill_rectangle_32bit");
3329   }
3330
3331   // TODO: clip
3332   clipx1 = clip.xh / 4;
3333   clipx2 = clip.xl / 4;
3334   clipy1 = clip.yh / 4;
3335   clipy2 = clip.yl / 4;
3336
3337   // clip
3338   if (x1 < clipx1)
3339   {
3340      x1 = clipx1;
3341   }
3342   if (y1 < clipy1)
3343   {
3344      y1 = clipy1;
3345   }
3346   if (x2 >= clipx2)
3347   {
3348      x2 = clipx2-1;
3349   }
3350   if (y2 >= clipy2)
3351   {
3352      y2 = clipy2-1;
3353   }
3354
3355   set_shade_for_rects();
3356
3357   fill_cvg = ((fill_color >> 5) & 7) + 1;
3358
3359   if (other_modes.cycle_type == CYCLE_TYPE_FILL)
3360   {
3361      for (j=y1; j <= y2; j++)
3362      {
3363         index = j * fb_width;
3364
3365         for (i=x1; i <= x2; i++)
3366         {
3367            fb[(index + i)^1] = fill_color;
3368         }
3369      }
3370   }
3371   else if (other_modes.cycle_type == CYCLE_TYPE_1)
3372   {
3373      for (j=y1; j <= y2; j++)
3374      {
3375         COLOR c;
3376         index = j * fb_width;
3377         for (i=x1; i <= x2; i++)
3378         {
3379            curpixel_cvg = fill_cvg;
3380            c = COLOR_COMBINER(machine, 0);
3381            BLENDER1_32(machine, &fb[(index + i)], c);
3382         }
3383      }
3384   }
3385   else if (other_modes.cycle_type == CYCLE_TYPE_2)
3386   {
3387      for (j=y1; j <= y2; j++)
3388      {
3389         COLOR c1, c2;
3390         index = j * fb_width;
3391         for (i=x1; i <= x2; i++)
3392         {
3393            curpixel_cvg = fill_cvg;
3394            c1 = COLOR_COMBINER(machine, 0);
3395            c2 = COLOR_COMBINER(machine, 1);
3396            BLENDER2_32(machine, &fb[(index + i)], c1, c2);
3397         }
3398      }
3399   }
3400   else
3401   {
3402      fatalerror("fill_rectangle_32bit: cycle type copy");
3403   }
3404}
3405
3406INLINE void texture_rectangle_32bit(running_machine *machine, TEX_RECTANGLE *rect)
3407{   // TODO: Z-compare and Z-update
3408   UINT32 *fb = (UINT32*)&rdram[(fb_address / 4)];
3409   int i, j;
3410   int x1, x2, y1, y2;
3411   int s, t;
3412   int ss, st;
3413
3414   int clipx1, clipx2, clipy1, clipy2;
3415
3416   UINT32 tilenum = rect ->tilenum;
3417   UINT32 tilenum2 = 0;
3418
3419   x1 = (rect->xh / 4);
3420   x2 = (rect->xl / 4);
3421   y1 = (rect->yh / 4);
3422   y2 = (rect->yl / 4);
3423
3424   if (x2 < x1)
3425   {
3426      stricterror( "x2 < x1: texture_rectangle_32bit" );
3427   }
3428
3429   if (other_modes.cycle_type == CYCLE_TYPE_FILL || other_modes.cycle_type == CYCLE_TYPE_COPY)
3430   {
3431      rect->dsdx /= 4;
3432      x2 += 1;
3433      y2 += 1;
3434   }
3435
3436   clipx1 = clip.xh / 4;
3437   clipx2 = clip.xl / 4;
3438   clipy1 = clip.yh / 4;
3439   clipy2 = clip.yl / 4;
3440
3441   calculate_clamp_diffs(tilenum);
3442
3443   if (other_modes.cycle_type == CYCLE_TYPE_2)
3444   {
3445      if (!other_modes.tex_lod_en)
3446      {
3447         tilenum2 = (tilenum + 1) & 7;
3448      }
3449      else
3450      {
3451         tilenum2 = (tilenum + 1) & 7;
3452      }
3453   }
3454
3455   set_shade_for_rects(); // Needed by Pilotwings 64
3456
3457   t = (int)(rect->t) << 5;
3458
3459   if (other_modes.cycle_type == CYCLE_TYPE_1)
3460   {
3461      for (j = y1; j < y2; j++)
3462      {
3463         int fb_index = j * fb_width;
3464
3465         s = (int)(rect->s) << 5;
3466
3467         for (i = x1; i < x2; i++)
3468         {
3469            COLOR c;
3470            curpixel_cvg=8;
3471            ss = s >> 5;
3472            st = t >> 5;
3473            if (rect->flip)
3474            {
3475               TEXTURE_PIPELINE(&texel0_color, st, ss,(rect->dsdx == (1 << 10)) && (rect->dtdy == (1 << 10)), tilenum);
3476            }
3477            else
3478            {
3479               TEXTURE_PIPELINE(&texel0_color, ss, st,(rect->dsdx == (1 << 10)) && (rect->dtdy == (1 << 10)), tilenum);
3480            }
3481
3482            c = COLOR_COMBINER(machine, 0);
3483
3484            BLENDER1_32(machine, &fb[(fb_index + i)], c);
3485
3486            s += rect->dsdx;
3487         }
3488
3489         t += rect->dtdy;
3490      }
3491   }
3492   else if (other_modes.cycle_type == CYCLE_TYPE_2)
3493   {
3494      for (j = y1; j < y2; j++)
3495      {
3496         int fb_index = j * fb_width;
3497
3498         s = (int)(rect->s) << 5;
3499
3500         for (i = x1; i < x2; i++)
3501         {
3502            COLOR c1, c2;
3503            curpixel_cvg=8;
3504            ss = s >> 5;
3505            st = t >> 5;
3506            if (rect->flip)
3507            {
3508               TEXTURE_PIPELINE(&texel0_color, st, ss, (rect->dsdx == (1 << 10)) && (rect->dtdy == (1 << 10)),tilenum);
3509               TEXTURE_PIPELINE(&texel1_color, st, ss, (rect->dsdx == (1 << 10)) && (rect->dtdy == (1 << 10)),tilenum2);
3510            }
3511            else
3512            {
3513               TEXTURE_PIPELINE(&texel0_color, ss, st, (rect->dsdx == (1 << 10)) && (rect->dtdy == (1 << 10)),tilenum);
3514               TEXTURE_PIPELINE(&texel1_color, ss, st, (rect->dsdx == (1 << 10)) && (rect->dtdy == (1 << 10)),tilenum2);
3515            }
3516
3517            c1 = COLOR_COMBINER(machine, 0);
3518            c2 = COLOR_COMBINER(machine, 1);
3519
3520            BLENDER2_32(machine, &fb[(fb_index + i)], c1, c2);
3521
3522            s += rect->dsdx;
3523         }
3524
3525         t += rect->dtdy;
3526      }
3527   }
3528   else if (other_modes.cycle_type == CYCLE_TYPE_COPY)
3529   {
3530      for (j = y1; j < y2; j++)
3531      {
3532         int fb_index = j * fb_width;
3533
3534         s = (int)(rect->s) << 5;
3535
3536         for (i = x1; i < x2; i++)
3537         {
3538            ss = s >> 5;
3539            st = t >> 5;
3540            if (rect->flip)
3541            {
3542               TEXTURE_PIPELINE(&texel0_color, st, ss,(rect->dsdx == (1 << 10)) && (rect->dtdy == (1 << 10)), tilenum);
3543            }
3544            else
3545            {
3546               TEXTURE_PIPELINE(&texel0_color, ss, st,(rect->dsdx == (1 << 10)) && (rect->dtdy == (1 << 10)), tilenum);
3547            }
3548
3549            fb[fb_index + i] = (texel0_color.r << 24) | (texel0_color.g << 16) | (texel0_color.b << 8)|1;
3550
3551            s += rect->dsdx;
3552         }
3553
3554         t += rect->dtdy;
3555      }
3556   }
3557   else
3558   {
3559      fatalerror("texture_rectangle_32bit: unknown cycle type %d\n", other_modes.cycle_type);
3560   }
3561}
3562
3563
3564static void render_spans_32(running_machine *machine, int start, int end, int tilenum, int shade, int texture, int zbuffer, int flip)
3565{
3566   UINT32 *fb = (UINT32*)&rdram[fb_address / 4];
3567   UINT16 *zb = (UINT16*)&rdram[zb_address / 4];
3568   UINT8 *zhb = &hidden_bits[zb_address >> 1];
3569   int i, j;
3570
3571   int clipx1, clipx2, clipy1, clipy2;
3572
3573   UINT32 tilenum2 = 0;
3574
3575   int dr = span[0].dr;
3576   int dg = span[0].dg;
3577   int db = span[0].db;
3578   int da = span[0].da;
3579   int dz = span[0].dz;
3580   int ds = span[0].ds;
3581   int dt = span[0].dt;
3582   int dw = span[0].dw;
3583   int dzpix = span[0].dzpix;
3584   int drinc, dginc, dbinc, dainc, dzinc, dsinc, dtinc, dwinc;
3585   int xinc = flip ? 1 : -1;
3586
3587   calculate_clamp_diffs(tilenum);
3588
3589   clipx1 = clip.xh / 4;
3590   clipx2 = clip.xl / 4;
3591   clipy1 = clip.yh / 4;
3592   clipy2 = clip.yl / 4;
3593
3594
3595   if (other_modes.key_en)
3596   {
3597      stricterror( "render_spans_32: key_en" );
3598   }
3599
3600   if (other_modes.cycle_type == CYCLE_TYPE_2 && texture)
3601   {
3602      if (!other_modes.tex_lod_en)
3603      {
3604         tilenum2 = (tilenum + 1) & 7;
3605      }
3606      else
3607      {
3608         tilenum2 = (tilenum + 1) & 7;
3609      }
3610   }
3611
3612   if (start < clipy1)
3613   {
3614      start = clipy1;
3615   }
3616   if (start >= clipy2)
3617   {
3618      start = clipy2-1;
3619   }
3620   if (end < clipy1)
3621   {
3622      end = clipy1;
3623   }
3624   if (end >= clipy2)
3625   {
3626      end = clipy2-1;
3627   }
3628
3629   drinc = flip ? (dr) : -dr;
3630   dginc = flip ? (dg) : -dg;
3631   dbinc = flip ? (db) : -db;
3632   dainc = flip ? (da) : -da;
3633   dzinc = flip ? (dz) : -dz;
3634   dsinc = flip ? (ds) : -ds;
3635   dtinc = flip ? (dt) : -dt;
3636   dwinc = flip ? (dw) : -dw;
3637
3638   set_shade_for_tris(shade);
3639
3640   for (i = start; i <= end; i++)
3641   {
3642      int xstart = span[i].lx;
3643      int xend = span[i].rx;
3644      int r = span[i].r;
3645      int g = span[i].g;
3646      int b = span[i].b;
3647      int a = span[i].a;
3648      int z = span[i].z;
3649      int s = span[i].s;
3650      int t = span[i].t;
3651      int w = span[i].w;
3652
3653      int x;
3654      int fb_index = fb_width * i;
3655      int length;
3656
3657      x = xend;
3658
3659      length = flip ? (xstart - xend) : (xend - xstart);
3660
3661      for (j=0; j <= length; j++)
3662      {
3663         int sr = r >> 16;
3664         int sg = g >> 16;
3665         int sb = b >> 16;
3666         int sa = a >> 16;
3667         int ss = s >> 16;
3668         int st = t >> 16;
3669         int sw = w >> 16;
3670         UINT32 sz = z >> 13;
3671         int sss = 0, sst = 0;
3672         if (other_modes.z_source_sel)
3673         {
3674            sz = (((UINT32)primitive_z) << 3) & 0x3ffff;
3675            dzpix = primitive_delta_z;
3676         }
3677
3678         if (x >= clipx1 && x < clipx2)
3679         {
3680            curpixel_cvg = span[i].cvg[x];
3681            if (curpixel_cvg > 8)
3682            {
3683               stricterror("render_spans_32: curpixel_cvg = %d", curpixel_cvg);
3684            }
3685            if (curpixel_cvg)
3686            {
3687               COLOR c1, c2;
3688               int curpixel = fb_index + x;
3689               UINT32* fbcur = &fb[curpixel];
3690               UINT16* zbcur = &zb[curpixel ^ WORD_ADDR_XOR];
3691               UINT8* zhbcur = &zhb[curpixel ^ BYTE_ADDR_XOR];
3692               UINT8* hbcur = 0;
3693               int z_compare_result = 1;
3694
3695               c1.r = c1.g = c1.b = c1.a = 0;
3696               c2.r = c2.g = c2.b = c2.a = 0;
3697
3698               if (other_modes.persp_tex_en)
3699               {
3700                  tcdiv(ss, st, sw, &sss, &sst);
3701               }
3702               else
3703               {
3704                  sss = ss;
3705                  sst = st;
3706               }
3707
3708               if (shade)
3709               {
3710                  // Needed by Superman
3711                  if (sr > 0xff) sr = 0xff;
3712                  if (sg > 0xff) sg = 0xff;
3713                  if (sb > 0xff) sb = 0xff;
3714                  if (sa > 0xff) sa = 0xff;
3715                  if (sr < 0) sr = 0;
3716                  if (sg < 0) sg = 0;
3717                  if (sb < 0) sb = 0;
3718                  if (sa < 0) sa = 0;
3719                  shade_color.r = sr;
3720                  shade_color.g = sg;
3721                  shade_color.b = sb;
3722                  shade_color.a = sa;
3723               }
3724
3725               if (texture)
3726               {
3727                  if (other_modes.cycle_type == CYCLE_TYPE_1)
3728                  {
3729                     TEXTURE_PIPELINE(&texel0_color, sss, sst, 0, tilenum);
3730                  }
3731                  else
3732                  {
3733                     TEXTURE_PIPELINE(&texel0_color, sss, sst, 0, tilenum);
3734                     TEXTURE_PIPELINE(&texel1_color, sss, sst, 0, tilenum2);
3735                  }
3736               }
3737
3738               if (other_modes.cycle_type == CYCLE_TYPE_1)
3739               {
3740                  c1 = COLOR_COMBINER(machine, 0);
3741               }
3742               else if (other_modes.cycle_type == CYCLE_TYPE_2)
3743               {
3744                  c1 = COLOR_COMBINER(machine, 0);
3745                  c2 = COLOR_COMBINER(machine, 1);
3746                 }
3747
3748               if ((zbuffer || other_modes.z_source_sel) && other_modes.z_compare_en)
3749               {
3750                  z_compare_result = z_compare(fbcur, hbcur, zbcur, zhbcur, sz, dzpix);
3751               }
3752
3753               if(z_compare_result)
3754               {
3755                  int rendered = 0;
3756
3757                  if (other_modes.cycle_type == CYCLE_TYPE_1)
3758                  {
3759                     rendered = BLENDER1_32(machine, fbcur, c1);
3760                  }
3761                      else
3762                      {
3763                     rendered = BLENDER2_32(machine, fbcur, c1, c2);
3764                  }
3765
3766                  if (other_modes.z_update_en && rendered)
3767                  {
3768                     z_store(zbcur, zhbcur, sz, dzpix);
3769                  }
3770               }
3771            }
3772         }
3773
3774         r += drinc;
3775         g += dginc;
3776         b += dbinc;
3777         a += dainc;
3778         z += dzinc;
3779         s += dsinc;
3780         t += dtinc;
3781         w += dwinc;
3782
3783         x += xinc;
3784      }
3785   }
3786}
3787
3788/*****************************************************************************/
3789
3790static void render_spans_16(running_machine *machine, int start, int end, int tilenum, int shade, int texture, int zbuffer, int flip)
3791{
3792   UINT16 *fb = (UINT16*)&rdram[fb_address / 4];
3793   UINT16 *zb = (UINT16*)&rdram[zb_address / 4];
3794   UINT8 *hb = &hidden_bits[fb_address >> 1];
3795   UINT8 *zhb = &hidden_bits[zb_address >> 1];
3796
3797   int i, j;
3798
3799   int clipx1, clipx2, clipy1, clipy2;
3800
3801   UINT32 prim_tile = tilenum;
3802   UINT32 tilenum2 = 0;
3803   UINT32 disable_lod = 0;
3804
3805   int LOD = 0;
3806   INT32 horstep, vertstep;
3807   INT32 l_tile;
3808   UINT32 magnify = 0;
3809   UINT32 distant = 0;
3810
3811   int dr = span[0].dr;
3812   int dg = span[0].dg;
3813   int db = span[0].db;
3814   int da = span[0].da;
3815   int dz = span[0].dz;
3816   int ds = span[0].ds;
3817   int dt = span[0].dt;
3818   int dw = span[0].dw;
3819   int dzpix = span[0].dzpix;
3820   int drinc, dginc, dbinc, dainc, dzinc, dsinc, dtinc, dwinc;
3821   int xinc = flip ? 1 : -1;
3822
3823   int nexts, nextt, nextsw;
3824   int lodclamp = 0;
3825
3826   calculate_clamp_diffs(tilenum);
3827
3828   clipx1 = clip.xh / 4;
3829   clipx2 = clip.xl / 4;
3830   clipy1 = clip.yh / 4;
3831   clipy2 = clip.yl / 4;
3832
3833   if (other_modes.cycle_type == CYCLE_TYPE_2 && texture && !other_modes.tex_lod_en)
3834   {
3835      tilenum2 = (prim_tile + 1) & 7;
3836   }
3837   if (texture && !other_modes.tex_lod_en)
3838   {
3839      tilenum = prim_tile;
3840   }
3841
3842
3843   if (other_modes.tex_lod_en && other_modes.cycle_type != CYCLE_TYPE_2) // Used by World Driver Championship
3844   {
3845      disable_lod = 1;
3846   }
3847
3848   drinc = flip ? (dr) : -dr;
3849   dginc = flip ? (dg) : -dg;
3850   dbinc = flip ? (db) : -db;
3851   dainc = flip ? (da) : -da;
3852   dzinc = flip ? (dz) : -dz;
3853   dsinc = flip ? (ds) : -ds;
3854   dtinc = flip ? (dt) : -dt;
3855   dwinc = flip ? (dw) : -dw;
3856
3857   if (start < clipy1)
3858   {
3859      start = clipy1;
3860   }
3861   if (start >= clipy2)
3862   {
3863      start = clipy2 - 1;
3864   }
3865   if (end < clipy1)
3866   {
3867      end = clipy1;
3868   }
3869   if (end >= clipy2) // Needed by 40 Winks
3870   {
3871      end = clipy2 - 1;
3872   }
3873
3874   set_shade_for_tris(shade); // Needed by backgrounds in Top Gear Rally 1
3875
3876   for (i = start; i <= end; i++)
3877   {
3878      int xstart = span[i].lx;
3879      int xend = span[i].rx;
3880      int r = 0, g = 0, b = 0, a = 0;
3881      int z = span[i].z;
3882      int s = span[i].s;
3883      int t = span[i].t;
3884      int w = span[i].w;
3885
3886      int x;
3887
3888      int fb_index = fb_width * i;
3889      int length;
3890
3891      if (shade)
3892      {
3893         r = span[i].r;
3894         g = span[i].g;
3895         b = span[i].b;
3896         a = span[i].a;
3897      }
3898
3899      x = xend;
3900
3901      length = flip ? (xstart - xend) : (xend - xstart); //Moogly
3902
3903      for (j = 0; j <= length; j++)
3904      {
3905         int sr = 0, sg = 0, sb = 0, sa = 0;
3906         int ss = s >> 16;
3907         int st = t >> 16;
3908         int sw = w >> 16;
3909         int sz = z >> 13;
3910         int sss = 0, sst = 0;
3911         COLOR c1, c2;
3912         if (shade)
3913         {
3914            sr = r >> 16;
3915            sg = g >> 16;
3916            sb = b >> 16;
3917            sa = a >> 16;
3918         }
3919         c1.r = c1.g = c1.b = c1.a = 0;
3920         c2.r = c2.g = c2.b = c2.a = 0;
3921         if (other_modes.z_source_sel)
3922         {
3923            sz = (((UINT32)primitive_z) << 3) & 0x3ffff;
3924            dzpix = primitive_delta_z;
3925         }
3926
3927
3928         if (x >= clipx1 && x < clipx2)
3929         {
3930            int z_compare_result = 1;
3931
3932            curpixel_cvg=span[i].cvg[x];
3933
3934            if (curpixel_cvg > 8)
3935            {
3936               stricterror("render_spans_16: cvg of current pixel is %d", curpixel_cvg);
3937            }
3938
3939            if (curpixel_cvg)
3940            {
3941               int curpixel = fb_index + x;
3942               UINT16* fbcur = &fb[curpixel ^ WORD_ADDR_XOR];
3943               UINT16* zbcur = &zb[curpixel ^ WORD_ADDR_XOR];
3944               UINT8* hbcur = &hb[curpixel ^ BYTE_ADDR_XOR];
3945               UINT8* zhbcur = &zhb[curpixel ^ BYTE_ADDR_XOR];
3946
3947               if (other_modes.persp_tex_en)
3948               {
3949                  tcdiv(ss, st, sw, &sss, &sst);
3950               }
3951               else // Hack for Bust-a-Move 2
3952               {
3953                  sss = ss;
3954                  sst = st;
3955               }
3956
3957               if (other_modes.tex_lod_en && !disable_lod)
3958               {
3959                  if (other_modes.persp_tex_en)
3960                  {
3961                     nextsw = (w + dwinc) >> 16;
3962                     nexts = (s + dsinc) >> 16;
3963                     nextt = (t + dtinc) >> 16;
3964                     tcdiv(nexts, nextt, nextsw, &nexts, &nextt);
3965                  }
3966                  else
3967                  {
3968                     nexts = (s + dsinc)>>16;
3969                     nextt = (t + dtinc)>>16;
3970                  }
3971
3972                  lodclamp = 0;
3973
3974                  horstep = SIGN17(nexts & 0x1ffff) - SIGN17(sss & 0x1ffff);
3975                  vertstep = SIGN17(nextt & 0x1ffff) - SIGN17(sst & 0x1ffff);
3976                  if (horstep & 0x20000)
3977                  {
3978                     horstep = ~horstep & 0x1ffff;
3979                  }
3980                  if (vertstep & 0x20000)
3981                  {
3982                     vertstep = ~vertstep & 0x1ffff;
3983                  }
3984                  LOD = ((horstep >= vertstep) ? horstep : vertstep);
3985                  LOD = (LOD >= span[0].dymax) ? LOD : span[0].dymax;
3986
3987                  if ((LOD & 0x1c000) || lodclamp)
3988                  {
3989                     LOD = 0x7fff;
3990                  }
3991                  if (LOD < min_level)
3992                  {
3993                     LOD = min_level;
3994                  }
3995
3996                  magnify = (LOD < 32) ? 1: 0;
3997                  l_tile = getlog2((LOD >> 5) & 0xff);
3998                  distant = ((LOD & 0x6000) || (l_tile >= max_level)) ? 1 : 0;
3999
4000                  lod_frac = ((LOD << 3) >> l_tile) & 0xff;
4001
4002                  if (distant)
4003                  {
4004                     l_tile = max_level;
4005                  }
4006                  if(!other_modes.sharpen_tex_en && !other_modes.detail_tex_en && magnify)
4007                  {
4008                     lod_frac = 0;
4009                  }
4010                  if(!other_modes.sharpen_tex_en && !other_modes.detail_tex_en && distant)
4011                  {
4012                     lod_frac = 0xff;
4013                  }
4014                  if(other_modes.sharpen_tex_en && magnify)
4015                  {
4016                     lod_frac |= 0x100;
4017                  }
4018
4019                  if (!other_modes.detail_tex_en)
4020                  {
4021                     tilenum = (prim_tile + l_tile);
4022                     tilenum &= 7;
4023                     if (other_modes.sharpen_tex_en)
4024                     {
4025                        tilenum2 = (tilenum + 1) & 7;
4026                     }
4027                     else if (!distant)
4028                     {
4029                        tilenum2 = (tilenum + 1) & 7;
4030                     }
4031                     else
4032                     {
4033                        tilenum2 = tilenum;
4034                     }
4035                  }
4036                  else
4037                  {
4038                     if (!magnify)
4039                     {
4040                        tilenum = (prim_tile + l_tile + 1);
4041                     }
4042                     else
4043                     {
4044                        tilenum = (prim_tile + l_tile);
4045                     }
4046                     tilenum &= 7;
4047
4048                     if (!distant && !magnify)
4049                     {
4050                        tilenum2 = (prim_tile + l_tile + 2) & 7;
4051                     }
4052                     else
4053                     {
4054                        tilenum2 = (prim_tile + l_tile + 1) & 7;
4055                     }
4056                  }
4057               }
4058
4059               if (shade)
4060               {
4061                  if (sr > 0xff) sr = 0xff;
4062                  if (sg > 0xff) sg = 0xff;
4063                  if (sb > 0xff) sb = 0xff;
4064                  if (sa > 0xff) sa = 0xff;
4065                  if (sr < 0) sr = 0;
4066                  if (sg < 0) sg = 0;
4067                  if (sb < 0) sb = 0;
4068                  if (sa < 0) sa = 0;
4069                  shade_color.r = sr;
4070                  shade_color.g = sg;
4071                  shade_color.b = sb;
4072                  shade_color.a = sa;
4073               }
4074
4075               if (texture)
4076               {
4077                  if (other_modes.cycle_type == CYCLE_TYPE_1)
4078                  {
4079                     TEXTURE_PIPELINE(&texel0_color, sss, sst, 0, tilenum);
4080                  }
4081                  else
4082                  {
4083                     TEXTURE_PIPELINE(&texel0_color, sss, sst, 0, tilenum);
4084                     TEXTURE_PIPELINE(&texel1_color, sss, sst, 0, tilenum2);
4085                  }
4086               }
4087
4088               if (other_modes.cycle_type == CYCLE_TYPE_1)
4089               {
4090                  c1 = COLOR_COMBINER(machine, 0);
4091               }
4092               else if (other_modes.cycle_type == CYCLE_TYPE_2)
4093               {
4094                  c1 = COLOR_COMBINER(machine, 0);
4095                  c2 = COLOR_COMBINER(machine, 1);
4096               }
4097
4098               if ((zbuffer || other_modes.z_source_sel) && other_modes.z_compare_en)
4099               {
4100                  z_compare_result = z_compare(fbcur, hbcur, zbcur, zhbcur, sz, dzpix);
4101               }
4102
4103               if(z_compare_result)
4104               {
4105                  int rendered = 0;
4106                  int dith = 0;
4107                  if (!other_modes.rgb_dither_sel)
4108                  {
4109                     dith = magic_matrix[(((i) & 3) << 2) + ((x ^ WORD_ADDR_XOR) & 3)];
4110                  }
4111                  else if (other_modes.rgb_dither_sel == 1)
4112                  {
4113                     dith = bayer_matrix[(((i) & 3) << 2) + ((x ^ WORD_ADDR_XOR) & 3)];
4114                  }
4115
4116                       if (other_modes.cycle_type == CYCLE_TYPE_1)
4117                       {
4118                     rendered = BLENDER1_16(machine, fbcur, hbcur, c1, dith);
4119                  }
4120                  else
4121                  {
4122                     rendered = BLENDER2_16(machine, fbcur, hbcur, c1, c2, dith);
4123                  }
4124
4125                  if (other_modes.z_update_en && rendered)
4126                  {
4127                     z_store(zbcur, zhbcur, sz, dzpix);
4128                  }
4129               }
4130            }
4131         }
4132
4133         if (shade)
4134         {
4135            r += drinc;
4136            g += dginc;
4137            b += dbinc;
4138            a += dainc;
4139         }
4140         z += dzinc;
4141         s += dsinc;
4142         t += dtinc;
4143         w += dwinc;
4144
4145         x += xinc;
4146      }
4147   }
4148}
4149
4150static void triangle(running_machine *machine, UINT32 w1, UINT32 w2, int shade, int texture, int zbuffer)
4151{
4152   int j;
4153   int xleft, xright, xleft_inc, xright_inc;
4154   int xstart, xend;
4155   int r = 0, g = 0, b = 0, a = 0, z = 0, s = 0, t = 0, w = 0;
4156   int dr, dg, db, da;
4157   int drdx = 0, dgdx = 0, dbdx = 0, dadx = 0, dzdx = 0, dsdx = 0, dtdx = 0, dwdx = 0;
4158   int drdy = 0, dgdy = 0, dbdy = 0, dady = 0, dzdy = 0, dsdy = 0, dtdy = 0, dwdy = 0;
4159   int drde = 0, dgde = 0, dbde = 0, dade = 0, dzde = 0, dsde = 0, dtde = 0, dwde = 0;
4160   int tilenum;
4161   int flip = (w1 & 0x800000) ? 1 : 0;
4162
4163   INT32 yl, ym, yh;
4164   INT32 xl, xm, xh;
4165   INT32 dxldy, dxhdy, dxmdy;
4166   int dzdy_dz, dzdx_dz;
4167   int dsdylod, dtdylod;
4168   UINT32 w3, w4, w5, w6, w7, w8;
4169
4170   int k = 0;
4171
4172   INT32 limcvg = 0;
4173   INT32 startcvg = 0;
4174
4175   int sign_dxldy = 0;
4176   int sign_dxmdy = 0;
4177   int samesign = 0;
4178
4179   int dsdiff = 0, dtdiff = 0, dwdiff = 0, drdiff = 0, dgdiff = 0, dbdiff = 0, dadiff = 0, dzdiff = 0;
4180   int sign_dxhdy = 0;
4181
4182   int dsdeh = 0, dtdeh = 0, dwdeh = 0, drdeh = 0, dgdeh = 0, dbdeh = 0, dadeh = 0, dzdeh = 0, dsdyh = 0, dtdyh = 0, dwdyh = 0, drdyh = 0, dgdyh = 0, dbdyh = 0, dadyh = 0, dzdyh = 0;
4183   int do_offset = 0;
4184
4185   int xfrac = 0;
4186   int dseoff = 0, dteoff = 0, dweoff = 0, dreoff = 0, dgeoff = 0, dbeoff = 0, daeoff = 0, dzeoff = 0;
4187
4188   int dsdxh = 0, dtdxh = 0, dwdxh = 0, drdxh = 0, dgdxh = 0, dbdxh = 0, dadxh = 0, dzdxh = 0;
4189
4190   int m_inc;
4191   UINT32 min=0, max=3;
4192   INT32 maxxmx = 0, minxmx = 0, maxxhx = 0, minxhx = 0;
4193
4194   int spix = 0; // Current subpixel
4195   int ycur;
4196   int ylfar;
4197   int ldflag;
4198   int yhpix;
4199   int ympix;
4200   int ylpix;
4201
4202   int shade_base = rdp_cmd_cur + 8;
4203   int texture_base = rdp_cmd_cur + 8;
4204   int zbuffer_base = rdp_cmd_cur + 8;
4205
4206   if (shade)
4207   {
4208      texture_base += 16;
4209      zbuffer_base += 16;
4210   }
4211   if (texture)
4212   {
4213      zbuffer_base += 16;
4214   }
4215
4216   w3 = rdp_cmd_data[rdp_cmd_cur+2];
4217   w4 = rdp_cmd_data[rdp_cmd_cur+3];
4218   w5 = rdp_cmd_data[rdp_cmd_cur+4];
4219   w6 = rdp_cmd_data[rdp_cmd_cur+5];
4220   w7 = rdp_cmd_data[rdp_cmd_cur+6];
4221   w8 = rdp_cmd_data[rdp_cmd_cur+7];
4222
4223   yl = (w1 & 0x3fff);
4224   ym = ((w2 >> 16) & 0x3fff);
4225   yh = ((w2 >>  0) & 0x3fff);
4226   xl = (INT32)(w3 & 0x3fffffff);
4227   xh = (INT32)(w5 & 0x3fffffff);
4228   xm = (INT32)(w7 & 0x3fffffff);
4229   // Inverse slopes in 16.16 format
4230   dxldy = (INT32)(w4);
4231   dxhdy = (INT32)(w6);
4232   dxmdy = (INT32)(w8);
4233
4234   max_level = ((w1 >> 19) & 7);
4235   tilenum = (w1 >> 16) & 0x7;
4236
4237   if (yl & 0x2000)  yl |= 0xffffc000;
4238   if (ym & 0x2000)  ym |= 0xffffc000;
4239   if (yh & 0x2000)  yh |= 0xffffc000;
4240
4241   if ((xl >> 16) & 0x2000)  xl |= 0xc0000000;
4242   if ((xm >> 16) & 0x2000)  xm |= 0xc0000000;
4243   if ((xh >> 16) & 0x2000)  xh |= 0xc0000000;
4244
4245   z = 0;
4246   s = 0;   t = 0;   w = 0;
4247   dr = 0;      dg = 0;      db = 0;      da = 0;
4248
4249   if (shade)
4250   {
4251      r    = (rdp_cmd_data[shade_base+0 ] & 0xffff0000) | ((rdp_cmd_data[shade_base+4 ] >> 16) & 0x0000ffff);
4252      g    = ((rdp_cmd_data[shade_base+0 ] << 16) & 0xffff0000) | (rdp_cmd_data[shade_base+4 ] & 0x0000ffff);
4253      b    = (rdp_cmd_data[shade_base+1 ] & 0xffff0000) | ((rdp_cmd_data[shade_base+5 ] >> 16) & 0x0000ffff);
4254      a    = ((rdp_cmd_data[shade_base+1 ] << 16) & 0xffff0000) | (rdp_cmd_data[shade_base+5 ] & 0x0000ffff);
4255      drdx = (rdp_cmd_data[shade_base+2 ] & 0xffff0000) | ((rdp_cmd_data[shade_base+6 ] >> 16) & 0x0000ffff);
4256      dgdx = ((rdp_cmd_data[shade_base+2 ] << 16) & 0xffff0000) | (rdp_cmd_data[shade_base+6 ] & 0x0000ffff);
4257      dbdx = (rdp_cmd_data[shade_base+3 ] & 0xffff0000) | ((rdp_cmd_data[shade_base+7 ] >> 16) & 0x0000ffff);
4258      dadx = ((rdp_cmd_data[shade_base+3 ] << 16) & 0xffff0000) | (rdp_cmd_data[shade_base+7 ] & 0x0000ffff);
4259      drde = (rdp_cmd_data[shade_base+8 ] & 0xffff0000) | ((rdp_cmd_data[shade_base+12] >> 16) & 0x0000ffff);
4260      dgde = ((rdp_cmd_data[shade_base+8 ] << 16) & 0xffff0000) | (rdp_cmd_data[shade_base+12] & 0x0000ffff);
4261      dbde = (rdp_cmd_data[shade_base+9 ] & 0xffff0000) | ((rdp_cmd_data[shade_base+13] >> 16) & 0x0000ffff);
4262      dade = ((rdp_cmd_data[shade_base+9 ] << 16) & 0xffff0000) | (rdp_cmd_data[shade_base+13] & 0x0000ffff);
4263      drdy = (rdp_cmd_data[shade_base+10] & 0xffff0000) | ((rdp_cmd_data[shade_base+14] >> 16) & 0x0000ffff);
4264      dgdy = ((rdp_cmd_data[shade_base+10] << 16) & 0xffff0000) | (rdp_cmd_data[shade_base+14] & 0x0000ffff);
4265      dbdy = (rdp_cmd_data[shade_base+11] & 0xffff0000) | ((rdp_cmd_data[shade_base+15] >> 16) & 0x0000ffff);
4266      dady = ((rdp_cmd_data[shade_base+11] << 16) & 0xffff0000) | (rdp_cmd_data[shade_base+15] & 0x0000ffff);
4267   }
4268   if (texture)
4269   {
4270      s    = (rdp_cmd_data[texture_base+0 ] & 0xffff0000) | ((rdp_cmd_data[texture_base+4 ] >> 16) & 0x0000ffff);
4271      t    = ((rdp_cmd_data[texture_base+0 ] << 16) & 0xffff0000)   | (rdp_cmd_data[texture_base+4 ] & 0x0000ffff);
4272      w    = (rdp_cmd_data[texture_base+1 ] & 0xffff0000) | ((rdp_cmd_data[texture_base+5 ] >> 16) & 0x0000ffff);
4273      dsdx = (rdp_cmd_data[texture_base+2 ] & 0xffff0000) | ((rdp_cmd_data[texture_base+6 ] >> 16) & 0x0000ffff);
4274      dtdx = ((rdp_cmd_data[texture_base+2 ] << 16) & 0xffff0000)   | (rdp_cmd_data[texture_base+6 ] & 0x0000ffff);
4275      dwdx = (rdp_cmd_data[texture_base+3 ] & 0xffff0000) | ((rdp_cmd_data[texture_base+7 ] >> 16) & 0x0000ffff);
4276      dsde = (rdp_cmd_data[texture_base+8 ] & 0xffff0000) | ((rdp_cmd_data[texture_base+12] >> 16) & 0x0000ffff);
4277      dtde = ((rdp_cmd_data[texture_base+8 ] << 16) & 0xffff0000)   | (rdp_cmd_data[texture_base+12] & 0x0000ffff);
4278      dwde = (rdp_cmd_data[texture_base+9 ] & 0xffff0000) | ((rdp_cmd_data[texture_base+13] >> 16) & 0x0000ffff);
4279      dsdy = (rdp_cmd_data[texture_base+10] & 0xffff0000) | ((rdp_cmd_data[texture_base+14] >> 16) & 0x0000ffff);
4280      dtdy = ((rdp_cmd_data[texture_base+10] << 16) & 0xffff0000)   | (rdp_cmd_data[texture_base+14] & 0x0000ffff);
4281      dwdy = (rdp_cmd_data[texture_base+11] & 0xffff0000) | ((rdp_cmd_data[texture_base+15] >> 16) & 0x0000ffff);
4282   }
4283   if (zbuffer)
4284   {
4285      z    = rdp_cmd_data[zbuffer_base+0];
4286      dzdx = rdp_cmd_data[zbuffer_base+1];
4287      dzde = rdp_cmd_data[zbuffer_base+2];
4288      dzdy = rdp_cmd_data[zbuffer_base+3];
4289   }
4290
4291   span[0].ds = dsdx;
4292   span[0].dt = dtdx;
4293   span[0].dw = dwdx;
4294   span[0].dr = drdx & ~0x1f;
4295   span[0].dg = dgdx & ~0x1f;
4296   span[0].db = dbdx & ~0x1f;
4297   span[0].da = dadx & ~0x1f;
4298   span[0].dz = dzdx;
4299   dzdy_dz = (dzdy >> 16) & 0xffff;
4300   dzdx_dz = (dzdx >> 16) & 0xffff;
4301   span[0].dzpix = ((dzdy_dz & 0x8000) ? ((~dzdy_dz) & 0x7fff) : dzdy_dz) + ((dzdx_dz & 0x8000) ? ((~dzdx_dz) & 0x7fff) : dzdx_dz);
4302   span[0].dzpix = normalize_dzpix(span[0].dzpix);
4303   dsdylod = dsdy >> 16;
4304   dtdylod = dtdy >> 16;
4305   if (dsdylod & 0x20000)
4306   {
4307      dsdylod = ~dsdylod & 0x1ffff;
4308   }
4309   if (dtdylod & 0x20000)
4310   {
4311      dtdylod = ~dtdylod & 0x1ffff;
4312   }
4313   span[0].dymax = (dsdylod > dtdylod)? dsdylod : dtdylod;
4314
4315   xleft_inc = dxmdy >> 2;
4316   xright_inc = dxhdy >> 2;
4317
4318   xright = xh;
4319   xleft = xm;
4320
4321   limcvg = ((yl>>2) <= 1023) ? (yl>>2) : 1023; // Needed by 40 Winks
4322   if (limcvg < 0)
4323   {
4324      limcvg = 0;
4325   }
4326
4327   startcvg = ((yh>>2)>=0) ? (yh>>2) : 0;
4328   for (k = startcvg; k <= limcvg; k++)
4329   {
4330      memset((void*)&span[k].cvg[0],0,640);
4331   }
4332
4333   sign_dxldy = (dxldy & 0x80000000) ? 1 : 0;
4334   sign_dxmdy = (dxmdy & 0x80000000) ? 1 : 0;
4335   samesign = !(sign_dxldy ^ sign_dxmdy);
4336
4337   sign_dxhdy = (dxhdy & 0x80000000) ? 1 : 0;
4338
4339   do_offset = !(sign_dxhdy ^ (flip));
4340
4341   if (do_offset)
4342   {
4343      dsdeh = dsde >> 9;   dsdyh = dsdy >> 9;
4344      dtdeh = dtde >> 9;   dtdyh = dtdy >> 9;
4345      dwdeh = dwde >> 9;   dwdyh = dwdy >> 9;
4346      drdeh = drde >> 9;   drdyh = drdy >> 9;
4347      dgdeh = dgde >> 9;   dgdyh = dgdy >> 9;
4348      dbdeh = dbde >> 9;   dbdyh = dbdy >> 9;
4349      dadeh = dade >> 9;   dadyh = dady >> 9;
4350      dzdeh = dzde >> 9;   dzdyh = dzdy >> 9;
4351
4352      dsdiff = (dsdeh*3 - dsdyh*3) << 7;
4353      dtdiff = (dtdeh*3 - dtdyh*3) << 7;
4354      dwdiff = (dwdeh*3 - dwdyh*3) << 7;
4355      drdiff = (drdeh*3 - drdyh*3) << 7;
4356      dgdiff = (dgdeh*3 - dgdyh*3) << 7;
4357      dbdiff = (dbdeh*3 - dbdyh*3) << 7;
4358      dadiff = (dadeh*3 - dadyh*3) << 7;
4359      dzdiff = (dzdeh*3 - dzdyh*3) << 7;
4360   }
4361   else
4362   {
4363      dsdiff = dtdiff = dwdiff = drdiff = dgdiff = dbdiff = dadiff = dzdiff = 0;
4364   }
4365
4366   if (do_offset)
4367   {
4368      dseoff = (dsdeh*3) << 7;
4369      dteoff = (dtdeh*3) << 7;
4370      dweoff = (dwdeh*3) << 7;
4371      dreoff = (drdeh*3) << 7;
4372      dgeoff = (dgdeh*3) << 7;
4373      dbeoff = (dbdeh*3) << 7;
4374      daeoff = (dadeh*3) << 7;
4375      dzeoff = (dzdeh*3) << 7;
4376   }
4377   else
4378   {
4379      dseoff = dteoff = dweoff = dreoff = dgeoff = dbeoff = daeoff = dzeoff = 0;
4380   }
4381#define adjust_deoff_only()      \
4382{                     \
4383         span[j].s = s + dseoff;            \
4384         span[j].t = t + dteoff;            \
4385         span[j].w = w + dweoff;            \
4386         span[j].r = r + dreoff;            \
4387         span[j].g = g + dgeoff;            \
4388         span[j].b = b + dbeoff;            \
4389         span[j].a = a + daeoff;            \
4390         span[j].z = z + dzeoff;            \
4391}
4392
4393#define addleft(x) addleftcvg(x,k)
4394#define addright(x) addrightcvg(x,k)
4395#define setvalues() {               \
4396         addvalues();            \
4397         adjust_attr();   \
4398}
4399
4400   dsdxh = dsdx >> 8;
4401   dtdxh = dtdx >> 8;
4402   dwdxh = dwdx >> 8;
4403   drdxh = drdx >> 8;
4404   dgdxh = dgdx >> 8;
4405   dbdxh = dbdx >> 8;
4406   dadxh = dadx >> 8;
4407   dzdxh = dzdx >> 8;
4408
4409#define adjust_attr()      \
4410{                     \
4411         span[j].s = (s + dsdiff - (xfrac * dsdxh)) & ~0x1f;            \
4412         span[j].t = (t + dtdiff - (xfrac * dtdxh)) & ~0x1f;            \
4413         span[j].w = (w + dwdiff - (xfrac * dwdxh)) & ~0x1f;            \
4414         span[j].r = r + drdiff - (xfrac * drdxh);            \
4415         span[j].g = g + dgdiff - (xfrac * dgdxh);            \
4416         span[j].b = b + dbdiff - (xfrac * dbdxh);            \
4417         span[j].a = a + dadiff - (xfrac * dadxh);            \
4418         span[j].z = z + dzdiff - (xfrac * dzdxh);            \
4419}
4420
4421#define adjust_diffonly()      \
4422{                     \
4423         span[j].s = s + dsdiff;            \
4424         span[j].t = t + dtdiff;            \
4425         span[j].w = w + dwdiff;            \
4426         span[j].r = r + drdiff;            \
4427         span[j].g = g + dgdiff;            \
4428         span[j].b = b + dbdiff;            \
4429         span[j].a = a + dadiff;            \
4430         span[j].z = z + dzdiff;            \
4431}
4432
4433#define addvalues() {   \
4434         s += dsde;   \
4435         t += dtde;   \
4436         w += dwde; \
4437         r += drde; \
4438         g += dgde; \
4439         b += dbde; \
4440         a += dade; \
4441         z += dzde; \
4442}
4443
4444#define justassign()      \
4445{                     \
4446         span[j].s = s & ~0x1f;            \
4447         span[j].t = t & ~0x1f;            \
4448         span[j].w = w & ~0x1f;            \
4449         span[j].r = r;            \
4450         span[j].g = g;            \
4451         span[j].b = b;            \
4452         span[j].a = a;            \
4453         span[j].z = z;            \
4454}
4455
4456   m_inc = flip ? 1 : -1;
4457
4458   ycur =   yh & ~3;
4459   ylfar = yl | 3;
4460   ldflag = (sign_dxhdy ^ flip) ? 0 : 3;
4461   yhpix = yh >> 2;
4462   ympix = ym >> 2;
4463   ylpix = yl >> 2;
4464
4465   for (k = ycur; k <= ylfar; k++)
4466   {
4467      if (k == ym)
4468      {
4469         xleft = xl;
4470         xleft_inc = dxldy >> 2;
4471      }
4472
4473      xstart = xleft >> 16;
4474      xend = xright >> 16;
4475      j = k >> 2;
4476      spix = k & 3;
4477
4478      if (k >= 0 && k < 0x1000)
4479      {
4480         int m = 0;
4481         int n = 0;
4482         int length = 0;
4483         min = 0; max = 3;
4484         if (j == yhpix)
4485         {
4486            min = yh & 3;
4487         }
4488         if (j == ylpix)
4489         {
4490            max = yl & 3;
4491         }
4492         if (spix >= min && spix <= max)
4493         {
4494            if (spix == min)
4495            {
4496               minxmx = maxxmx = xstart;
4497               minxhx = maxxhx = xend;
4498            }
4499            else
4500            {
4501               minxmx = (xstart < minxmx) ? xstart : minxmx;
4502               maxxmx = (xstart > maxxmx) ? xstart : maxxmx;
4503               minxhx = (xend < minxhx) ? xend : minxhx;
4504               maxxhx = (xend > maxxhx) ? xend : maxxhx;
4505            }
4506         }
4507
4508         if (spix == max)
4509         {
4510            if (flip)
4511            {
4512               span[j].lx = maxxmx;
4513               span[j].rx = minxhx;
4514            }
4515            else
4516            {
4517               span[j].lx = minxmx;
4518               span[j].rx = maxxhx;
4519            }
4520         }
4521
4522         length = flip ? (xstart - xend) : (xend - xstart);
4523
4524         if (spix == ldflag)
4525         {
4526            xfrac = ((xright >> 8) & 0xff);
4527            adjust_attr();
4528         }
4529
4530         m = flip ? (xend+1) : (xend-1);
4531
4532         if (k >= yh && length >= 0 && k <= yl)
4533         {
4534            if (xstart>=0 && xstart <1024)
4535            {
4536               if (!flip)
4537               {
4538                  span[j].cvg[xstart] += addleft(xleft);
4539               }
4540               else
4541               {
4542                  span[j].cvg[xstart] += addright(xleft);
4543               }
4544            }
4545            if (xend>=0 && xend<1024)
4546            {
4547               if (xstart != xend)
4548               {
4549                  if (!flip)
4550                  {
4551                     span[j].cvg[xend] += addright(xright);
4552                  }
4553                  else
4554                  {
4555                     span[j].cvg[xend] += addleft(xright);
4556                  }
4557               }
4558               else
4559               {
4560                  if (!flip)
4561                  {
4562                     span[j].cvg[xend] -= (2 - addright(xright));
4563                  }
4564                  else
4565                  {
4566                     span[j].cvg[xend] -= (2 - addleft(xright));
4567                  }
4568                  if (span[j].cvg[xend] > 200)
4569                  {
4570                     span[j].cvg[xend] = 0;
4571                  }
4572               }
4573            }
4574            for (n = 0; n < (length - 1); n++)
4575            {
4576               if (m>=0 && m < 640)
4577               {
4578                  span[j].cvg[m] += 2;
4579               }
4580
4581               m += m_inc;
4582            }
4583         }
4584      }
4585
4586      if (spix == 3)
4587      {
4588         addvalues();
4589      }
4590      xleft += xleft_inc;
4591      xright += xright_inc;
4592   }
4593
4594   switch (fb_size) // 8bpp needs to be implemented
4595   {
4596      case PIXEL_SIZE_16BIT:   render_spans_16(machine, yh>>2, yl>>2, tilenum, shade, texture, zbuffer, flip); break;
4597      case PIXEL_SIZE_32BIT:   render_spans_32(machine, yh>>2, yl>>2, tilenum, shade, texture, zbuffer, flip); break;
4598      default: break; // V-Rally2 does this, fb_size=0
4599   }
4600}
4601
4602/*****************************************************************************/
4603
4604INLINE UINT32 READ_RDP_DATA(UINT32 address)
4605{
4606   if (dp_status & 0x1)      // XBUS_DMEM_DMA enabled
4607   {
4608      return rsp_dmem[(address & 0xfff) / 4];
4609   }
4610   else
4611   {
4612      return rdram[((address & 0xffffff) / 4)];
4613   }
4614}
4615
4616static const char *const image_format[] = { "RGBA", "YUV", "CI", "IA", "I", "???", "???", "???" };
4617static const char *const image_size[] = { "4-bit", "8-bit", "16-bit", "32-bit" };
4618
4619static const int rdp_command_length[64] =
4620{
4621   8,         // 0x00, No Op
4622   8,         // 0x01, ???
4623   8,         // 0x02, ???
4624   8,         // 0x03, ???
4625   8,         // 0x04, ???
4626   8,         // 0x05, ???
4627   8,         // 0x06, ???
4628   8,         // 0x07, ???
4629   32,         // 0x08, Non-Shaded Triangle
4630   32+16,      // 0x09, Non-Shaded, Z-Buffered Triangle
4631   32+64,      // 0x0a, Textured Triangle
4632   32+64+16,   // 0x0b, Textured, Z-Buffered Triangle
4633   32+64,      // 0x0c, Shaded Triangle
4634   32+64+16,   // 0x0d, Shaded, Z-Buffered Triangle
4635   32+64+64,   // 0x0e, Shaded+Textured Triangle
4636   32+64+64+16,// 0x0f, Shaded+Textured, Z-Buffered Triangle
4637   8,         // 0x10, ???
4638   8,         // 0x11, ???
4639   8,         // 0x12, ???
4640   8,         // 0x13, ???
4641   8,         // 0x14, ???
4642   8,         // 0x15, ???
4643   8,         // 0x16, ???
4644   8,         // 0x17, ???
4645   8,         // 0x18, ???
4646   8,         // 0x19, ???
4647   8,         // 0x1a, ???
4648   8,         // 0x1b, ???
4649   8,         // 0x1c, ???
4650   8,         // 0x1d, ???
4651   8,         // 0x1e, ???
4652   8,         // 0x1f, ???
4653   8,         // 0x20, ???
4654   8,         // 0x21, ???
4655   8,         // 0x22, ???
4656   8,         // 0x23, ???
4657   16,         // 0x24, Texture_Rectangle
4658   16,         // 0x25, Texture_Rectangle_Flip
4659   8,         // 0x26, Sync_Load
4660   8,         // 0x27, Sync_Pipe
4661   8,         // 0x28, Sync_Tile
4662   8,         // 0x29, Sync_Full
4663   8,         // 0x2a, Set_Key_GB
4664   8,         // 0x2b, Set_Key_R
4665   8,         // 0x2c, Set_Convert
4666   8,         // 0x2d, Set_Scissor
4667   8,         // 0x2e, Set_Prim_Depth
4668   8,         // 0x2f, Set_Other_Modes
4669   8,         // 0x30, Load_TLUT
4670   8,         // 0x31, ???
4671   8,         // 0x32, Set_Tile_Size
4672   8,         // 0x33, Load_Block
4673   8,         // 0x34, Load_Tile
4674   8,         // 0x35, Set_Tile
4675   8,         // 0x36, Fill_Rectangle
4676   8,         // 0x37, Set_Fill_Color
4677   8,         // 0x38, Set_Fog_Color
4678   8,         // 0x39, Set_Blend_Color
4679   8,         // 0x3a, Set_Prim_Color
4680   8,         // 0x3b, Set_Env_Color
4681   8,         // 0x3c, Set_Combine
4682   8,         // 0x3d, Set_Texture_Image
4683   8,         // 0x3e, Set_Mask_Image
4684   8         // 0x3f, Set_Color_Image
4685};
4686
4687static int rdp_dasm(char *buffer)
4688{
4689   int i;
4690   int tile;
4691   const char *format, *size;
4692   char sl[32], tl[32], sh[32], th[32];
4693   char s[32], t[32], w[32];
4694   char dsdx[32], dtdx[32], dwdx[32];
4695   char dsdy[32], dtdy[32], dwdy[32];
4696   char dsde[32], dtde[32], dwde[32];
4697   char yl[32], yh[32], ym[32], xl[32], xh[32], xm[32];
4698   char dxldy[32], dxhdy[32], dxmdy[32];
4699   char rt[32], gt[32], bt[32], at[32];
4700   char drdx[32], dgdx[32], dbdx[32], dadx[32];
4701   char drdy[32], dgdy[32], dbdy[32], dady[32];
4702   char drde[32], dgde[32], dbde[32], dade[32];
4703   UINT32 r,g,b,a;
4704
4705   UINT32 cmd[64];
4706   UINT32 length;
4707   UINT32 command;
4708
4709   length = rdp_cmd_ptr * 4;
4710   if (length < 8)
4711   {
4712      sprintf(buffer, "ERROR: length = %d\n", length);
4713      return 0;
4714   }
4715
4716   cmd[0] = rdp_cmd_data[rdp_cmd_cur+0];
4717   cmd[1] = rdp_cmd_data[rdp_cmd_cur+1];
4718
4719   tile = (cmd[1] >> 24) & 0x7;
4720   sprintf(sl, "%4.2f", (float)((cmd[0] >> 12) & 0xfff) / 4.0f);
4721   sprintf(tl, "%4.2f", (float)((cmd[0] >>  0) & 0xfff) / 4.0f);
4722   sprintf(sh, "%4.2f", (float)((cmd[1] >> 12) & 0xfff) / 4.0f);
4723   sprintf(th, "%4.2f", (float)((cmd[1] >>  0) & 0xfff) / 4.0f);
4724
4725   format = image_format[(cmd[0] >> 21) & 0x7];
4726   size = image_size[(cmd[0] >> 19) & 0x3];
4727
4728   r = (cmd[1] >> 24) & 0xff;
4729   g = (cmd[1] >> 16) & 0xff;
4730   b = (cmd[1] >>  8) & 0xff;
4731   a = (cmd[1] >>  0) & 0xff;
4732
4733   command = (cmd[0] >> 24) & 0x3f;
4734   switch (command)
4735   {
4736      case 0x00:   sprintf(buffer, "No Op"); break;
4737      case 0x08:      // Tri_NoShade
4738      {
4739         int lft = (command >> 23) & 0x1;
4740
4741         if (length != rdp_command_length[command])
4742         {
4743            sprintf(buffer, "ERROR: Tri_NoShade length = %d\n", length);
4744            return 0;
4745         }
4746
4747         cmd[2] = rdp_cmd_data[rdp_cmd_cur+2];
4748         cmd[3] = rdp_cmd_data[rdp_cmd_cur+3];
4749         cmd[4] = rdp_cmd_data[rdp_cmd_cur+4];
4750         cmd[5] = rdp_cmd_data[rdp_cmd_cur+5];
4751         cmd[6] = rdp_cmd_data[rdp_cmd_cur+6];
4752         cmd[7] = rdp_cmd_data[rdp_cmd_cur+7];
4753
4754         sprintf(yl,      "%4.4f", (float)((cmd[0] >>  0) & 0x1fff) / 4.0f);
4755         sprintf(ym,      "%4.4f", (float)((cmd[1] >> 16) & 0x1fff) / 4.0f);
4756         sprintf(yh,      "%4.4f", (float)((cmd[1] >>  0) & 0x1fff) / 4.0f);
4757         sprintf(xl,      "%4.4f", (float)(cmd[2] / 65536.0f));
4758         sprintf(dxldy,   "%4.4f", (float)(cmd[3] / 65536.0f));
4759         sprintf(xh,      "%4.4f", (float)(cmd[4] / 65536.0f));
4760         sprintf(dxhdy,   "%4.4f", (float)(cmd[5] / 65536.0f));
4761         sprintf(xm,      "%4.4f", (float)(cmd[6] / 65536.0f));
4762         sprintf(dxmdy,   "%4.4f", (float)(cmd[7] / 65536.0f));
4763
4764               sprintf(buffer, "Tri_NoShade            %d, XL: %s, XM: %s, XH: %s, YL: %s, YM: %s, YH: %s\n", lft, xl,xm,xh,yl,ym,yh);
4765         break;
4766      }
4767      case 0x0a:      // Tri_Tex
4768      {
4769         int lft = (command >> 23) & 0x1;
4770
4771         if (length < rdp_command_length[command])
4772         {
4773            sprintf(buffer, "ERROR: Tri_Tex length = %d\n", length);
4774            return 0;
4775         }
4776
4777         for (i=2; i < 24; i++)
4778         {
4779            cmd[i] = rdp_cmd_data[rdp_cmd_cur+i];
4780         }
4781
4782         sprintf(yl,      "%4.4f", (float)((cmd[0] >>  0) & 0x1fff) / 4.0f);
4783         sprintf(ym,      "%4.4f", (float)((cmd[1] >> 16) & 0x1fff) / 4.0f);
4784         sprintf(yh,      "%4.4f", (float)((cmd[1] >>  0) & 0x1fff) / 4.0f);
4785         sprintf(xl,      "%4.4f", (float)((INT32)cmd[2] / 65536.0f));
4786         sprintf(dxldy,   "%4.4f", (float)((INT32)cmd[3] / 65536.0f));
4787         sprintf(xh,      "%4.4f", (float)((INT32)cmd[4] / 65536.0f));
4788         sprintf(dxhdy,   "%4.4f", (float)((INT32)cmd[5] / 65536.0f));
4789         sprintf(xm,      "%4.4f", (float)((INT32)cmd[6] / 65536.0f));
4790         sprintf(dxmdy,   "%4.4f", (float)((INT32)cmd[7] / 65536.0f));
4791
4792         sprintf(s,      "%4.4f", (float)(INT32)((cmd[ 8] & 0xffff0000) | ((cmd[12] >> 16) & 0xffff)) / 65536.0f);
4793         sprintf(t,      "%4.4f", (float)(INT32)(((cmd[ 8] & 0xffff) << 16) | (cmd[12] & 0xffff)) / 65536.0f);
4794         sprintf(w,      "%4.4f", (float)(INT32)((cmd[ 9] & 0xffff0000) | ((cmd[13] >> 16) & 0xffff)) / 65536.0f);
4795         sprintf(dsdx,   "%4.4f", (float)(INT32)((cmd[10] & 0xffff0000) | ((cmd[14] >> 16) & 0xffff)) / 65536.0f);
4796         sprintf(dtdx,   "%4.4f", (float)(INT32)(((cmd[10] & 0xffff) << 16) | (cmd[14] & 0xffff)) / 65536.0f);
4797         sprintf(dwdx,   "%4.4f", (float)(INT32)((cmd[11] & 0xffff0000) | ((cmd[15] >> 16) & 0xffff)) / 65536.0f);
4798         sprintf(dsde,   "%4.4f", (float)(INT32)((cmd[16] & 0xffff0000) | ((cmd[20] >> 16) & 0xffff)) / 65536.0f);
4799         sprintf(dtde,   "%4.4f", (float)(INT32)(((cmd[16] & 0xffff) << 16) | (cmd[20] & 0xffff)) / 65536.0f);
4800         sprintf(dwde,   "%4.4f", (float)(INT32)((cmd[17] & 0xffff0000) | ((cmd[21] >> 16) & 0xffff)) / 65536.0f);
4801         sprintf(dsdy,   "%4.4f", (float)(INT32)((cmd[18] & 0xffff0000) | ((cmd[22] >> 16) & 0xffff)) / 65536.0f);
4802         sprintf(dtdy,   "%4.4f", (float)(INT32)(((cmd[18] & 0xffff) << 16) | (cmd[22] & 0xffff)) / 65536.0f);
4803         sprintf(dwdy,   "%4.4f", (float)(INT32)((cmd[19] & 0xffff0000) | ((cmd[23] >> 16) & 0xffff)) / 65536.0f);
4804
4805
4806         buffer+=sprintf(buffer, "Tri_Tex               %d, XL: %s, XM: %s, XH: %s, YL: %s, YM: %s, YH: %s\n", lft, xl,xm,xh,yl,ym,yh);
4807         buffer+=sprintf(buffer, "                              ");
4808         buffer+=sprintf(buffer, "                       S: %s, T: %s, W: %s\n", s, t, w);
4809         buffer+=sprintf(buffer, "                              ");
4810         buffer+=sprintf(buffer, "                       DSDX: %s, DTDX: %s, DWDX: %s\n", dsdx, dtdx, dwdx);
4811         buffer+=sprintf(buffer, "                              ");
4812         buffer+=sprintf(buffer, "                       DSDE: %s, DTDE: %s, DWDE: %s\n", dsde, dtde, dwde);
4813         buffer+=sprintf(buffer, "                              ");
4814         buffer+=sprintf(buffer, "                       DSDY: %s, DTDY: %s, DWDY: %s\n", dsdy, dtdy, dwdy);
4815         break;
4816      }
4817      case 0x0c:      // Tri_Shade
4818      {
4819         int lft = (command >> 23) & 0x1;
4820
4821         if (length != rdp_command_length[command])
4822         {
4823            sprintf(buffer, "ERROR: Tri_Shade length = %d\n", length);
4824            return 0;
4825         }
4826
4827         for (i=2; i < 24; i++)
4828         {
4829            cmd[i] = rdp_cmd_data[i];
4830         }
4831
4832         sprintf(yl,      "%4.4f", (float)((cmd[0] >>  0) & 0x1fff) / 4.0f);
4833         sprintf(ym,      "%4.4f", (float)((cmd[1] >> 16) & 0x1fff) / 4.0f);
4834         sprintf(yh,      "%4.4f", (float)((cmd[1] >>  0) & 0x1fff) / 4.0f);
4835         sprintf(xl,      "%4.4f", (float)((INT32)cmd[2] / 65536.0f));
4836         sprintf(dxldy,   "%4.4f", (float)((INT32)cmd[3] / 65536.0f));
4837         sprintf(xh,      "%4.4f", (float)((INT32)cmd[4] / 65536.0f));
4838         sprintf(dxhdy,   "%4.4f", (float)((INT32)cmd[5] / 65536.0f));
4839         sprintf(xm,      "%4.4f", (float)((INT32)cmd[6] / 65536.0f));
4840         sprintf(dxmdy,   "%4.4f", (float)((INT32)cmd[7] / 65536.0f));
4841         sprintf(rt,      "%4.4f", (float)(INT32)((cmd[8] & 0xffff0000) | ((cmd[12] >> 16) & 0xffff)) / 65536.0f);
4842         sprintf(gt,      "%4.4f", (float)(INT32)(((cmd[8] & 0xffff) << 16) | (cmd[12] & 0xffff)) / 65536.0f);
4843         sprintf(bt,      "%4.4f", (float)(INT32)((cmd[9] & 0xffff0000) | ((cmd[13] >> 16) & 0xffff)) / 65536.0f);
4844         sprintf(at,      "%4.4f", (float)(INT32)(((cmd[9] & 0xffff) << 16) | (cmd[13] & 0xffff)) / 65536.0f);
4845         sprintf(drdx,   "%4.4f", (float)(INT32)((cmd[10] & 0xffff0000) | ((cmd[14] >> 16) & 0xffff)) / 65536.0f);
4846         sprintf(dgdx,   "%4.4f", (float)(INT32)(((cmd[10] & 0xffff) << 16) | (cmd[14] & 0xffff)) / 65536.0f);
4847         sprintf(dbdx,   "%4.4f", (float)(INT32)((cmd[11] & 0xffff0000) | ((cmd[15] >> 16) & 0xffff)) / 65536.0f);
4848         sprintf(dadx,   "%4.4f", (float)(INT32)(((cmd[11] & 0xffff) << 16) | (cmd[15] & 0xffff)) / 65536.0f);
4849         sprintf(drde,   "%4.4f", (float)(INT32)((cmd[16] & 0xffff0000) | ((cmd[20] >> 16) & 0xffff)) / 65536.0f);
4850         sprintf(dgde,   "%4.4f", (float)(INT32)(((cmd[16] & 0xffff) << 16) | (cmd[20] & 0xffff)) / 65536.0f);
4851         sprintf(dbde,   "%4.4f", (float)(INT32)((cmd[17] & 0xffff0000) | ((cmd[21] >> 16) & 0xffff)) / 65536.0f);
4852         sprintf(dade,   "%4.4f", (float)(INT32)(((cmd[17] & 0xffff) << 16) | (cmd[21] & 0xffff)) / 65536.0f);
4853         sprintf(drdy,   "%4.4f", (float)(INT32)((cmd[18] & 0xffff0000) | ((cmd[22] >> 16) & 0xffff)) / 65536.0f);
4854         sprintf(dgdy,   "%4.4f", (float)(INT32)(((cmd[18] & 0xffff) << 16) | (cmd[22] & 0xffff)) / 65536.0f);
4855         sprintf(dbdy,   "%4.4f", (float)(INT32)((cmd[19] & 0xffff0000) | ((cmd[23] >> 16) & 0xffff)) / 65536.0f);
4856         sprintf(dady,   "%4.4f", (float)(INT32)(((cmd[19] & 0xffff) << 16) | (cmd[23] & 0xffff)) / 65536.0f);
4857
4858         buffer+=sprintf(buffer, "Tri_Shade              %d, XL: %s, XM: %s, XH: %s, YL: %s, YM: %s, YH: %s\n", lft, xl,xm,xh,yl,ym,yh);
4859         buffer+=sprintf(buffer, "                              ");
4860         buffer+=sprintf(buffer, "                       R: %s, G: %s, B: %s, A: %s\n", rt, gt, bt, at);
4861         buffer+=sprintf(buffer, "                              ");
4862         buffer+=sprintf(buffer, "                       DRDX: %s, DGDX: %s, DBDX: %s, DADX: %s\n", drdx, dgdx, dbdx, dadx);
4863         buffer+=sprintf(buffer, "                              ");
4864         buffer+=sprintf(buffer, "                       DRDE: %s, DGDE: %s, DBDE: %s, DADE: %s\n", drde, dgde, dbde, dade);
4865         buffer+=sprintf(buffer, "                              ");
4866         buffer+=sprintf(buffer, "                       DRDY: %s, DGDY: %s, DBDY: %s, DADY: %s\n", drdy, dgdy, dbdy, dady);
4867         break;
4868      }
4869      case 0x0e:      // Tri_TexShade
4870      {
4871         int lft = (command >> 23) & 0x1;
4872
4873         if (length < rdp_command_length[command])
4874         {
4875            sprintf(buffer, "ERROR: Tri_TexShade length = %d\n", length);
4876            return 0;
4877         }
4878
4879         for (i=2; i < 40; i++)
4880         {
4881            cmd[i] = rdp_cmd_data[rdp_cmd_cur+i];
4882         }
4883
4884         sprintf(yl,      "%4.4f", (float)((cmd[0] >>  0) & 0x1fff) / 4.0f);
4885         sprintf(ym,      "%4.4f", (float)((cmd[1] >> 16) & 0x1fff) / 4.0f);
4886         sprintf(yh,      "%4.4f", (float)((cmd[1] >>  0) & 0x1fff) / 4.0f);
4887         sprintf(xl,      "%4.4f", (float)((INT32)cmd[2] / 65536.0f));
4888         sprintf(dxldy,   "%4.4f", (float)((INT32)cmd[3] / 65536.0f));
4889         sprintf(xh,      "%4.4f", (float)((INT32)cmd[4] / 65536.0f));
4890         sprintf(dxhdy,   "%4.4f", (float)((INT32)cmd[5] / 65536.0f));
4891         sprintf(xm,      "%4.4f", (float)((INT32)cmd[6] / 65536.0f));
4892         sprintf(dxmdy,   "%4.4f", (float)((INT32)cmd[7] / 65536.0f));
4893         sprintf(rt,      "%4.4f", (float)(INT32)((cmd[8] & 0xffff0000) | ((cmd[12] >> 16) & 0xffff)) / 65536.0f);
4894         sprintf(gt,      "%4.4f", (float)(INT32)(((cmd[8] & 0xffff) << 16) | (cmd[12] & 0xffff)) / 65536.0f);
4895         sprintf(bt,      "%4.4f", (float)(INT32)((cmd[9] & 0xffff0000) | ((cmd[13] >> 16) & 0xffff)) / 65536.0f);
4896         sprintf(at,      "%4.4f", (float)(INT32)(((cmd[9] & 0xffff) << 16) | (cmd[13] & 0xffff)) / 65536.0f);
4897         sprintf(drdx,   "%4.4f", (float)(INT32)((cmd[10] & 0xffff0000) | ((cmd[14] >> 16) & 0xffff)) / 65536.0f);
4898         sprintf(dgdx,   "%4.4f", (float)(INT32)(((cmd[10] & 0xffff) << 16) | (cmd[14] & 0xffff)) / 65536.0f);
4899         sprintf(dbdx,   "%4.4f", (float)(INT32)((cmd[11] & 0xffff0000) | ((cmd[15] >> 16) & 0xffff)) / 65536.0f);
4900         sprintf(dadx,   "%4.4f", (float)(INT32)(((cmd[11] & 0xffff) << 16) | (cmd[15] & 0xffff)) / 65536.0f);
4901         sprintf(drde,   "%4.4f", (float)(INT32)((cmd[16] & 0xffff0000) | ((cmd[20] >> 16) & 0xffff)) / 65536.0f);
4902         sprintf(dgde,   "%4.4f", (float)(INT32)(((cmd[16] & 0xffff) << 16) | (cmd[20] & 0xffff)) / 65536.0f);
4903         sprintf(dbde,   "%4.4f", (float)(INT32)((cmd[17] & 0xffff0000) | ((cmd[21] >> 16) & 0xffff)) / 65536.0f);
4904         sprintf(dade,   "%4.4f", (float)(INT32)(((cmd[17] & 0xffff) << 16) | (cmd[21] & 0xffff)) / 65536.0f);
4905         sprintf(drdy,   "%4.4f", (float)(INT32)((cmd[18] & 0xffff0000) | ((cmd[22] >> 16) & 0xffff)) / 65536.0f);
4906         sprintf(dgdy,   "%4.4f", (float)(INT32)(((cmd[18] & 0xffff) << 16) | (cmd[22] & 0xffff)) / 65536.0f);
4907         sprintf(dbdy,   "%4.4f", (float)(INT32)((cmd[19] & 0xffff0000) | ((cmd[23] >> 16) & 0xffff)) / 65536.0f);
4908         sprintf(dady,   "%4.4f", (float)(INT32)(((cmd[19] & 0xffff) << 16) | (cmd[23] & 0xffff)) / 65536.0f);
4909
4910         sprintf(s,      "%4.4f", (float)(INT32)((cmd[24] & 0xffff0000) | ((cmd[28] >> 16) & 0xffff)) / 65536.0f);
4911         sprintf(t,      "%4.4f", (float)(INT32)(((cmd[24] & 0xffff) << 16) | (cmd[28] & 0xffff)) / 65536.0f);
4912         sprintf(w,      "%4.4f", (float)(INT32)((cmd[25] & 0xffff0000) | ((cmd[29] >> 16) & 0xffff)) / 65536.0f);
4913         sprintf(dsdx,   "%4.4f", (float)(INT32)((cmd[26] & 0xffff0000) | ((cmd[30] >> 16) & 0xffff)) / 65536.0f);
4914         sprintf(dtdx,   "%4.4f", (float)(INT32)(((cmd[26] & 0xffff) << 16) | (cmd[30] & 0xffff)) / 65536.0f);
4915         sprintf(dwdx,   "%4.4f", (float)(INT32)((cmd[27] & 0xffff0000) | ((cmd[31] >> 16) & 0xffff)) / 65536.0f);
4916         sprintf(dsde,   "%4.4f", (float)(INT32)((cmd[32] & 0xffff0000) | ((cmd[36] >> 16) & 0xffff)) / 65536.0f);
4917         sprintf(dtde,   "%4.4f", (float)(INT32)(((cmd[32] & 0xffff) << 16) | (cmd[36] & 0xffff)) / 65536.0f);
4918         sprintf(dwde,   "%4.4f", (float)(INT32)((cmd[33] & 0xffff0000) | ((cmd[37] >> 16) & 0xffff)) / 65536.0f);
4919         sprintf(dsdy,   "%4.4f", (float)(INT32)((cmd[34] & 0xffff0000) | ((cmd[38] >> 16) & 0xffff)) / 65536.0f);
4920         sprintf(dtdy,   "%4.4f", (float)(INT32)(((cmd[34] & 0xffff) << 16) | (cmd[38] & 0xffff)) / 65536.0f);
4921         sprintf(dwdy,   "%4.4f", (float)(INT32)((cmd[35] & 0xffff0000) | ((cmd[39] >> 16) & 0xffff)) / 65536.0f);
4922
4923
4924         buffer+=sprintf(buffer, "Tri_TexShade           %d, XL: %s, XM: %s, XH: %s, YL: %s, YM: %s, YH: %s\n", lft, xl,xm,xh,yl,ym,yh);
4925         buffer+=sprintf(buffer, "                              ");
4926         buffer+=sprintf(buffer, "                       R: %s, G: %s, B: %s, A: %s\n", rt, gt, bt, at);
4927         buffer+=sprintf(buffer, "                              ");
4928         buffer+=sprintf(buffer, "                       DRDX: %s, DGDX: %s, DBDX: %s, DADX: %s\n", drdx, dgdx, dbdx, dadx);
4929         buffer+=sprintf(buffer, "                              ");
4930         buffer+=sprintf(buffer, "                       DRDE: %s, DGDE: %s, DBDE: %s, DADE: %s\n", drde, dgde, dbde, dade);
4931         buffer+=sprintf(buffer, "                              ");
4932         buffer+=sprintf(buffer, "                       DRDY: %s, DGDY: %s, DBDY: %s, DADY: %s\n", drdy, dgdy, dbdy, dady);
4933
4934         buffer+=sprintf(buffer, "                              ");
4935         buffer+=sprintf(buffer, "                       S: %s, T: %s, W: %s\n", s, t, w);
4936         buffer+=sprintf(buffer, "                              ");
4937         buffer+=sprintf(buffer, "                       DSDX: %s, DTDX: %s, DWDX: %s\n", dsdx, dtdx, dwdx);
4938         buffer+=sprintf(buffer, "                              ");
4939         buffer+=sprintf(buffer, "                       DSDE: %s, DTDE: %s, DWDE: %s\n", dsde, dtde, dwde);
4940         buffer+=sprintf(buffer, "                              ");
4941         buffer+=sprintf(buffer, "                       DSDY: %s, DTDY: %s, DWDY: %s\n", dsdy, dtdy, dwdy);
4942         break;
4943      }
4944      case 0x24:
4945      case 0x25:
4946      {
4947         if (length < 16)
4948         {
4949            sprintf(buffer, "ERROR: Texture_Rectangle length = %d\n", length);
4950            return 0;
4951         }
4952         cmd[2] = rdp_cmd_data[rdp_cmd_cur+2];
4953         cmd[3] = rdp_cmd_data[rdp_cmd_cur+3];
4954         sprintf(s,    "%4.4f", (float)(INT16)((cmd[2] >> 16) & 0xffff) / 32.0f);
4955         sprintf(t,    "%4.4f", (float)(INT16)((cmd[2] >>  0) & 0xffff) / 32.0f);
4956         sprintf(dsdx, "%4.4f", (float)(INT16)((cmd[3] >> 16) & 0xffff) / 1024.0f);
4957         sprintf(dtdy, "%4.4f", (float)(INT16)((cmd[3] >> 16) & 0xffff) / 1024.0f);
4958
4959         if (command == 0x24)
4960               sprintf(buffer, "Texture_Rectangle      %d, %s, %s, %s, %s,  %s, %s, %s, %s", tile, sh, th, sl, tl, s, t, dsdx, dtdy);
4961         else
4962               sprintf(buffer, "Texture_Rectangle_Flip %d, %s, %s, %s, %s,  %s, %s, %s, %s", tile, sh, th, sl, tl, s, t, dsdx, dtdy);
4963
4964         break;
4965      }
4966      case 0x26:   sprintf(buffer, "Sync_Load"); break;
4967      case 0x27:   sprintf(buffer, "Sync_Pipe"); break;
4968      case 0x28:   sprintf(buffer, "Sync_Tile"); break;
4969      case 0x29:   sprintf(buffer, "Sync_Full"); break;
4970      case 0x2d:   sprintf(buffer, "Set_Scissor            %s, %s, %s, %s", sl, tl, sh, th); break;
4971      case 0x2e:   sprintf(buffer, "Set_Prim_Depth         %04X, %04X", (cmd[1] >> 16) & 0xffff, cmd[1] & 0xffff); break;
4972      case 0x2f:   sprintf(buffer, "Set_Other_Modes        %08X %08X", cmd[0], cmd[1]); break;
4973      case 0x30:   sprintf(buffer, "Load_TLUT              %d, %s, %s, %s, %s", tile, sl, tl, sh, th); break;
4974      case 0x32:   sprintf(buffer, "Set_Tile_Size          %d, %s, %s, %s, %s", tile, sl, tl, sh, th); break;
4975      case 0x33:   sprintf(buffer, "Load_Block             %d, %03X, %03X, %03X, %03X", tile, (cmd[0] >> 12) & 0xfff, cmd[0] & 0xfff, (cmd[1] >> 12) & 0xfff, cmd[1] & 0xfff); break;
4976      case 0x34:   sprintf(buffer, "Load_Tile              %d, %s, %s, %s, %s", tile, sl, tl, sh, th); break;
4977      case 0x35:   sprintf(buffer, "Set_Tile               %d, %s, %s, %d, %04X", tile, format, size, ((cmd[0] >> 9) & 0x1ff) * 8, (cmd[0] & 0x1ff) * 8); break;
4978      case 0x36:   sprintf(buffer, "Fill_Rectangle         %s, %s, %s, %s", sh, th, sl, tl); break;
4979      case 0x37:   sprintf(buffer, "Set_Fill_Color         R: %d, G: %d, B: %d, A: %d", r, g, b, a); break;
4980      case 0x38:   sprintf(buffer, "Set_Fog_Color          R: %d, G: %d, B: %d, A: %d", r, g, b, a); break;
4981      case 0x39:   sprintf(buffer, "Set_Blend_Color        R: %d, G: %d, B: %d, A: %d", r, g, b, a); break;
4982      case 0x3a:   sprintf(buffer, "Set_Prim_Color         %d, %d, R: %d, G: %d, B: %d, A: %d", (cmd[0] >> 8) & 0x1f, cmd[0] & 0xff, r, g, b, a); break;
4983      case 0x3b:   sprintf(buffer, "Set_Env_Color          R: %d, G: %d, B: %d, A: %d", r, g, b, a); break;
4984      case 0x3c:   sprintf(buffer, "Set_Combine            %08X %08X", cmd[0], cmd[1]); break;
4985      case 0x3d:   sprintf(buffer, "Set_Texture_Image      %s, %s, %d, %08X", format, size, (cmd[0] & 0x1ff)+1, cmd[1]); break;
4986      case 0x3e:   sprintf(buffer, "Set_Mask_Image         %08X", cmd[1]); break;
4987      case 0x3f:   sprintf(buffer, "Set_Color_Image        %s, %s, %d, %08X", format, size, (cmd[0] & 0x1ff)+1, cmd[1]); break;
4988      default:   sprintf(buffer, "??? (%08X %08X)", cmd[0], cmd[1]); break;
4989   }
4990
4991   return rdp_command_length[command];
4992}
4993
4994/*****************************************************************************/
4995
4996////////////////////////
4997// RDP COMMANDS
4998////////////////////////
4999
5000typedef void (*rdp_command_func)(running_machine *machine, UINT32 w1, UINT32 w2);
5001#define RDP_COMMAND(name) void name(running_machine *machine, UINT32 w1, UINT32 w2)
5002
5003static RDP_COMMAND( rdp_invalid )
5004{
5005   fatalerror("RDP: invalid command  %d, %08X %08X\n", (w1 >> 24) & 0x3f, w1, w2);
5006}
5007
5008static RDP_COMMAND( rdp_noop )
5009{
5010
5011}
5012
5013static RDP_COMMAND( rdp_tri_noshade )
5014{
5015   triangle(machine, w1, w2, 0, 0, 0);
5016}
5017
5018static RDP_COMMAND( rdp_tri_noshade_z )
5019{
5020   triangle(machine, w1, w2, 0, 0, 1);
5021}
5022
5023static RDP_COMMAND( rdp_tri_tex )
5024{
5025   triangle(machine, w1, w2, 0, 1, 0);
5026}
5027
5028static RDP_COMMAND( rdp_tri_tex_z )
5029{
5030   triangle(machine, w1, w2, 0, 1, 1);
5031}
5032
5033static RDP_COMMAND( rdp_tri_shade )
5034{
5035   triangle(machine, w1, w2, 1, 0, 0);
5036}
5037
5038static RDP_COMMAND( rdp_tri_shade_z )
5039{
5040   triangle(machine, w1, w2, 1, 0, 1);
5041}
5042
5043static RDP_COMMAND( rdp_tri_texshade )
5044{
5045   triangle(machine, w1, w2, 1, 1, 0);
5046}
5047
5048static RDP_COMMAND( rdp_tri_texshade_z )
5049{
5050   triangle(machine, w1, w2, 1, 1, 1);
5051}
5052
5053static RDP_COMMAND( rdp_tex_rect )
5054{
5055   UINT32 w3, w4;
5056   TEX_RECTANGLE rect;
5057
5058   w3 = rdp_cmd_data[rdp_cmd_cur+2];
5059   w4 = rdp_cmd_data[rdp_cmd_cur+3];
5060
5061   rect.tilenum   = (w2 >> 24) & 0x7;
5062   rect.xl         = (w1 >> 12) & 0xfff;
5063   rect.yl         = (w1 >>  0) & 0xfff;
5064   rect.xh         = (w2 >> 12) & 0xfff;
5065   rect.yh         = (w2 >>  0) & 0xfff;
5066   rect.s         = (w3 >> 16) & 0xffff;
5067   rect.t         = (w3 >>  0) & 0xffff;
5068   rect.dsdx      = (w4 >> 16) & 0xffff;
5069   rect.dtdy      = (w4 >>  0) & 0xffff;
5070   rect.flip      = 0;
5071
5072   switch (fb_size)
5073   {
5074      case PIXEL_SIZE_16BIT:      texture_rectangle_16bit(machine, &rect); break;
5075      case PIXEL_SIZE_32BIT:      texture_rectangle_32bit(machine, &rect); break;
5076   }
5077}
5078
5079static RDP_COMMAND( rdp_tex_rect_flip )
5080{
5081   UINT32 w3, w4;
5082   TEX_RECTANGLE rect;
5083
5084   w3 = rdp_cmd_data[rdp_cmd_cur+2];
5085   w4 = rdp_cmd_data[rdp_cmd_cur+3];
5086
5087   rect.tilenum   = (w2 >> 24) & 0x7;
5088   rect.xl         = (w1 >> 12) & 0xfff;
5089   rect.yl         = (w1 >>  0) & 0xfff;
5090   rect.xh         = (w2 >> 12) & 0xfff;
5091   rect.yh         = (w2 >>  0) & 0xfff;
5092   rect.t         = (w3 >> 16) & 0xffff;
5093   rect.s         = (w3 >>  0) & 0xffff;
5094   rect.dtdy      = (w4 >> 16) & 0xffff;
5095   rect.dsdx      = (w4 >>  0) & 0xffff;
5096   rect.flip      = 1;
5097
5098   switch (fb_size)
5099   {
5100      case PIXEL_SIZE_16BIT:      texture_rectangle_16bit(machine, &rect); break;
5101      case PIXEL_SIZE_32BIT:      texture_rectangle_32bit(machine, &rect); break;
5102   }
5103}
5104
5105static RDP_COMMAND( rdp_sync_load )
5106{
5107   // Nothing to do?
5108   //rdp_poly_wait(machine);
5109}
5110
5111static RDP_COMMAND( rdp_sync_pipe )
5112{
5113   // Nothing to do?
5114   //rdp_poly_wait(machine);
5115}
5116
5117static RDP_COMMAND( rdp_sync_tile )
5118{
5119   // Nothing to do?
5120   //rdp_poly_wait(machine);
5121}
5122
5123static RDP_COMMAND( rdp_sync_full )
5124{
5125   dp_full_sync(machine);
5126   //rdp_poly_wait(machine);
5127}
5128
5129static RDP_COMMAND( rdp_set_key_gb )
5130{
5131   key_scale.b = w2 & 0xff;
5132   key_scale.g = (w2 >> 16) & 0xff;
5133}
5134
5135static RDP_COMMAND( rdp_set_key_r )
5136{
5137   key_scale.r = w2 & 0xff;
5138}
5139
5140static RDP_COMMAND( rdp_set_convert )
5141{
5142   k0 = (w1 >> 13) & 0xff;
5143   k0 = ((w1 >> 21) & 1) ? (-(0x100 - k0)) : k0;
5144   k1 = (w1 >> 4) & 0xff;
5145   k1 = ((w1 >> 12) & 1) ?   (-(0x100 - k1)) : k1;
5146   k2 = ((w1 & 7) << 5) | ((w2 >> 27) & 0x1f);
5147   k2 = (w1 & 0xf) ? (-(0x100 - k2)) : k2;
5148   k3 = (w2 >> 18) & 0xff;
5149   k3 = ((w2 >> 26) & 1) ? (-(0x100 - k3)) : k3;
5150   k4 = (w2 >> 9) & 0xff;
5151   k4 = ((w2 >> 17) & 1) ? (-(0x100 - k4)) : k4;
5152   k5 = w2 & 0xff;
5153   k5 = ((w2 >> 8) & 1) ? (-(0x100 - k5)) : k5;
5154}
5155
5156static RDP_COMMAND( rdp_set_scissor )
5157{
5158   clip.xh = (w1 >> 12) & 0xfff;
5159   clip.yh = (w1 >>  0) & 0xfff;
5160   clip.xl = (w2 >> 12) & 0xfff;
5161   clip.yl = (w2 >>  0) & 0xfff;
5162
5163   // TODO: handle f & o?
5164}
5165
5166static RDP_COMMAND( rdp_set_prim_depth )
5167{
5168   primitive_z = (UINT16)(w2 >> 16) & 0x7fff;
5169   primitive_delta_z = (UINT16)(w1);
5170}
5171
5172static RDP_COMMAND( rdp_set_other_modes )
5173{
5174   other_modes.cycle_type         = (w1 >> 20) & 0x3;
5175   other_modes.persp_tex_en       = (w1 & 0x80000) ? 1 : 0;
5176   other_modes.detail_tex_en      = (w1 & 0x40000) ? 1 : 0;
5177   other_modes.sharpen_tex_en      = (w1 & 0x20000) ? 1 : 0;
5178   other_modes.tex_lod_en         = (w1 & 0x10000) ? 1 : 0;
5179   other_modes.en_tlut            = (w1 & 0x08000) ? 1 : 0;
5180   other_modes.tlut_type         = (w1 & 0x04000) ? 1 : 0;
5181   other_modes.sample_type         = (w1 & 0x02000) ? 1 : 0;
5182   other_modes.mid_texel         = (w1 & 0x01000) ? 1 : 0;
5183   other_modes.bi_lerp0         = (w1 & 0x00800) ? 1 : 0;
5184   other_modes.bi_lerp1         = (w1 & 0x00400) ? 1 : 0;
5185   other_modes.convert_one         = (w1 & 0x00200) ? 1 : 0;
5186   other_modes.key_en            = (w1 & 0x00100) ? 1 : 0;
5187   other_modes.rgb_dither_sel      = (w1 >> 6) & 0x3;
5188   other_modes.alpha_dither_sel   = (w1 >> 4) & 0x3;
5189   other_modes.blend_m1a_0         = (w2 >> 30) & 0x3;
5190   other_modes.blend_m1a_1         = (w2 >> 28) & 0x3;
5191   other_modes.blend_m1b_0         = (w2 >> 26) & 0x3;
5192   other_modes.blend_m1b_1         = (w2 >> 24) & 0x3;
5193   other_modes.blend_m2a_0         = (w2 >> 22) & 0x3;
5194   other_modes.blend_m2a_1         = (w2 >> 20) & 0x3;
5195   other_modes.blend_m2b_0         = (w2 >> 18) & 0x3;
5196   other_modes.blend_m2b_1         = (w2 >> 16) & 0x3;
5197   other_modes.force_blend         = (w2 & 0x4000) ? 1 : 0;
5198   other_modes.alpha_cvg_select   = (w2 & 0x2000) ? 1 : 0;
5199   other_modes.cvg_times_alpha      = (w2 & 0x1000) ? 1 : 0;
5200   other_modes.z_mode            = (w2 >> 10) & 0x3;
5201   other_modes.cvg_dest         = (w2 >> 8) & 0x3;
5202   other_modes.color_on_cvg      = (w2 & 0x80) ? 1 : 0;
5203   other_modes.image_read_en      = (w2 & 0x40) ? 1 : 0;
5204   other_modes.z_update_en         = (w2 & 0x20) ? 1 : 0;
5205   other_modes.z_compare_en      = (w2 & 0x10) ? 1 : 0;
5206   other_modes.antialias_en      = (w2 & 0x08) ? 1 : 0;
5207   other_modes.z_source_sel      = (w2 & 0x04) ? 1 : 0;
5208   other_modes.dither_alpha_en      = (w2 & 0x02) ? 1 : 0;
5209   other_modes.alpha_compare_en   = (w2 & 0x01) ? 1 : 0;
5210
5211   SET_BLENDER_INPUT(0, 0, &blender1a_r[0], &blender1a_g[0], &blender1a_b[0], &blender1b_a[0],
5212                 other_modes.blend_m1a_0, other_modes.blend_m1b_0);
5213   SET_BLENDER_INPUT(0, 1, &blender2a_r[0], &blender2a_g[0], &blender2a_b[0], &blender2b_a[0],
5214                 other_modes.blend_m2a_0, other_modes.blend_m2b_0);
5215   SET_BLENDER_INPUT(1, 0, &blender1a_r[1], &blender1a_g[1], &blender1a_b[1], &blender1b_a[1],
5216                 other_modes.blend_m1a_1, other_modes.blend_m1b_1);
5217   SET_BLENDER_INPUT(1, 1, &blender2a_r[1], &blender2a_g[1], &blender2a_b[1], &blender2b_a[1],
5218                 other_modes.blend_m2a_1, other_modes.blend_m2b_1);
5219}
5220
5221static RDP_COMMAND( rdp_load_tlut )
5222{
5223   int i;
5224   int tl, th, sl, sh;
5225   int tilenum = (w2 >> 24) & 7;
5226
5227   sl = tile[tilenum].sl = ((w1 >> 12) & 0xfff);
5228   tl = tile[tilenum].tl =  w1 & 0xfff;
5229   sh = tile[tilenum].sh = ((w2 >> 12) & 0xfff);
5230   th = tile[tilenum].th = w2 & 0xfff;
5231
5232   switch (ti_size)
5233   {
5234      case PIXEL_SIZE_16BIT:
5235      {
5236         //UINT16 *src = (UINT16*)&rdram[(ti_address + (tl >> 2) * (ti_width << 1) + (sl >> 1)) >> 2];
5237         UINT16 *src = (UINT16*)rdram;
5238         UINT32 srcstart = (ti_address + (tl >> 2) * (ti_width << 1) + (sl >> 1)) >> 1;
5239         UINT16 *dst = (UINT16*)&TMEM[tile[tilenum].tmem];
5240         int count = ((sh >> 2) - (sl >> 2)) + 1;
5241
5242         for (i = 0; i < count; i++)
5243         {
5244            if((i*4) < 0x400)
5245            {
5246               dst[i*4] = src[(srcstart + i) ^ WORD_ADDR_XOR];
5247               dst[i*4+1] = 0;
5248               dst[i*4+2] = 0;
5249               dst[i*4+3] = 0;
5250            }
5251            //tlut[i] = src[i];
5252         }
5253         break;
5254      }
5255      /*
5256        case PIXEL_SIZE_16BIT:
5257        {
5258            UINT16 *src = (UINT16*)&rdram[(ti_address + (tl >> 2) * (ti_width << 1) + (sl >> 1)) >> 2];
5259
5260            for (i = (sl >> 2); i <= (sh >> 2); i++)
5261            {
5262                tlut[i] = src[i];
5263            }
5264            break;
5265        }*/
5266      default:   stricterror("RDP: load_tlut: size = %d\n", ti_size);
5267   }
5268
5269   if (TMEM[0x1000] != 25 || TMEM[0x1001] != 25)
5270   {
5271      stricterror("rdp_load_tlut: TMEM has been written out-of-bounds");
5272   }
5273}
5274
5275static RDP_COMMAND( rdp_set_tile_size )
5276{
5277   int tilenum = (w2 >> 24) & 0x7;
5278
5279   tile[tilenum].sl = (w1 >> 12) & 0xfff;
5280   tile[tilenum].tl = (w1 >>  0) & 0xfff;
5281   tile[tilenum].sh = (w2 >> 12) & 0xfff;
5282   tile[tilenum].th = (w2 >>  0) & 0xfff;
5283}
5284
5285static RDP_COMMAND( rdp_load_block )
5286{
5287   int i, width;
5288   UINT16 sl, sh, tl, dxt;
5289   int tilenum = (w2 >> 24) & 0x7;
5290   UINT32 *src, *tc;
5291   UINT32 tb;
5292   UINT16 *ram16 = (UINT16*)rdram;
5293   UINT32 ti_address2 = ti_address - ((ti_address & 3) ? 4 : 0);
5294   int ti_width2 = ti_width;
5295   int slindwords = 0;
5296
5297   tile[tilenum].sl = sl = ((w1 >> 12) & 0xfff);
5298   tile[tilenum].tl = tl = ((w1 >>  0) & 0xfff);
5299   tile[tilenum].sh = sh = ((w2 >> 12) & 0xfff);
5300   dxt   = ((w2 >>  0) & 0xfff);
5301
5302   if (sh < sl)
5303   {
5304      //fatalerror( "load_block: sh < sl" );
5305   }
5306
5307   width = (sh - sl) + 1;
5308
5309   if (width > 2048) // Hack for Magical Tetris Challenge
5310   {
5311      width = 2048;
5312   }
5313
5314   switch (ti_size)
5315   {
5316      case PIXEL_SIZE_4BIT:   width >>= 1; break;
5317      case PIXEL_SIZE_8BIT:   break;
5318      case PIXEL_SIZE_16BIT:   width <<= 1; break;
5319      case PIXEL_SIZE_32BIT:   width <<= 2; break;
5320   }
5321
5322   if ((ti_address & 3) && (ti_address & 0xffffff00) != 0xf8a00)
5323   {
5324      stricterror( "load block: unaligned ti_address 0x%x",ti_address ); // Rat Attack, Frogger 2 prototype
5325   }
5326
5327   src = (UINT32*)&ram16[ti_address2 >> 1];
5328   tc = (UINT32*)TMEM;
5329   tb = tile[tilenum].tmem >> 2;
5330
5331   if ((tb + (width >> 2)) > 0x400)
5332   {
5333      width = 0x1000 - tb*4; // Hack for Magical Tetris Challenge
5334   }
5335
5336   if (ti_width2 < 0)
5337   {
5338      fatalerror( "load_block: negative ti_width2" );
5339   }
5340
5341   switch (ti_size)
5342   {
5343      case PIXEL_SIZE_4BIT:   ti_width2 >>= 1; break;
5344      case PIXEL_SIZE_8BIT:   break;
5345      case PIXEL_SIZE_16BIT:   ti_width2 <<= 1; break;
5346      case PIXEL_SIZE_32BIT:   ti_width2 <<= 2; break;
5347   }
5348
5349   slindwords = sl;
5350   switch (ti_size) // Needed by Vigilante 8
5351   {
5352      case PIXEL_SIZE_4BIT:   slindwords >>= 3; break;
5353      case PIXEL_SIZE_8BIT:   slindwords >>= 2;break;
5354      case PIXEL_SIZE_16BIT:   slindwords >>= 1; break;
5355      case PIXEL_SIZE_32BIT:   break;
5356   }
5357
5358   if (width & 7)   // Sigh... another Rat Attack-specific thing.
5359   {
5360      width = (width & (~7)) + 8;
5361   }
5362
5363   if (dxt != 0)
5364   {
5365      int j= 0;
5366      int t = 0;
5367      int oldt = 0;
5368      int ptr;
5369      int xorval = (fb_size == PIXEL_SIZE_16BIT && ti_size == PIXEL_SIZE_32BIT ) ? 2 : 1; // Wave Race-specific
5370      UINT32 srcstart = ((tl * ti_width2) >> 2) + slindwords;
5371      src = &src[srcstart];
5372      for (i = 0; i < (width >> 2); i += 2)
5373      {
5374         oldt = t;
5375         t = ((j >> 11) & 1) ? xorval : 0;
5376         if (t > oldt)
5377         {
5378            i += ((tile[tilenum].line >> 3) << 1);
5379         }
5380         ptr = tb + i;
5381         tc[ptr & 0x3ff] = src[i ^ t];
5382         tc[(ptr + 1) & 0x3ff] = src[(i + 1) ^ t];
5383         j += dxt;
5384      }
5385      tile[tilenum].th = tl + (j >> 11);
5386   }
5387   else // Needed by Pilotwings 64 intro, Top Gear Rally intro
5388   {
5389      UINT32 srcstart = ((tl * ti_width2) >> 2) + slindwords;
5390      memcpy(&tc[tb],&src[srcstart],width);
5391      tile[tilenum].th = tl;
5392   }
5393}
5394
5395static RDP_COMMAND( rdp_load_tile )
5396{
5397   int i, j;
5398   UINT16 sl, sh, tl, th;
5399   int width, height;
5400   int tilenum = (w2 >> 24) & 0x7;
5401   int line = tile[tilenum].line; // Per Ziggy
5402   int toppad;
5403
5404   if (!line)
5405   {
5406      return; // Needed by Wipeout 64
5407   }
5408
5409   if ((ti_format != tile[tilenum].format || ti_size != tile[tilenum].size))
5410   {
5411      fatalerror("load_tile: format conversion required!\n %d %d %d %d", ti_format, tile[tilenum].format, ti_size, tile[tilenum].size);
5412   }
5413
5414   tile[tilenum].sl = ((w1 >> 12) & 0xfff);
5415   tile[tilenum].tl = ((w1 >>  0) & 0xfff);
5416   tile[tilenum].sh = ((w2 >> 12) & 0xfff);
5417   tile[tilenum].th = ((w2 >>  0) & 0xfff);
5418   sl = tile[tilenum].sl / 4;
5419   tl = tile[tilenum].tl / 4;
5420   sh = tile[tilenum].sh / 4;
5421   th = tile[tilenum].th / 4;
5422
5423   width = (sh - sl) + 1;
5424   height = (th - tl) + 1;
5425
5426   if (ti_size < 3)
5427   {
5428      toppad = (width * ti_size) & 0x7;
5429   }
5430   else
5431   {
5432      toppad = (width << 2) & 0x7;
5433   }
5434   toppad = 0; // Currently disabled
5435
5436   switch (ti_size)
5437   {
5438      case PIXEL_SIZE_8BIT:
5439      {
5440         UINT8 *src = (UINT8*)rdram;
5441         UINT8 *tc = (UINT8*)TMEM;
5442         int tb = tile[tilenum].tmem;
5443
5444         if (tb + (width * height) > 4096)
5445         {
5446            height = (4096 - tb) / line; // Per Ziggy
5447         }
5448
5449         for (j=0; j < height; j++)
5450         {
5451            int tline = tb + (tile[tilenum].line * j);
5452            int s = ((j + tl) * ti_width) + sl;
5453#define BYTE_XOR_DWORD_SWAP 7
5454            int xorval8 = ((j & 1) ? BYTE_XOR_DWORD_SWAP : BYTE_ADDR_XOR); // Per Ziggy
5455
5456            for (i=0; i < width; i++)
5457            {
5458               tc[(tline + i) ^ xorval8] = src[(ti_address + s + i) ^ BYTE_ADDR_XOR];
5459            }
5460            //for (int k=0; k < (topad); k++) // Padding is possibly necessary, not yet known.
5461            //{
5462            //    tc[((tline+i+k) ^ xorval8] = src[(ti_address + s + i) ^ BYTE_ADDR_XOR];
5463            //}
5464         }
5465         break;
5466      }
5467      case PIXEL_SIZE_16BIT:
5468      {
5469         UINT16 *src = (UINT16*)rdram;
5470         UINT32 ti_addr16 = ti_address >> 1;
5471         UINT16 *tc = (UINT16*)TMEM;
5472         int tb = (tile[tilenum].tmem / 2);
5473         int taddr;
5474
5475         if ((tb + (width * height)) > 2048)
5476         {
5477            height = (2048 - tb) / (line / 2); // Per Ziggy
5478         }
5479
5480         for (j = 0; j < height; j++)
5481         {
5482            int tline = tb + ((tile[tilenum].line / 2) * j);
5483            int s = 0;
5484            int xorval16 = 0;
5485            if (tile[tilenum].format == 1) // Needed by Ogre Battle 64
5486            {
5487               tline = tb + (tile[tilenum].line * j);
5488            }
5489            s = ((j + tl) * ti_width) + sl;
5490#define WORD_XOR_DWORD_SWAP 3
5491            xorval16 = (j & 1) ? WORD_XOR_DWORD_SWAP : WORD_ADDR_XOR;
5492
5493            for (i = 0; i < width; i++)
5494            {
5495               taddr = (tline+i) ^ xorval16;
5496               if (taddr < 2048) // Needed by World Driver Championship
5497               {
5498                  tc[taddr] = src[(ti_addr16 + s + i) ^ WORD_ADDR_XOR];
5499               }
5500            }
5501            //for (int k=0; k < (topad>>1); k++) // Padding is possibly necessary, not yet known.
5502            //{
5503            //    tc[((tline+i+k) ^ xorval16] = src[(ti_addr16+s+i) ^ WORD_ADDR_XOR];
5504            //}
5505         }
5506         break;
5507      }
5508      case PIXEL_SIZE_32BIT:
5509      {
5510         UINT32 *src = (UINT32*)&rdram[ti_address / 4];
5511         UINT32 *tc = (UINT32*)TMEM;
5512         int tb = (tile[tilenum].tmem / 4);
5513         int xorval32 = ((fb_size == PIXEL_SIZE_16BIT) ? 2 : 1);
5514
5515         if (tb + (width * height) > 1024)
5516         {
5517            height = (1024 - tb) / (line/4); // Per Ziggy
5518         }
5519
5520         for (j=0; j < height; j++)
5521         {
5522            int tline = tb + ((tile[tilenum].line / 2) * j);
5523            int s = ((j + tl) * ti_width) + sl;
5524            int xorval32cur = (j & 1) ? xorval32 : 0;
5525            for (i=0; i < width; i++)
5526            {
5527               tc[(tline + i) ^ xorval32cur] = src[s + i];
5528            }
5529         }
5530         break;
5531      }
5532
5533      default:   fatalerror("RDP: load_tile: size = %d\n", ti_size);
5534   }
5535
5536}
5537
5538static RDP_COMMAND( rdp_set_tile )
5539{
5540   int tilenum = (w2 >> 24) & 0x7;
5541
5542   tile[tilenum].format   = (w1 >> 21) & 0x7;
5543   tile[tilenum].size      = (w1 >> 19) & 0x3;
5544   tile[tilenum].line      = ((w1 >>  9) & 0x1ff) * 8;
5545   tile[tilenum].tmem      = ((w1 >>  0) & 0x1ff) * 8;
5546   tile[tilenum].palette   = (w2 >> 20) & 0xf;
5547   tile[tilenum].ct      = (w2 >> 19) & 0x1;
5548   tile[tilenum].mt      = (w2 >> 18) & 0x1;
5549   tile[tilenum].mask_t   = (w2 >> 14) & 0xf;
5550   tile[tilenum].shift_t   = (w2 >> 10) & 0xf;
5551   tile[tilenum].cs      = (w2 >>  9) & 0x1;
5552   tile[tilenum].ms      = (w2 >>  8) & 0x1;
5553   tile[tilenum].mask_s   = (w2 >>  4) & 0xf;
5554   tile[tilenum].shift_s   = (w2 >>  0) & 0xf;
5555
5556   // TODO: clamp & mirror parameters
5557}
5558
5559static RDP_COMMAND( rdp_fill_rect )
5560{
5561   RECTANGLE rect;
5562   rect.xl = (w1 >> 12) & 0xfff;
5563   rect.yl = (w1 >>  0) & 0xfff;
5564   rect.xh = (w2 >> 12) & 0xfff;
5565   rect.yh = (w2 >>  0) & 0xfff;
5566
5567   switch (fb_size)
5568   {
5569      case PIXEL_SIZE_16BIT:      fill_rectangle_16bit(machine, &rect); break;
5570      case PIXEL_SIZE_32BIT:      fill_rectangle_32bit(machine, &rect); break;
5571   }
5572}
5573
5574static RDP_COMMAND( rdp_set_fill_color )
5575{
5576   fill_color = w2;
5577}
5578
5579static RDP_COMMAND( rdp_set_fog_color )
5580{
5581   fog_color.r = (w2 >> 24) & 0xff;
5582   fog_color.g = (w2 >> 16) & 0xff;
5583   fog_color.b = (w2 >>  8) & 0xff;
5584   fog_color.a = (w2 >>  0) & 0xff;
5585}
5586
5587static RDP_COMMAND( rdp_set_blend_color )
5588{
5589   blend_color.r = (w2 >> 24) & 0xff;
5590   blend_color.g = (w2 >> 16) & 0xff;
5591   blend_color.b = (w2 >>  8) & 0xff;
5592   blend_color.a = (w2 >>  0) & 0xff;
5593}
5594
5595static RDP_COMMAND( rdp_set_prim_color )
5596{
5597   min_level = (w1 >> 8) & 0x1f;
5598   primitive_lod_frac = (w1 & 0xff);
5599   prim_color.r = (w2 >> 24) & 0xff;
5600   prim_color.g = (w2 >> 16) & 0xff;
5601   prim_color.b = (w2 >>  8) & 0xff;
5602   prim_color.a = (w2 >>  0) & 0xff;
5603}
5604
5605static RDP_COMMAND( rdp_set_env_color )
5606{
5607   env_color.r = (w2 >> 24) & 0xff;
5608   env_color.g = (w2 >> 16) & 0xff;
5609   env_color.b = (w2 >>  8) & 0xff;
5610   env_color.a = (w2 >>  0) & 0xff;
5611}
5612
5613static RDP_COMMAND( rdp_set_combine )
5614{
5615   combine.sub_a_rgb0   = (w1 >> 20) & 0xf;
5616   combine.mul_rgb0   = (w1 >> 15) & 0x1f;
5617   combine.sub_a_a0   = (w1 >> 12) & 0x7;
5618   combine.mul_a0      = (w1 >>  9) & 0x7;
5619   combine.sub_a_rgb1   = (w1 >>  5) & 0xf;
5620   combine.mul_rgb1   = (w1 >>  0) & 0x1f;
5621
5622   combine.sub_b_rgb0   = (w2 >> 28) & 0xf;
5623   combine.sub_b_rgb1   = (w2 >> 24) & 0xf;
5624   combine.sub_a_a1   = (w2 >> 21) & 0x7;
5625   combine.mul_a1      = (w2 >> 18) & 0x7;
5626   combine.add_rgb0   = (w2 >> 15) & 0x7;
5627   combine.sub_b_a0   = (w2 >> 12) & 0x7;
5628   combine.add_a0      = (w2 >>  9) & 0x7;
5629   combine.add_rgb1   = (w2 >>  6) & 0x7;
5630   combine.sub_b_a1   = (w2 >>  3) & 0x7;
5631   combine.add_a1      = (w2 >>  0) & 0x7;
5632
5633   SET_SUBA_RGB_INPUT(&combiner_rgbsub_a_r[0], &combiner_rgbsub_a_g[0], &combiner_rgbsub_a_b[0], combine.sub_a_rgb0);
5634   SET_SUBB_RGB_INPUT(&combiner_rgbsub_b_r[0], &combiner_rgbsub_b_g[0], &combiner_rgbsub_b_b[0], combine.sub_b_rgb0);
5635   SET_MUL_RGB_INPUT(&combiner_rgbmul_r[0], &combiner_rgbmul_g[0], &combiner_rgbmul_b[0], combine.mul_rgb0);
5636   SET_ADD_RGB_INPUT(&combiner_rgbadd_r[0], &combiner_rgbadd_g[0], &combiner_rgbadd_b[0], combine.add_rgb0);
5637   SET_SUB_ALPHA_INPUT(&combiner_alphasub_a[0], combine.sub_a_a0);
5638   SET_SUB_ALPHA_INPUT(&combiner_alphasub_b[0], combine.sub_b_a0);
5639   SET_MUL_ALPHA_INPUT(&combiner_alphamul[0], combine.mul_a0);
5640   SET_SUB_ALPHA_INPUT(&combiner_alphaadd[0], combine.add_a0);
5641
5642   SET_SUBA_RGB_INPUT(&combiner_rgbsub_a_r[1], &combiner_rgbsub_a_g[1], &combiner_rgbsub_a_b[1], combine.sub_a_rgb1);
5643   SET_SUBB_RGB_INPUT(&combiner_rgbsub_b_r[1], &combiner_rgbsub_b_g[1], &combiner_rgbsub_b_b[1], combine.sub_b_rgb1);
5644   SET_MUL_RGB_INPUT(&combiner_rgbmul_r[1], &combiner_rgbmul_g[1], &combiner_rgbmul_b[1], combine.mul_rgb1);
5645   SET_ADD_RGB_INPUT(&combiner_rgbadd_r[1], &combiner_rgbadd_g[1], &combiner_rgbadd_b[1], combine.add_rgb1);
5646   SET_SUB_ALPHA_INPUT(&combiner_alphasub_a[1], combine.sub_a_a1);
5647   SET_SUB_ALPHA_INPUT(&combiner_alphasub_b[1], combine.sub_b_a1);
5648   SET_MUL_ALPHA_INPUT(&combiner_alphamul[1], combine.mul_a1);
5649   SET_SUB_ALPHA_INPUT(&combiner_alphaadd[1], combine.add_a1);
5650}
5651
5652static RDP_COMMAND( rdp_set_texture_image )
5653{
5654   ti_format   = (w1 >> 21) & 0x7;
5655   ti_size      = (w1 >> 19) & 0x3;
5656   ti_width   = (w1 & 0x3ff) + 1;
5657   ti_address   = w2 & 0x01ffffff;
5658}
5659
5660static RDP_COMMAND( rdp_set_mask_image )
5661{
5662   zb_address   = w2 & 0x01ffffff;
5663}
5664
5665static RDP_COMMAND( rdp_set_color_image )
5666{
5667   fb_format    = (w1 >> 21) & 0x7;
5668   fb_size      = (w1 >> 19) & 0x3;
5669   fb_width   = (w1 & 0x3ff) + 1;
5670   fb_address   = w2 & 0x01ffffff;
5671   if (fb_format && fb_format != 2) // Jet Force Gemini sets the format to 4, Intensity.  Protection?
5672   {
5673      if (fb_size == 1)
5674      {
5675         fb_format = 2;
5676      }
5677      else
5678      {
5679         fb_format = 0;
5680      }
5681   }
5682
5683   if (fb_format != 0)
5684   {
5685      fb_format = 0;
5686   }
5687}
5688
5689/*****************************************************************************/
5690
5691static const rdp_command_func rdp_command_table[64] =
5692{
5693   /* 0x00 */
5694   rdp_noop,         rdp_invalid,         rdp_invalid,         rdp_invalid,
5695   rdp_invalid,      rdp_invalid,         rdp_invalid,         rdp_invalid,
5696   rdp_tri_noshade,   rdp_tri_noshade_z,      rdp_tri_tex,         rdp_tri_tex_z,
5697   rdp_tri_shade,      rdp_tri_shade_z,      rdp_tri_texshade,      rdp_tri_texshade_z,
5698   /* 0x10 */
5699   rdp_invalid,      rdp_invalid,         rdp_invalid,         rdp_invalid,
5700   rdp_invalid,      rdp_invalid,         rdp_invalid,         rdp_invalid,
5701   rdp_invalid,      rdp_invalid,         rdp_invalid,         rdp_invalid,
5702   rdp_invalid,      rdp_invalid,         rdp_invalid,         rdp_invalid,
5703   /* 0x20 */
5704   rdp_invalid,      rdp_invalid,         rdp_invalid,         rdp_invalid,
5705   rdp_tex_rect,      rdp_tex_rect_flip,      rdp_sync_load,         rdp_sync_pipe,
5706   rdp_sync_tile,      rdp_sync_full,         rdp_set_key_gb,         rdp_set_key_r,
5707   rdp_set_convert,   rdp_set_scissor,      rdp_set_prim_depth,      rdp_set_other_modes,
5708   /* 0x30 */
5709   rdp_load_tlut,      rdp_invalid,         rdp_set_tile_size,      rdp_load_block,
5710   rdp_load_tile,      rdp_set_tile,         rdp_fill_rect,         rdp_set_fill_color,
5711   rdp_set_fog_color,   rdp_set_blend_color,   rdp_set_prim_color,      rdp_set_env_color,
5712   rdp_set_combine,   rdp_set_texture_image,   rdp_set_mask_image,      rdp_set_color_image
5713};
5714
5715static void *rdp_command_item_callback(void *param, int threadid)
5716{
5717   command_work_unit *unit = (command_work_unit *)param;
5718   UINT8 cmd = (unit->command[0] >> 24) & 0x3f;
5719
5720   while(1)
5721   {
5722      command_work_unit *unit = (command_work_unit *)param;
5723      UINT32 orig_count_next;
5724
5725      /* if our previous item isn't done yet, enqueue this item to the end and proceed */
5726      if (unit->previtem != 0xffff)
5727      {
5728         command_work_unit *prevunit = units[unit->previtem];
5729         if (prevunit->count_next != 0)
5730         {
5731            UINT32 unitnum = ((UINT8 *)unit - (UINT8 *)units[0]) / unit_size;
5732            UINT32 new_count_next;
5733
5734            /* attempt to atomically swap in this new value */
5735            do
5736            {
5737               orig_count_next = prevunit->count_next;
5738               new_count_next = orig_count_next | (unitnum << 16);
5739            } while (compare_exchange32((volatile INT32 *)&prevunit->count_next, orig_count_next, new_count_next) != orig_count_next);
5740
5741            /* if we succeeded, skip out early so we can do other work */
5742            if (orig_count_next != 0)
5743            {
5744               break;
5745            }
5746         }
5747      }
5748
5749      // execute the command
5750      rdp_command_table[cmd](unit->machine, unit->command[0], unit->command[1]);
5751
5752      /* set our count to 0 and re-fetch the original count value */
5753      do
5754      {
5755         orig_count_next = unit->count_next;
5756      } while (compare_exchange32((volatile INT32 *)&unit->count_next, orig_count_next, 0) != orig_count_next);
5757
5758      /* if we have no more work to do, do nothing */
5759      orig_count_next >>= 16;
5760      if (orig_count_next == 0)
5761         break;
5762      param = units[orig_count_next];
5763   }
5764
5765   return NULL;
5766}
5767
5768void rdp_process_list(running_machine *machine)
5769{
5770   int i;
5771   UINT32 cmd, length, cmd_length, cur_cmd = 0;
5772   int startunit = unit_next;
5773
5774   length = dp_end - dp_current;
5775
5776   // load command data
5777   for (i=0; i < length; i += 4)
5778   {
5779      rdp_cmd_data[rdp_cmd_ptr++] = READ_RDP_DATA((dp_current & 0x1fffffff) + i);
5780      if (rdp_cmd_ptr >= 0x1000)
5781      {
5782         fatalerror("rdp_process_list: rdp_cmd_ptr overflow\n");
5783      }
5784   }
5785
5786   dp_current = dp_end;
5787
5788   cmd = (rdp_cmd_data[0] >> 24) & 0x3f;
5789   cmd_length = (rdp_cmd_ptr + 1) * 4;
5790
5791   // check if more data is needed
5792   if (cmd_length < rdp_command_length[cmd])
5793   {
5794      return;
5795   }
5796
5797   while (rdp_cmd_cur < rdp_cmd_ptr)
5798   {
5799      UINT32 bucketnum = ((UINT32)cur_cmd / COMMANDS_PER_BUCKET) % TOTAL_BUCKETS;
5800      UINT32 unit_index = unit_next++;
5801      UINT32 *data = units[unit_index]->command;
5802      int data_index = 0;
5803      units[unit_index]->machine = machine;
5804      cmd = (rdp_cmd_data[rdp_cmd_cur] >> 24) & 0x3f;
5805   //  if (((rdp_cmd_data[rdp_cmd_cur] >> 24) & 0xc0) != 0xc0)
5806   //  {
5807   //      fatalerror("rdp_process_list: invalid rdp command %08X at %08X\n", rdp_cmd_data[rdp_cmd_cur], dp_start+(rdp_cmd_cur * 4));
5808   //  }
5809
5810      if (((rdp_cmd_ptr-rdp_cmd_cur) * 4) < rdp_command_length[cmd])
5811      {
5812         return;
5813         //fatalerror("rdp_process_list: not enough rdp command data: cur = %d, ptr = %d, expected = %d\n", rdp_cmd_cur, rdp_cmd_ptr, rdp_command_length[cmd]);
5814      }
5815
5816      if (LOG_RDP_EXECUTION)
5817      {
5818         char string[4000];
5819         rdp_dasm(string);
5820
5821         fprintf(rdp_exec, "%08X: %08X %08X   %s\n", dp_start+(rdp_cmd_cur * 4), rdp_cmd_data[rdp_cmd_cur+0], rdp_cmd_data[rdp_cmd_cur+1], string);
5822      }
5823
5824      // execute the command
5825      //rdp_command_table[cmd](machine, rdp_cmd_data[rdp_cmd_cur+0], rdp_cmd_data[rdp_cmd_cur+1]);
5826
5827      // spawn the work unit
5828      for(data_index = 0; data_index < rdp_command_length[cmd] / 4; data_index++)
5829      {
5830         data[data_index] = rdp_cmd_data[rdp_cmd_cur+data_index];
5831      }
5832      units[unit_index]->count_next = 0;
5833      units[unit_index]->previtem = unit_bucket[bucketnum];
5834      unit_bucket[bucketnum] = unit_index;
5835
5836      rdp_cmd_cur += rdp_command_length[cmd] / 4;
5837   };
5838
5839   osd_work_item_queue_multiple(queue, rdp_command_item_callback, unit_next - startunit, units[startunit], unit_size, WORK_ITEM_FLAG_AUTO_RELEASE);
5840   rdp_cmd_ptr = 0;
5841   rdp_cmd_cur = 0;
5842
5843   dp_start = dp_current = dp_end;
5844}
5845
5846INLINE int alpha_compare(running_machine *machine, UINT8 comb_alpha)
5847{
5848   if (other_modes.alpha_compare_en)
5849   {
5850      if (other_modes.dither_alpha_en)
5851      {
5852         if (comb_alpha < (mame_rand(machine) & 0xff))
5853         {
5854            return 0;
5855         }
5856      }
5857      else
5858      {
5859         if (comb_alpha < blend_color.a)
5860         {
5861            return 0;
5862         }
5863      }
5864      return 1;
5865   }
5866   return 1;
5867}
5868
5869INLINE UINT8 alpha_cvg_get(UINT8 comb_alpha)
5870{
5871   UINT32 temp = comb_alpha;
5872   UINT32 temp2 = curpixel_cvg;
5873   UINT32 temp3 = 0;
5874
5875   if (other_modes.cvg_times_alpha > 1 || other_modes.alpha_cvg_select > 1)
5876   {
5877      fatalerror( "alpha_cvg_get failed" );
5878   }
5879
5880   if (other_modes.cvg_times_alpha)
5881   {
5882      temp3 = (temp * temp2) + 4;
5883      curpixel_cvg = temp3 >> 8;
5884   }
5885
5886   if (other_modes.alpha_cvg_select)
5887   {
5888      temp = (other_modes.cvg_times_alpha) ? (temp3 >> 3) : (temp2 << 5);
5889   }
5890
5891   if (temp > 0xff)
5892   {
5893      temp = 0xff;
5894   }
5895
5896   return (UINT8)temp;
5897}
5898
5899INLINE UINT8 COMBINER_EQUATION(UINT8 A, UINT8 B, UINT8 C, UINT8 D)
5900{
5901   INT32 color = (((A-B)* C) + (D << 8) + 0x80);
5902   color >>= 8;
5903   if (color > 255)
5904   {
5905      color = 255;
5906   }
5907   if (color < 0)
5908   {
5909      color = 0;
5910   }
5911   return (UINT8)color;
5912}
5913
5914INLINE void BLENDER_EQUATION(INT32* r, INT32* g, INT32* b, int cycle, int bsel_special)
5915{
5916   UINT8 blend1a, blend2a;
5917   UINT32 sum = 0;
5918   blend1a = *blender1b_a[cycle];
5919   blend2a = *blender2b_a[cycle];
5920   if (bsel_special)
5921   {
5922      blend1a &= 0xe0;
5923   }
5924
5925   sum = (((blend1a >> 5) + (blend2a >> 5) + 1) & 0xf) << 5;
5926
5927   *r = (((int)(*blender1a_r[cycle]) * (int)(blend1a))) +
5928      (((int)(*blender2a_r[cycle]) * (int)(blend2a)));
5929   *r += (bsel_special) ? (((int)(*blender2a_r[cycle])) << 5) : (((int)(*blender2a_r[cycle])) << 3);
5930
5931   *g = (((int)(*blender1a_g[cycle]) * (int)(blend1a))) +
5932      (((int)(*blender2a_g[cycle]) * (int)(blend2a)));
5933   *g += (bsel_special) ? ((int)((*blender2a_g[cycle])) << 5) : (((int)(*blender2a_g[cycle])) << 3);
5934
5935   *b = (((int)(*blender1a_b[cycle]) * (int)(blend1a))) +
5936      (((int)(*blender2a_b[cycle]) * (int)(blend2a)));
5937   *b += (bsel_special) ? (((int)(*blender2a_b[cycle])) << 5) : (((int)(*blender2a_b[cycle])) << 3);
5938
5939   if (other_modes.force_blend)
5940   {
5941      *r >>= 8;
5942      *g >>= 8;
5943      *b >>= 8;
5944   }
5945   else
5946   {
5947      if (sum)
5948      {
5949         *r /= sum;
5950         *g /= sum;
5951         *b /= sum;
5952      }
5953      else
5954      {
5955         *r = *g = *b = 0xff;
5956      }
5957   }
5958
5959
5960   if (*r > 255) *r = 255;
5961   if (*g > 255) *g = 255;
5962   if (*b > 255) *b = 255;
5963}
5964
5965INLINE UINT32 addrightcvg(UINT32 x, UINT32 k)
5966{
5967//#undef FULL_SUBPIXELS
5968#define FULL_SUBPIXELS
5969   UINT32 coveredsubpixels=((x >> 14) & 3);
5970   if (!(x & 0xffff))
5971   {
5972      return 0;
5973   }
5974#ifdef FULL_SUBPIXELS
5975   if (!coveredsubpixels)
5976   {
5977      return 0;
5978   }
5979   if (!(k & 1))
5980   {
5981      return (coveredsubpixels<3) ? 1 : 2;
5982   }
5983   else
5984   {
5985      return (coveredsubpixels<2) ? 0 : 1;
5986   }
5987#endif
5988   if (!(k & 1))
5989   {
5990      return (coveredsubpixels < 2) ? 1 : 2;
5991   }
5992   else
5993   {
5994      if (coveredsubpixels<1)
5995      {
5996         return 0;
5997      }
5998      else if (coveredsubpixels<3)
5999      {
6000         return 1;
6001      }
6002      else
6003      {
6004         return 2;
6005      }
6006   }
6007}
6008
6009INLINE UINT32 addleftcvg(UINT32 x, UINT32 k)
6010{
6011   UINT32 coveredsubpixels = 3 - ((x >> 14) & 3);
6012   if (!(x & 0xffff))
6013   {
6014      return 2;
6015   }
6016#ifdef FULL_SUBPIXELS
6017   if (!coveredsubpixels)
6018   {
6019      return 0;
6020   }
6021   if (!(k & 1))
6022   {
6023      return (coveredsubpixels<2) ? 0 : 1;
6024   }
6025   else
6026   {
6027      return (coveredsubpixels<3) ? 1 : 2;
6028   }
6029#endif
6030   if (k & 1)
6031   {
6032      return (coveredsubpixels<2) ? 1 : 2;
6033   }
6034   else
6035   {
6036      if (coveredsubpixels < 1)
6037      {
6038         return 0;
6039      }
6040      else if (coveredsubpixels < 3)
6041      {
6042         return 1;
6043      }
6044      else
6045      {
6046         return 2;
6047      }
6048   }
6049}
6050
6051INLINE UINT32 FBWRITE_16(UINT16 *fb, UINT8* hb, UINT32 r, UINT32 g, UINT32 b)
6052{
6053#undef CVG_DRAW
6054   UINT16 finalcolor;
6055   UINT32 memory_cvg;
6056   UINT32 newcvg;
6057   UINT32 wrapflag;
6058   UINT32 clampcvg;
6059#ifdef CVG_DRAW
6060   int covdraw;
6061   if (curpixel_cvg == 8)
6062   {
6063      covdraw=255;
6064   }
6065   else
6066   {
6067      covdraw = curpixel_cvg << 5;
6068   }
6069   r=covdraw; g=covdraw; b=covdraw;
6070#endif
6071
6072   if (!other_modes.z_compare_en)
6073   {
6074      curpixel_overlap = 0;
6075   }
6076   if (other_modes.image_read_en)
6077   {
6078      memory_cvg = ((*fb & 1) << 2) + (*hb & 3) + 1;
6079   }
6080   else
6081   {
6082      memory_cvg = 8;
6083   }
6084
6085   if (curpixel_cvg > 8)
6086   {
6087      fatalerror("FBWRITE_16: curpixel_cvg %d", curpixel_cvg);
6088   }
6089
6090   newcvg = curpixel_cvg + memory_cvg;
6091   wrapflag = (newcvg > 8) ? 1 : 0;
6092
6093   finalcolor = ((r >> 3) << 11) | ((g >> 3) << 6) | ((b >> 3) << 1);
6094
6095   clampcvg = (newcvg > 8) ? 8 : newcvg;
6096   newcvg = (wrapflag)? (newcvg - 8) : newcvg;
6097
6098   if (!curpixel_cvg)
6099   {
6100      fatalerror("cvg underflow");
6101   }
6102
6103   curpixel_cvg--;
6104   newcvg--;
6105   memory_cvg--;
6106   clampcvg--;
6107
6108   if (other_modes.color_on_cvg && !wrapflag)
6109   {
6110      *fb &= 0xfffe;
6111      *fb |= ((newcvg >> 2) & 1);
6112      *hb = (newcvg & 3);
6113      return 0;
6114   }
6115
6116   if (!other_modes.cvg_dest)
6117   {
6118      if (!other_modes.force_blend && !curpixel_overlap)
6119      {
6120         *fb = finalcolor|((curpixel_cvg >>2)&1);
6121         *hb = (curpixel_cvg & 3);
6122      }
6123      else
6124      {
6125         *fb = finalcolor|((clampcvg>>2)&1);
6126         *hb = (clampcvg&3);
6127      }
6128   }
6129   else if (other_modes.cvg_dest == 2)
6130   {
6131      *fb = finalcolor|1;
6132      *hb = 3;
6133   }
6134   else if (other_modes.cvg_dest == 3)
6135   {
6136      *fb = finalcolor|((memory_cvg >> 2) & 1);
6137      *hb = (memory_cvg & 3);
6138   }
6139   else if (other_modes.cvg_dest == 1)
6140   {
6141      *fb = finalcolor|((newcvg >> 2) & 1);
6142      *hb = (newcvg & 3);
6143   }
6144   return 1;
6145}
6146
6147INLINE UINT32 FBWRITE_32(UINT32 *fb, UINT32 r, UINT32 g, UINT32 b)
6148{
6149   UINT32 finalcolor=(r << 24) | (g << 16) | (b << 8);
6150   UINT32 memory_alphachannel = *fb & 0xff;
6151   UINT32 memory_cvg;
6152   UINT32 newcvg;
6153   UINT32 wrapflag;
6154   UINT32 clampcvg;
6155   if (other_modes.image_read_en)
6156   {
6157      memory_cvg = ((*fb >>5) & 7) + 1;
6158   }
6159   else
6160   {
6161      memory_cvg = 8;
6162   }
6163
6164   newcvg = curpixel_cvg + memory_cvg;
6165   wrapflag = (newcvg > 8) ? 1 : 0;
6166   clampcvg = (newcvg > 8) ? 8 : newcvg;
6167   newcvg = (wrapflag)? (newcvg - 8) : newcvg;
6168
6169   curpixel_cvg--;
6170   newcvg--;
6171   memory_cvg--;
6172   clampcvg--;
6173
6174   if (other_modes.color_on_cvg && !wrapflag)
6175   {
6176      *fb &= 0xffffff00;
6177      *fb |= ((newcvg << 5) & 0xff);
6178      return 0;
6179   }
6180
6181   if (!other_modes.cvg_dest)
6182   {
6183      if (!other_modes.force_blend && !curpixel_overlap)
6184      {
6185         *fb = finalcolor|(curpixel_cvg << 5);
6186      }
6187      else
6188      {
6189         *fb = finalcolor|(clampcvg << 5);
6190      }
6191   }
6192   else if (other_modes.cvg_dest==2)
6193   {
6194      *fb = finalcolor | 0xE0;
6195   }
6196   else if (other_modes.cvg_dest == 3)
6197   {
6198      *fb = finalcolor | memory_alphachannel;
6199   }
6200   else if (other_modes.cvg_dest == 1)
6201   {
6202      *fb = finalcolor | (newcvg << 5);
6203   }
6204   return 1;
6205}
6206
src/mame/drivers/mirderby.c
r8415r8416
1/*   Miracle Derby - Ascot
2
3   - has the same GX61A01 custom (blitter?) as homedata.c and a 'similar' CPU setup (this has more CPUs)
4     and similar board / rom numbering (X**-)
5
6     The drivers can probably be merged later, although the current per-game handling of the blitter in
7     homedata.c should be looked at.
8
9
10
11        Notes from Stefan Lindberg:
12
13        Eprom "x70_a04.5g" had wires attached to it, pin 2 and 16 was joined and pin 1,32,31,30 was joined, i
14        removed them and read the eprom as the type it was (D27c1000D).
15
16        Measured frequencies:
17        MBL68B09E = 2mhz
18        MBL68B09E = 2mhz
19        z80 = 4mhz
20        YM2203 = 2mhz
21
22        See included PCB pics.
23
24
25
26        Roms:
27
28        Name              Size     CRC32         Chip Type
29        ---------------------------------------------------------------------------------
30        x70a07.8l         256      0x7d4c9712    82s129
31        x70a08.7l         256      0xc4e77174    82s129
32        x70a09.6l         256      0xd0187957    82s129
33        x70_a03.8g        32768    0x4e298b2d    27c256
34        x70_a04.5g        131072   0x14392fdb    D27c1000D
35        x70_a11.1g        32768    0xb394eef7    27c256
36        x70_b02.12e       32768    0x76c9bb6f    27c256
37        x70_c01.14e       65536    0xd79d072d    27c512
38
39
40
41*/
42
43/* clocks are 16mhz and 9mhz */
44
45#include "emu.h"
46#include "cpu/z80/z80.h"
47#include "cpu/m6809/m6809.h"
48#include "sound/2203intf.h"
49
50static VIDEO_START(mirderby)
51{
52
53}
54
55static VIDEO_UPDATE(mirderby)
56{
57   return 0;
58}
59
60static ADDRESS_MAP_START( cpu0_map, ADDRESS_SPACE_PROGRAM, 8 )
61   AM_RANGE(0x0000, 0x7fff) AM_ROM
62ADDRESS_MAP_END
63
64static ADDRESS_MAP_START( cpu1_map, ADDRESS_SPACE_PROGRAM, 8 )
65   AM_RANGE(0x0000, 0xffff) AM_ROM
66ADDRESS_MAP_END
67
68static ADDRESS_MAP_START( cpu2_map, ADDRESS_SPACE_PROGRAM, 8 )
69   AM_RANGE(0x8000, 0xffff) AM_ROM
70ADDRESS_MAP_END
71
72
73
74static PALETTE_INIT( mirderby )
75{
76   int i;
77
78   for (i = 0; i < 0x100; i++)
79   {
80      int r,g,b;
81      r = color_prom[0x000+i];
82      g = color_prom[0x100+i];
83      b = color_prom[0x200+i];
84
85      palette_set_color_rgb(machine,i,pal4bit(r),pal4bit(g),pal4bit(b));
86   }
87}
88
89static const gfx_layout char_layout =
90{
91   8,8,
92   RGN_FRAC(1,1),
93   4,
94   { 0, 1, 2, 3 },
95   { 0*4, 1*4, 2*4, 3*4, 4*4, 5*4, 6*4, 7*4 },
96   { 0*32, 1*32, 2*32, 3*32, 4*32, 5*32, 6*32, 7*32 },
97   32*8
98};
99
100static GFXDECODE_START( mirderby )
101   GFXDECODE_ENTRY( "gfx1", 0, char_layout, 0x0000, 0x10 )
102   GFXDECODE_ENTRY( "gfx2", 0, char_layout, 0x0000, 0x10 )
103GFXDECODE_END
104
105static MACHINE_DRIVER_START( mirderby )
106
107   /* basic machine hardware */
108   MDRV_CPU_ADD("cpu0", Z80, 16000000/4)   /* 4 Mhz */
109   MDRV_CPU_PROGRAM_MAP(cpu0_map)
110
111   MDRV_CPU_ADD("cpu1", M6809, 16000000/8)   /* 2 Mhz */
112   MDRV_CPU_PROGRAM_MAP(cpu1_map)
113
114   MDRV_CPU_ADD("cpu2", M6809, 16000000/8)   /* 2 Mhz */
115   MDRV_CPU_PROGRAM_MAP(cpu2_map)
116
117   MDRV_QUANTUM_TIME(HZ(6000))
118
119   /* video hardware */
120   MDRV_SCREEN_ADD("screen", RASTER)
121   MDRV_SCREEN_REFRESH_RATE(59)
122   MDRV_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(0))
123   MDRV_SCREEN_FORMAT(BITMAP_FORMAT_INDEXED16)
124   MDRV_SCREEN_SIZE(64*8, 32*8)
125   MDRV_SCREEN_VISIBLE_AREA(0*8, 54*8-1, 2*8, 30*8-1)
126
127   MDRV_GFXDECODE(mirderby)
128   MDRV_PALETTE_LENGTH(0x100)
129
130   MDRV_PALETTE_INIT(mirderby)
131   MDRV_VIDEO_START(mirderby)
132   MDRV_VIDEO_UPDATE(mirderby)
133
134   /* sound hardware */
135   MDRV_SPEAKER_STANDARD_MONO("mono")
136
137   MDRV_SOUND_ADD("ymsnd", YM2203, 2000000)
138   MDRV_SOUND_ROUTE(0, "mono", 0.25)
139   MDRV_SOUND_ROUTE(1, "mono", 0.25)
140   MDRV_SOUND_ROUTE(2, "mono", 0.25)
141   MDRV_SOUND_ROUTE(3, "mono", 1.0)
142MACHINE_DRIVER_END
143
144
145static INPUT_PORTS_START( mirderby )
146INPUT_PORTS_END
147
148
149ROM_START( mirderby )
150   ROM_REGION( 0x8000, "cpu0", 0 ) /* Z80 Code */
151   ROM_LOAD( "x70_a11.1g", 0x2000, 0x6000, CRC(b394eef7) SHA1(a646596d09b90eda44aaf8ccbf8f3fccfd3d5dad) ) // first 0x6000 bytes are blank!
152   ROM_CONTINUE(0x0000, 0x2000) // main z80 code is here
153
154   ROM_REGION( 0x10000, "cpu1", 0 ) /* M6809 code */
155   ROM_LOAD( "x70_c01.14e", 0x00000, 0x10000, CRC(d79d072d) SHA1(8e189931de9c4eb520c1ec2d0898d8eaba0f01b5) )
156
157   ROM_REGION( 0x10000, "cpu2", 0 ) /* M6809 code */
158   ROM_LOAD( "x70_b02.12e", 0x8000, 0x8000, CRC(76c9bb6f) SHA1(dd8893f3082d33d366247295e9531f8879c219c5) )
159
160   ROM_REGION( 0x8000, "gfx1", 0 ) // horse gfx
161   ROM_LOAD( "x70_a03.8g", 0x0000, 0x8000, CRC(4e298b2d) SHA1(ae78327d1f30c8d19ef772b82803dab4d6b7b919))
162
163   ROM_REGION( 0x20000, "gfx2", 0 ) // fonts etc.
164   ROM_LOAD( "x70_a04.5g", 0x0000, 0x20000, CRC(14392fdb) SHA1(dafdce473b2d2ebbdbf49fbd12f85c1ad69b2877) )
165
166   ROM_REGION( 0x300, "proms", 0 ) /* colours */
167   ROM_LOAD( "x70a07.8l", 0x000, 0x100, CRC(7d4c9712) SHA1(fe2a89841fdf5e4fd6cd41478ad2f29d28bed54d) )
168   ROM_LOAD( "x70a08.7l", 0x100, 0x100, CRC(c4e77174) SHA1(ada238ded69f01b4daeb0159a2c5c422977bb95e) )
169   ROM_LOAD( "x70a09.6l", 0x200, 0x100, CRC(d0187957) SHA1(6b36c1bccad24708cfa2fc78da08313f9bcfdbc0) )
170ROM_END
171
172static DRIVER_INIT( mirderby )
173{
174
175}
176
177GAME( 1988, mirderby, 0, mirderby, mirderby, mirderby,   ROT0, "Home Data?", "Miracle Derby - Ascot", GAME_NO_SOUND|GAME_NOT_WORKING )
178
src/mame/drivers/janshi.c
r8415r8416
1/* Janshi */
2
3/*
4
5Janshi
6(c)1992 Eagle
7
8CPU: HD647180X0P6 (16K EPROM internal rom)
9Sound: AY-3-8910, M6295
10Others: Battery
11OSC: 32MHz, 21MHz & 12.2880MHz
12
13ROMs:
141.1A         [92b140a5]
152.1B         [6de7e086]
163.1D         [4e94d8f2]
174.1F         [a5f6e3ef]
185.1H         [ff2cc769]
196.1K         [8197034d]
2011.1L        [a7692ddf]
21
22
23
24--- Team Japump!!! ---
25Dumped by Chackn
2604/May/2007
27
28*/
29
30#include "emu.h"
31#include "includes/news.h"
32#include "cpu/z80/z80.h"
33#include "sound/okim6295.h"
34
35
36static ADDRESS_MAP_START( mainmap, ADDRESS_SPACE_PROGRAM, 8 )
37   AM_RANGE(0x0000, 0x3fff) AM_ROM
38ADDRESS_MAP_END
39
40static VIDEO_START(janshi)
41{
42
43}
44
45static VIDEO_UPDATE(janshi)
46{
47   return 0;
48}
49
50
51static INPUT_PORTS_START( janshi )
52INPUT_PORTS_END
53
54
55static const gfx_layout tiles8x8_layout =
56{
57   8,8,
58   RGN_FRAC(1,5),
59   5,
60   { RGN_FRAC(0,5),RGN_FRAC(1,5),RGN_FRAC(2,5),RGN_FRAC(3,5),RGN_FRAC(4,5) },
61   { 0, 1,2,3,4,5,6,7 },
62   { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8 },
63   8*8
64};
65
66static GFXDECODE_START( janshi )
67   GFXDECODE_ENTRY( "gfx1", 0, tiles8x8_layout, 0, 16 )
68GFXDECODE_END
69
70
71
72static MACHINE_DRIVER_START( janshi )
73   /* basic machine hardware */
74   MDRV_CPU_ADD("maincpu", Z80,6000000) /* Z180 */       /* ? MHz */
75   MDRV_CPU_PROGRAM_MAP(mainmap)
76//  MDRV_CPU_VBLANK_INT("screen", irq0_line_hold)
77
78   /* video hardware */
79   MDRV_SCREEN_ADD("screen", RASTER)
80   MDRV_SCREEN_REFRESH_RATE(60)
81   MDRV_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(0))
82   MDRV_SCREEN_FORMAT(BITMAP_FORMAT_INDEXED16)
83   MDRV_SCREEN_SIZE(256, 256)
84   MDRV_SCREEN_VISIBLE_AREA(0, 256-1, 16, 256-16-1)
85
86   MDRV_GFXDECODE(janshi)
87   MDRV_PALETTE_LENGTH(0x100)
88
89   MDRV_VIDEO_START(janshi)
90   MDRV_VIDEO_UPDATE(janshi)
91
92   /* sound hardware */
93   MDRV_SPEAKER_STANDARD_MONO("mono")
94
95   MDRV_SOUND_ADD("oki", OKIM6295, 1056000)
96   MDRV_SOUND_CONFIG(okim6295_interface_pin7high) // clock frequency & pin 7 not verified
97   MDRV_SOUND_ROUTE(ALL_OUTPUTS, "mono", 1.0)
98MACHINE_DRIVER_END
99
100
101
102ROM_START( janshi )
103   ROM_REGION( 0x20000, "user1", 0 )
104   ROM_LOAD( "11.1l", 0x00000, 0x20000, CRC(a7692ddf) SHA1(5e7f43d8337583977baf22a28bbcd9b2182c0cde) )
105
106   ROM_REGION( 0x10000, "maincpu", 0 )
107   ROM_COPY( "user1", 0x10000, 0x00000, 0x4000 )// Missing 16K internal rom (might need decapping)
108
109   ROM_REGION( 0x140000, "gfx1", 0 )
110   ROM_LOAD( "1.1a", 0x000000, 0x40000, CRC(92b140a5) SHA1(f3b38563f74650604ed0faaf84460e0b04b386b7) )
111   ROM_LOAD( "2.1b", 0x040000, 0x40000, CRC(6de7e086) SHA1(e87426264f0181c17383ffe0f7ec7ff5fce3d809) )
112   ROM_LOAD( "3.1d", 0x080000, 0x40000, CRC(4e94d8f2) SHA1(a25f542943d74915fc82910baafb9ff9db1ffd70) )
113   ROM_LOAD( "4.1f", 0x0c0000, 0x40000, CRC(a5f6e3ef) SHA1(f1f3d28b27eea682aa71855a311fb3abdf9af2cd) )
114   ROM_LOAD( "5.1h", 0x100000, 0x40000, CRC(ff2cc769) SHA1(ba4cf2923cf3d4d815a9327595f8e1801c3c8a2b) )
115
116   ROM_REGION( 0x40000, "oki", 0 )
117   ROM_LOAD( "6.1k", 0x00000, 0x40000, CRC(8197034d) SHA1(b501dc7a27b1faad1361c309afd726da14b8b5f5) )
118ROM_END
119
120GAME( 1992, janshi,  0,    janshi, janshi,  0, ROT0, "Eagle", "Janshi", GAME_NOT_WORKING )
src/emu/cpuintrf.h
r8415r8416
1/***************************************************************************
2
3    cpuintrf.h
4
5    Core CPU interface functions and definitions.
6
7    Copyright Nicola Salmoria and the MAME Team.
8    Visit http://mamedev.org for licensing and usage restrictions.
9
10***************************************************************************/
11
12#pragma once
13
14#ifndef __EMU_H__
15#error Dont include this file directly; include emu.h instead.
16#endif
17
18#ifndef __CPUINTRF_H__
19#define __CPUINTRF_H__
20
21
22
23/***************************************************************************
24    CONSTANTS
25***************************************************************************/
26
27#define MAX_INPUT_EVENTS      32
28
29
30/* alternate address space names for common use */
31enum
32{
33   ADDRESS_SPACE_PROGRAM = ADDRESS_SPACE_0,   /* program address space */
34   ADDRESS_SPACE_DATA = ADDRESS_SPACE_1,      /* data address space */
35   ADDRESS_SPACE_IO = ADDRESS_SPACE_2         /* I/O address space */
36};
37
38
39/* I/O line states */
40enum
41{
42   CLEAR_LINE = 0,            /* clear (a fired or held) line */
43   ASSERT_LINE,            /* assert an interrupt immediately */
44   HOLD_LINE,               /* hold interrupt line until acknowledged */
45   PULSE_LINE               /* pulse interrupt line instantaneously (only for NMI, RESET) */
46};
47
48
49/* I/O line definitions */
50enum
51{
52   /* input lines */
53   MAX_INPUT_LINES = 32+3,
54   INPUT_LINE_IRQ0 = 0,
55   INPUT_LINE_IRQ1 = 1,
56   INPUT_LINE_IRQ2 = 2,
57   INPUT_LINE_IRQ3 = 3,
58   INPUT_LINE_IRQ4 = 4,
59   INPUT_LINE_IRQ5 = 5,
60   INPUT_LINE_IRQ6 = 6,
61   INPUT_LINE_IRQ7 = 7,
62   INPUT_LINE_IRQ8 = 8,
63   INPUT_LINE_IRQ9 = 9,
64   INPUT_LINE_NMI = MAX_INPUT_LINES - 3,
65
66   /* special input lines that are implemented in the core */
67   INPUT_LINE_RESET = MAX_INPUT_LINES - 2,
68   INPUT_LINE_HALT = MAX_INPUT_LINES - 1,
69
70   /* output lines */
71   MAX_OUTPUT_LINES = 32
72};
73
74
75/* register definitions */
76enum
77{
78   MAX_REGS = 256,
79
80   REG_GENPCBASE = MAX_REGS - 1,   /* generic "base" PC, should point to start of current opcode */
81   REG_GENPC = MAX_REGS - 2,      /* generic PC, may point within an opcode */
82   REG_GENSP = MAX_REGS - 3      /* generic SP, or closest equivalent */
83};
84
85
86/* CPU information constants */
87enum
88{
89   /* --- the following bits of info are returned as 64-bit signed integers --- */
90   CPUINFO_INT_FIRST = DEVINFO_INT_FIRST,
91
92      /* CPU-specific additions */
93      CPUINFO_INT_CONTEXT_SIZE = DEVINFO_INT_CLASS_SPECIFIC,   /* R/O: size of CPU context in bytes */
94      CPUINFO_INT_INPUT_LINES,                     /* R/O: number of input lines */
95      CPUINFO_INT_OUTPUT_LINES,                     /* R/O: number of output lines */
96      CPUINFO_INT_DEFAULT_IRQ_VECTOR,                  /* R/O: default IRQ vector */
97      CPUINFO_INT_CLOCK_MULTIPLIER,                  /* R/O: internal clock multiplier */
98      CPUINFO_INT_CLOCK_DIVIDER,                     /* R/O: internal clock divider */
99      CPUINFO_INT_MIN_INSTRUCTION_BYTES,               /* R/O: minimum bytes per instruction */
100      CPUINFO_INT_MAX_INSTRUCTION_BYTES,               /* R/O: maximum bytes per instruction */
101      CPUINFO_INT_MIN_CYCLES,                        /* R/O: minimum cycles for a single instruction */
102      CPUINFO_INT_MAX_CYCLES,                        /* R/O: maximum cycles for a single instruction */
103
104      CPUINFO_INT_LOGADDR_WIDTH,                     /* R/O: address bus size for logical accesses in each space (0=same as physical) */
105      CPUINFO_INT_LOGADDR_WIDTH_PROGRAM = CPUINFO_INT_LOGADDR_WIDTH + ADDRESS_SPACE_PROGRAM,
106      CPUINFO_INT_LOGADDR_WIDTH_DATA = CPUINFO_INT_LOGADDR_WIDTH + ADDRESS_SPACE_DATA,
107      CPUINFO_INT_LOGADDR_WIDTH_IO = CPUINFO_INT_LOGADDR_WIDTH + ADDRESS_SPACE_IO,
108      CPUINFO_INT_LOGADDR_WIDTH_LAST = CPUINFO_INT_LOGADDR_WIDTH + ADDRESS_SPACES - 1,
109      CPUINFO_INT_PAGE_SHIFT,                        /* R/O: size of a page log 2 (i.e., 12=4096), or 0 if paging not supported */
110      CPUINFO_INT_PAGE_SHIFT_PROGRAM = CPUINFO_INT_PAGE_SHIFT + ADDRESS_SPACE_PROGRAM,
111      CPUINFO_INT_PAGE_SHIFT_DATA = CPUINFO_INT_PAGE_SHIFT + ADDRESS_SPACE_DATA,
112      CPUINFO_INT_PAGE_SHIFT_IO = CPUINFO_INT_PAGE_SHIFT + ADDRESS_SPACE_IO,
113      CPUINFO_INT_PAGE_SHIFT_LAST = CPUINFO_INT_PAGE_SHIFT + ADDRESS_SPACES - 1,
114
115      CPUINFO_INT_INPUT_STATE,                     /* R/W: states for each input line */
116      CPUINFO_INT_INPUT_STATE_LAST = CPUINFO_INT_INPUT_STATE + MAX_INPUT_LINES - 1,
117      CPUINFO_INT_OUTPUT_STATE,                     /* R/W: states for each output line */
118      CPUINFO_INT_OUTPUT_STATE_LAST = CPUINFO_INT_OUTPUT_STATE + MAX_OUTPUT_LINES - 1,
119      CPUINFO_INT_REGISTER,                        /* R/W: values of up to MAX_REGs registers */
120      CPUINFO_INT_SP = CPUINFO_INT_REGISTER + REG_GENSP,      /* R/W: the current stack pointer value */
121      CPUINFO_INT_PC = CPUINFO_INT_REGISTER + REG_GENPC,      /* R/W: the current PC value */
122      CPUINFO_INT_PREVIOUSPC = CPUINFO_INT_REGISTER + REG_GENPCBASE,   /* R/W: the previous PC value */
123      CPUINFO_INT_REGISTER_LAST = CPUINFO_INT_REGISTER + MAX_REGS - 1,
124
125   CPUINFO_INT_CPU_SPECIFIC = 0x08000,                  /* R/W: CPU-specific values start here */
126
127   /* --- the following bits of info are returned as pointers to data or functions --- */
128   CPUINFO_PTR_FIRST = DEVINFO_PTR_FIRST,
129
130      /* CPU-specific additions */
131      CPUINFO_PTR_INSTRUCTION_COUNTER = DEVINFO_PTR_CLASS_SPECIFIC,
132                                             /* R/O: int *icount */
133      CPUINFO_PTR_STATE_TABLE,                     /* R/O: cpu_state_table *state */
134
135   CPUINFO_PTR_CPU_SPECIFIC = DEVINFO_PTR_DEVICE_SPECIFIC,   /* R/W: CPU-specific values start here */
136
137   /* --- the following bits of info are returned as pointers to functions --- */
138   CPUINFO_FCT_FIRST = DEVINFO_FCT_FIRST,
139
140      /* CPU-specific additions */
141      CPUINFO_FCT_SET_INFO = DEVINFO_FCT_CLASS_SPECIFIC,   /* R/O: void (*set_info)(running_device *device, UINT32 state, INT64 data, void *ptr) */
142      CPUINFO_FCT_INIT,                           /* R/O: void (*init)(running_device *device, int index, int clock, int (*irqcallback)(running_device *device, int)) */
143      CPUINFO_FCT_RESET,                           /* R/O: void (*reset)(running_device *device) */
144      CPUINFO_FCT_EXIT,                           /* R/O: void (*exit)(running_device *device) */
145      CPUINFO_FCT_EXECUTE,                        /* R/O: int (*execute)(running_device *device, int cycles) */
146      CPUINFO_FCT_BURN,                           /* R/O: void (*burn)(running_device *device, int cycles) */
147      CPUINFO_FCT_DISASSEMBLE,                     /* R/O: offs_t (*disassemble)(running_device *device, char *buffer, offs_t pc, const UINT8 *oprom, const UINT8 *opram, int options) */
148      CPUINFO_FCT_TRANSLATE,                        /* R/O: int (*translate)(running_device *device, int space, int intention, offs_t *address) */
149      CPUINFO_FCT_READ,                           /* R/O: int (*read)(running_device *device, int space, UINT32 offset, int size, UINT64 *value) */
150      CPUINFO_FCT_WRITE,                           /* R/O: int (*write)(running_device *device, int space, UINT32 offset, int size, UINT64 value) */
151      CPUINFO_FCT_READOP,                           /* R/O: int (*readop)(running_device *device, UINT32 offset, int size, UINT64 *value) */
152      CPUINFO_FCT_DEBUG_INIT,                        /* R/O: void (*debug_init)(running_device *device) */
153      CPUINFO_FCT_VALIDITY_CHECK,                     /* R/O: int (*validity_check)(const game_driver *driver, const void *config) */
154      CPUINFO_FCT_IMPORT_STATE,                     /* R/O: void (*import_state)(running_device *device, void *baseptr, const cpu_state_entry *entry) */
155      CPUINFO_FCT_EXPORT_STATE,                     /* R/O: void (*export_state)(running_device *device, void *baseptr, const cpu_state_entry *entry) */
156      CPUINFO_FCT_IMPORT_STRING,                     /* R/O: void (*import_string)(running_device *device, void *baseptr, const cpu_state_entry *entry, const char *format, char *string) */
157      CPUINFO_FCT_EXPORT_STRING,                     /* R/O: void (*export_string)(running_device *device, void *baseptr, const cpu_state_entry *entry, const char *format, char *string) */
158
159   CPUINFO_FCT_CPU_SPECIFIC = DEVINFO_FCT_DEVICE_SPECIFIC,   /* R/W: CPU-specific values start here */
160
161   /* --- the following bits of info are returned as NULL-terminated strings --- */
162   CPUINFO_STR_FIRST = DEVINFO_STR_FIRST,
163
164      /* CPU-specific additions */
165      CPUINFO_STR_FLAGS = DEVINFO_STR_CLASS_SPECIFIC,      /* R/O: string representation of the main flags value */
166      CPUINFO_STR_REGISTER,                        /* R/O: string representation of up to MAX_REGs registers */
167      CPUINFO_STR_REGISTER_LAST = CPUINFO_STR_REGISTER + MAX_REGS - 1,
168
169   CPUINFO_STR_CPU_SPECIFIC = DEVINFO_STR_DEVICE_SPECIFIC   /* R/W: CPU-specific values start here */
170};
171
172
173/* Translation intentions */
174#define TRANSLATE_TYPE_MASK      0x03      /* read write or fetch */
175#define TRANSLATE_USER_MASK      0x04      /* user mode or fully privileged */
176#define TRANSLATE_DEBUG_MASK   0x08      /* debug mode (no side effects) */
177
178#define TRANSLATE_READ         0         /* translate for read */
179#define TRANSLATE_WRITE         1         /* translate for write */
180#define TRANSLATE_FETCH         2         /* translate for instruction fetch */
181#define TRANSLATE_READ_USER      (TRANSLATE_READ | TRANSLATE_USER_MASK)
182#define TRANSLATE_WRITE_USER   (TRANSLATE_WRITE | TRANSLATE_USER_MASK)
183#define TRANSLATE_FETCH_USER   (TRANSLATE_FETCH | TRANSLATE_USER_MASK)
184#define TRANSLATE_READ_DEBUG   (TRANSLATE_READ | TRANSLATE_DEBUG_MASK)
185#define TRANSLATE_WRITE_DEBUG   (TRANSLATE_WRITE | TRANSLATE_DEBUG_MASK)
186#define TRANSLATE_FETCH_DEBUG   (TRANSLATE_FETCH | TRANSLATE_DEBUG_MASK)
187
188
189/* Disassembler constants */
190#define DASMFLAG_SUPPORTED      0x80000000   /* are disassembly flags supported? */
191#define DASMFLAG_STEP_OUT      0x40000000   /* this instruction should be the end of a step out sequence */
192#define DASMFLAG_STEP_OVER      0x20000000   /* this instruction should be stepped over by setting a breakpoint afterwards */
193#define DASMFLAG_OVERINSTMASK   0x18000000   /* number of extra instructions to skip when stepping over */
194#define DASMFLAG_OVERINSTSHIFT   27         /* bits to shift after masking to get the value */
195#define DASMFLAG_LENGTHMASK    0x0000ffff   /* the low 16-bits contain the actual length */
196#define DASMFLAG_STEP_OVER_EXTRA(x)         ((x) << DASMFLAG_OVERINSTSHIFT)
197
198
199/* state table flags */
200#define CPUSTATE_NOSHOW         0x01      /* don't display this entry in the registers view */
201#define CPUSTATE_IMPORT         0x02      /* call the import function after writing new data */
202#define CPUSTATE_IMPORT_SEXT   0x04      /* sign-extend the data when writing new data */
203#define CPUSTATE_EXPORT         0x08      /* call the export function prior to fetching the data */
204
205
206
207/***************************************************************************
208    MACROS
209***************************************************************************/
210
211/* device iteration helpers */
212#define cpu_count(config)            (config)->devicelist.count(CPU)
213#define cpu_first(config)            (config)->devicelist.first(CPU)
214#define cpu_next(previous)            (previous)->typenext()
215#define cpu_get_index(cpu)            (cpu)->machine->devicelist.index(CPU, (cpu)->tag())
216
217
218/* IRQ callback to be called by CPU cores when an IRQ is actually taken */
219#define IRQ_CALLBACK(func)            int func(running_device *device, int irqline)
220
221
222/* CPU interface functions */
223#define CPU_GET_INFO_NAME(name)         cpu_get_info_##name
224#define CPU_GET_INFO(name)            void CPU_GET_INFO_NAME(name)(const device_config *devconfig, running_device *device, UINT32 state, cpuinfo *info)
225#define CPU_GET_INFO_CALL(name)         CPU_GET_INFO_NAME(name)(devconfig, device, state, info)
226
227#define CPU_SET_INFO_NAME(name)         cpu_set_info_##name
228#define CPU_SET_INFO(name)            void CPU_SET_INFO_NAME(name)(running_device *device, UINT32 state, cpuinfo *info)
229#define CPU_SET_INFO_CALL(name)         CPU_SET_INFO_NAME(name)(device, state, info)
230
231#define CPU_INIT_NAME(name)            cpu_init_##name
232#define CPU_INIT(name)               void CPU_INIT_NAME(name)(running_device *device, cpu_irq_callback irqcallback)
233#define CPU_INIT_CALL(name)            CPU_INIT_NAME(name)(device, irqcallback)
234
235#define CPU_RESET_NAME(name)         cpu_reset_##name
236#define CPU_RESET(name)               void CPU_RESET_NAME(name)(running_device *device)
237#define CPU_RESET_CALL(name)         CPU_RESET_NAME(name)(device)
238
239#define CPU_EXIT_NAME(name)            cpu_exit_##name
240#define CPU_EXIT(name)               void CPU_EXIT_NAME(name)(running_device *device)
241#define CPU_EXIT_CALL(name)            CPU_EXIT_NAME(name)(device)
242
243#define CPU_EXECUTE_NAME(name)         cpu_execute_##name
244#define CPU_EXECUTE(name)            int CPU_EXECUTE_NAME(name)(running_device *device, int cycles)
245#define CPU_EXECUTE_CALL(name)         CPU_EXECUTE_NAME(name)(device, cycles)
246
247#define CPU_BURN_NAME(name)            cpu_burn_##name
248#define CPU_BURN(name)               void CPU_BURN_NAME(name)(running_device *device, int cycles)
249#define CPU_BURN_CALL(name)            CPU_BURN_NAME(name)(device, cycles)
250
251#define CPU_TRANSLATE_NAME(name)      cpu_translate_##name
252#define CPU_TRANSLATE(name)            int CPU_TRANSLATE_NAME(name)(running_device *device, int space, int intention, offs_t *address)
253#define CPU_TRANSLATE_CALL(name)      CPU_TRANSLATE_NAME(name)(device, space, intention, address)
254
255#define CPU_READ_NAME(name)            cpu_read_##name
256#define CPU_READ(name)               int CPU_READ_NAME(name)(running_device *device, int space, UINT32 offset, int size, UINT64 *value)
257#define CPU_READ_CALL(name)            CPU_READ_NAME(name)(device, space, offset, size, value)
258
259#define CPU_WRITE_NAME(name)         cpu_write_##name
260#define CPU_WRITE(name)               int CPU_WRITE_NAME(name)(running_device *device, int space, UINT32 offset, int size, UINT64 value)
261#define CPU_WRITE_CALL(name)         CPU_WRITE_NAME(name)(device, space, offset, size, value)
262
263#define CPU_READOP_NAME(name)         cpu_readop_##name
264#define CPU_READOP(name)            int CPU_READOP_NAME(name)(running_device *device, UINT32 offset, int size, UINT64 *value)
265#define CPU_READOP_CALL(name)         CPU_READOP_NAME(name)(device, offset, size, value)
266
267#define CPU_DEBUG_INIT_NAME(name)      cpu_debug_init_##name
268#define CPU_DEBUG_INIT(name)         void CPU_DEBUG_INIT_NAME(name)(running_device *device)
269#define CPU_DEBUG_INIT_CALL(name)      CPU_DEBUG_INIT_NAME(name)(device)
270
271#define CPU_DISASSEMBLE_NAME(name)      cpu_disassemble_##name
272#define CPU_DISASSEMBLE(name)         offs_t CPU_DISASSEMBLE_NAME(name)(running_device *device, char *buffer, offs_t pc, const UINT8 *oprom, const UINT8 *opram, int options)
273#define CPU_DISASSEMBLE_CALL(name)      CPU_DISASSEMBLE_NAME(name)(device, buffer, pc, oprom, opram, options)
274
275#define CPU_VALIDITY_CHECK_NAME(name)   cpu_validity_check_##name
276#define CPU_VALIDITY_CHECK(name)      int CPU_VALIDITY_CHECK_NAME(name)(const game_driver *driver, const void *config)
277#define CPU_VALIDITY_CHECK_CALL(name)   CPU_VALIDITY_CHECK_NAME(name)(driver, config)
278
279#define CPU_IMPORT_STATE_NAME(name)      cpu_state_import_##name
280#define CPU_IMPORT_STATE(name)         void CPU_IMPORT_STATE_NAME(name)(running_device *device, void *baseptr, const cpu_state_entry *entry)
281#define CPU_IMPORT_STATE_CALL(name)      CPU_IMPORT_STATE_NAME(name)(device, baseptr, entry)
282
283#define CPU_EXPORT_STATE_NAME(name)      cpu_state_export_##name
284#define CPU_EXPORT_STATE(name)         void CPU_EXPORT_STATE_NAME(name)(running_device *device, void *baseptr, const cpu_state_entry *entry)
285#define CPU_EXPORT_STATE_CALL(name)      CPU_EXPORT_STATE_NAME(name)(device, baseptr, entry)
286
287#define CPU_IMPORT_STRING_NAME(name)   cpu_string_import_##name
288#define CPU_IMPORT_STRING(name)         void CPU_IMPORT_STRING_NAME(name)(running_device *device, void *baseptr, const cpu_state_entry *entry, char *string)
289#define CPU_IMPORT_STRING_CALL(name)   CPU_IMPORT_STRING_NAME(name)(device, baseptr, entry, string)
290
291#define CPU_EXPORT_STRING_NAME(name)   cpu_string_export_##name
292#define CPU_EXPORT_STRING(name)         void CPU_EXPORT_STRING_NAME(name)(running_device *device, void *baseptr, const cpu_state_entry *entry, char *string)
293#define CPU_EXPORT_STRING_CALL(name)   CPU_EXPORT_STRING_NAME(name)(device, baseptr, entry, string)
294
295
296/* base macro for defining CPU state entries */
297#define CPU_STATE_ENTRY(_index, _symbol, _format, _struct, _member, _datamask, _validmask, _flags) \
298   { _index, _validmask, offsetof(_struct, _member), _datamask, sizeof(((_struct *)0)->_member), _flags, _symbol, _format },
299
300
301/* helpers for accessing common CPU state */
302#define cpu_get_context_size(cpu)         (cpu)->get_config_int(CPUINFO_INT_CONTEXT_SIZE)
303#define cpu_get_input_lines(cpu)         (cpu)->get_config_int(CPUINFO_INT_INPUT_LINES)
304#define cpu_get_output_lines(cpu)         (cpu)->get_config_int(CPUINFO_INT_OUTPUT_LINES)
305#define cpu_get_default_irq_vector(cpu)      (cpu)->get_config_int(CPUINFO_INT_DEFAULT_IRQ_VECTOR)
306#define cpu_get_clock_multiplier(cpu)      (cpu)->get_config_int(CPUINFO_INT_CLOCK_MULTIPLIER)
307#define cpu_get_clock_divider(cpu)         (cpu)->get_config_int(CPUINFO_INT_CLOCK_DIVIDER)
308#define cpu_get_min_opcode_bytes(cpu)      (cpu)->get_config_int(CPUINFO_INT_MIN_INSTRUCTION_BYTES)
309#define cpu_get_max_opcode_bytes(cpu)      (cpu)->get_config_int(CPUINFO_INT_MAX_INSTRUCTION_BYTES)
310#define cpu_get_min_cycles(cpu)            (cpu)->get_config_int(CPUINFO_INT_MIN_CYCLES)
311#define cpu_get_max_cycles(cpu)            (cpu)->get_config_int(CPUINFO_INT_MAX_CYCLES)
312#define cpu_get_logaddr_width(cpu, space)   (cpu)->get_config_int(CPUINFO_INT_LOGADDR_WIDTH + (space))
313#define cpu_get_page_shift(cpu, space)      (cpu)->get_config_int(CPUINFO_INT_PAGE_SHIFT + (space))
314#define cpu_get_reg(cpu, reg)            (cpu)->get_runtime_int(CPUINFO_INT_REGISTER + (reg))
315#define   cpu_get_previouspc(cpu)            ((offs_t)cpu_get_reg(cpu, REG_GENPCBASE))
316#define   cpu_get_pc(cpu)                  ((offs_t)cpu_get_reg(cpu, REG_GENPC))
317#define   cpu_get_sp(cpu)                  cpu_get_reg(cpu, REG_GENSP)
318#define cpu_get_icount_ptr(cpu)            (int *)(cpu)->get_runtime_ptr(CPUINFO_PTR_INSTRUCTION_COUNTER)
319#define cpu_get_state_table(cpu)         (const cpu_state_table *)(cpu)->get_runtime_ptr(CPUINFO_PTR_STATE_TABLE)
320#define cpu_get_flags_string(cpu)         (cpu)->get_runtime_string(CPUINFO_STR_FLAGS)
321#define cpu_get_irq_string(cpu, irq)      (cpu)->get_runtime_string(CPUINFO_STR_IRQ_STATE + (irq))
322#define cpu_get_reg_string(cpu, reg)      (cpu)->get_runtime_string(CPUINFO_STR_REGISTER + (reg))
323
324#define cpu_set_reg(cpu, reg, val)         cpu_set_info(cpu, CPUINFO_INT_REGISTER + (reg), (val))
325
326
327
328/***************************************************************************
329    TYPE DEFINITIONS
330***************************************************************************/
331
332/* forward declaration of types */
333typedef union _cpuinfo cpuinfo;
334typedef struct _cpu_state_entry cpu_state_entry;
335
336
337/* IRQ callback to be called by CPU cores when an IRQ is actually taken */
338typedef int (*cpu_irq_callback)(running_device *device, int irqnum);
339
340
341/* CPU interface functions */
342typedef void (*cpu_get_info_func)(const device_config *devconfig, running_device *device, UINT32 state, cpuinfo *info);
343typedef void (*cpu_set_info_func)(running_device *device, UINT32 state, cpuinfo *info);
344typedef void (*cpu_init_func)(running_device *device, cpu_irq_callback irqcallback);
345typedef void (*cpu_reset_func)(running_device *device);
346typedef void (*cpu_exit_func)(running_device *device);
347typedef int   (*cpu_execute_func)(running_device *device, int cycles);
348typedef void (*cpu_burn_func)(running_device *device, int cycles);
349typedef int   (*cpu_translate_func)(running_device *device, int space, int intention, offs_t *address);
350typedef int   (*cpu_read_func)(running_device *device, int space, UINT32 offset, int size, UINT64 *value);
351typedef int   (*cpu_write_func)(running_device *device, int space, UINT32 offset, int size, UINT64 value);
352typedef int   (*cpu_readop_func)(running_device *device, UINT32 offset, int size, UINT64 *value);
353typedef void (*cpu_debug_init_func)(running_device *device);
354typedef offs_t (*cpu_disassemble_func)(running_device *device, char *buffer, offs_t pc, const UINT8 *oprom, const UINT8 *opram, int options);
355typedef int (*cpu_validity_check_func)(const game_driver *driver, const void *config);
356typedef void (*cpu_state_io_func)(running_device *device, void *baseptr, const cpu_state_entry *entry);
357typedef void (*cpu_string_io_func)(running_device *device, void *baseptr, const cpu_state_entry *entry, char *string);
358
359
360/* a cpu_type is just a pointer to the CPU's get_info function */
361typedef cpu_get_info_func cpu_type;
362
363
364/* structure describing a single item of exposed CPU state */
365struct _cpu_state_entry
366{
367   UINT32               index;                  /* state index this entry applies to */
368   UINT32               validmask;               /* mask for which CPU subtypes this entry is valid */
369   FPTR               dataoffs;               /* offset to the data, relative to the baseptr */
370   UINT64               mask;                  /* mask applied to the data */
371   UINT8               datasize;               /* size of the data item in memory */
372   UINT8               flags;                  /* flags */
373   const char *         symbol;                  /* symbol for display; all lower-case version for expressions */
374   const char *         format;                  /* supported formats */
375};
376
377
378/* structure describing a table of exposed CPU state */
379typedef struct _cpu_state_table cpu_state_table;
380struct _cpu_state_table
381{
382   void *               baseptr;               /* pointer to the base of state (offsets are relative to this) */
383   UINT32               subtypemask;            /* mask of subtypes that apply to this CPU */
384   UINT32               entrycount;               /* number of entries */
385   const cpu_state_entry *   entrylist;               /* array of entries */
386};
387
388
389/* cpuinfo union used to pass data to/from the get_info/set_info functions */
390union _cpuinfo
391{
392   INT64               i;                     /* generic integers */
393   void *               p;                     /* generic pointers */
394   genf *              f;                     /* generic function pointers */
395   char *               s;                     /* generic strings */
396
397   cpu_set_info_func      setinfo;               /* CPUINFO_FCT_SET_INFO */
398   cpu_init_func         init;                  /* CPUINFO_FCT_INIT */
399   cpu_reset_func         reset;                  /* CPUINFO_FCT_RESET */
400   cpu_exit_func         exit;                  /* CPUINFO_FCT_EXIT */
401   cpu_execute_func      execute;               /* CPUINFO_FCT_EXECUTE */
402   cpu_burn_func         burn;                  /* CPUINFO_FCT_BURN */
403   cpu_translate_func      translate;               /* CPUINFO_FCT_TRANSLATE */
404   cpu_read_func         read;                  /* CPUINFO_FCT_READ */
405   cpu_write_func         write;                  /* CPUINFO_FCT_WRITE */
406   cpu_readop_func         readop;                  /* CPUINFO_FCT_READOP */
407   cpu_debug_init_func      debug_init;               /* CPUINFO_FCT_DEBUG_INIT */
408   cpu_disassemble_func   disassemble;            /* CPUINFO_FCT_DISASSEMBLE */
409   cpu_validity_check_func   validity_check;            /* CPUINFO_FCT_VALIDITY_CHECK */
410   cpu_state_io_func      import_state;            /* CPUINFO_FCT_IMPORT_STATE */
411   cpu_state_io_func      export_state;            /* CPUINFO_FCT_EXPORT_STATE */
412   cpu_string_io_func      import_string;            /* CPUINFO_FCT_IMPORT_STRING */
413   cpu_string_io_func      export_string;            /* CPUINFO_FCT_EXPORT_STRING */
414   int *               icount;                  /* CPUINFO_PTR_INSTRUCTION_COUNTER */
415   const cpu_state_table *   state_table;            /* CPUINFO_PTR_STATE_TABLE */
416   const addrmap8_token *   internal_map8;            /* DEVINFO_PTR_INTERNAL_MEMORY_MAP */
417   const addrmap16_token *   internal_map16;            /* DEVINFO_PTR_INTERNAL_MEMORY_MAP */
418   const addrmap32_token *   internal_map32;            /* DEVINFO_PTR_INTERNAL_MEMORY_MAP */
419   const addrmap64_token *   internal_map64;            /* DEVINFO_PTR_INTERNAL_MEMORY_MAP */
420   const addrmap8_token *   default_map8;            /* DEVINFO_PTR_DEFAULT_MEMORY_MAP */
421   const addrmap16_token *   default_map16;            /* DEVINFO_PTR_DEFAULT_MEMORY_MAP */
422   const addrmap32_token *   default_map32;            /* DEVINFO_PTR_DEFAULT_MEMORY_MAP */
423   const addrmap64_token *   default_map64;            /* DEVINFO_PTR_DEFAULT_MEMORY_MAP */
424};
425
426
427void cpu_set_info(running_device *device, UINT32 state, UINT64 value);
428
429#endif   /* __CPUINTRF_H__ */
src/emu/cpuexec.c
r8415r8416
1/***************************************************************************
2
3    cpuexec.c
4
5    Core multi-CPU execution engine.
6
7    Copyright Nicola Salmoria and the MAME Team.
8    Visit http://mamedev.org for licensing and usage restrictions.
9
10***************************************************************************/
11
12#include "emu.h"
13#include "profiler.h"
14#include "debugger.h"
15
16
17/***************************************************************************
18    DEBUGGING
19***************************************************************************/
20
21#define VERBOSE 0
22
23#define LOG(x)   do { if (VERBOSE) logerror x; } while (0)
24
25
26
27/***************************************************************************
28    CONSTANTS
29***************************************************************************/
30
31/* internal trigger IDs */
32enum
33{
34   TRIGGER_INT       = -2000,
35   TRIGGER_YIELDTIME   = -3000,
36   TRIGGER_SUSPENDTIME = -4000
37};
38
39
40
41/***************************************************************************
42    TYPE DEFINITIONS
43***************************************************************************/
44
45/* internal information about the state of inputs */
46typedef struct _cpu_input_data cpu_input_data;
47struct _cpu_input_data
48{
49   INT32         vector;            /* most recently written vector */
50   INT32         curvector;         /* most recently processed vector */
51   UINT8         curstate;         /* most recently processed state */
52   INT32         queue[MAX_INPUT_EVENTS]; /* queue of pending events */
53   int            qindex;            /* index within the queue */
54};
55
56
57/* internal data hanging off of the classtoken */
58typedef struct _cpu_class_data cpu_class_data;
59struct _cpu_class_data
60{
61   /* execution lists */
62   running_device *device;               /* pointer back to our device */
63   cpu_class_data *next;               /* pointer to the next CPU to execute, in order */
64   cpu_execute_func execute;            /* execute function pointer */
65
66   /* cycle counting and executing */
67   int            profiler;            /* profiler tag */
68   int *         icount;               /* pointer to the icount */
69   int          cycles_running;         /* number of cycles we are executing */
70   int            cycles_stolen;         /* number of cycles we artificially stole */
71
72   /* input states and IRQ callbacks */
73   cpu_irq_callback driver_irq;         /* driver-specific IRQ callback */
74   cpu_input_data   input[MAX_INPUT_LINES]; /* data about inputs */
75
76   /* suspend states */
77   UINT8         suspend;            /* suspend reason mask (0 = not suspended) */
78   UINT8         nextsuspend;         /* pending suspend reason mask */
79   UINT8         eatcycles;            /* true if we eat cycles while suspended */
80   UINT8         nexteatcycles;         /* pending value */
81   INT32         trigger;            /* pending trigger to release a trigger suspension */
82   INT32         inttrigger;            /* interrupt trigger index */
83
84   /* clock and timing information */
85   UINT64         totalcycles;         /* total CPU cycles executed */
86   attotime      localtime;            /* local time, relative to the timer system's global time */
87   INT32         clock;               /* current active clock */
88   double         clockscale;            /* current active clock scale factor */
89   INT32         divisor;            /* 32-bit attoseconds_per_cycle divisor */
90   UINT8         divshift;            /* right shift amount to fit the divisor into 32 bits */
91   emu_timer *      timedint_timer;         /* reference to this CPU's periodic interrupt timer */
92   UINT32         cycles_per_second;      /* cycles per second, adjusted for multipliers */
93   attoseconds_t   attoseconds_per_cycle;   /* attoseconds per adjusted clock cycle */
94
95   /* internal state reflection */
96   const cpu_state_table *state;         /* pointer to the base table */
97   const cpu_state_entry *regstate[MAX_REGS];/* pointer to the state entry for each register */
98
99   /* these below are hacks to support multiple interrupts per frame */
100   INT32         iloops;             /* number of interrupts remaining this frame */
101   emu_timer *      partial_frame_timer;   /* the timer that triggers partial frame interrupts */
102   attotime      partial_frame_period;   /* the length of one partial frame for interrupt purposes */
103};
104
105
106/* global data stored in the machine */
107/* In mame.h: typedef struct _cpuexec_private cpuexec_private; */
108struct _cpuexec_private
109{
110   running_device *executingcpu;         /* pointer to the currently executing CPU */
111   cpu_class_data *executelist;         /* execution list; suspended CPUs are at the back */
112   char         statebuf[256];         /* string buffer containing state description */
113};
114
115
116
117/***************************************************************************
118    FUNCTION PROTOTYPES
119***************************************************************************/
120
121static void update_clock_information(running_device *device);
122static void compute_perfect_interleave(running_machine *machine);
123static void on_vblank(running_device *device, void *param, int vblank_state);
124static TIMER_CALLBACK( trigger_partial_frame_interrupt );
125static TIMER_CALLBACK( trigger_periodic_interrupt );
126static TIMER_CALLBACK( triggertime_callback );
127static TIMER_CALLBACK( empty_event_queue );
128static IRQ_CALLBACK( standard_irq_callback );
129static void register_save_states(running_device *device);
130static void rebuild_execute_list(running_machine *machine);
131static UINT64 get_register_value(running_device *device, void *baseptr, const cpu_state_entry *entry);
132static void set_register_value(running_device *device, void *baseptr, const cpu_state_entry *entry, UINT64 value);
133static void get_register_string_value(running_device *device, void *baseptr, const cpu_state_entry *entry, char *dest);
134#ifdef UNUSED_FUNCTION
135static int get_register_string_max_width(running_device *device, void *baseptr, const cpu_state_entry *entry);
136#endif
137
138
139
140/***************************************************************************
141    MACROS
142***************************************************************************/
143
144/* these are macros to ensure inlining in cpuexec_timeslice */
145#define ATTOTIME_LT(a,b)      ((a).seconds < (b).seconds || ((a).seconds == (b).seconds && (a).attoseconds < (b).attoseconds))
146#define ATTOTIME_NORMALIZE(a)   do { if ((a).attoseconds >= ATTOSECONDS_PER_SECOND) { (a).seconds++; (a).attoseconds -= ATTOSECONDS_PER_SECOND; } } while (0)
147
148
149
150/***************************************************************************
151    INLINE FUNCTIONS
152***************************************************************************/
153
154/*-------------------------------------------------
155    get_class_data - return a pointer to the
156    class data
157-------------------------------------------------*/
158
159INLINE cpu_class_data *get_class_data(running_device *device)
160{
161   assert(device != NULL);
162   assert(device->devclass == DEVICE_CLASS_CPU_CHIP);
163   assert(device->token != NULL);
164   return (cpu_class_data *)cpu_get_class_header(device) - 1;
165}
166
167
168/*-------------------------------------------------
169    get_minimum_quantum - return the minimum
170    quantum required for a given CPU device
171-------------------------------------------------*/
172
173INLINE attoseconds_t get_minimum_quantum(running_device *device)
174{
175   attoseconds_t basetick = 0;
176
177   /* fetch the base clock from the classdata if present */
178   if (device->token != NULL)
179      basetick = get_class_data(device)->attoseconds_per_cycle;
180
181   /* otherwise compute it from the raw data */
182   if (basetick == 0)
183   {
184      UINT32 baseclock = (UINT64)device->clock * cpu_get_clock_multiplier(device) / cpu_get_clock_divider(device);
185      basetick = HZ_TO_ATTOSECONDS(baseclock);
186   }
187
188   /* apply the minimum cycle count */
189   return basetick * cpu_get_min_cycles(device);
190}
191
192
193/*-------------------------------------------------
194    suspend_until_trigger - suspend execution
195    until the given trigger fires
196-------------------------------------------------*/
197
198INLINE void suspend_until_trigger(running_device *device, int trigger, int eatcycles)
199{
200   cpu_class_data *classdata = get_class_data(device);
201
202   /* suspend the CPU immediately if it's not already */
203   cpu_suspend(device, SUSPEND_REASON_TRIGGER, eatcycles);
204
205   /* set the trigger */
206   classdata->trigger = trigger;
207}
208
209
210
211/***************************************************************************
212    CORE CPU EXECUTION
213***************************************************************************/
214
215/*-------------------------------------------------
216    cpuexec_init - initialize internal states of
217    all CPUs
218-------------------------------------------------*/
219
220void cpuexec_init(running_machine *machine)
221{
222   attotime min_quantum;
223
224   /* allocate global state */
225   machine->cpuexec_data = auto_alloc_clear(machine, cpuexec_private);
226
227   /* set the core scheduling quantum */
228   min_quantum = machine->config->minimum_quantum;
229   if (attotime_compare(min_quantum, attotime_zero) == 0)
230      min_quantum = ATTOTIME_IN_HZ(60);
231   if (machine->config->perfect_cpu_quantum != NULL)
232   {
233      running_device *cpu = machine->device(machine->config->perfect_cpu_quantum);
234      attotime cpu_quantum;
235
236      if (cpu == NULL)
237         fatalerror("CPU '%s' specified for perfect interleave is not present!", machine->config->perfect_cpu_quantum);
238      cpu_quantum = attotime_make(0, get_minimum_quantum(cpu));
239      min_quantum = attotime_min(cpu_quantum, min_quantum);
240   }
241   assert(min_quantum.seconds == 0);
242   timer_add_scheduling_quantum(machine, min_quantum.attoseconds, attotime_never);
243}
244
245
246/*-------------------------------------------------
247    cpuexec_timeslice - execute all CPUs for a
248    single timeslice
249-------------------------------------------------*/
250
251void cpuexec_timeslice(running_machine *machine)
252{
253   int call_debugger = ((machine->debug_flags & DEBUG_FLAG_ENABLED) != 0);
254   timer_execution_state *timerexec = timer_get_execution_state(machine);
255   cpuexec_private *global = machine->cpuexec_data;
256   int ran;
257
258   /* build the execution list if we don't have one yet */
259   if (global->executelist == NULL)
260      rebuild_execute_list(machine);
261
262   /* loop until we hit the next timer */
263   while (ATTOTIME_LT(timerexec->basetime, timerexec->nextfire))
264   {
265      cpu_class_data *classdata;
266      UINT32 suspendchanged;
267      attotime target;
268
269      /* by default, assume our target is the end of the next quantum */
270      target.seconds = timerexec->basetime.seconds;
271      target.attoseconds = timerexec->basetime.attoseconds + timerexec->curquantum;
272      ATTOTIME_NORMALIZE(target);
273
274      /* however, if the next timer is going to fire before then, override */
275      assert(attotime_sub(timerexec->nextfire, target).seconds <= 0);
276      if (ATTOTIME_LT(timerexec->nextfire, target))
277         target = timerexec->nextfire;
278
279      LOG(("------------------\n"));
280      LOG(("cpu_timeslice: target = %s\n", attotime_string(target, 9)));
281
282      /* apply pending suspension changes */
283      suspendchanged = 0;
284      for (classdata = global->executelist; classdata != NULL; classdata = classdata->next)
285      {
286         suspendchanged |= (classdata->suspend ^ classdata->nextsuspend);
287         classdata->suspend = classdata->nextsuspend;
288         classdata->nextsuspend &= ~SUSPEND_REASON_TIMESLICE;
289         classdata->eatcycles = classdata->nexteatcycles;
290      }
291
292      /* recompute the execute list if any CPUs changed their suspension state */
293      if (suspendchanged != 0)
294         rebuild_execute_list(machine);
295
296      /* loop over non-suspended CPUs */
297      for (classdata = global->executelist; classdata != NULL; classdata = classdata->next)
298      {
299         /* only process if our target is later than the CPU's current time (coarse check) */
300         if (target.seconds >= classdata->localtime.seconds)
301         {
302            attoseconds_t delta, actualdelta;
303
304            /* compute how many attoseconds to execute this CPU */
305            delta = target.attoseconds - classdata->localtime.attoseconds;
306            if (delta < 0 && target.seconds > classdata->localtime.seconds)
307               delta += ATTOSECONDS_PER_SECOND;
308            assert(delta == attotime_to_attoseconds(attotime_sub(target, classdata->localtime)));
309
310            /* if we have enough for at least 1 cycle, do the math */
311            if (delta >= classdata->attoseconds_per_cycle)
312            {
313               /* compute how many cycles we want to execute */
314               ran = classdata->cycles_running = divu_64x32((UINT64)delta >> classdata->divshift, classdata->divisor);
315               LOG(("  cpu '%s': %d cycles\n", classdata->device->tag(), classdata->cycles_running));
316
317               /* if we're not suspended, actually execute */
318               if (classdata->suspend == 0)
319               {
320                  profiler_mark_start(classdata->profiler);
321
322                  /* note that this global variable cycles_stolen can be modified */
323                  /* via the call to cpu_execute */
324                  classdata->cycles_stolen = 0;
325                  global->executingcpu = classdata->device;
326                  *classdata->icount = classdata->cycles_running;
327                  if (!call_debugger)
328                     ran = (*classdata->execute)(classdata->device, classdata->cycles_running);
329                  else
330                  {
331                     debugger_start_cpu_hook(classdata->device, target);
332                     ran = (*classdata->execute)(classdata->device, classdata->cycles_running);
333                     debugger_stop_cpu_hook(classdata->device);
334                  }
335
336                  /* adjust for any cycles we took back */
337                  assert(ran >= classdata->cycles_stolen);
338                  ran -= classdata->cycles_stolen;
339                  profiler_mark_end();
340               }
341
342               /* account for these cycles */
343               classdata->totalcycles += ran;
344
345               /* update the local time for this CPU */
346               actualdelta = classdata->attoseconds_per_cycle * ran;
347               classdata->localtime.attoseconds += actualdelta;
348               ATTOTIME_NORMALIZE(classdata->localtime);
349               LOG(("         %d ran, %d total, time = %s\n", ran, (INT32)classdata->totalcycles, attotime_string(classdata->localtime, 9)));
350
351               /* if the new local CPU time is less than our target, move the target up */
352               if (ATTOTIME_LT(classdata->localtime, target))
353               {
354                  assert(attotime_compare(classdata->localtime, target) < 0);
355                  target = classdata->localtime;
356
357                  /* however, if this puts us before the base, clamp to the base as a minimum */
358                  if (ATTOTIME_LT(target, timerexec->basetime))
359                  {
360                     assert(attotime_compare(target, timerexec->basetime) < 0);
361                     target = timerexec->basetime;
362                  }
363                  LOG(("         (new target)\n"));
364               }
365            }
366         }
367      }
368      global->executingcpu = NULL;
369
370      /* update the base time */
371      timerexec->basetime = target;
372   }
373
374   /* execute timers */
375   timer_execute_timers(machine);
376}
377
378
379/*-------------------------------------------------
380    cpuexec_boost_interleave - temporarily boosts
381    the interleave factor
382-------------------------------------------------*/
383
384void cpuexec_boost_interleave(running_machine *machine, attotime timeslice_time, attotime boost_duration)
385{
386   /* ignore timeslices > 1 second */
387   if (timeslice_time.seconds > 0)
388      return;
389   timer_add_scheduling_quantum(machine, timeslice_time.attoseconds, boost_duration);
390}
391
392
393
394/***************************************************************************
395    GLOBAL HELPERS
396***************************************************************************/
397
398/*-------------------------------------------------
399    cpuexec_abort_timeslice - abort execution
400    for the current timeslice
401-------------------------------------------------*/
402
403void cpuexec_abort_timeslice(running_machine *machine)
404{
405   running_device *executingcpu = machine->cpuexec_data->executingcpu;
406   if (executingcpu != NULL)
407      cpu_abort_timeslice(executingcpu);
408}
409
410
411/*-------------------------------------------------
412    cpuexec_describe_context - return a string
413    describing which CPUs are currently executing
414    and their PC
415-------------------------------------------------*/
416
417const char *cpuexec_describe_context(running_machine *machine)
418{
419   cpuexec_private *global = machine->cpuexec_data;
420   running_device *executingcpu = global->executingcpu;
421
422   /* if we have an executing CPU, output data */
423   if (executingcpu != NULL)
424   {
425      const address_space *space = cpu_get_address_space(executingcpu, ADDRESS_SPACE_PROGRAM);
426      sprintf(global->statebuf, "'%s' (%s)", executingcpu->tag(), core_i64_hex_format(cpu_get_pc(executingcpu), space->logaddrchars));
427   }
428   else
429      strcpy(global->statebuf, "(no context)");
430
431   return global->statebuf;
432}
433
434
435
436/***************************************************************************
437    CPU DEVICE INTERFACE
438***************************************************************************/
439
440/*-------------------------------------------------
441    device_start_cpu - device start callback
442-------------------------------------------------*/
443
444static DEVICE_START( cpu )
445{
446   int index = cpu_get_index(device);
447   cpu_class_header *header;
448   cpu_class_data *classdata;
449   const cpu_config *config;
450   cpu_init_func init;
451   int num_regs;
452   int line;
453
454   /* validate some basic stuff */
455   assert(device != NULL);
456   assert(device->baseconfig().inline_config != NULL);
457   assert(device->machine != NULL);
458   assert(device->machine->config != NULL);
459
460   /* get pointers to our data */
461   config = (const cpu_config *)device->baseconfig().inline_config;
462   header = cpu_get_class_header(device);
463   classdata = get_class_data(device);
464
465   /* build the header */
466   header->debug = NULL;
467   header->set_info = (cpu_set_info_func)device->get_config_fct(CPUINFO_FCT_SET_INFO);
468
469   /* fill in the input states and IRQ callback information */
470   for (line = 0; line < ARRAY_LENGTH(classdata->input); line++)
471   {
472      cpu_input_data *inputline = &classdata->input[line];
473      /* vector and curvector are initialized later */
474      inputline->curstate = CLEAR_LINE;
475      inputline->qindex = 0;
476   }
477
478   /* fill in the suspend states */
479   classdata->device = device;
480   classdata->execute = (cpu_execute_func)device->get_config_fct(CPUINFO_FCT_EXECUTE);
481   classdata->profiler = index + PROFILER_CPU_FIRST;
482   classdata->suspend = SUSPEND_REASON_RESET;
483   classdata->inttrigger = index + TRIGGER_INT;
484
485   /* fill in the clock and timing information */
486   classdata->clock = (UINT64)device->clock * cpu_get_clock_multiplier(device) / cpu_get_clock_divider(device);
487   classdata->clockscale = 1.0;
488
489   /* allocate timers if we need them */
490   if (config->vblank_interrupts_per_frame > 1)
491      classdata->partial_frame_timer = timer_alloc(device->machine, trigger_partial_frame_interrupt, (void *)device);
492   if (config->timed_interrupt_period != 0)
493      classdata->timedint_timer = timer_alloc(device->machine, trigger_periodic_interrupt, (void *)device);
494
495   /* initialize this CPU */
496   num_regs = state_save_get_reg_count(device->machine);
497   init = (cpu_init_func)device->get_config_fct(CPUINFO_FCT_INIT);
498   (*init)(device, standard_irq_callback);
499   num_regs = state_save_get_reg_count(device->machine) - num_regs;
500
501   /* fetch post-initialization data */
502   classdata->icount = cpu_get_icount_ptr(device);
503   for (line = 0; line < ARRAY_LENGTH(classdata->input); line++)
504   {
505      cpu_input_data *inputline = &classdata->input[line];
506      inputline->vector = cpu_get_default_irq_vector(device);
507      inputline->curvector = inputline->vector;
508   }
509   update_clock_information(device);
510
511   /* fetch information about the CPU states */
512   classdata->state = cpu_get_state_table(device);
513   if (classdata->state != NULL)
514   {
515      int stateindex;
516
517      /* loop over all states specified, and work with any that apply */
518      for (stateindex = 0; stateindex < classdata->state->entrycount; stateindex++)
519      {
520         const cpu_state_entry *entry = &classdata->state->entrylist[stateindex];
521         if (entry->validmask == 0 || (entry->validmask & classdata->state->subtypemask) != 0)
522         {
523            assert(entry->index < MAX_REGS);
524            assert(classdata->regstate[entry->index] == NULL);
525            classdata->regstate[entry->index] = entry;
526         }
527      }
528   }
529
530   /* if no state registered for saving, we can't save */
531   if (num_regs == 0)
532   {
533      logerror("CPU '%s' did not register any state to save!\n", device->tag());
534      if (device->machine->gamedrv->flags & GAME_SUPPORTS_SAVE)
535         fatalerror("CPU '%s' did not register any state to save!", device->tag());
536   }
537
538   /* register some internal states as well */
539   register_save_states(device);
540}
541
542
543/*-------------------------------------------------
544    device_reset_cpu - device reset callback
545-------------------------------------------------*/
546
547static DEVICE_RESET( cpu )
548{
549   cpu_class_data *classdata = get_class_data(device);
550   const cpu_config *config = (const cpu_config *)device->baseconfig().inline_config;
551   cpu_reset_func reset;
552   int line;
553
554   /* enable all CPUs (except for disabled CPUs) */
555   if (!(config->flags & CPU_DISABLE))
556      cpu_resume(device, SUSPEND_ANY_REASON);
557   else
558      cpu_suspend(device, SUSPEND_REASON_DISABLE, 1);
559
560   /* reset the total number of cycles */
561   classdata->totalcycles = 0;
562
563   /* then reset the CPU directly */
564   reset = (cpu_reset_func)device->get_config_fct(CPUINFO_FCT_RESET);
565   if (reset != NULL)
566      (*reset)(device);
567
568   /* reset the interrupt vectors and queues */
569   for (line = 0; line < ARRAY_LENGTH(classdata->input); line++)
570   {
571      cpu_input_data *inputline = &classdata->input[line];
572      inputline->vector = cpu_get_default_irq_vector(device);
573      inputline->qindex = 0;
574   }
575
576   /* reconfingure VBLANK interrupts */
577   if (config->vblank_interrupts_per_frame > 0 || config->vblank_interrupt_screen != NULL)
578   {
579      running_device *screen;
580
581      /* get the screen that will trigger the VBLANK */
582
583      /* new style - use screen tag directly */
584      if (config->vblank_interrupt_screen != NULL)
585         screen = device->machine->device(config->vblank_interrupt_screen);
586
587      /* old style 'hack' setup - use screen #0 */
588      else
589         screen = video_screen_first(device->machine);
590
591      assert(screen != NULL);
592      video_screen_register_vblank_callback(screen, on_vblank, NULL);
593   }
594
595   /* reconfigure periodic interrupts */
596   if (config->timed_interrupt_period != 0)
597   {
598      attotime timedint_period = UINT64_ATTOTIME_TO_ATTOTIME(config->timed_interrupt_period);
599      assert(classdata->timedint_timer != NULL);
600      timer_adjust_periodic(classdata->timedint_timer, timedint_period, 0, timedint_period);
601   }
602}
603
604
605/*-------------------------------------------------
606    device_stop_cpu - device stop callback
607-------------------------------------------------*/
608
609static DEVICE_STOP( cpu )
610{
611   cpu_exit_func exit;
612
613   /* call the CPU's exit function if present */
614   exit = (cpu_exit_func)device->get_config_fct(CPUINFO_FCT_EXIT);
615   if (exit != NULL)
616      (*exit)(device);
617}
618
619
620/*-------------------------------------------------
621    cpu_set_info - device set info callback
622-------------------------------------------------*/
623
624void cpu_set_info(running_device *device, UINT32 state, UINT64 value)
625{
626   cpu_class_header *header = cpu_get_class_header(device);
627   cpu_set_info_func set_info;
628   cpuinfo cinfo;
629
630   /* if we are live and have a header, save ourself a call */
631   if (header != NULL)
632      set_info = header->set_info;
633   else
634      set_info = (cpu_set_info_func)device->get_config_fct(CPUINFO_FCT_SET_INFO);
635
636   switch (state)
637   {
638      /* no parameters to set */
639
640      default:
641         /* if we have a state pointer, we can handle some stuff for free */
642         if (device->token != NULL)
643         {
644            const cpu_class_data *classdata = get_class_data(device);
645            if (classdata->state != NULL)
646            {
647               if (state >= CPUINFO_INT_REGISTER && state <= CPUINFO_INT_REGISTER_LAST)
648               {
649                  set_register_value(device, classdata->state->baseptr, classdata->regstate[state - CPUINFO_INT_REGISTER], value);
650                  return;
651               }
652            }
653         }
654
655         /* integer data */
656         assert(state >= DEVINFO_INT_FIRST && state <= DEVINFO_INT_LAST);
657         if (state >= DEVINFO_INT_FIRST && state <= DEVINFO_INT_LAST)
658         {
659            cinfo.i = value;
660            (*set_info)(device, state, &cinfo);
661         }
662         break;
663   }
664}
665
666
667/*-------------------------------------------------
668    cpu_get_info - device get info
669    callback
670-------------------------------------------------*/
671
672static DEVICE_GET_RUNTIME_INFO( cpu )
673{
674   const cpu_config *config = (device != NULL) ? (const cpu_config *)device->baseconfig().inline_config : NULL;
675   cpuinfo cinfo = { 0 };
676
677   /* if we don't have a device pointer, ignore everything else */
678   if (device == NULL)
679      return;
680
681   /* if we have a state pointer, we can handle some stuff for free */
682   if (device->token != NULL)
683   {
684      const cpu_class_data *classdata = get_class_data(device);
685      if (classdata->state != NULL)
686      {
687         if (state >= CPUINFO_INT_REGISTER && state <= CPUINFO_INT_REGISTER_LAST)
688         {
689            info->i = get_register_value(device, classdata->state->baseptr, classdata->regstate[state - CPUINFO_INT_REGISTER]);
690            return;
691         }
692         else if (state >= CPUINFO_STR_REGISTER && state <= CPUINFO_STR_REGISTER_LAST)
693         {
694            cinfo.s = info->s;
695            get_register_string_value(device, classdata->state->baseptr, classdata->regstate[state - CPUINFO_STR_REGISTER], cinfo.s);
696            info->s = cinfo.s;
697            return;
698         }
699      }
700   }
701
702   /* integer data */
703   if (state >= DEVINFO_INT_FIRST && state <= DEVINFO_INT_LAST)
704   {
705      cinfo.i = info->i;
706      (*config->type)(&device->baseconfig(), device, state, &cinfo);
707      info->i = cinfo.i;
708   }
709
710   /* pointer data */
711   else if ((state >= DEVINFO_PTR_FIRST && state <= DEVINFO_PTR_LAST) ||
712          (state >= DEVINFO_FCT_FIRST && state <= DEVINFO_FCT_LAST) ||
713          (state >= DEVINFO_STR_FIRST && state <= DEVINFO_STR_LAST))
714   {
715      cinfo.p = info->p;
716      (*config->type)(&device->baseconfig(), device, state, &cinfo);
717      info->p = cinfo.p;
718   }
719}
720
721
722DEVICE_GET_INFO( cpu )
723{
724   const cpu_config *config = (const cpu_config *)device->inline_config;
725   cpuinfo cinfo = { 0 };
726
727   switch (state)
728   {
729      /* --- the following bits of info are returned as 64-bit signed integers --- */
730      case DEVINFO_INT_TOKEN_BYTES:
731         cinfo.i = 0;
732         (*config->type)(device, NULL, CPUINFO_INT_CONTEXT_SIZE, &cinfo);
733         info->i = cinfo.i + sizeof(cpu_class_data) + sizeof(cpu_class_header);
734         break;
735
736      case DEVINFO_INT_INLINE_CONFIG_BYTES:   info->i = sizeof(cpu_config);            break;
737      case DEVINFO_INT_CLASS:               info->i = DEVICE_CLASS_CPU_CHIP;         break;
738
739      /* --- the following bits of info are returned as pointers to data or functions --- */
740      case DEVINFO_FCT_START:               info->start = DEVICE_START_NAME(cpu);      break;
741      case DEVINFO_FCT_STOP:               info->stop = DEVICE_STOP_NAME(cpu);       break;
742      case DEVINFO_FCT_RESET:               info->reset = DEVICE_RESET_NAME(cpu);      break;
743      case DEVINFO_FCT_GET_RUNTIME_INFO:      info->get_runtime_info = DEVICE_GET_RUNTIME_INFO_NAME(cpu);      break;
744
745      default:
746         /* integer data */
747         if (state >= DEVINFO_INT_FIRST && state <= DEVINFO_INT_LAST)
748         {
749            cinfo.i = info->i;
750            (*config->type)(device, NULL, state, &cinfo);
751            info->i = cinfo.i;
752         }
753
754         /* pointer data */
755         else if ((state >= DEVINFO_PTR_FIRST && state <= DEVINFO_PTR_LAST) ||
756                (state >= DEVINFO_FCT_FIRST && state <= DEVINFO_FCT_LAST) ||
757                (state >= DEVINFO_STR_FIRST && state <= DEVINFO_STR_LAST))
758         {
759            cinfo.p = info->p;
760            (*config->type)(device, NULL, state, &cinfo);
761            info->p = cinfo.p;
762         }
763         break;
764   }
765}
766
767
768
769/***************************************************************************
770    CPU SCHEDULING
771***************************************************************************/
772
773/*-------------------------------------------------
774    cpu_suspend - set a suspend reason for the
775    given CPU
776-------------------------------------------------*/
777
778void cpu_suspend(running_device *device, int reason, int eatcycles)
779{
780   cpu_class_data *classdata = get_class_data(device);
781
782   /* set the suspend reason and eat cycles flag */
783   classdata->nextsuspend |= reason;
784   classdata->nexteatcycles = eatcycles;
785
786   /* if we're active, synchronize */
787   cpu_abort_timeslice(device);
788}
789
790
791/*-------------------------------------------------
792    cpu_resume - clear a suspend reason for the
793    given CPU
794-------------------------------------------------*/
795
796void cpu_resume(running_device *device, int reason)
797{
798   cpu_class_data *classdata = get_class_data(device);
799
800   /* clear the suspend reason and eat cycles flag */
801   classdata->nextsuspend &= ~reason;
802
803   /* if we're active, synchronize */
804   cpu_abort_timeslice(device);
805}
806
807
808/*-------------------------------------------------
809    cpu_is_executing - return TRUE if the given
810    CPU is within its execute function
811-------------------------------------------------*/
812
813int cpu_is_executing(running_device *device)
814{
815   return (device == device->machine->cpuexec_data->executingcpu);
816}
817
818
819/*-------------------------------------------------
820    cpu_is_suspended - returns TRUE if the
821    given CPU is suspended for any of the given
822    reasons
823-------------------------------------------------*/
824
825int cpu_is_suspended(running_device *device, int reason)
826{
827   cpu_class_data *classdata = get_class_data(device);
828
829   /* return true if the given reason is indicated */
830   return ((classdata->nextsuspend & reason) != 0);
831}
832
833
834
835/***************************************************************************
836    CPU CLOCK MANAGEMENT
837***************************************************************************/
838
839/*-------------------------------------------------
840    cpu_get_clock - gets the given CPU's
841    clock speed
842-------------------------------------------------*/
843
844int cpu_get_clock(running_device *device)
845{
846   cpu_class_data *classdata;
847
848   /* if we haven't been started yet, compute it manually */
849   if (device->token == NULL)
850      return (UINT64)device->clock * cpu_get_clock_multiplier(device) / cpu_get_clock_divider(device);
851
852   /* return the current clock value */
853   classdata = get_class_data(device);
854   return classdata->clock;
855}
856
857
858/*-------------------------------------------------
859    cpu_set_clock - sets the given CPU's
860    clock speed
861-------------------------------------------------*/
862
863void cpu_set_clock(running_device *device, int clock)
864{
865   cpu_class_data *classdata = get_class_data(device);
866
867   /* set the clock and update the information */
868   classdata->clock = clock;
869   update_clock_information(device);
870}
871
872
873/*-------------------------------------------------
874    cpu_get_clockscale - returns the current
875    scaling factor for a CPU's clock speed
876-------------------------------------------------*/
877
878double cpu_get_clockscale(running_device *device)
879{
880   cpu_class_data *classdata = get_class_data(device);
881
882   /* return the current clock scale factor */
883   return classdata->clockscale;
884}
885
886
887/*-------------------------------------------------
888    cpu_set_clockscale - sets the current
889    scaling factor for a CPU's clock speed
890-------------------------------------------------*/
891
892void cpu_set_clockscale(running_device *device, double clockscale)
893{
894   cpu_class_data *classdata = get_class_data(device);
895
896   /* set the scale factor and update the information */
897   classdata->clockscale = clockscale;
898   update_clock_information(device);
899}
900
901
902/*-------------------------------------------------
903    cpu_clocks_to_attotime - converts a number of
904    clock ticks to an attotime
905-------------------------------------------------*/
906
907attotime cpu_clocks_to_attotime(running_device *device, UINT64 clocks)
908{
909   cpu_class_data *classdata = get_class_data(device);
910   if (clocks < classdata->cycles_per_second)
911      return attotime_make(0, clocks * classdata->attoseconds_per_cycle);
912   else
913   {
914      UINT32 remainder;
915      UINT32 quotient = divu_64x32_rem(clocks, classdata->cycles_per_second, &remainder);
916      return attotime_make(quotient, (UINT64)remainder * (UINT64)classdata->attoseconds_per_cycle);
917   }
918}
919
920
921/*-------------------------------------------------
922    cpu_attotime_to_clocks - converts a duration
923    as attotime to CPU clock ticks
924-------------------------------------------------*/
925
926UINT64 cpu_attotime_to_clocks(running_device *device, attotime duration)
927{
928   cpu_class_data *classdata = get_class_data(device);
929   return mulu_32x32(duration.seconds, classdata->cycles_per_second) + (UINT64)duration.attoseconds / (UINT64)classdata->attoseconds_per_cycle;
930}
931
932
933
934/***************************************************************************
935    CPU TIMING
936***************************************************************************/
937
938/*-------------------------------------------------
939    cpu_get_local_time - returns the current
940    local time for a CPU
941-------------------------------------------------*/
942
943attotime cpu_get_local_time(running_device *device)
944{
945   cpu_class_data *classdata = get_class_data(device);
946   attotime result;
947
948   /* if we're active, add in the time from the current slice */
949   result = classdata->localtime;
950   if (device == device->machine->cpuexec_data->executingcpu)
951   {
952      int cycles = classdata->cycles_running - *classdata->icount;
953      result = attotime_add(result, cpu_clocks_to_attotime(device, cycles));
954   }
955   return result;
956}
957
958
959/*-------------------------------------------------
960    cpuexec_override_local_time - overrides the
961    given time with the executing CPU's local
962    time, if present (this function is private
963    to timer.c)
964-------------------------------------------------*/
965
966attotime cpuexec_override_local_time(running_machine *machine, attotime default_time)
967{
968   if (machine->cpuexec_data != NULL && machine->cpuexec_data->executingcpu != NULL)
969      return cpu_get_local_time(machine->cpuexec_data->executingcpu);
970   return default_time;
971}
972
973
974/*-------------------------------------------------
975    cpu_get_total_cycles - return the total
976    number of CPU cycles executed on the active
977    CPU
978-------------------------------------------------*/
979
980UINT64 cpu_get_total_cycles(running_device *device)
981{
982   cpu_class_data *classdata = get_class_data(device);
983
984   if (device == device->machine->cpuexec_data->executingcpu)
985      return classdata->totalcycles + classdata->cycles_running - *classdata->icount;
986   else
987      return classdata->totalcycles;
988}
989
990
991/*-------------------------------------------------
992    cpu_eat_cycles - safely eats cycles so
993    we don't cross a timeslice boundary
994-------------------------------------------------*/
995
996void cpu_eat_cycles(running_device *device, int cycles)
997{
998   cpu_class_data *classdata = get_class_data(device);
999
1000   /* ignore if not the executing CPU */
1001   if (device != device->machine->cpuexec_data->executingcpu)
1002      return;
1003
1004   if (cycles > *classdata->icount)
1005      cycles = *classdata->icount;
1006   *classdata->icount -= cycles;
1007}
1008
1009
1010/*-------------------------------------------------
1011    cpu_adjust_icount - apply a +/- to the current
1012    icount
1013-------------------------------------------------*/
1014
1015void cpu_adjust_icount(running_device *device, int delta)
1016{
1017   cpu_class_data *classdata = get_class_data(device);
1018
1019   /* ignore if not the executing CPU */
1020   if (device != device->machine->cpuexec_data->executingcpu)
1021      return;
1022
1023   *classdata->icount += delta;
1024}
1025
1026
1027/*-------------------------------------------------
1028    cpu_abort_timeslice - abort execution
1029    for the current timeslice, allowing other
1030    CPUs to run before we run again
1031-------------------------------------------------*/
1032
1033void cpu_abort_timeslice(running_device *device)
1034{
1035   cpu_class_data *classdata = get_class_data(device);
1036   int delta;
1037
1038   /* ignore if not the executing CPU */
1039   if (device != device->machine->cpuexec_data->executingcpu)
1040      return;
1041
1042   /* swallow the remaining cycles */
1043   if (classdata->icount != NULL)
1044   {
1045      delta = *classdata->icount;
1046      classdata->cycles_stolen += delta;
1047      classdata->cycles_running -= delta;
1048      *classdata->icount -= delta;
1049   }
1050}
1051
1052
1053
1054/***************************************************************************
1055    SYNCHRONIZATION HELPERS
1056***************************************************************************/
1057
1058/*-------------------------------------------------
1059    cpu_yield - yield the given CPU until the end
1060    of the current timeslice
1061-------------------------------------------------*/
1062
1063void cpu_yield(running_device *device)
1064{
1065   /* suspend against the timeslice */
1066   cpu_suspend(device, SUSPEND_REASON_TIMESLICE, FALSE);
1067}
1068
1069
1070/*-------------------------------------------------
1071    cpu_spin - burn CPU cycles until our timeslice
1072    is up
1073-------------------------------------------------*/
1074
1075void cpu_spin(running_device *device)
1076{
1077   /* suspend against the timeslice */
1078   cpu_suspend(device, SUSPEND_REASON_TIMESLICE, TRUE);
1079}
1080
1081
1082/*-------------------------------------------------
1083    cpu_spinuntil_trigger - burn specified CPU
1084    cycles until a timer trigger
1085-------------------------------------------------*/
1086
1087void cpu_spinuntil_trigger(running_device *device, int trigger)
1088{
1089   /* suspend until the given trigger fires */
1090   suspend_until_trigger(device, trigger, TRUE);
1091}
1092
1093
1094/*-------------------------------------------------
1095    cpu_spinuntil_int - burn CPU cycles until the
1096    next interrupt
1097-------------------------------------------------*/
1098
1099void cpu_spinuntil_int(running_device *device)
1100{
1101   cpu_class_data *classdata = get_class_data(device);
1102
1103   /* suspend until the given trigger fires */
1104   suspend_until_trigger(device, classdata->inttrigger, TRUE);
1105}
1106
1107
1108/*-------------------------------------------------
1109    cpu_spinuntil_time - burn CPU cycles for a
1110    specific period of time
1111-------------------------------------------------*/
1112
1113void cpu_spinuntil_time(running_device *device, attotime duration)
1114{
1115   static int timetrig = 0;
1116
1117   /* suspend until the given trigger fires */
1118   suspend_until_trigger(device, TRIGGER_SUSPENDTIME + timetrig, TRUE);
1119
1120   /* then set a timer for it */
1121   cpuexec_triggertime(device->machine, TRIGGER_SUSPENDTIME + timetrig, duration);
1122   timetrig = (timetrig + 1) % 256;
1123}
1124
1125
1126
1127/***************************************************************************
1128    TRIGGERS
1129***************************************************************************/
1130
1131/*-------------------------------------------------
1132    cpuexec_trigger - generate a trigger now
1133-------------------------------------------------*/
1134
1135void cpuexec_trigger(running_machine *machine, int trigger)
1136{
1137   running_device *cpu;
1138
1139   /* look for suspended CPUs waiting for this trigger and unsuspend them */
1140   for (cpu = machine->firstcpu; cpu != NULL; cpu = cpu_next(cpu))
1141   {
1142      cpu_class_data *classdata = get_class_data(cpu);
1143
1144      /* if we're executing, for an immediate abort */
1145      cpu_abort_timeslice(cpu);
1146
1147      /* see if this is a matching trigger */
1148      if ((classdata->nextsuspend & SUSPEND_REASON_TRIGGER) != 0 && classdata->trigger == trigger)
1149      {
1150         cpu_resume(cpu, SUSPEND_REASON_TRIGGER);
1151         classdata->trigger = 0;
1152      }
1153   }
1154}
1155
1156
1157/*-------------------------------------------------
1158    cpuexec_triggertime - generate a trigger after a
1159    specific period of time
1160-------------------------------------------------*/
1161
1162void cpuexec_triggertime(running_machine *machine, int trigger, attotime duration)
1163{
1164   timer_set(machine, duration, NULL, trigger, triggertime_callback);
1165}
1166
1167
1168/*-------------------------------------------------
1169    cpu_triggerint - generate a trigger
1170    corresponding to an interrupt on the given CPU
1171-------------------------------------------------*/
1172
1173void cpu_triggerint(running_device *device)
1174{
1175   cpu_class_data *classdata = get_class_data(device);
1176
1177   /* signal this CPU's interrupt trigger */
1178   cpuexec_trigger(device->machine, classdata->inttrigger);
1179}
1180
1181
1182
1183/***************************************************************************
1184    INTERRUPTS
1185***************************************************************************/
1186
1187/*-------------------------------------------------
1188    cpu_set_input_line - set the logical state
1189    (ASSERT_LINE/CLEAR_LINE) of an input line
1190    on a CPU
1191-------------------------------------------------*/
1192
1193void cpu_set_input_line(running_device *device, int line, int state)
1194{
1195   cpu_class_data *classdata = get_class_data(device);
1196   int vector = (line >= 0 && line < MAX_INPUT_LINES) ? classdata->input[line].vector : 0xff;
1197   cpu_set_input_line_and_vector(device, line, state, vector);
1198}
1199
1200
1201/*-------------------------------------------------
1202    cpu_set_input_line_vector - set the vector to
1203    be returned during a CPU's interrupt
1204    acknowledge cycle
1205-------------------------------------------------*/
1206
1207void cpu_set_input_line_vector(running_device *device, int line, int vector)
1208{
1209   cpu_class_data *classdata = get_class_data(device);
1210   if (line >= 0 && line < MAX_INPUT_LINES)
1211   {
1212      classdata->input[line].vector = vector;
1213      return;
1214   }
1215   LOG(("cpu_set_input_line_vector CPU '%s' line %d > max input lines\n", device->tag(), line));
1216}
1217
1218
1219/*-------------------------------------------------
1220    cpu_set_input_line_and_vector - set the logical
1221    state (ASSERT_LINE/CLEAR_LINE) of an input
1222    line on a CPU and its associated vector
1223-------------------------------------------------*/
1224
1225void cpu_set_input_line_and_vector(running_device *device, int line, int state, int vector)
1226{
1227   cpu_class_data *classdata = get_class_data(device);
1228
1229   /* catch errors where people use PULSE_LINE for CPUs that don't support it */
1230   if (state == PULSE_LINE && line != INPUT_LINE_NMI && line != INPUT_LINE_RESET)
1231      fatalerror("CPU %s: PULSE_LINE can only be used for NMI and RESET lines\n", device->tag());
1232
1233   if (line >= 0 && line < MAX_INPUT_LINES)
1234   {
1235      cpu_input_data *inputline = &classdata->input[line];
1236      INT32 input_event = (state & 0xff) | (vector << 8);
1237      int event_index = inputline->qindex++;
1238
1239      LOG(("cpu_set_input_line_and_vector('%s',%d,%d,%02x)\n", device->tag(), line, state, vector));
1240
1241      /* if we're full of events, flush the queue and log a message */
1242      if (event_index >= ARRAY_LENGTH(inputline->queue))
1243      {
1244         inputline->qindex--;
1245         empty_event_queue(device->machine, (void *)device, line);
1246         event_index = inputline->qindex++;
1247         logerror("Exceeded pending input line event queue on CPU '%s'!\n", device->tag());
1248      }
1249
1250      /* enqueue the event */
1251      if (event_index < ARRAY_LENGTH(inputline->queue))
1252      {
1253         inputline->queue[event_index] = input_event;
1254
1255         /* if this is the first one, set the timer */
1256         if (event_index == 0)
1257            timer_call_after_resynch(device->machine, (void *)device, line, empty_event_queue);
1258      }
1259   }
1260}
1261
1262
1263/*-------------------------------------------------
1264    cpu_set_irq_callback - install a driver-
1265    specific callback for IRQ acknowledge
1266-------------------------------------------------*/
1267
1268void cpu_set_irq_callback(running_device *device, cpu_irq_callback callback)
1269{
1270   cpu_class_data *classdata = get_class_data(device);
1271   classdata->driver_irq = callback;
1272}
1273
1274
1275
1276/***************************************************************************
1277    CHEESY FAKE VIDEO TIMING (OBSOLETE)
1278***************************************************************************/
1279
1280/*-------------------------------------------------
1281    cpu_getiloops - return the cheesy VBLANK
1282    interrupt counter (deprecated)
1283-------------------------------------------------*/
1284
1285int cpu_getiloops(running_device *device)
1286{
1287   cpu_class_data *classdata = get_class_data(device);
1288   return classdata->iloops;
1289}
1290
1291
1292
1293/***************************************************************************
1294    INTERNAL FUNCTIONS
1295***************************************************************************/
1296
1297/*-------------------------------------------------
1298    update_clock_information - recomputes clock
1299    information for the specified CPU
1300-------------------------------------------------*/
1301
1302static void update_clock_information(running_device *device)
1303{
1304   cpu_class_data *classdata = get_class_data(device);
1305   INT64 attos;
1306
1307   /* recompute cps and spc */
1308   classdata->cycles_per_second = (double)classdata->clock * classdata->clockscale;
1309   classdata->attoseconds_per_cycle = HZ_TO_ATTOSECONDS((double)classdata->clock * classdata->clockscale);
1310
1311   /* update the CPU's divisor */
1312   attos = classdata->attoseconds_per_cycle;
1313   classdata->divshift = 0;
1314   while (attos >= (1UL << 31))
1315   {
1316      classdata->divshift++;
1317      attos >>= 1;
1318   }
1319   classdata->divisor = attos;
1320
1321   /* re-compute the perfect interleave factor */
1322   compute_perfect_interleave(device->machine);
1323}
1324
1325
1326/*-------------------------------------------------
1327    compute_perfect_interleave - compute the
1328    "perfect" interleave interval
1329-------------------------------------------------*/
1330
1331static void compute_perfect_interleave(running_machine *machine)
1332{
1333   running_device *firstcpu = machine->firstcpu;
1334   if (firstcpu != NULL)
1335   {
1336      attoseconds_t smallest = get_minimum_quantum(firstcpu);
1337      attoseconds_t perfect = ATTOSECONDS_PER_SECOND - 1;
1338      running_device *cpu;
1339
1340      /* start with a huge time factor and find the 2nd smallest cycle time */
1341      for (cpu = cpu_next(firstcpu); cpu != NULL; cpu = cpu_next(cpu))
1342      {
1343         attoseconds_t curquantum = get_minimum_quantum(cpu);
1344
1345         /* find the 2nd smallest cycle interval */
1346         if (curquantum < smallest)
1347         {
1348            perfect = smallest;
1349            smallest = curquantum;
1350         }
1351         else if (curquantum < perfect)
1352            perfect = curquantum;
1353      }
1354
1355      /* adjust the final value */
1356      timer_set_minimum_quantum(machine, perfect);
1357
1358      LOG(("Perfect interleave = %.9f, smallest = %.9f\n", ATTOSECONDS_TO_DOUBLE(perfect), ATTOSECONDS_TO_DOUBLE(smallest)));
1359   }
1360}
1361
1362
1363/*-------------------------------------------------
1364    on_vblank - calls any external callbacks
1365    for this screen
1366-------------------------------------------------*/
1367
1368static void on_vblank(running_device *device, void *param, int vblank_state)
1369{
1370   /* VBLANK starting */
1371   if (vblank_state)
1372   {
1373      running_device *cpu;
1374
1375      /* find any CPUs that have this screen as their VBLANK interrupt source */
1376      for (cpu = device->machine->firstcpu; cpu != NULL; cpu = cpu_next(cpu))
1377      {
1378         const cpu_config *config = (const cpu_config *)cpu->baseconfig().inline_config;
1379         cpu_class_data *classdata = get_class_data(cpu);
1380         int cpu_interested;
1381
1382         /* start the interrupt counter */
1383         if (!(classdata->suspend & SUSPEND_REASON_DISABLE))
1384            classdata->iloops = 0;
1385         else
1386            classdata->iloops = -1;
1387
1388         /* the hack style VBLANK decleration always uses the first screen */
1389         if (config->vblank_interrupts_per_frame > 1)
1390            cpu_interested = TRUE;
1391
1392         /* for new style declaration, we need to compare the tags */
1393         else if (config->vblank_interrupt_screen != NULL)
1394            cpu_interested = (strcmp(config->vblank_interrupt_screen, device->tag()) == 0);
1395
1396         /* no VBLANK interrupt, not interested */
1397         else
1398            cpu_interested = FALSE;
1399
1400         /* if interested, call the interrupt handler */
1401         if (cpu_interested)
1402         {
1403            if (!(classdata->suspend & (SUSPEND_REASON_HALT | SUSPEND_REASON_RESET | SUSPEND_REASON_DISABLE)))
1404               (*config->vblank_interrupt)(cpu);
1405
1406            /* if we have more than one interrupt per frame, start the timer now to trigger the rest of them */
1407            if (config->vblank_interrupts_per_frame > 1 && !(classdata->suspend & SUSPEND_REASON_DISABLE))
1408            {
1409               classdata->partial_frame_period = attotime_div(video_screen_get_frame_period(device->machine->primary_screen), config->vblank_interrupts_per_frame);
1410               timer_adjust_oneshot(classdata->partial_frame_timer, classdata->partial_frame_period, 0);
1411            }
1412         }
1413      }
1414   }
1415}
1416
1417
1418/*-------------------------------------------------
1419    trigger_partial_frame_interrupt - called to
1420    trigger a partial frame interrupt
1421-------------------------------------------------*/
1422
1423static TIMER_CALLBACK( trigger_partial_frame_interrupt )
1424{
1425   running_device *device = (running_device *)ptr;
1426   const cpu_config *config = (const cpu_config *)device->baseconfig().inline_config;
1427   cpu_class_data *classdata = get_class_data(device);
1428
1429   if (classdata->iloops == 0)
1430      classdata->iloops = config->vblank_interrupts_per_frame;
1431
1432   classdata->iloops--;
1433
1434   /* call the interrupt handler */
1435   if (!cpu_is_suspended(device, SUSPEND_REASON_HALT | SUSPEND_REASON_RESET | SUSPEND_REASON_DISABLE))
1436      (*config->vblank_interrupt)(device);
1437
1438   /* more? */
1439   if (classdata->iloops > 1)
1440      timer_adjust_oneshot(classdata->partial_frame_timer, classdata->partial_frame_period, 0);
1441}
1442
1443
1444/*-------------------------------------------------
1445    trigger_periodic_interrupt - timer callback for
1446    timed interrupts
1447-------------------------------------------------*/
1448
1449static TIMER_CALLBACK( trigger_periodic_interrupt )
1450{
1451   running_device *device = (running_device *)ptr;
1452   const cpu_config *config = (const cpu_config *)device->baseconfig().inline_config;
1453
1454   /* bail if there is no routine */
1455   if (config->timed_interrupt != NULL && !cpu_is_suspended(device, SUSPEND_REASON_HALT | SUSPEND_REASON_RESET | SUSPEND_REASON_DISABLE))
1456      (*config->timed_interrupt)(device);
1457}
1458
1459
1460/*-------------------------------------------------
1461    triggertime_callback - signal a global trigger
1462-------------------------------------------------*/
1463
1464static TIMER_CALLBACK( triggertime_callback )
1465{
1466   cpuexec_trigger(machine, param);
1467}
1468
1469
1470/*-------------------------------------------------
1471    empty_event_queue - empty a CPU's event queue
1472    for a specific input line
1473-------------------------------------------------*/
1474
1475static TIMER_CALLBACK( empty_event_queue )
1476{
1477   running_device *device = (running_device *)ptr;
1478   cpu_class_data *classdata = get_class_data(device);
1479   cpu_input_data *inputline = &classdata->input[param];
1480   int curevent;
1481
1482   /* loop over all events */
1483   for (curevent = 0; curevent < inputline->qindex; curevent++)
1484   {
1485      INT32 input_event = inputline->queue[curevent];
1486      int state = input_event & 0xff;
1487      int vector = input_event >> 8;
1488
1489      /* set the input line state and vector */
1490      inputline->curstate = state;
1491      inputline->curvector = vector;
1492
1493      /* special case: RESET */
1494      if (param == INPUT_LINE_RESET)
1495      {
1496         /* if we're asserting the line, just halt the CPU */
1497         if (state == ASSERT_LINE)
1498            cpu_suspend(device, SUSPEND_REASON_RESET, 1);
1499         else
1500         {
1501            /* if we're clearing the line that was previously asserted, or if we're just */
1502            /* pulsing the line, reset the CPU */
1503            if ((state == CLEAR_LINE && cpu_is_suspended(device, SUSPEND_REASON_RESET)) || state == PULSE_LINE)
1504               device->reset();
1505
1506            /* if we're clearing the line, make sure the CPU is not halted */
1507            cpu_resume(device, SUSPEND_REASON_RESET);
1508         }
1509      }
1510
1511      /* special case: HALT */
1512      else if (param == INPUT_LINE_HALT)
1513      {
1514         /* if asserting, halt the CPU */
1515         if (state == ASSERT_LINE)
1516            cpu_suspend(device, SUSPEND_REASON_HALT, 1);
1517
1518         /* if clearing, unhalt the CPU */
1519         else if (state == CLEAR_LINE)
1520            cpu_resume(device, SUSPEND_REASON_HALT);
1521      }
1522
1523      /* all other cases */
1524      else
1525      {
1526         /* switch off the requested state */
1527         switch (state)
1528         {
1529            case PULSE_LINE:
1530               cpu_set_info(device, CPUINFO_INT_INPUT_STATE + param, ASSERT_LINE);
1531               cpu_set_info(device, CPUINFO_INT_INPUT_STATE + param, CLEAR_LINE);
1532               break;
1533
1534            case HOLD_LINE:
1535            case ASSERT_LINE:
1536               cpu_set_info(device, CPUINFO_INT_INPUT_STATE + param, ASSERT_LINE);
1537               break;
1538
1539            case CLEAR_LINE:
1540               cpu_set_info(device, CPUINFO_INT_INPUT_STATE + param, CLEAR_LINE);
1541               break;
1542
1543            default:
1544               logerror("empty_event_queue cpu '%s', line %d, unknown state %d\n", device->tag(), param, state);
1545               break;
1546         }
1547
1548         /* generate a trigger to unsuspend any CPUs waiting on the interrupt */
1549         if (state != CLEAR_LINE)
1550            cpu_triggerint(device);
1551      }
1552   }
1553
1554   /* reset counter */
1555   inputline->qindex = 0;
1556}
1557
1558
1559/*-------------------------------------------------
1560    standard_irq_callback - IRQ acknowledge
1561    callback; handles HOLD_LINE case and signals
1562    to the debugger
1563-------------------------------------------------*/
1564
1565static IRQ_CALLBACK( standard_irq_callback )
1566{
1567   cpu_class_data *classdata = get_class_data(device);
1568   cpu_input_data *inputline = &classdata->input[irqline];
1569   int vector = inputline->curvector;
1570
1571   LOG(("standard_irq_callback('%s', %d) $%04x\n", device->tag(), irqline, vector));
1572
1573   /* if the IRQ state is HOLD_LINE, clear it */
1574   if (inputline->curstate == HOLD_LINE)
1575   {
1576      LOG(("->set_irq_line('%s',%d,%d)\n", device->tag(), irqline, CLEAR_LINE));
1577      cpu_set_info(device, CPUINFO_INT_INPUT_STATE + irqline, CLEAR_LINE);
1578      inputline->curstate = CLEAR_LINE;
1579   }
1580
1581   /* if there's a driver callback, run it */
1582   if (classdata->driver_irq != NULL)
1583      vector = (*classdata->driver_irq)(device, irqline);
1584
1585   /* notify the debugger */
1586   debugger_interrupt_hook(device, irqline);
1587
1588   /* otherwise, just return the current vector */
1589   return vector;
1590}
1591
1592
1593/*-------------------------------------------------
1594    register_save_states - register for CPU-
1595    specific save states
1596-------------------------------------------------*/
1597
1598static void register_save_states(running_device *device)
1599{
1600   cpu_class_data *classdata = get_class_data(device);
1601   int line;
1602
1603   state_save_register_device_item(device, 0, classdata->suspend);
1604   state_save_register_device_item(device, 0, classdata->nextsuspend);
1605   state_save_register_device_item(device, 0, classdata->eatcycles);
1606   state_save_register_device_item(device, 0, classdata->nexteatcycles);
1607   state_save_register_device_item(device, 0, classdata->trigger);
1608
1609   state_save_register_device_item(device, 0, classdata->iloops);
1610
1611   state_save_register_device_item(device, 0, classdata->totalcycles);
1612   state_save_register_device_item(device, 0, classdata->localtime.seconds);
1613   state_save_register_device_item(device, 0, classdata->localtime.attoseconds);
1614   state_save_register_device_item(device, 0, classdata->clock);
1615   state_save_register_device_item(device, 0, classdata->clockscale);
1616
1617   for (line = 0; line < ARRAY_LENGTH(classdata->input); line++)
1618   {
1619      cpu_input_data *inputline = &classdata->input[line];
1620      state_save_register_device_item(device, line, inputline->vector);
1621      state_save_register_device_item(device, line, inputline->curvector);
1622      state_save_register_device_item(device, line, inputline->curstate);
1623   }
1624}
1625
1626
1627/*-------------------------------------------------
1628    rebuild_execute_list - rebuild the list of
1629    executing CPUs, moving suspended CPUs to the
1630    end
1631-------------------------------------------------*/
1632
1633static void rebuild_execute_list(running_machine *machine)
1634{
1635   cpuexec_private *global = machine->cpuexec_data;
1636   running_device *curcpu;
1637   cpu_class_data **tailptr;
1638
1639   /* start with an empty list */
1640   tailptr = &global->executelist;
1641   *tailptr = NULL;
1642
1643   /* first iterate over non-suspended CPUs */
1644   for (curcpu = machine->firstcpu; curcpu != NULL; curcpu = cpu_next(curcpu))
1645   {
1646      cpu_class_data *classdata = get_class_data(curcpu);
1647      if (classdata->suspend == 0)
1648      {
1649         *tailptr = classdata;
1650         tailptr = &classdata->next;
1651         classdata->next = NULL;
1652      }
1653   }
1654
1655   /* then add the suspended CPUs */
1656   for (curcpu = machine->firstcpu; curcpu != NULL; curcpu = cpu_next(curcpu))
1657   {
1658      cpu_class_data *classdata = get_class_data(curcpu);
1659      if (classdata->suspend != 0)
1660      {
1661         *tailptr = classdata;
1662         tailptr = &classdata->next;
1663         classdata->next = NULL;
1664      }
1665   }
1666}
1667
1668
1669/*-------------------------------------------------
1670    get_register_value - return a register value
1671    of a CPU using the state table
1672-------------------------------------------------*/
1673
1674static UINT64 get_register_value(running_device *device, void *baseptr, const cpu_state_entry *entry)
1675{
1676   void *dataptr;
1677   UINT64 result;
1678
1679   /* NULL entry returns 0 */
1680   if (entry == NULL || baseptr == NULL)
1681      return 0;
1682
1683   /* if we have an exporter, call it now */
1684   if ((entry->flags & CPUSTATE_EXPORT) != 0)
1685   {
1686      cpu_state_io_func exportcb = (cpu_state_io_func)device->get_config_fct(CPUINFO_FCT_EXPORT_STATE);
1687      assert(exportcb != NULL);
1688      (*exportcb)(device, baseptr, entry);
1689   }
1690
1691   /* pick up the value */
1692   dataptr = (UINT8 *)baseptr + entry->dataoffs;
1693   switch (entry->datasize)
1694   {
1695      default:
1696      case 1:   result = *(UINT8 *)dataptr;      break;
1697      case 2:   result = *(UINT16 *)dataptr;   break;
1698      case 4:   result = *(UINT32 *)dataptr;   break;
1699      case 8:   result = *(UINT64 *)dataptr;   break;
1700   }
1701   return result & entry->mask;
1702}
1703
1704
1705/*-------------------------------------------------
1706    set_register_value - set the value of a
1707    CPU register using the state table
1708-------------------------------------------------*/
1709
1710static void set_register_value(running_device *device, void *baseptr, const cpu_state_entry *entry, UINT64 value)
1711{
1712   void *dataptr;
1713
1714   /* NULL entry is a no-op */
1715   if (entry == NULL || baseptr == NULL)
1716      return;
1717
1718   /* apply the mask */
1719   value &= entry->mask;
1720
1721   /* sign-extend if necessary */
1722   if ((entry->flags & CPUSTATE_IMPORT_SEXT) != 0 && value > (entry->mask >> 1))
1723      value |= ~entry->mask;
1724
1725   /* store the value */
1726   dataptr = (UINT8 *)baseptr + entry->dataoffs;
1727   switch (entry->datasize)
1728   {
1729      default:
1730      case 1:   *(UINT8 *)dataptr = value;      break;
1731      case 2:   *(UINT16 *)dataptr = value;      break;
1732      case 4:   *(UINT32 *)dataptr = value;      break;
1733      case 8:   *(UINT64 *)dataptr = value;      break;
1734   }
1735
1736   /* if we have an importer, call it now */
1737   if ((entry->flags & CPUSTATE_IMPORT) != 0)
1738   {
1739      cpu_state_io_func importcb = (cpu_state_io_func)device->get_config_fct(CPUINFO_FCT_IMPORT_STATE);
1740      assert(importcb != NULL);
1741      (*importcb)(device, baseptr, entry);
1742   }
1743}
1744
1745
1746/*-------------------------------------------------
1747    get_register_string_value - return a string
1748    representation of a CPU register using the
1749    state table
1750-------------------------------------------------*/
1751
1752static void get_register_string_value(running_device *device, void *baseptr, const cpu_state_entry *entry, char *dest)
1753{
1754   static const UINT64 decdivisor[] = {
1755      1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000,
1756      U64(10000000000),         U64(100000000000),         U64(1000000000000),
1757      U64(10000000000000),      U64(100000000000000),      U64(1000000000000000),
1758      U64(10000000000000000),    U64(100000000000000000),   U64(1000000000000000000),
1759      U64(10000000000000000000)
1760   };
1761   static const char hexchars[] = "0123456789ABCDEF";
1762   int leadzero = 0, width = 0, percent = 0, explicitsign = 0, hitnonzero = 0, reset;
1763   const char *fptr;
1764   UINT64 result;
1765
1766   /* NULL entry does nothing */
1767   if (entry == NULL || entry->symbol == NULL || entry->format == NULL)
1768      return;
1769
1770   /* fetch the data */
1771   result = get_register_value(device, baseptr, entry);
1772
1773   /* start with the basics */
1774   dest += sprintf(dest, "%s%s:", (entry->flags & CPUSTATE_NOSHOW) ? "~" : "", entry->symbol);
1775
1776   /* parse the format */
1777   reset = TRUE;
1778   for (fptr = entry->format; *fptr != 0; fptr++)
1779   {
1780      int digitnum;
1781
1782      /* reset any accumulated state */
1783      if (reset)
1784         leadzero = width = percent = explicitsign = reset = 0;
1785
1786      /* if we're not within a format, then anything other than a % outputs directly */
1787      if (!percent && *fptr != '%')
1788      {
1789         *dest++ = *fptr;
1790         continue;
1791      }
1792
1793      /* handle each character in turn */
1794      switch (*fptr)
1795      {
1796         /* % starts a format; %% outputs a single % */
1797         case '%':
1798            if (!percent)
1799               percent = TRUE;
1800            else
1801            {
1802               *dest++ = *fptr;
1803               percent = FALSE;
1804            }
1805            break;
1806
1807         /* 0 means insert leading 0s, unless it follows another width digit */
1808         case '0':
1809            if (width == 0)
1810               leadzero = TRUE;
1811            else
1812               width *= 10;
1813            break;
1814
1815         /* 1-9 accumulate into the width */
1816         case '1':   case '2':   case '3':   case '4':   case '5':
1817         case '6':   case '7':   case '8':   case '9':
1818            width = width * 10 + (*fptr - '0');
1819            break;
1820
1821         /* + means explicit sign */
1822         case '+':
1823            explicitsign = TRUE;
1824            break;
1825
1826         /* X outputs as hexadecimal */
1827         case 'X':
1828            if (width == 0)
1829               fatalerror("Width required for %%X formats\n");
1830            hitnonzero = FALSE;
1831            while (leadzero && width > 16)
1832            {
1833               *dest++ = ' ';
1834               width--;
1835            }
1836            for (digitnum = 15; digitnum >= 0; digitnum--)
1837            {
1838               int digit = (result >> (4 * digitnum)) & 0x0f;
1839               if (digit != 0)
1840                  *dest++ = hexchars[digit];
1841               else if (hitnonzero || (leadzero && digitnum < width) || digitnum == 0)
1842                  *dest++ = '0';
1843               hitnonzero |= digit;
1844            }
1845            reset = TRUE;
1846            break;
1847
1848         /* d outputs as signed decimal */
1849         case 'd':
1850            if (width == 0)
1851               fatalerror("Width required for %%d formats\n");
1852            if ((result & entry->mask) > (entry->mask >> 1))
1853            {
1854               result = -result & entry->mask;
1855               *dest++ = '-';
1856               width--;
1857            }
1858            else if (explicitsign)
1859            {
1860               *dest++ = '+';
1861               width--;
1862            }
1863            /* fall through to unsigned case */
1864
1865         /* u outputs as unsigned decimal */
1866         case 'u':
1867            if (width == 0)
1868               fatalerror("Width required for %%u formats\n");
1869            hitnonzero = FALSE;
1870            while (leadzero && width > ARRAY_LENGTH(decdivisor))
1871            {
1872               *dest++ = ' ';
1873               width--;
1874            }
1875            for (digitnum = ARRAY_LENGTH(decdivisor) - 1; digitnum >= 0; digitnum--)
1876            {
1877               int digit = (result >= decdivisor[digitnum]) ? (result / decdivisor[digitnum]) % 10 : 0;
1878               if (digit != 0)
1879                  *dest++ = '0' + digit;
1880               else if (hitnonzero || (leadzero && digitnum < width) || digitnum == 0)
1881                  *dest++ = '0';
1882               hitnonzero |= digit;
1883            }
1884            reset = TRUE;
1885            break;
1886
1887         /* s is a custom format */
1888         case 's':
1889         {
1890            cpu_string_io_func exportstring = (cpu_string_io_func)device->get_config_fct(CPUINFO_FCT_EXPORT_STRING);
1891            assert(exportstring != NULL);
1892            (*exportstring)(device, baseptr, entry, dest);
1893            dest += strlen(dest);
1894            break;
1895         }
1896
1897         /* other formats unknown */
1898         default:
1899            fatalerror("Unknown format character '%c'\n", *fptr);
1900            break;
1901      }
1902   }
1903   *dest = 0;
1904}
1905
1906
1907/*-------------------------------------------------
1908    get_register_string_max_width - return the
1909    maximum width of a string described by a
1910    format
1911-------------------------------------------------*/
1912
1913#ifdef UNUSED_FUNCTION
1914static int get_register_string_max_width(running_device *device, void *baseptr, const cpu_state_entry *entry)
1915{
1916   int /*leadzero = 0,*/ width = 0, percent = 0, explicitsign = 0, reset;
1917   int totalwidth = 0;
1918   const char *fptr;
1919
1920   /* NULL entry does nothing */
1921   if (entry == NULL || entry->symbol == NULL || entry->format == NULL)
1922      return 0;
1923
1924   /* parse the format */
1925   reset = TRUE;
1926   for (fptr = entry->format; *fptr != 0; fptr++)
1927   {
1928      /* reset any accumulated state */
1929      if (reset)
1930         /*leadzero =*/ width = percent = explicitsign = reset = 0;
1931
1932      /* if we're not within a format, then anything other than a % outputs directly */
1933      if (!percent && *fptr != '%')
1934      {
1935         totalwidth++;
1936         continue;
1937      }
1938
1939      /* handle each character in turn */
1940      switch (*fptr)
1941      {
1942         /* % starts a format; %% outputs a single % */
1943         case '%':
1944            if (!percent)
1945               percent = TRUE;
1946            else
1947            {
1948               totalwidth++;
1949               percent = FALSE;
1950            }
1951            break;
1952
1953         /* 0 means insert leading 0s, unless it follows another width digit */
1954         case '0':
1955            if (width == 0) {
1956               //leadzero = TRUE;
1957            }
1958            else
1959               width *= 10;
1960            break;
1961
1962         /* 1-9 accumulate into the width */
1963         case '1':   case '2':   case '3':   case '4':   case '5':
1964         case '6':   case '7':   case '8':   case '9':
1965            width = width * 10 + (*fptr - '0');
1966            break;
1967
1968         /* + means explicit sign */
1969         case '+':
1970            explicitsign = TRUE;
1971            break;
1972
1973         /* X outputs as hexadecimal */
1974         /* d outputs as signed decimal */
1975         /* u outputs as unsigned decimal */
1976         /* s outputs as custom format */
1977         case 'X':
1978         case 'd':
1979         case 'u':
1980         case 's':
1981            totalwidth += width;
1982            reset = TRUE;
1983            break;
1984
1985            if (width == 0)
1986               fatalerror("Width required for %%d formats\n");
1987            totalwidth += width;
1988            break;
1989
1990         /* other formats unknown */
1991         default:
1992            fatalerror("Unknown format character '%c'\n", *fptr);
1993            break;
1994      }
1995   }
1996   return totalwidth;
1997}
1998#endif
src/emu/cpuexec.h
r8415r8416
1/***************************************************************************
2
3    cpuexec.h
4
5    Core multi-CPU execution engine.
6
7    Copyright Nicola Salmoria and the MAME Team.
8    Visit http://mamedev.org for licensing and usage restrictions.
9
10***************************************************************************/
11
12#pragma once
13
14#ifndef __EMU_H__
15#error Dont include this file directly; include emu.h instead.
16#endif
17
18#ifndef __CPUEXEC_H__
19#define __CPUEXEC_H__
20
21
22/***************************************************************************
23    CONSTANTS
24***************************************************************************/
25
26/* flags for MDRV_CPU_FLAGS */
27enum
28{
29   /* set this flag to disable execution of a CPU (if one is there for documentation */
30   /* purposes only, for example */
31   CPU_DISABLE = 0x0001
32};
33
34
35/* suspension reasons for cpunum_suspend */
36enum
37{
38   SUSPEND_REASON_HALT    = 0x0001,
39   SUSPEND_REASON_RESET   = 0x0002,
40   SUSPEND_REASON_SPIN    = 0x0004,
41   SUSPEND_REASON_TRIGGER   = 0x0008,
42   SUSPEND_REASON_DISABLE   = 0x0010,
43   SUSPEND_REASON_TIMESLICE= 0x0020,
44   SUSPEND_ANY_REASON      = ~0
45};
46
47
48
49/***************************************************************************
50    TYPE DEFINITIONS
51***************************************************************************/
52
53/* opaque definition of CPU internal and debugging info */
54typedef struct _cpu_debug_data cpu_debug_data;
55
56
57/* interrupt callback for VBLANK and timed interrupts */
58typedef void (*cpu_interrupt_func)(running_device *device);
59
60
61/* CPU description for drivers */
62typedef struct _cpu_config cpu_config;
63struct _cpu_config
64{
65   cpu_type         type;                  /* index for the CPU type */
66   UINT32            flags;                  /* flags; see #defines below */
67   cpu_interrupt_func   vblank_interrupt;         /* for interrupts tied to VBLANK */
68   int             vblank_interrupts_per_frame;/* usually 1 */
69   const char *      vblank_interrupt_screen;   /* the screen that causes the VBLANK interrupt */
70   cpu_interrupt_func   timed_interrupt;         /* for interrupts not tied to VBLANK */
71   UINT64            timed_interrupt_period;      /* period for periodic interrupts */
72};
73
74
75/* public data at the end of the device->token */
76typedef struct _cpu_class_header cpu_class_header;
77struct _cpu_class_header
78{
79   cpu_debug_data *      debug;               /* debugging data */
80   cpu_set_info_func      set_info;            /* this CPU's set_info function */
81};
82
83
84
85/***************************************************************************
86    CPU DEVICE CONFIGURATION MACROS
87***************************************************************************/
88
89#define MDRV_CPU_ADD(_tag, _type, _clock) \
90   MDRV_DEVICE_ADD(_tag, CPU, _clock) \
91   MDRV_DEVICE_CONFIG_DATAPTR(cpu_config, type, CPU_##_type)
92
93#define MDRV_CPU_MODIFY(_tag) \
94   MDRV_DEVICE_MODIFY(_tag)
95
96#define MDRV_CPU_TYPE(_type) \
97   MDRV_DEVICE_CONFIG_DATAPTR(cpu_config, type, CPU_##_type)
98
99#define MDRV_CPU_CLOCK(_clock) \
100   MDRV_DEVICE_CLOCK(_clock)
101
102#define MDRV_CPU_REPLACE(_tag, _type, _clock) \
103   MDRV_DEVICE_MODIFY(_tag) \
104   MDRV_DEVICE_CONFIG_DATAPTR(cpu_config, type, CPU_##_type) \
105   MDRV_DEVICE_CLOCK(_clock)
106
107#define MDRV_CPU_FLAGS(_flags) \
108   MDRV_DEVICE_CONFIG_DATA32(cpu_config, flags, _flags)
109
110#define MDRV_CPU_CONFIG(_config) \
111   MDRV_DEVICE_CONFIG(_config)
112
113#define MDRV_CPU_PROGRAM_MAP(_map) \
114   MDRV_DEVICE_PROGRAM_MAP(_map)
115
116#define MDRV_CPU_DATA_MAP(_map) \
117   MDRV_DEVICE_DATA_MAP(_map)
118
119#define MDRV_CPU_IO_MAP(_map) \
120   MDRV_DEVICE_IO_MAP(_map)
121
122#define MDRV_CPU_VBLANK_INT(_tag, _func) \
123   MDRV_DEVICE_CONFIG_DATAPTR(cpu_config, vblank_interrupt, _func) \
124   MDRV_DEVICE_CONFIG_DATAPTR(cpu_config, vblank_interrupt_screen, _tag) \
125   MDRV_DEVICE_CONFIG_DATA32(cpu_config, vblank_interrupts_per_frame, 0)
126
127#define MDRV_CPU_PERIODIC_INT(_func, _rate)   \
128   MDRV_DEVICE_CONFIG_DATAPTR(cpu_config, timed_interrupt, _func) \
129   MDRV_DEVICE_CONFIG_DATA64(cpu_config, timed_interrupt_period, UINT64_ATTOTIME_IN_HZ(_rate))
130
131
132
133/***************************************************************************
134    MACROS
135***************************************************************************/
136
137#define INTERRUPT_GEN(func)      void func(running_device *device)
138
139/* helpers for using machine/cputag instead of cpu objects */
140#define cputag_get_address_space(mach, tag, spc)                  (mach)->device(tag)->space(spc)
141#define cputag_suspend(mach, tag, reason, eat)                     cpu_suspend((mach)->device(tag), reason, eat)
142#define cputag_resume(mach, tag, reason)                        cpu_resume((mach)->device(tag), reason)
143#define cputag_is_suspended(mach, tag, reason)                     cpu_is_suspended((mach)->device(tag), reason)
144#define cputag_get_clock(mach, tag)                              cpu_get_clock((mach)->device(tag))
145#define cputag_set_clock(mach, tag, clock)                        cpu_set_clock((mach)->device(tag), clock)
146#define cputag_clocks_to_attotime(mach, tag, clocks)               cpu_clocks_to_attotime((mach)->device(tag), clocks)
147#define cputag_attotime_to_clocks(mach, tag, duration)               cpu_attotime_to_clocks((mach)->device(tag), duration)
148#define cputag_get_local_time(mach, tag)                        cpu_get_local_time((mach)->device(tag))
149#define cputag_get_total_cycles(mach, tag)                        cpu_get_total_cycles((mach)->device(tag))
150#define cputag_set_input_line(mach, tag, line, state)               cpu_set_input_line((mach)->device(tag), line, state)
151#define cputag_set_input_line_and_vector(mach, tag, line, state, vec)   cpu_set_input_line_and_vector((mach)->device(tag), line, state, vec)
152
153
154
155/***************************************************************************
156    FUNCTION PROTOTYPES
157***************************************************************************/
158
159
160/* ----- core CPU execution ----- */
161
162/* prepare CPUs for execution */
163void cpuexec_init(running_machine *machine);
164
165/* execute for a single timeslice */
166void cpuexec_timeslice(running_machine *machine);
167
168/* temporarily boosts the interleave factor */
169void cpuexec_boost_interleave(running_machine *machine, attotime timeslice_time, attotime boost_duration);
170
171
172
173/* ----- CPU device interface ----- */
174
175/* device get info callback */
176#define CPU DEVICE_GET_INFO_NAME(cpu)
177DEVICE_GET_INFO( cpu );
178
179
180
181/* ----- global helpers ----- */
182
183/* abort execution for the current timeslice */
184void cpuexec_abort_timeslice(running_machine *machine);
185
186/* return a string describing which CPUs are currently executing and their PC */
187const char *cpuexec_describe_context(running_machine *machine);
188
189
190
191/* ----- CPU scheduling----- */
192
193/* suspend the given CPU for a specific reason */
194void cpu_suspend(running_device *device, int reason, int eatcycles);
195
196/* resume the given CPU for a specific reason */
197void cpu_resume(running_device *device, int reason);
198
199/* return TRUE if the given CPU is within its execute function */
200int cpu_is_executing(running_device *device);
201
202/* returns TRUE if the given CPU is suspended for any of the given reasons */
203int cpu_is_suspended(running_device *device, int reason);
204
205
206
207/* ----- CPU clock management ----- */
208
209/* returns the current CPU's unscaled running clock speed */
210int cpu_get_clock(running_device *device);
211
212/* sets the current CPU's clock speed and then adjusts for scaling */
213void cpu_set_clock(running_device *device, int clock);
214
215/* returns the current scaling factor for a CPU's clock speed */
216double cpu_get_clockscale(running_device *device);
217
218/* sets the current scaling factor for a CPU's clock speed */
219void cpu_set_clockscale(running_device *device, double clockscale);
220
221/* converts a number of clock ticks to an attotime */
222attotime cpu_clocks_to_attotime(running_device *device, UINT64 clocks);
223
224/* converts a duration as attotime to CPU clock ticks */
225UINT64 cpu_attotime_to_clocks(running_device *device, attotime duration);
226
227
228
229/* ----- CPU timing ----- */
230
231/* returns the current local time for a CPU */
232attotime cpu_get_local_time(running_device *device);
233
234/* returns the total number of CPU cycles for a given CPU */
235UINT64 cpu_get_total_cycles(running_device *device);
236
237/* safely eats cycles so we don't cross a timeslice boundary */
238void cpu_eat_cycles(running_device *device, int cycles);
239
240/* apply a +/- to the current icount */
241void cpu_adjust_icount(running_device *device, int delta);
242
243/* abort execution for the current timeslice, allowing other CPUs to run before we run again */
244void cpu_abort_timeslice(running_device *device);
245
246
247
248/* ----- synchronization helpers ----- */
249
250/* yield the given CPU until the end of the current timeslice */
251void cpu_yield(running_device *device);
252
253/* burn CPU cycles until the end of the current timeslice */
254void cpu_spin(running_device *device);
255
256/* burn specified CPU cycles until a trigger */
257void cpu_spinuntil_trigger(running_device *device, int trigger);
258
259/* burn CPU cycles until the next interrupt */
260void cpu_spinuntil_int(running_device *device);
261
262/* burn CPU cycles for a specific period of time */
263void cpu_spinuntil_time(running_device *device, attotime duration);
264
265
266
267/* ----- triggers ----- */
268
269/* generate a global trigger now */
270void cpuexec_trigger(running_machine *machine, int trigger);
271
272/* generate a global trigger after a specific period of time */
273void cpuexec_triggertime(running_machine *machine, int trigger, attotime duration);
274
275/* generate a trigger corresponding to an interrupt on the given CPU */
276void cpu_triggerint(running_device *device);
277
278
279
280/* ----- interrupts ----- */
281
282/* set the logical state (ASSERT_LINE/CLEAR_LINE) of the an input line on a CPU */
283void cpu_set_input_line(running_device *cpu, int line, int state);
284
285/* set the vector to be returned during a CPU's interrupt acknowledge cycle */
286void cpu_set_input_line_vector(running_device *cpu, int irqline, int vector);
287
288/* set the logical state (ASSERT_LINE/CLEAR_LINE) of the an input line on a CPU and its associated vector */
289void cpu_set_input_line_and_vector(running_device *cpu, int line, int state, int vector);
290
291/* install a driver-specific callback for IRQ acknowledge */
292void cpu_set_irq_callback(running_device *cpu, cpu_irq_callback callback);
293
294
295
296/***************************************************************************
297    INLINE FUNCTIONS
298***************************************************************************/
299
300/*-------------------------------------------------
301    cpu_get_type - return the type of the
302    specified CPU
303-------------------------------------------------*/
304
305INLINE cpu_type cpu_get_type(running_device *device)
306{
307   const cpu_config *config = (const cpu_config *)device->baseconfig().inline_config;
308   return config->type;
309}
310
311
312/*-------------------------------------------------
313    cpu_get_class_header - return a pointer to
314    the class header
315-------------------------------------------------*/
316
317INLINE cpu_class_header *cpu_get_class_header(running_device *device)
318{
319   if (device->token != NULL)
320      return (cpu_class_header *)((UINT8 *)device->token + device->tokenbytes) - 1;
321   return NULL;
322}
323
324
325/*-------------------------------------------------
326    cpu_get_debug_data - return a pointer to
327    the given CPU's debugger data
328-------------------------------------------------*/
329
330INLINE cpu_debug_data *cpu_get_debug_data(running_device *device)
331{
332   cpu_class_header *classheader = cpu_get_class_header(device);
333   return classheader->debug;
334}
335
336
337/*-------------------------------------------------
338    cpu_get_address_space - return a pointer to
339    the given CPU's address space
340-------------------------------------------------*/
341
342INLINE const address_space *cpu_get_address_space(running_device *device, int spacenum)
343{
344   return device->space(spacenum);
345}
346
347#endif   /* __CPUEXEC_H__ */

Previous 15994 Revisions Next


© 1998-2018 The MESS Team