mspan.c 39.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548
/**************************************************************************
 *                                                                        *
 *               Copyright (C) 1994, Silicon Graphics, Inc.               *
 *                                                                        *
 *  These coded instructions, statements, and computer programs  contain  *
 *  unpublished  proprietary  information of Silicon Graphics, Inc., and  *
 *  are protected by Federal copyright law.  They  may  not be disclosed  *
 *  to  third  parties  or copied or duplicated in any form, in whole or  *
 *  in part, without the prior written consent of Silicon Graphics, Inc.  *
 *                                                                        *
 **************************************************************************/

/*
 *  Memory Span Unit
 */

#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#ifdef __sgi__
#include <gl.h>
#else
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#endif
#include <PRimage.h>

#include "mspan.h"
#include "mbi.h"
#include "rdp_opts.h"
#include "verify.h"


#define POSEDGE         (save_clk && !save_clk_old)
#define NEGEDGE         (!save_clk && save_clk_old)
#define ODD(x)		((x) & 0x1)
#define EVEN(x)		!ODD(x)
#ifndef MIN
#define MIN(x, y)       (((x) < (y)) ? (x) : (y))
#endif

/* XXX I wish there was someway to get both of these */
#define MAXX_INIT	320
#define MAXY_INIT	240

/* Global data - Ok since only one instance */
static rdram_t ram;
static ms_cmd_t ms_commands[MAX_MEMSPAN_CMDS];
static int ncapture;
#ifdef __sgi__
static char *outputFilename = "\0";	
#else
static char *outputFilename[256];
#endif
static char *infilename = "test"; /* if no outputFilename specified, use this */
static int visualoutput;
static int exitonsyncfull;
static int ms_dump;				
static int screen_width=MAXX_INIT;
static int screen_height=MAXY_INIT;
static int zbufdump=0;
static unsigned long nClocks;
#ifndef __sgi__
Display *xdpy;
Window xwin;
Pixmap xpix;
GC xgc;
Colormap xcmap;
#endif

static unsigned char hiddenmask[] = {
    ~0xc0, 
    ~0x30,
    ~0x0c, 
    ~0x03 
};

static int hiddenshift[] = {
    6,
    4, 
    2, 
    0
};

static
openwindow()
{
#ifdef __sgi__
    prefposition(50, 49 + screen_width, 300, 299 + screen_height);
    foreground();
    winopen("memspan simulation");
    RGBmode();
    gconfig();
    RGBcolor(0, 0, 0);
    clear();
#else
    XSetWindowAttributes swa;
    int screen;
    Atom wm_protocols, wm_delete_window;
    XVisualInfo vinfo;
    XGCValues gcv;
    XColor rgb;

    xdpy = XOpenDisplay(0);
    if (!xdpy) {
    	fprintf(stderr, "can't open display\n");
	exit(1);
    }
    screen = DefaultScreen(xdpy);
    if (!XMatchVisualInfo(xdpy, screen, 24, TrueColor, &vinfo)) {
    	fprintf(stderr, "can't find truecolor visual\n");
	exit(1);
    }
    xcmap = swa.colormap = XCreateColormap(xdpy, RootWindow(xdpy, screen), vinfo.visual, AllocNone);
    swa.background_pixel = 0;
    swa.event_mask = ExposureMask | StructureNotifyMask ;
    xwin = XCreateWindow(xdpy, RootWindow(xdpy, screen), 0, 0, screen_width,
                        screen_height, 0, vinfo.depth, CopyFromParent,
			vinfo.visual,
                        CWColormap|CWBackPixel|CWEventMask, &swa);
    xpix = XCreatePixmap(xdpy, xwin, screen_width, screen_height,
    	vinfo.depth);
    XStoreName(xdpy, xwin, "mspan");
    wm_protocols = XInternAtom(xdpy, "WM_PROTOCOLS", False);
    wm_delete_window = XInternAtom(xdpy, "WM_DELETE_WINDOW", False);
    XSetWMProtocols(xdpy, xwin, &wm_delete_window, 1);
    XMapWindow(xdpy, xwin);
    XClearWindow(xdpy, xwin);
    XSync(xdpy, 0); /* need to wait for map */
    xgc = XCreateGC(xdpy, xwin, 0, &gcv);
#if 1
    rgb.red = rgb.green = rgb.blue = 0xFFFF/3;
    rgb.flags = DoRed | DoGreen | DoBlue;
    XAllocColor(xdpy, swa.colormap, &rgb);
    XSetForeground(xdpy, xgc, rgb.pixel);
    XFillRectangle(xdpy, xwin, xgc, 0, 0, screen_width, screen_height);
#endif
    XFlush(xdpy);
#endif
}


/* Routine from Kevin to dump data out in his format for backend filter */
static
WriteCVGFile(int Format, int Size, int Width, int Height, 
	     char *MainBase, char *HiddenBase, char *TmemBase)
{
    FILE *CVGFile;
    char FileName[100];
    int MainSize, HiddenSize, TmemSize;
    unsigned char F, S;
    unsigned short W, H;
    struct CVGHeader ConvHeader;

    sprintf(FileName, "OutData/%s_%d.cvg", outputFilename, ncapture);
    fprintf(stderr, "saving %s\n", FileName);

    if ((CVGFile = fopen(FileName, "w")) == NULL)
	{
	    fprintf(stderr, "Couldn't create .cvg file \n");
	    return;
	}

    if ((Format == G_IM_FMT_RGBA) && (Size == G_IM_SIZ_32b))
	{
	    MainSize   = (Width * Height) << 2;
	    HiddenSize = 0;
	    TmemSize   = 0;
	}
    else if ((Format == G_IM_FMT_IA) && (Size == G_IM_SIZ_16b))
	{
	    MainSize   = (Width * Height) << 1;
	    HiddenSize = 0;
	    TmemSize   = 0;
	}
    else if ((Format == G_IM_FMT_RGBA) && (Size == G_IM_SIZ_16b))
	{
	    MainSize   = (Width * Height) << 1;
	    HiddenSize = (MainSize >> 3) + ((MainSize % 8) ? 1 : 0);
	    TmemSize   = 0;
	}
    else if ((Format == G_IM_FMT_I) && (Size == G_IM_SIZ_8b))
	{
	    MainSize   = (Width * Height) << 0;
	    HiddenSize = 0;
	    TmemSize   = 0;
	}
    else if ((Format == G_IM_FMT_CI) && (Size == G_IM_SIZ_8b))
	{
	    MainSize   = (Width * Height) << 0;
	    HiddenSize = 0;
	    /* TmemSize   = Something; */
	}
    else
	{
	    fprintf(stderr, "Error in size/format \n");
	    return;
	}
	
    bzero(&ConvHeader, sizeof(ConvHeader));	
    ConvHeader.magic  = htonl(CVGMAGIC);
    ConvHeader.format = Format;
    ConvHeader.size   = Size;
    ConvHeader.width  = htons(Width);
    ConvHeader.height = htons(Height);

    fwrite(&ConvHeader, sizeof(struct CVGHeader), 1, CVGFile);

    fwrite(MainBase,   1, MainSize,   CVGFile);
    fwrite(HiddenBase, 1, HiddenSize, CVGFile);
    fwrite(TmemBase,   1, TmemSize,   CVGFile);

    fclose(CVGFile);
}


captureimage32(unsigned char *base, long xsize, long ysize)
{
    IMAGE		*img;
    char filename[100];
    unsigned char *p;
    unsigned short *rbuf, *gbuf, *bbuf;
    int i, j;

    sprintf(filename, "OutData/%s_%d.rgb", outputFilename, ncapture);
    fprintf(stderr, "saving (32 bit RGB) %s\n", filename);
    
    img = iopen(filename, "w", RLE(1), 3, xsize, ysize, 3);
    if (img == (IMAGE *)0) {
	fprintf(stderr, "couldn't create .rgb file\n");
	return;
    }
    
    rbuf = (unsigned short *)malloc(sizeof(unsigned short) * xsize);
    if (rbuf == NULL)
	goto cleanup;
    
    gbuf = (unsigned short *)malloc(sizeof(unsigned short) * xsize);
    if (gbuf == NULL)
	goto cleanup;

    
    bbuf = (unsigned short *)malloc(sizeof(unsigned short) * xsize);
    if (bbuf == NULL)
	goto cleanup;

        
    /* read data out of framebuffer into .rgb file */
    for ( i = 0; i < ysize; i++) {
	p = base + ((ysize - i - 1) * xsize * 4);
	for (j = 0; j < xsize; j++) {
	    rbuf[j] = *p++;
	    gbuf[j] = *p++;
	    bbuf[j] = *p++;
	    *p++;
	}
	putrow(img, rbuf, i, 0);
	putrow(img, gbuf, i, 1);
	putrow(img, bbuf, i, 2);
    }
    
cleanup:
    if (rbuf) free(rbuf);
    if (gbuf) free(gbuf);
    if (bbuf) free(bbuf);
    iclose(img);
}

captureimage16(unsigned char *base, long xsize, long ysize)
{
    IMAGE		*img, *cvgimg;
    char filename[100];
    unsigned char *p, c1, c2;
    unsigned short *rbuf, *gbuf, *bbuf, *cbuf;
    int i, j, offset;

    sprintf(filename, "OutData/%s_%d.rgb", outputFilename, ncapture);
    fprintf(stderr, "saving (16 bit RGB) %s\n", filename);
    
    img = iopen(filename, "w", RLE(1), 3, xsize, ysize, 3);
    if (img == (IMAGE *)0) {
	fprintf(stderr, "couldn't create .rgb file\n");
	return;
    }
    sprintf(filename, "OutData/%s_%d.cvg", outputFilename, ncapture);
    cvgimg = iopen(filename, "w", RLE(1), 2, xsize, ysize, 1);
    if (cvgimg == (IMAGE *)0) {
	fprintf(stderr, "couldn't create .cvg file\n");
	return;
    }
     
    rbuf = (unsigned short *)malloc(sizeof(unsigned short) * xsize);
    if (rbuf == NULL)
	goto cleanup;
    
    gbuf = (unsigned short *)malloc(sizeof(unsigned short) * xsize);
    if (gbuf == NULL)
	goto cleanup;

    
    bbuf = (unsigned short *)malloc(sizeof(unsigned short) * xsize);
    if (bbuf == NULL)
	goto cleanup;
	
    cbuf = (unsigned short *)malloc(sizeof(unsigned short) * xsize);
    if (cbuf == NULL)
	goto cleanup;

        
    /* read data out of framebuffer into .rgb file */
    for ( i = 0; i < ysize; i++) {
	p = base + ((ysize - i - 1) * xsize * 2);
	for (j = 0; j < xsize; j++) {
	    c1 = *p++;
	    c2 = *p++;
	    rbuf[j] = c1 & 0xf8;
	    gbuf[j] = ((c1 << 5) | (c2 >> 3)) & 0xf8;
	    bbuf[j] = (c2 << 2) & 0xf8;
	    
	    /* coverage bits */
	    offset = (i * xsize) + j;
	}
	putrow(img, rbuf, i, 0);
	putrow(img, gbuf, i, 1);
	putrow(img, bbuf, i, 2);
    }
    
cleanup:
    if (rbuf) free(rbuf);
    if (gbuf) free(gbuf);
    if (bbuf) free(bbuf);
    if (cbuf) free(bbuf);
    if (img) iclose(img);
    if (cvgimg) iclose(cvgimg);
}

capturezbuf(unsigned char *Mainbase, char *Hiddenbase, 
             long xsize, long ysize)
{
    IMAGE		*img;
    char filename[100];
    unsigned char *p, c1, c2;
    unsigned char *h, h1;
    unsigned short *rbuf, *gbuf, *bbuf, *cbuf;
    int i, j, offset;
    int exp,man,dz,z;

    sprintf(filename, "OutData/%s_%d.z", outputFilename, ncapture);
    fprintf(stderr, "saving (18 bit zbuffer) %s\n", filename);
    
    img = iopen(filename, "w", RLE(1), 3, xsize, ysize, 3);
    if (img == (IMAGE *)0) {
	fprintf(stderr, "couldn't create .z file\n");
	return;
    }
     
    rbuf = (unsigned short *)malloc(sizeof(unsigned short) * xsize);
    if (rbuf == NULL)
	goto cleanup;
    
    gbuf = (unsigned short *)malloc(sizeof(unsigned short) * xsize);
    if (gbuf == NULL)
	goto cleanup;

    
    bbuf = (unsigned short *)malloc(sizeof(unsigned short) * xsize);
    if (bbuf == NULL)
	goto cleanup;
	
    cbuf = (unsigned short *)malloc(sizeof(unsigned short) * xsize);
    if (cbuf == NULL)
	goto cleanup;

        
    /* read data out of zbuffer into .z file */
    assert ((xsize % 4) == 0);
    for ( i = 0; i < ysize; i++) {
	p = Mainbase + ((ysize - i - 1) * xsize * 2);
	h = Hiddenbase + (((ysize - i - 1) * xsize * 2)/HIDDEN_FACTOR);
	for (j = 0; j < xsize; j++) {
	    c1 = *p++;
	    c2 = *p++;
	    h1 = (*h >> hiddenshift[j % 4]) & 0x3;
	    if ((j % 4) == 3)
		h++;

	    exp = (c1>>5) & 0x7;
            man = (((int)c1<<6) & 0x7c0)  | ((c2 >> 2) & 0x3f);
	    dz  = ((c2<<2) & 0xc) | (h1 & 0x3);

	    if (exp > 6)
		z = 0x7f << 11;
	    else {
		man <<= (6-exp);
		z = 0x7f << (18-exp);
	    }
	    z = (z | man) & 0x3ffff;
	    z |= dz << 20;


	    bbuf[j] = (z >> 16) & 0xff;
	    gbuf[j] = (z >>  8) & 0xff;
	    rbuf[j] = (z)       & 0xff;
	    
	    /* coverage bits */
	    offset = (i * xsize) + j;
	}
	putrow(img, rbuf, i, 0);
	putrow(img, gbuf, i, 1);
	putrow(img, bbuf, i, 2);
    }
    
cleanup:
    if (rbuf) free(rbuf);
    if (gbuf) free(gbuf);
    if (bbuf) free(bbuf);
    if (cbuf) free(cbuf);
    if (img) iclose(img);
}

captureimage(unsigned long imagebase, int size, int format, unsigned long zbase)
{
    /*
     * Create the OutData directory, if it doesn't already exist.
     */
    if (access("./OutData", F_OK) == -1) {
        if (mkdir("./OutData", 06775) == -1) {
	    fprintf(stderr, "memspan: couldn't open OutData directory.\n");
	    perror(NULL);
	    exit(1);
	}
    }

    /*
     * Call msync to flush all writes; that way the close of the mmapped
     * .mem file should proceed swiftly, even if it is nfs mounted.
     */
    msync(ram.main_addr, MAIN_MEMORY_SIZE, MS_SYNC);

    if (size == G_IM_SIZ_32b)
	captureimage32(ram.main_addr + imagebase, screen_width, screen_height);
	
    if (size == G_IM_SIZ_16b)
	captureimage16(ram.main_addr + imagebase, screen_width, screen_height);
	
    WriteCVGFile(format, size, screen_width, screen_height, ram.main_addr + imagebase,
		ram.hidden_addr + (imagebase / HIDDEN_FACTOR), NULL);
    if (zbufdump)
        capturezbuf(ram.main_addr + zbase, 
                ram.hidden_addr + (zbase / HIDDEN_FACTOR), 
                screen_width, screen_height);
    
    ncapture++;
}

/*
 * writecolor
 *   r, g, b, a - all 8 bits
 *     (a is really cvg and only 3 bits)
 *   format - G_IM_FMT_RGBA, G_IM_FMT_CI, G_IM_FMT_IA
 *   size - G_IM_SIZ_32b, G_IM_SIZ_16b, G_IM_SIZ_8b
 *   base - base address of color buffer (a byte address)
 *   offset - pixel offset into color buffer (ie units is # of pixels)
 * 
 * XXX assert that base is on x word boundary
 */
static void
writecolor(unsigned char r, unsigned char g, unsigned char b, unsigned char a,
unsigned char format, unsigned char size,
unsigned long base, unsigned long offset, int ncmd)
{
    unsigned char *addr;
    unsigned char hidden;
    
    if (ms_dump > 2) {
	fprintf(stderr, "memspan write[%d, %d]: 0x%x (0x%x, 0x%x, 0x%x)\n", ncmd, nClocks,
		offset, r, g, b);
    }
    
    switch (format) {
    case G_IM_FMT_RGBA:
	switch (size) {
	case G_IM_SIZ_32b:
	    addr = ram.main_addr + base + (offset*4);
	    *addr++ = r;
	    *addr++ = g;
	    *addr++ = b;
	    *addr = a << 5;
	    break;
	    
	case G_IM_SIZ_16b:
	    addr = ram.main_addr + base + (offset*2);
	    *addr++ = (r & 0xf8) | (g >> 5);
	    *addr = ( (g & 0x18) << 3) | ((b & 0xf8) >> 2) | ((a & 0x4) >> 2);
	    /* now for the hidden part */
	    addr = ram.hidden_addr + (base / HIDDEN_FACTOR) + (offset / 4);
	    hidden = *addr;
	    hidden &= hiddenmask[offset % 4];
	    hidden |= ((a & 0x3) << hiddenshift[offset % 4]);
	    *addr = hidden;
	    break;
	
	default:
	    fprintf(stderr, "memspan write: RGB size of %d not supported\n", format);
	    break;
	}
	break;
	
    default:
	fprintf(stderr, "memspan write: format not supported (%d)\n", format);
	break;
    }
        
    if (visualoutput) {
#ifdef __sgi__
	RGBcolor(r, g, b);
	pnt2i(offset%screen_width, screen_height - offset/screen_width - 1);
#else
	XColor rgb;
	rgb.red = r << 8; rgb.green = g << 8; rgb.blue = b << 8;
	rgb.flags = DoRed | DoGreen | DoBlue;
	XAllocColor(xdpy, xcmap, &rgb);
	XSetForeground(xdpy, xgc, rgb.pixel);
	XFillRectangle(xdpy, xpix, xgc, offset%screen_width, offset/screen_width, 1, 1);
	XFillRectangle(xdpy, xwin, xgc, offset%screen_width, offset/screen_width, 1, 1);
	XFlush(xdpy);
#endif
    }
}

/*
 * readcolor
 *   rp, gp, bp, ap - all pointers to 8 bits
 *   format - G_IM_FMT_RGBA, G_IM_FMT_CI, G_IM_FMT_IA
 *   size - G_IM_SIZ_32b, G_IM_SIZ_16b, G_IM_SIZ_8b
 *   base - base address of color buffer (a byte address)
 *   offset - pixel offset into color buffer (ie units is # of pixels)
 */
static void
readcolor(unsigned char *rp, unsigned char *gp, unsigned char *bp, unsigned char *ap,
unsigned char format, unsigned char size,
unsigned long base, unsigned long offset)
{
    unsigned char *addr;
    unsigned char c1, c2;
    
    switch (format) {
    case G_IM_FMT_RGBA:
	switch (size) {
	case G_IM_SIZ_32b:
	    addr = ram.main_addr + base + (offset*4);
	    *rp = *addr++;
	    *gp = *addr++;
	    *bp = *addr++;
	    *ap = (*addr >> 5);
	    break;
	    
	case G_IM_SIZ_16b:
	    addr = ram.main_addr + base + (offset*2);
	    c1 = *addr++;
	    c2 = *addr;
	    *rp = c1 & 0xf8;
	    *gp = ((c1 & 0x7) << 5) | ((c2 & 0xc0) >> 3);
	    *bp = (c2 & 0x3e) << 2;
	    /* now for the hidden part XXX check endian of bits */
	    addr = ram.hidden_addr + (base / HIDDEN_FACTOR) + (offset / 4);
	    *ap = ((c2 & 0x01) << 2) | ((*addr >> hiddenshift[offset % 4]) & 0x03);
	    break;
	
	default:
	    fprintf(stderr, "memspan read: RGB size of %d not supported\n", size);
	    break;
	}
	break;
	
    default:
	fprintf(stderr, "memspan read: format not supported (%d)\n", format);
	break;
    }
}

/*
 * writez
 *   z - 18 bits of info
 *   base - base address of z buffer (a byte address)
 *   offset - pixel offset into z buffer (ie units is # of pixels)
 * 
 * XXX check order & endian of hidden bits
 */
static void
writez(unsigned long z, unsigned long base, unsigned long offset, int ncmd)
{
    unsigned char *addr;
    unsigned char c;
    
    if (ms_dump > 1) {
	fprintf(stderr, "writez[%d, %d]: z 0x%x, base 0x%x, offset 0x%x\n", ncmd, nClocks,
	    z, base, offset);
    }
    
    addr = ram.main_addr + base + (offset*2);
    *addr++ = (z >> 10) & 0xff;
    *addr++ = (z >> 2) & 0xff;
    /* now for hidden part */
    addr = ram.hidden_addr + (base / HIDDEN_FACTOR) + (offset / 4);
    c = *addr;
    c &= hiddenmask[offset % 4];
    c |= ((z & 0x3) << hiddenshift[offset % 4]);
    *addr = c;
}

/*
 * readz
 *   z - pointer to long (only 18 bits of info needed)
 *   base - base address of z buffer (a byte address)
 *   offset - pixel offset into z buffer (ie units is # of pixels)
 */
static void
readz(unsigned long *zp, unsigned long base, unsigned long offset, int ncmd)
{
    
    unsigned char *addr;
    unsigned char c;
    long z;
    unsigned phys_adrs;
    
    phys_adrs = base + (offset*2);
    phys_adrs %= 0x200000;
    addr = ram.main_addr + phys_adrs;

#ifdef COREDUMP    
    if (ms_dump > 1) {
	fprintf(stderr, "coredump readz[%d, %d]: addr 0x%x = main_addr 0x%x + base 0x%x + offset 0x%x\n", ncmd, nClocks, addr, ram.main_addr, base, (offset*2));
    }
#endif /* COREDUMP */

    z = *addr++ << 10;
    z |= *addr++ << 2;
    /* now for hidden part */
    addr = ram.hidden_addr + (base / HIDDEN_FACTOR) + (offset / 4);
    c = *addr >> hiddenshift[offset % 4];
    z |= (c & 0x3);
    
    *zp = z;
    
    if (ms_dump > 1) {
	fprintf(stderr, "readz[%d, %d]: z 0x%x, base 0x%x, offset 0x%x\n", ncmd, nClocks,
	    z, base, offset);
    }
}

/*
 * This is really inefficient code,  but who cares
 * 
 * returns # of clocks to delay
 */
int
fillcolorbuf(unsigned long base, unsigned char size, unsigned long data,
unsigned long offset, int length, int ncmd)
{
    int i, olen = length;
    int retval;
    unsigned char r, g, b, a;
    unsigned char *addr;
    int save_dump;
	unsigned long clr_data;
    

    if (ms_dump > 0)  
	fprintf(stderr, "fillcolorbuf[%d, %d]: buf 0x%x, size %d, data 0x%x, offset 0x%x, len %d\n", 
	    ncmd, nClocks, base, size, data, offset, length);
	    
    save_dump = ms_dump;
    ms_dump = 0;
  
    switch (size) {
    
    case G_IM_SIZ_16b:
	retval = (length / 4) + 2;
		
	/* write z will write into hidden bits */    
	while (length-- >= 0) {
		if(offset & 1)
	  		clr_data = data & 0xffff;
		else
	  		clr_data = (data >> 16) & 0xffff;
		clr_data <<= 2;

		if (clr_data & 0x4)
	   		clr_data |= 3;

	    writez(clr_data, base, offset, ncmd);
	    offset++;
	}
	break;
    
    case G_IM_SIZ_32b:
	retval = (length / 2) + 2;
	r = (data >> 24) & 0xff;
	g = (data >> 16) & 0xff;
	b = (data >>  8) & 0xff;
	a = (data) & 0xe0;
	addr = ram.main_addr + base + (offset*4);
	while (length-- >= 0) {
	    *addr++ = r;
	    *addr++ = g;
	    *addr++ = b;
	    *addr++ = a;
	}
	break;
    
    default:
	fprintf(stderr, "memspan fill: size of %d not supported\n", size);
	retval = 0;
	break;	
    }
#if 1
    if (visualoutput) {
#ifndef __sgi__
	XColor rgb;
#endif
	if (size == G_IM_SIZ_16b) {
	    unsigned char c1 = (clr_data >> 10)&0xff;
	    unsigned char c2 = (clr_data >> 2)&0xff;
	    r = c1 & 0xf8;
	    g = ((c1 & 0x7) << 5) | ((c2 & 0xc0) >> 3);
	    b = (c2 & 0x3e) << 2;
	    /* try to detect zbuffer clear and skip it */
	    if (data == 0xfffcfffc) goto out;
	}
#ifndef __sgi__
	rgb.red = r << 8; rgb.green = g << 8; rgb.blue = b << 8;
	rgb.flags = DoRed | DoGreen | DoBlue;
	XAllocColor(xdpy, xcmap, &rgb);
	XSetForeground(xdpy, xgc, rgb.pixel);
	XFillRectangle(xdpy, xpix, xgc, (offset)%screen_width, (offset)/screen_width, olen, 1);
	XFillRectangle(xdpy, xwin, xgc, (offset)%screen_width, (offset)/screen_width, olen, 1);
	XFlush(xdpy);
#endif
out:;
    }
#endif
    
    ms_dump = save_dump;
    return retval;
}

void
loadtex(int64 *ptex, unsigned long offset, int size, int tbase, int ncmd)
{
    int64 texture;
    unsigned char *addr;
    int base;

    base = tbase & ~0x7;
    switch (size) {

    case G_IM_SIZ_4b:
	fprintf(stderr, "loadtex: should never load G_IM_SIZ_4b textures.\n");
	/* do something so we don't core dump */
	addr = ram.main_addr + base + (offset);
	break;

    case G_IM_SIZ_8b:
	addr = ram.main_addr + base + (offset);
	break;

    case G_IM_SIZ_16b:
	addr = ram.main_addr + base + (offset*2);
	break;
    
    case G_IM_SIZ_32b:
	addr = ram.main_addr + base + (offset*4);
	break;

    }
    /* Big endian memory, word0 of int64 is LSB */
    texture.word1 = *addr << 24 | *(addr+1) << 16 | *(addr+2) << 8 | *(addr+3);
    addr += 4;
    texture.word0 = *addr << 24 | *(addr+1) << 16 | *(addr+2) << 8 | *(addr+3);
    
    *ptex = texture;
    
    if (ms_dump > 1) {
	fprintf(stderr, "loadtex[%d, %d] 0x%08x%08x offset 0x%x size %d base 0x%x\n", 
	    ncmd, nClocks, texture.word1, texture.word0, offset, size, base);
	if (tbase & 0x7)
	    fprintf(stderr, "    Loadtex Warning: Texture image nonaligned base 0x%x\n", tbase);
    }
}

/* size must be 16b */
void
loadtextlut(int64 *ptex, unsigned long offset, int tbase, int ncmd)
{
    int64 texture;
    unsigned char *addr;
    unsigned short texword;
    int base;

    base = tbase & ~0x7;
    addr = ram.main_addr + base + (offset*2);
    texword = *addr << 8 | *(addr+1);
    /* Big endian memory, word0 of int64 is LSB */
    texture.word0 = texture.word1 = (texword << 16 | texword);
    *ptex = texture;
    
    if (ms_dump > 1) {
	fprintf(stderr, "loadtextlut[%d, %d] 0x%08x%08x offset 0x%x base 0x%x\n", 
	    ncmd, nClocks, texture.word1, texture.word0, offset, base);
	if (tbase & 0x7)
	    fprintf(stderr, "    loadtextlut Warning: Texture image nonaligned base 0x%x\n", tbase);
    }
}
/*
 * XXX Check allignment, hidden bits??,  write enable??
 */
void
copytexture(int64 texture, int size, int base, unsigned long offset, int ntexels, int ncmd)
{
    unsigned char *caddr;
    unsigned short *saddr;
    unsigned tex[NUM_COPY_TEXELS];
    int i;
    unsigned char *haddr;
    unsigned char hidden;
    unsigned char alpha;
    unsigned long hoffset;
    
    assert((size == G_IM_SIZ_8b) || (size == G_IM_SIZ_16b));
    
    if (size == G_IM_SIZ_8b) {
	caddr = ram.main_addr + base + offset;
	tex[0] = (texture.word1 >> 24) & 0xff;
	tex[1] = (texture.word1 >> 16) & 0xff;
	tex[2] = (texture.word1 >>  8) & 0xff;
	tex[3] = (texture.word1) & 0xff;
    } else {
	saddr = (unsigned short *)(ram.main_addr + base + (offset*2));
#ifndef __sgi__
	caddr = ram.main_addr + base + offset*2;
#endif
	tex[0] = (texture.word1 >> 16) & 0xffff;
	tex[1] = (texture.word1) & 0xffff;
	tex[2] = (texture.word0 >> 16) & 0xffff;
	tex[3] = (texture.word0) & 0xffff;
    }
    
    hoffset=offset;
    for (i=0; i<ntexels; i++) {
	if (size == G_IM_SIZ_8b) {
	    *caddr++ = tex[i];
	} else {
#ifdef __sgi__
	    *saddr++ = tex[i];	    
#else
	    *caddr++ = (tex[i] >> 8)&0xff;	    
	    *caddr++ = (tex[i] >> 0)&0xff;	    
#endif
	    alpha = tex[i]&0x1;
	    alpha = alpha | alpha<<1;
	    haddr = (ram.hidden_addr + (base/HIDDEN_FACTOR) + (hoffset/4));
	    hidden = *haddr;
	    hidden &= hiddenmask[hoffset % 4];
	    hidden |= ((alpha & 0x3) << hiddenshift[hoffset % 4]);
	    *haddr = hidden;

	    hoffset++;
	}
	
    }
    
    if (ms_dump > 1)  
	fprintf(stderr, "copytex[%d, %d] 0x%08x%08x offset 0x%x size %d base 0x%x\n", 
	    ncmd, nClocks, texture.word1, texture.word0, offset, size, base);    
	    
    if (visualoutput && size == G_IM_SIZ_16b) {
	short r, g, b;
#ifndef __sgi__
	XColor rgb;
#endif
	
	for (i=0; i < ntexels; i++) {
	    r = ((tex[i] >> 11) & 0x1f) << 3;
	    g = ((tex[i] >>  6) & 0x1f) << 3;
	    b = ((tex[i] >>  1) & 0x1f) << 3;
#ifdef __sgi__
	    RGBcolor(r, g, b);
	    pnt2i((offset+i)%screen_width, screen_height - (offset+i)/screen_width - 1);
#else
	    rgb.red = r << 8; rgb.green = g << 8; rgb.blue = b << 8;
	    rgb.flags = DoRed | DoGreen | DoBlue;
	    XAllocColor(xdpy, xcmap, &rgb);
	    XSetForeground(xdpy, xgc, rgb.pixel);
	    XFillRectangle(xdpy, xpix, xgc, (offset+i)%screen_width, (offset+i)/screen_width, 1, 1);
	    XFillRectangle(xdpy, xwin, xgc, (offset+i)%screen_width, (offset+i)/screen_width, 1, 1);
	    XFlush(xdpy);
#endif
	}	
    }
}

void
printmspancmd(i)
{
    ms_cmd_t *pcmd;
    
    pcmd = &ms_commands[i];
    
    fprintf(stderr, "mspan:[%d, %d] ",i, nClocks);
    
    if (pcmd->state == MSCMD_IDLE) {
	fprintf(stderr, "Idle\n");
	return;
    }
    
    switch (pcmd->cmdtype) {
    case CMD_FILL:
	fprintf(stderr, "Fill, ");
	break;
	
    case CMD_1CYCLE:
	fprintf(stderr, "1CYC, ");
	break;
	
    case CMD_2CYCLE:
	fprintf(stderr, "2CYC, ");
	break;
	
    case CMD_LOAD:
	fprintf(stderr, "LOAD, ");
	break;
	
    case CMD_LOAD_TLUT:
	fprintf(stderr, "LOADTLUT, ");
	break;
	
    case CMD_COPY:
	fprintf(stderr, "COPY, ");
	break;
	
    default:
	fprintf(stderr, "Unknown %d, ", pcmd->cmdtype);
	break;
	
    }
    fprintf(stderr, "saddr 0x%x, eaddr 0x%x, len %d,", pcmd->startaddr, pcmd->endaddr, pcmd->length);
    if ( pcmd->dir < 0 )
	fprintf(stderr, " <, ");
    else
	fprintf(stderr, " >, ");
    fprintf(stderr, "skip %d, vld %d\n",pcmd->skipcnt, pcmd->validcnt);
    if (pcmd->cmdtype == CMD_LOAD || pcmd->cmdtype == CMD_LOAD_TLUT) {
	fprintf(stderr, "\tinc %d, texvalidcnt %d\n", pcmd->loadtexinc, pcmd->loadtexvalidcnt);
    }
}

void
printallmspancmds()
{
    int i;

    fprintf(stderr, "List of all Commands:\n");
    for (i=0; i<MAX_MEMSPAN_CMDS; i++) {
	printmspancmd(i);
    }
    fprintf(stderr, "End of List\n");

}

void
mspan(mspan_t **pp0, mspan_t **pp1)
{
    mspan_t *p0, *p1;
    int save_clk;
    int save_clk_old;
    int i;
    ms_cmd_t *pcmd;
    unsigned char red,  grn, blue, cvg;
    unsigned long z;
    
    /*
     *  Get pointers, clocks
     */
    p0 = *pp0;
    p1 = *pp1;
    save_clk = p0->gclk;
    save_clk_old = p1->gclk_old;
    
    if(POSEDGE && p0->gclk_en)
    {
	/* transfer all next-clock register values to register outputs. */
	*pp0 = p1; /* swap */
	*pp1 = p0;
	p0 = *pp0; /* fix pointers */
	p1 = *pp1;
	
	if (p1->strobe_sync_full) {
	    p1->sync_full = 1;
	} else {
	    p1->sync_full = p0->sync_full;	/* hold */
	}
	
	/* update clocks for each active command */
	pcmd = &ms_commands[0];
	p1->rel_sync_full = 1;	    /* assume idle */
	for (i=0; i<MAX_MEMSPAN_CMDS; i++) {
	    if (pcmd->state != MSCMD_IDLE) {
		p1->rel_sync_full = 0;	    /* not idle */
		pcmd->clocks++;
	    }
	    pcmd++;
	}
	
	if (p1->sync_full && p1->rel_sync_full) {
	    p1->sync_full = 0;
	} else {
	    p1->rel_sync_full = 0;
	}
	
	
	/* check if we need to capture an image and exit */
	if (p1->reset && p1->reset_negedge && (p1->capture  || (exitonsyncfull && p1->rel_sync_full))) {
	    captureimage(p1->at_color_base, p1->at_color_size, p1->at_color_format,
				p1->at_z_base);
	    /*dump_tmem("dump.tmem");*/
            printf("Number of Clocks (%s): %d\n", outputFilename, nClocks);
	    if (visualoutput) {
                fprintf(stderr,"hit ^c to exit\n");
                fflush(stdout);
#ifndef __sgi__
		for(;;) {
		    XEvent ev;
		    if (XCheckTypedEvent(xdpy, Expose, &ev)) {
			XCopyArea(xdpy, xpix, xwin, xgc, 0, 0, screen_width, screen_height, 0, 0);
			XFlush(xdpy);
		    }
		    sleep(1);
		}
#endif
                pause();
            }

	    p0->exit = 1;
	}
	
	/* HACK ALERT */
	/* SetColorImage() with format = 5 */
	if (p1->at_color_format == 5) {
	    switch (p1->at_color_size) {
	    case G_IM_SIZ_16b:
	    case G_IM_SIZ_32b:
		fprintf(stderr, "HACK ALERT fill buffer %d size\n", p1->at_color_size);
		for (i=0; i<screen_height; i++) {
		    fillcolorbuf(p1->at_color_base, p1->at_color_size,
			p1->at_fill_color, i*screen_width, screen_width-1, -1);
		}
		if (visualoutput) {
#ifndef __sgi__
		    XColor rgb;
#endif
		    int r, g, b;
		    int data = p1->at_fill_color;
		    if (p1->at_color_size == G_IM_SIZ_16b) {
			unsigned char c1 = (data >> 24)&0xff;
			unsigned char c2 = (data >> 16)&0xff;
			r = c1 & 0xf8;
			g = ((c1 & 0x7) << 5) | ((c2 & 0xc0) >> 3);
			b = (c2 & 0x3e) << 2;
			/* try to detect zbuffer clear and skip it */
			if (data == 0xfffcfffc) break;
		    } else {
			r = (data >> 24) & 0xff;
			g = (data >> 16) & 0xff;
			b = (data >>  8) & 0xff;
		    }
#ifndef __sgi__
		    rgb.red = r << 8; rgb.green = g << 8; rgb.blue = b << 8;
		    rgb.flags = DoRed | DoGreen | DoBlue;
		    XAllocColor(xdpy, xcmap, &rgb);
		    XSetForeground(xdpy, xgc, rgb.pixel);
		    XFillRectangle(xdpy, xpix, xgc, 0, 0, screen_width, screen_height);
		    XFillRectangle(xdpy, xwin, xgc, 0, 0, screen_width, screen_height);
		    XFlush(xdpy);
#endif
		}
		break;
		
	    default:
		fprintf(stderr, "HACK ALERT fill buffer %d not implemented\n",
		    p1->at_color_size);
	    }
	}
#ifndef __sgi__
	if (visualoutput && nClocks % 100 == 0) {
		XEvent ev;
		if (XCheckTypedEvent(xdpy, Expose, &ev)) {
		    XCopyArea(xdpy, xpix, xwin, xgc, 0, 0, screen_width, screen_height, 0, 0);
		    XFlush(xdpy);
		}
	}
#endif

        /* remember that negative edge of reset occured */
	if(p1->reset == 0 && p0->reset == 1)
          p0->reset_negedge = 1;
        else /* hold */
          p0->reset_negedge = p1->reset_negedge;

	/* Check for new command */	
	if (p1->ew_cv_newspan && p1->reset && p1->reset_negedge) {
	    for (i=0; i<MAX_MEMSPAN_CMDS; i++) {
		pcmd = &ms_commands[i];
		if (pcmd->state == MSCMD_IDLE)
		    break;
	    }
	    if (i == MAX_MEMSPAN_CMDS) {
		fprintf(stderr, "No free memspan commands\n");
		printallmspancmds();
	    } else {
		/* initialize the memspan command */
		pcmd->state = MSCMD_BUSY;
		pcmd->clocks = 0;		
	    }
	}
	
	/* Do work for all active commands */
	pcmd = &ms_commands[0];
	for (i=0; i<MAX_MEMSPAN_CMDS; i++) {
	    if (pcmd->state != MSCMD_IDLE) {
	    
		if (pcmd->clocks == CLOCKS_TO_START_VALID) {
		    pcmd->startaddr = p1->ew_ms_addr;
		    pcmd->length = p1->ew_ms_length;
		}
		
		if (pcmd->clocks == CLOCKS_TO_END_VALID) {
		    pcmd->endaddr = p1->ew_ms_addr;
		    /* calculate some useful data */
		    if (pcmd->endaddr < pcmd->startaddr)
			pcmd->dir = -1;
		    else
			pcmd->dir = 1;
		    pcmd->validcnt = (pcmd->endaddr - pcmd->startaddr) * pcmd->dir;
		    pcmd->skipcnt = pcmd->length - pcmd->validcnt;
		    pcmd->rzaddr = pcmd->rcoloraddr = pcmd->wzaddr =
			pcmd->wcoloraddr = pcmd->startaddr;
		    pcmd->rzskip = pcmd->rcolorskip = pcmd->wzskip =
			pcmd->wcolorskip = pcmd->skipcnt;
		    pcmd->rzvalidcnt = pcmd->rcolorvalidcnt = pcmd->wzvalidcnt =
			pcmd->wcolorvalidcnt = pcmd->validcnt;
		    pcmd->cmdtype = p1->at_cycle_type;
		    		    
		    if (p1->ew_scissor_load) {
			/* ignore cycle type & convert to load command */
			pcmd->cmdtype = CMD_LOAD;
			pcmd->loadtexaddr = pcmd->startaddr;

			switch (p1->at_tex_size) {
			
			case G_IM_SIZ_8b:
			    pcmd->loadtexinc = 8;
			    break;
			    
			case G_IM_SIZ_16b:
			    pcmd->loadtexinc = 4;
			    break;
			    
			case G_IM_SIZ_32b:
			    pcmd->loadtexinc = 2;
			    break;
			    
			default:
			    fprintf(stderr, "mspan load command invalid size %d\n", p1->at_tex_size);
			    
			}
			pcmd->loadtexvalidcnt = pcmd->validcnt / pcmd->loadtexinc;
		    } else { 
		    
			switch (pcmd->cmdtype) {
			
			case CMD_1CYCLE:
			    pcmd->clockszneeded = CLOCKS_TO_Z_NEEDED;
			    pcmd->clocksclrneeded = CLOCKS_TO_COLOR_NEEDED;
			    pcmd->clockszvalid = CLOCKS_TO_Z_VALID;
			    pcmd->clocksclrvalid = CLOCKS_TO_COLOR_VALID;
			    break;
			    
			case CMD_2CYCLE:
			    pcmd->clockszneeded = CLOCKS_TO_Z_NEEDED + CLOCKS_2CYCLE_DELAY;
			    pcmd->clocksclrneeded = CLOCKS_TO_COLOR_NEEDED + CLOCKS_2CYCLE_DELAY;
			    pcmd->clockszvalid = CLOCKS_TO_Z_VALID + CLOCKS_2CYCLE_DELAY;
			    pcmd->clocksclrvalid = CLOCKS_TO_COLOR_VALID + CLOCKS_2CYCLE_DELAY;
			    break;
    
			case CMD_FILL:
			    pcmd->wcolorvalidcnt = fillcolorbuf(p1->at_color_base,
				p1->at_color_size, p1->at_fill_color,
				pcmd->startaddr, pcmd->length, pcmd->num);
			    break;
			
			case CMD_COPY:
			    if (pcmd->endaddr < pcmd->startaddr) {
				fprintf(stderr, "MSPAN: copy cmd end < start  SKIPPING ");
				fprintf(stderr, "start 0x%x, end 0x%x length %d\n",
				    pcmd->startaddr, pcmd->endaddr, pcmd->length);
				pcmd->state = MSCMD_IDLE;
			    }
			    if (p1->at_color_size != G_IM_SIZ_8b &&
				    p1->at_color_size != G_IM_SIZ_16b) {
				fprintf(stderr, "MSPAN: unsupported copy size %d SKIP\n", 
				    p1->at_color_size);
				pcmd->state = MSCMD_IDLE;
			    }
			    if (pcmd->skipcnt) {
				fprintf(stderr, "MSPAN: copy len != end - start SKIP\n");
				fprintf(stderr, "start 0x%x, end 0x%x length %d\n",
				    pcmd->startaddr, pcmd->endaddr, pcmd->length);
				pcmd->state = MSCMD_IDLE;
			    }
			    pcmd->copyaddr = pcmd->startaddr;
			    pcmd->copyvalidcnt = pcmd->validcnt / NUM_COPY_TEXELS;
			    break;
			}
		    }
		    
		    if (ms_dump > 0)
			printmspancmd(i);

		    /* Validity checks */
		    if(pcmd->length < pcmd->validcnt){
			fprintf(stderr, "MSPAN: pcmd->length < pcmd->validcnt SKIPPING ");
			fprintf(stderr, "start 0x%x, end 0x%x length %d\n",
			    pcmd->startaddr, pcmd->endaddr, pcmd->length);
			pcmd->state = MSCMD_IDLE;
		    }
		}
				
		if (pcmd->clocks > CLOCKS_TO_END_VALID) {
		
		    switch (pcmd->cmdtype) {
		    
		    case CMD_FILL:
			if (pcmd->wcolorvalidcnt == 0) {
			    pcmd->state = MSCMD_IDLE;
			} else {
			    pcmd->wcolorvalidcnt--;
			}
			break;		/* Fill */
		    
		    case CMD_1CYCLE:
		    case CMD_2CYCLE:
		    
			if ((pcmd->clocks >= pcmd->clockszneeded) && 
			    (pcmd->cmdtype == CMD_1CYCLE || ODD(pcmd->clocks))) {
			    if (pcmd->rzskip > 0) {
				pcmd->rzskip--;
			    } else {
#ifdef COREDUMP
    if (ms_dump > 1) {
	fprintf(stderr, "coredump:  rzvalidcnt %d\n", pcmd->rzvalidcnt);
    }
#endif /* COREDUMP */
				if ((pcmd->rzvalidcnt >= 0) && p1->at_z_enable) { /* was-at_z_rmw */
				    readz(&z, p1->at_z_base, pcmd->rzaddr, pcmd->num);
				    p0->bl_mem_z = z;
				}
				pcmd->rzaddr += pcmd->dir;
				pcmd->rzvalidcnt--;
			    }
			}
			    
			if ((pcmd->clocks >= pcmd->clocksclrneeded) && 
			    (pcmd->cmdtype == CMD_1CYCLE || EVEN(pcmd->clocks))) {
			    if (pcmd->rcolorskip > 0) {
				pcmd->rcolorskip--;
			    } else {
				if (pcmd->rcolorvalidcnt >= 0) {
				    if (p1->at_color_rmw) {
					readcolor(&red, &grn, &blue, &cvg,
					    p1->at_color_format, p1->at_color_size, 
					    p1->at_color_base, pcmd->rcoloraddr);
					p0->bl_mem_r = red;
					p0->bl_mem_g = grn;
					p0->bl_mem_b = blue;
					p0->bl_mem_a = cvg;
				    } else {
					p0->bl_mem_a = 0x7;
				    }
				}
				pcmd->rcoloraddr += pcmd->dir;
				pcmd->rcolorvalidcnt--;
			    }
			}
			    
			if ((pcmd->clocks >= pcmd->clockszvalid) && 
			    (pcmd->cmdtype == CMD_1CYCLE || ODD(pcmd->clocks))) {
			    if (pcmd->wzskip > 0) {
				pcmd->wzskip--;
			    } else {
				if ((pcmd->wzvalidcnt >= 0) && p1->bl_z_we) {
				    writez(p1->bl_z, p1->at_z_base, pcmd->wzaddr, pcmd->num);
				}
				pcmd->wzaddr += pcmd->dir;
				pcmd->wzvalidcnt--;
			    }
			}
			
			if ((pcmd->clocks >= pcmd->clocksclrvalid) && 
			    (pcmd->cmdtype == CMD_1CYCLE || EVEN(pcmd->clocks))) {
			    if (pcmd->wcolorskip > 0) {
				pcmd->wcolorskip--;
			    } else {
				if (p1->bl_color_we) {
				    assert(pcmd->wcolorvalidcnt >= 0);
				    writecolor(p1->bl_r, p1->bl_g, p1->bl_b, p1->bl_a,
					p1->at_color_format, p1->at_color_size, 
					p1->at_color_base, pcmd->wcoloraddr, pcmd->num);
				}
				pcmd->wcoloraddr += pcmd->dir;
				if (pcmd->wcolorvalidcnt == 0)
				    pcmd->state = MSCMD_IDLE;
				else
				    pcmd->wcolorvalidcnt--;
			    }
			}
			break;		/* 1 & 2 Cycle */
			
		    case CMD_LOAD:
		    case CMD_LOAD_TLUT:
			if (pcmd->clocks == 4) {    /* hack */
			    if (p1->ms_load_tlut) {
				if (p1->at_tex_size != G_IM_SIZ_16b) {
				    fprintf(stderr, "MSPAN: LOAD_TLUT tex size !16 (%d)SKIPPING ", 
					    p1->at_tex_size);
				    pcmd->state = MSCMD_IDLE; 
				}
				pcmd->loadtexinc = 1;
				pcmd->loadtexvalidcnt = pcmd->validcnt / pcmd->loadtexinc;
				pcmd->cmdtype = CMD_LOAD_TLUT;
		    
				if (ms_dump > 0) {
				    fprintf(stderr, "LOAD changed to LOAD_TLUT!!\n");
				    printmspancmd(i);
				}
			    }
			}
			if (pcmd->clocks >= CLOCKS_TO_LOAD_NEEDED) {
			    int64 texture;
			    
			    assert(pcmd->loadtexvalidcnt >= -1);
				
			    if (pcmd->loadtexvalidcnt < 0) {
				pcmd->state = MSCMD_IDLE;
				p0->tex_bus_e = 0;
				p0->tex_data_valid = 0;
				p1->tex_bus_e = 0;
				p1->tex_data_valid = 0;
			    } else {
				if (pcmd->cmdtype == CMD_LOAD_TLUT) {
				    loadtextlut(&texture, pcmd->loadtexaddr,
						p1->at_tex_base, pcmd->num);
				} else {
				    loadtex(&texture, pcmd->loadtexaddr, p1->at_tex_size,
					    p1->at_tex_base, pcmd->num);
				}
				p0->tex_bus = texture;
				p0->tex_bus_e = 1;
				p0->tex_data_valid = 1;
				pcmd->loadtexaddr += pcmd->loadtexinc;
				pcmd->loadtexvalidcnt--;
			    }
			    
			}
			break;		/* texture LOAD */
			
		    case CMD_COPY:
			if (pcmd->clocks >= CLOCKS_TO_COPY_VALID) {
			    
			    assert(pcmd->copyvalidcnt >= 0);
			    
			    copytexture(p1->tex_bus, p1->at_color_size, p1->at_color_base,
				pcmd->copyaddr,
				MIN((pcmd->endaddr - pcmd->copyaddr) + 1, NUM_COPY_TEXELS),
				pcmd->num);
			    pcmd->copyaddr += NUM_COPY_TEXELS;
			    
			    if (pcmd->copyvalidcnt == 0)
				pcmd->state = MSCMD_IDLE;
			    else
				pcmd->copyvalidcnt--;
			    
			}
			
			break;		/* texture copy */
			
		    default:
			fprintf(stderr, "Unknown mspan command: %d\n", pcmd->cmdtype);
		    }
		}
	    }
	    pcmd++;
	}

	if(p1->reset)	
 	  nClocks++;
	else
	  nClocks = 0;

    } /* POSEDGE */

    /* save last clock state */
    p0->gclk_old = p1->gclk_old = save_clk;
}

void
mspan_init(mspan_t *p0, mspan_t *p1)
{
    int c;
    char *dump_str, *memfile;
    extern int optind, opterr, optopt;
    int memfd;
    char *indata_dir;
    char *indata = NULL;
    char *extension;
    char infile[512];
  
    optind = 1;
    opterr = 0;

    p1->gclk = p0->gclk = 0;
    p1->gclk_old = p0->gclk_old = 0;
    p1->exit = p0->exit = 0;
    p1->reset_negedge = p0->reset_negedge = 0;

    /* get directory locations */
    if((indata_dir = getenv("RDP_INDATA")) == NULL)
      indata_dir = DEF_RDP_INDATA;
 
    memfile = NULL;
    
    while((c = getopt(p1->argc, p1->argv, OPTARG)) != EOF)
    {
        switch(c) {
	case 'v':
	    visualoutput = 1;
	    break;
	       
	case 'e':
	    exitonsyncfull = 1;
	    break;

        case 'I':
            indata_dir = optarg;
            break;
	       
	case 'i':
	    infilename = optarg;
	    break;
        
	case 'W':
	    sscanf(optarg,"%i",&screen_width);
	    break;
	
	case 'm':
	    memfile = optarg;
	    break;	
        
	case 'H':
	    sscanf(optarg,"%i",&screen_height);
	    break;
	       
	case 'f':
	    strcpy(outputFilename, optarg);
	    break;
        
	case 'z':
	    zbufdump = 1;
	    break;
        }
    }

    /*
     * Provide backwards compatibility for older command line users who use
     * the '-i' option as a means of filename generation (instead of the newer
     * '-t' option).
     */
    if (outputFilename[0] == NULL) {
	strcpy(outputFilename, infilename);
    }
 
    assert(ram.main_addr == 0);
    
    if (memfile == NULL) {
	if ( (ram.main_addr = malloc(MAIN_MEMORY_SIZE)) == NULL) {
	    fprintf(stderr, "memspan: couldn't malloc 0x%x bytes for main mem\n",
		MAIN_MEMORY_SIZE);
	    exit(1);
	}
	ram.main_size = MAIN_MEMORY_SIZE;
	bzero(ram.main_addr, ram.main_size);
    } else {
	/* strip extension */
    	extension = strstr(memfile,".mem");
    	if(extension) *extension = '\0';
    	sprintf(infile,"%s/%s.mem\0",indata_dir,memfile);
	memfd = open(infile, O_RDWR);
	if (memfd == -1) {
	    fprintf(stderr, "memspan: couldn't open memory file %s\n", infile);
	    perror(NULL);
	    exit(1);
	}
	ram.main_addr = mmap(NULL, MAIN_MEMORY_SIZE, (PROT_READ | PROT_WRITE),
			    MAP_SHARED, memfd, 0);
	if (ram.main_addr == (unsigned char *)-1) {
	    fprintf(stderr, "memspan: couldn't mmap memory file %s\n", infile);
	    perror(NULL);
	    exit(1);
	}
    }
    
    if ( (ram.hidden_addr = malloc(HIDDEN_MEMORY_SIZE)) == NULL) {
	fprintf(stderr, "memspan: couldn't malloc 0x%x bytes for hidden mem\n",
	    HIDDEN_MEMORY_SIZE);
	exit(1);
    }
    ram.hidden_size = HIDDEN_MEMORY_SIZE;
    bzero(ram.hidden_addr, ram.hidden_size);
    
    if (visualoutput)
	openwindow();
	
    if (dump_str = getenv("MSPAN_DUMP")) {
	if (!(sscanf(dump_str,"%i",&ms_dump)))
	    ms_dump = 0;
    }
    
    for (c=0; c<MAX_MEMSPAN_CMDS; c++) {
	ms_commands[c].num = c;
    }

}