int main(int argc, char *argv[]) { FILE *fpOut=NULL; int traceLevel; ATerm bottom; ATinit(argc,argv,&bottom); switch(parseArgs(argc, argv,&fpOut,&traceLevel)) { case ERR_ARGS: doHelp(argv[0]); exit(EXIT_ERR_ARGS); break; case ERR_FILE: exit(EXIT_ERR_FILE); break; case CMD_HELP: doHelp(argv[0]); exit(EXIT_OK); break; case CMD_VERSION: doVersion(argv[0]); exit(EXIT_OK); case CMD_CONVERT: exit(doConvert(fpOut, traceLevel)); break; default: exit(EXIT_OK); } } /* main */
int main(int argc, char* argv[]) { int argPos = 0, argNum = argc, ncid; char *fname = (char *) NULL, *tname = "time"; FILE *output = stdout; NCtable_t *tbl = (NCtable_t *) NULL; initMemInfo(); for(argPos = 1; argPos < argNum;) { if (CMargTest(argv[argPos],"-d","--debug")) { SetDebug(); CMargShiftLeft(argPos,argv,argc); argNum--; continue; } if (CMargTest(argv[argPos],"-h","--help")) { if((argPos + 1 < argNum) && (argv[argPos+1][0] == 'e')) doHelp (CMprgName(argv[0]),true); else doHelp (CMprgName (argv[0]),false); cleanup(NCsucceeded); } if (CMargTest(argv[argPos],"-t","--table")) { CMargShiftLeft(argPos,argv,argc); argNum--; tname = argv[argPos]; CMargShiftLeft(argPos,argv,argc); argNum--; continue; } if (CMargTest(argv[argPos],"-f","--file")) { if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) { CMmsgPrint (CMmsgUsrError,"Missing file!"); return (CMfailed); } fname = argv[argPos]; if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-o","--output")) { if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) { CMmsgPrint (CMmsgUsrError,"Missing output!"); return (CMfailed); } if(output != stdout) { CMmsgPrint (CMmsgUsrError, "Output file defined twice!"); cleanup(NCfailed); } if((output = fopen(argv[argPos],"w")) == (FILE *) NULL) { CMmsgPrint (CMmsgUsrError, "Cannot open for writing: %s",argv[argPos]); cleanup(NCfailed); } if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) break; continue; } if ((argv[argPos][0] == '-') && (strlen (argv[argPos]) > 1)) { CMmsgPrint (CMmsgUsrError, "Unknown option: %s!",argv[argPos]); cleanup(NCfailed); } argPos++; } if(fname == (char *) NULL) { doHelp(argv[0],false); CMmsgPrint (CMmsgUsrError, "No file specified!"); cleanup(NCfailed); } if(nc_open(fname,NC_NOWRITE,&ncid) != NC_NOERR) { CMmsgPrint (CMmsgUsrError, "Error opening file!"); cleanup(NCfailed); } if((tbl = NCtableOpen(ncid,tname)) == (NCtable_t *) NULL) { CMmsgPrint (CMmsgUsrError, "Error opening table!"); cleanup(NCfailed); } if(GetDebug()) CMmsgPrint (CMmsgUsrError, "Loaded file!"); NCtableExportAscii(tbl,output); cleanup(NCsucceeded); }
int main(int argc, char** argv) { if (argc < 2) { doHelp(); return 0; } std::vector<plString> fFiles; plDebug::Init(plDebug::kDLAll); plResManager rm; plPageInfo* page; for (int i=1; i<argc; i++) { if (argv[i][0] == '-') { if (argv[i][1] == '-') argv[i]++; if (strcmp(argv[i], "-help") == 0) { doHelp(); return 0; } } else { fFiles.push_back(argv[i]); } } for (size_t i=0; i<fFiles.size(); i++) { try { page = rm.ReadPage(fFiles[i], true); } catch (hsException& e) { fprintf(stderr, "%s:%lu: %s\n", e.File(), e.Line(), e.what()); return 1; } catch (std::exception& e) { fprintf(stderr, "PrcExtract Exception: %s\n", e.what()); return 1; } catch (...) { fprintf(stderr, "Undefined error!\n"); return 1; } std::vector<short> types = rm.getTypes(page->getLocation()); printf("%s :: %s\n", page->getAge().cstr(), page->getPage().cstr()); for (unsigned int f = 0; f < types.size(); f++) { printf("|---[%04X] %s\n", types[f], pdUnifiedTypeMap::ClassName(types[f])); std::vector<plKey> mykeys = rm.getKeys(page->getLocation(), types[f]); for (unsigned int ks = 0; ks < mykeys.size(); ks++) { printf("| |--- %s\n", mykeys[ks]->getName().cstr()); } } } }
int QTshotWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QMAINWINDOW::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: doHelp(); break; case 1: doQuit(); break; case 2: doOpen(); break; case 3: doNew(); break; case 4: doSave(); break; case 5: doData(); break; case 6: doExport(); break; case 7: doExportOK(); break; case 8: doOptions(); break; case 9: doToggle(); break; case 10: doCollapse(); break; case 11: doPlan(); break; case 12: doExtended(); break; case 13: do3D(); break; case 14: doCrossSection((*reinterpret_cast< DBlock*(*)>(_a[1])),(*reinterpret_cast< bool(*)>(_a[2])),(*reinterpret_cast< bool(*)>(_a[3]))); break; case 15: doCrossSection((*reinterpret_cast< DBlock*(*)>(_a[1])),(*reinterpret_cast< bool(*)>(_a[2]))); break; case 16: value_changed((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break; case 17: double_clicked((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3])),(*reinterpret_cast< const QPoint(*)>(_a[4]))); break; } _id -= 18; } return _id; }
void Stop(int code, char *msg) { int cl; int mcl; doHeader(); switch (code) { case 1: doHelp(); break; case 2: cl = strlen(cmdLine); mcl = strlen(msg); cmdLine[cl - mcl] = 0; SetColor(colYELLOW, colSAME); printf("à Error in command-line option:\nà %s", cmdLine); SetColor(colLRED, colSAME); printf("%s\n", msg); break; case 3: SetColor(colLRED, colSAME); printf("Cannot open mutex semaphore \\SEM32\\CONSOLE"); break; } SetColor(colBLUE, colSAME); printf("À´ Done\n"); SetColor(colCYAN, colSAME); exit(code); }
///////////////////// /// \brief doArgs /// \param arguments /// \param stream /// \param getLogFile /// \return /// QString doArgs(const QStringList& arguments, QTextStream &stream, bool *getLogFile) { QString arg; for (int n = 1; n < arguments.count(); ++n) { arg = arguments.at(n); if ((arg == QLatin1String("-h")) || (arg == QLatin1String("-help")) || (arg == QLatin1String("--help"))) { doHelp(stream); exit(0); } else if ((arg == QLatin1String("-v")) || (arg == QLatin1String("-version")) || (arg == QLatin1String("--version"))) { doVersion(stream); exit(0); } else if ((arg == QLatin1String("-d")) || (arg == QLatin1String("-debug")) || (arg == QLatin1String("--debug"))) { *getLogFile = true; } // else if ((arg == QLatin1String("-l")) // || (arg == QLatin1String("-lang")) // || (arg == QLatin1String("--lang"))) // { // doLocale(stream); // } else if (arg[0] == QLatin1Char('-')) { // no other valid options stream << QObject::tr("Invalid parameter \"%1\"\n") .arg(arg); doHelp(stream); exit(1); } else { // it must be a filename return arg; } } return Defs::DEFAULT_PROJECT_FILENAME; }
void doAdmin(int sock, ControlStruct *p) { char *cp, *cp1, tmpBuf[20]; int x; if (dbg) syslog(LOG_DEBUG, "doAdmin():Enter |%s|", p->buf); if (p->passwdMode != 0) { doPrivilege(p, "", sock); } else { for (cp = p->buf; *cp != '\0' && isspace(*cp); cp++); memset(tmpBuf, '\0', sizeof(tmpBuf)); for (x = 0, cp1 = tmpBuf; *cp != '\0' && !isspace(*cp) && (unsigned)x < sizeof(tmpBuf); x++) { *(cp1++) = tolower(*cp++); *cp1 = '\0'; } if (dbg) syslog(LOG_DEBUG, "doAdmin():Command = |%s|", tmpBuf); for (; *cp != '\0' && isspace(*cp); cp++); if (dbg) syslog(LOG_DEBUG, "doAdmin():Remainder Command = |%s|", cp); if (strcmp(tmpBuf, "enable") == 0) doEnable(p, cp); else if (strcmp(tmpBuf, "disable") == 0) doDisable(p, cp); else if (strcmp(tmpBuf, "disconnect") == 0) doDisconnect(p, cp); // else if (strcmp(tmpBuf, "privilege") == 0) // doPrivilege(p, cp, sock); else if (strcmp(tmpBuf, "set") == 0) doSet(p, cp); else if (strcmp(tmpBuf, "help") == 0) doHelp(p, cp); else if (strcmp(tmpBuf, "show") == 0) doShow(p, cp); else if (strcmp(tmpBuf, "verbose") == 0) p->verbose = (p->verbose == 0) ? 1 : 0; else { if (p->verbose) fputs("Error, Command Not recognized\n", p->fp); else fputs("904:Command Not recognized\n", p->fp); } } fflush(p->fp); }
MainWindowComplex::MainWindowComplex(QWidget *parent) :// 基类构造函数 QMainWindow(parent), ui(new Ui::MainWindowComplex) { ui->setupUi(this);mainToolBar=new QToolBar(this); mainToolBar->setAllowedAreas(Qt::TopToolBarArea); actAbout=mainToolBar->addAction("关于",this,SLOT(doAbout())); actHelp=mainToolBar->addAction("帮助",this,SLOT(doHelp())); setWindowTitle("复数运算"); }
int main(int argc, char **argv){ // Interpret the command-lin arguments and decide if they make sense int status = parseArgs(argc, argv, &prefs); printf(COPYRIGHT); setLogLevel(LOG_INFO); if (status == FAIL){ // The command-line was duff... if (prefs.errorMsg != NULL){ // ...and we have a specific error to show the user printf("Error: %s\n", prefs.errorMsg); } else { // ...and we have no specific error message, so show a vague one printf("BitMeter did not understand. "); } printf("Use the '-h' option to display help.\n"); } else if (prefs.help){ // Dump the help info and stop doHelp(); } else if (prefs.version){ // Show the version and stop doVersion(); } else { // We will need to go to the database if we end up here openDb(); dbVersionCheck(); switch(prefs.mode){ case PREF_MODE_DUMP: doDump(); break; case PREF_MODE_SUMMARY: doSummary(); break; case PREF_MODE_MONITOR: doMonitor(); break; case PREF_MODE_QUERY: doQuery(); break; default: assert(FALSE); // Any other mode value should cause parseArgs to fail break; } closeDb(); } return 0; }
MainWindowPoly::MainWindowPoly(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindowPoly) { ui->setupUi(this); mainToolBar=new QToolBar(this); mainToolBar->setAllowedAreas(Qt::TopToolBarArea); actAbout=mainToolBar->addAction("关于",this,SLOT(doAbout())); actHelp=mainToolBar->addAction("帮助",this,SLOT(doHelp())); setWindowTitle("多项式功能"); }
/* Main program (obviously) */ int main(void) { while (1) { initialize(); clearScreen(); printf("%s", introText); while (!gameOver) { prompt(); if (buffer[0] == '\0') { } else if (tolower(buffer[0]) == 'h') { doHelp(); } else if (tolower(buffer[0]) == 'i') { doInventory(); } else if ((tolower(buffer[0]) == 'g') || !strcasecmp(buffer, "n") || !strcasecmp(buffer, "s") || !strcasecmp(buffer, "e") || !strcasecmp(buffer, "w") || !strcasecmp(buffer, "u") || !strcasecmp(buffer, "d") || !strcasecmp(buffer, "north") || !strcasecmp(buffer, "south") || !strcasecmp(buffer, "east") || !strcasecmp(buffer, "west") || !strcasecmp(buffer, "up") || !strcasecmp(buffer, "down")) { doGo(); } else if (tolower(buffer[0]) == 'l') { doLook(); } else if (tolower(buffer[0]) == 't') { doTake(); } else if (tolower(buffer[0]) == 'e') { doExamine(); } else if (tolower(buffer[0]) == 'u') { doUse(); } else if (tolower(buffer[0]) == 'd') { doDrop(); } else if (tolower(buffer[0]) == 'q') { doQuit(); } else if (!strcasecmp(buffer, "xyzzy")) { printf("Nice try, but that won't work here.\n"); } else { printf("I don't understand. Try 'help'.\n"); } /* Handle special actions. */ doActions(); } printf("Game over after %d turns.\n", turnsPlayed); printf("%s", "Do you want to play again (y/n)? "); fgets(buffer, sizeof(buffer)-1, stdin); if (tolower(buffer[0]) == 'n') { break; } } return 0; }
int main(int argc , char **argv) { unsigned short colorArray[INDEX_MAX]; int fd; if (argc < 5 ) { perror(" Args number is less than 4\n"); doHelp(); return 1; } colorArray[INDEX_LED] =(unsigned short) atoi(argv[1]); if (colorArray[INDEX_LED] > 3 ) { doHelp(); perror("led index over range.\n"); return 1; } colorArray[INDEX_REG_LED] =(unsigned short) atoi(argv[2]); colorArray[INDEX_GREEN_LED] =(unsigned short) atoi(argv[3]); colorArray[INDEX_BLUE_LED] =(unsigned short) atoi(argv[4]); // open driver fd = open(DRIVER_NAME,O_RDWR); if ( fd < 0 ) { perror("driver open error.\n"); return 1; } printf("index(%d) r(%d) g(%d) b(%d)\n",colorArray[INDEX_LED],colorArray[INDEX_REG_LED],colorArray[INDEX_GREEN_LED],colorArray[INDEX_BLUE_LED]); write(fd,&colorArray,6); close(fd); return 0; }
fractin::fractin(QWidget *parent) : QMainWindow(parent), ui(new Ui::fractin) { ui->setupUi(this); mainToolBar=new QToolBar(this); mainToolBar->setAllowedAreas(Qt::TopToolBarArea); setWindowTitle("分数"); actHelp=mainToolBar->addAction("帮助",this,SLOT(doHelp())); addToolBar(mainToolBar); mainToolBar->setFloatable(false); mainToolBar->setMovable(false); setFixedSize(249,279); // error="格式不支持!"; }
int main(int argc, char *argv[]) { FILE *streamOut = stdout; parseArgs(argc,argv); if( bTestInternHelp == 1) { doHelp(); /* PrintoutMem(0x12345678); */ return EXIT_SUCCESS; } MEI_TEST_Intern(streamOut); return 0; }
//0:exit,1:continue int CwxBinlogOp::doCommand(char* szCmd) { string strCmd; list < string > value; CwxCommon::trim(szCmd); strCmd = szCmd; CwxCommon::split(strCmd, value, ' '); list<string>::iterator iter = value.begin(); //remove the empty value while (iter != value.end()) { if ((*iter).length() == 0) { value.erase(iter); iter = value.begin(); continue; } iter++; } if (value.size() == 0) return 1; iter = value.begin(); CWX_UINT32 uiItemNum = value.size(); if (0 == strcasecmp((*iter).c_str(), "help")) { doHelp(); } else if (0 == strcasecmp((*iter).c_str(), "info")) { doInfo(); } else if (0 == strcasecmp((*iter).c_str(), "next")) { CWX_UINT32 uiNum = 1; if (1 != uiItemNum) { iter++; uiNum = strtoul((*iter).c_str(), NULL, 0); } doNext(uiNum); } else if (0 == strcasecmp((*iter).c_str(), "prev")) { CWX_UINT32 uiNum = 1; if (1 != uiItemNum) { iter++; uiNum = strtoul((*iter).c_str(), NULL, 0); } doPrev(uiNum); } else if (0 == strcasecmp((*iter).c_str(), "sid")) { if (2 != uiItemNum) { printf("Invalid sid command, using: sid value.\n"); return 1; } iter++; doSid(strtoull((*iter).c_str(), NULL, 0)); } else if (0 == strcasecmp((*iter).c_str(), "rec")) { if (2 != uiItemNum) { printf("Invalid rec command, using: rec value.\n"); return 1; } iter++; doRecord(strtoul((*iter).c_str(), NULL, 0)); } else if (0 == strcasecmp((*iter).c_str(), "group")) { if (2 != uiItemNum) { printf("Invalid group command, using: group value.\n"); return 1; } iter++; doGroup(strtoul((*iter).c_str(), NULL, 0)); } else if (0 == strcasecmp((*iter).c_str(), "key")) { if (3 != uiItemNum) { printf("Invalid key command, using: key k v.\n"); return 1; } iter++; string strKey = *iter; doKey(strKey.c_str(), (*iter).c_str()); } else if (0 == strcasecmp((*iter).c_str(), "head")) { doHead(); } else if (0 == strcasecmp((*iter).c_str(), "data")) { doData(); } else if (0 == strcasecmp((*iter).c_str(), "save")) { if (1 == uiItemNum) { printf("Invalid save command, using: save file.\n"); return 1; } iter++; doSave(*iter); } else if (0 == strcasecmp((*iter).c_str(), "exit")) { return 0; } else { printf("Invalid command %s\n", (*iter).c_str()); doHelp(); } return 1; }
void main( int argc, char **argv) { char match; char **remArgs; int rv; GrScreenResolution_t resolution = GR_RESOLUTION_640x480; float scrWidth = 640.0f; float scrHeight = 480.0f; int frames = -1; float minColor = 10.f, /* Vertex min color */ maxColor = 245.f; /* Vertex max color */ GrVertex localVerts[VERT_COUNT], /* Vertices in world coordinates */ texVerts[4]; /* Texture vertices for background */ float alpha = 192.0f, /* Alpha for blending tringle over background */ y_angle = 0.0f; /* rotation amount */ int firstTime; /* Used for performance calculations */ FxBool plugging = FXFALSE, /* Show shameless plug */ printPerf = FXFALSE, /* Print performance numbers */ lines = FXFALSE, /* Draw lines instead of triangles */ blend = FXFALSE, /* Blend the triangle over the background */ texturing = FXFALSE, /* Texture the tiangle */ antialias = FXTRUE, /* Antialias the triangle? */ bilinear = FXTRUE, /* Perform bilinear filtering on the texture? */ render = FXTRUE, /* Draw? */ backbuffer = FXTRUE, /* Draw to backbuffer? */ background = FXTRUE; /* Draw background? */ GrOriginLocation_t origin = GR_ORIGIN_LOWER_LEFT; /* Origin */ FxU32 swapDelay = 1, /* Arg to grBufferSwap */ trisDrawn, /* # triangles drawn */ trisProcessed, /* # triangles through pipeline */ lastFrame, /* Number of last frame we did perf stats */ frameNum = 0L; /* id of each frame drawn */ GrCullMode_t cullMode = GR_CULL_DISABLE; /* backface culling */ FxU32 startAddress = 0, bgDecalAddress = 0, triDecalAddress = 0; GrTexInfo triDecal, /* Triangle decal texture */ bgDecal; /* Background decal texture */ Gu3dfInfo bgInfo, /* Info on background texture */ triInfo; /* Info on triangle texture */ GrColorCombineFnc_t ccFnc = GR_COLORCOMBINE_ITRGB; /* Start of w/ Gouraud shading */ char *bgFileName = NULL, /* Name of background texture file */ *triFileName = NULL; /* Name of triangle texture file */ int frameCount = 0; FxU32 wrange[2]; FxI32 state_size; void *oldState; /* Initialize Glide */ grGlideInit(); assert( hwconfig = tlVoodooType() ); /* Process Command Line Arguments */ while( rv = tlGetOpt( argc, argv, "nrbtea", &match, &remArgs ) ) { if ( rv == -1 ) { printf( "Unrecognized command line argument\n" ); printf( "%s %s\n", name, usage ); printf( "Available resolutions:\n%s\n", tlGetResolutionList() ); return; } switch( match ) { case 'n': frames = atoi( remArgs[0] ); break; case 'r': resolution = tlGetResolutionConstant( remArgs[0], &scrWidth, &scrHeight ); break; case 'b': bgFileName = strdup( remArgs[0] ); break; case 't': triFileName = strdup( remArgs[0] ); break; case 'a': alpha = (float)atof( remArgs[0] ); break; } } tlSetScreen( scrWidth, scrHeight ); version = grGetString( GR_VERSION ); printf( "%s:\n%s\n", name, purpose ); printf( "%s\n", version ); printf( "Resolution: %s\n", tlGetResolutionString( resolution ) ); if ( frames == -1 ) { printf( "Press A Key To Begin Test.\n" ); tlGetCH(); } grSstSelect( 0 ); assert( grSstWinOpen(tlGethWnd(), resolution, GR_REFRESH_60Hz, GR_COLORFORMAT_ABGR, origin, 2, 1 ) ); grVertexLayout(GR_PARAM_XY, GR_VERTEX_X_OFFSET << 2, GR_PARAM_ENABLE); grVertexLayout(GR_PARAM_RGB, GR_VERTEX_R_OFFSET << 2, GR_PARAM_ENABLE); grVertexLayout(GR_PARAM_A, GR_VERTEX_A_OFFSET << 2, GR_PARAM_ENABLE); grGet(GR_WDEPTH_MIN_MAX, 8, wrange); grGet(GR_GLIDE_STATE_SIZE, 4, &state_size); oldState = malloc(state_size); tlConSet( 0.0f, 0.0f, 1.0f, 1.0f, 80, 40, 0xffffff ); if(frames == -1) { doHelp(); } localVerts[0].x = 0.f; localVerts[0].y = 0.75f; localVerts[0].z = 0.0f; localVerts[0].tmuvtx[0].sow = 255.f; localVerts[0].tmuvtx[0].tow = 255.f; localVerts[0].oow = 1.f; localVerts[0].r = maxColor; localVerts[0].g = minColor; localVerts[0].b = minColor; localVerts[0].a = 255.f; localVerts[1].x = -0.75f; localVerts[1].y = -0.75f; localVerts[1].z = 0.0f; localVerts[1].tmuvtx[0].sow = 0.f; localVerts[1].tmuvtx[0].tow = 255.f; localVerts[1].oow = 1.f; localVerts[1].r = minColor; localVerts[1].g = maxColor; localVerts[1].b = minColor; localVerts[1].a = 255.f; localVerts[2].x = 0.75f; localVerts[2].y = -0.75f; localVerts[2].z = 0.0f; localVerts[2].tmuvtx[0].sow = 255.f; localVerts[2].tmuvtx[0].tow = 0.f; localVerts[2].oow = 1.f; localVerts[2].r = minColor; localVerts[2].g = minColor; localVerts[2].b = maxColor; localVerts[2].a = 255.f; texVerts[0].x = 0.f; texVerts[0].y = 0.f; texVerts[0].a = 255.f; texVerts[0].oow = 1.f; texVerts[0].tmuvtx[0].sow = 0.f * texVerts[0].oow; texVerts[0].tmuvtx[0].tow = 255.f * texVerts[0].oow; texVerts[1].x = scrWidth; texVerts[1].y = 0.f; texVerts[1].a = 255.f; texVerts[1].oow = 1.f; texVerts[1].tmuvtx[0].sow = 255.f * texVerts[1].oow; texVerts[1].tmuvtx[0].tow = 255.f * texVerts[1].oow; texVerts[2].x = scrWidth; texVerts[2].y = scrHeight; texVerts[2].a = 255.f; texVerts[2].oow = 1.f; texVerts[2].tmuvtx[0].sow = 255.f * texVerts[2].oow; texVerts[2].tmuvtx[0].tow = 0.f * texVerts[2].oow; texVerts[3].x = 0.f; texVerts[3].y = scrHeight; texVerts[3].a = 255.f; texVerts[3].oow = 1.f; texVerts[3].tmuvtx[0].sow = 0.f * texVerts[3].oow; texVerts[3].tmuvtx[0].tow = 0.f * texVerts[3].oow; if (bgFileName == NULL) bgFileName = "miro.3df"; if (triFileName == NULL) triFileName = "matt1.3df"; /* Read in background texture file */ if ( gu3dfGetInfo( bgFileName, &bgInfo ) ) { bgInfo.data = malloc( bgInfo.mem_required ); if ( bgInfo.data == 0 ) { fprintf( stderr, "out of memory for texture file %s\n", bgFileName ); grGlideShutdown(); exit( -1 ); } if ( !gu3dfLoad( bgFileName, &bgInfo ) ) { fprintf( stderr, "could not load texture file %s\n", bgFileName ); grGlideShutdown(); exit( -1 ); } bgDecal.smallLodLog2 = bgInfo.header.small_lod; bgDecal.largeLodLog2 = bgInfo.header.large_lod; bgDecal.aspectRatioLog2 = bgInfo.header.aspect_ratio; bgDecal.data = bgInfo.data; bgDecal.format = bgInfo.header.format; grTexDownloadMipMap( GR_TMU0, startAddress, GR_MIPMAPLEVELMASK_BOTH, &bgDecal); grTexMipMapMode(GR_TMU0, GR_MIPMAP_NEAREST, FXTRUE); grTexClampMode( GR_TMU0, GR_TEXTURECLAMP_WRAP, GR_TEXTURECLAMP_WRAP); grTexFilterMode( GR_TMU0, GR_TEXTUREFILTER_BILINEAR, GR_TEXTUREFILTER_BILINEAR ); bgDecalAddress = startAddress; startAddress += grTexCalcMemRequired ( bgDecal.smallLodLog2, bgDecal.largeLodLog2, bgDecal.aspectRatioLog2, bgDecal.format ); free( bgInfo.data ); } else { fprintf( stderr, "could not get info on %s\n", bgFileName ); grGlideShutdown(); exit( -1 ); } if ( gu3dfGetInfo( triFileName, &triInfo ) ) { triInfo.data = malloc( triInfo.mem_required ); if ( triInfo.data == 0 ) { fprintf( stderr, "out of memory for texture file %s\n", triFileName ); grGlideShutdown(); exit( -1 ); } if ( !gu3dfLoad( triFileName, &triInfo ) ) { fprintf( stderr, "could not load texture file %s\n", triFileName ); grGlideShutdown(); exit( -1 ); } triDecal.smallLodLog2 = triInfo.header.small_lod; triDecal.largeLodLog2 = triInfo.header.large_lod; triDecal.aspectRatioLog2 = triInfo.header.aspect_ratio; triDecal.data = triInfo.data; triDecal.format = triInfo.header.format; grTexDownloadMipMap( GR_TMU0, startAddress, GR_MIPMAPLEVELMASK_BOTH, &triDecal); grTexMipMapMode(GR_TMU0, GR_MIPMAP_NEAREST, FXTRUE); grTexClampMode( GR_TMU0, GR_TEXTURECLAMP_WRAP, GR_TEXTURECLAMP_WRAP); grTexFilterMode( GR_TMU0, GR_TEXTUREFILTER_BILINEAR, GR_TEXTUREFILTER_BILINEAR ); triDecalAddress = startAddress; free( triInfo.data ); } else { fprintf( stderr, "could not get info on %s\n", triFileName ); grGlideShutdown(); exit( -1 ); } grTexCombine( GR_TMU0, GR_COMBINE_FUNCTION_LOCAL, GR_COMBINE_FACTOR_NONE, GR_COMBINE_FUNCTION_LOCAL, GR_COMBINE_FACTOR_NONE, FXFALSE, FXFALSE ); grRenderBuffer(backbuffer == FXTRUE ? GR_BUFFER_BACKBUFFER : GR_BUFFER_FRONTBUFFER); /* Set up alpha blending for AA and compositing... */ grAlphaCombine( GR_COMBINE_FUNCTION_LOCAL, GR_COMBINE_FACTOR_NONE, GR_COMBINE_LOCAL_ITERATED, GR_COMBINE_OTHER_NONE, FXFALSE ); grAlphaBlendFunction( GR_BLEND_SRC_ALPHA, GR_BLEND_ONE_MINUS_SRC_ALPHA, GR_BLEND_ONE, GR_BLEND_ZERO ); grAlphaTestFunction( GR_CMP_ALWAYS ); while ( 1 ) { Matrix rotm; GrVertex xformedVerts[VERT_COUNT]; int i; MatMakeYRot( rotm, DEG2RAD( y_angle ) ); if (resolution == GR_RESOLUTION_NONE) tlGetResolutionConstant("0", &scrWidth, &scrHeight ); for( i = 0; i < VERT_COUNT; i++ ) { PointMatMult( &xformedVerts[i], &localVerts[i], rotm ); xformedVerts[i].x = xformedVerts[i].x / ( xformedVerts[i].z + 2.0f ); xformedVerts[i].y = xformedVerts[i].y / ( xformedVerts[i].z + 2.0f ); xformedVerts[i].x *= scrWidth / 2.0f; xformedVerts[i].y *= scrHeight / 2.0f; xformedVerts[i].x += scrWidth / 2.0f; xformedVerts[i].y += scrHeight / 2.0f; xformedVerts[i].oow = 1.f / ((xformedVerts[i].z + 2) * scrHeight); xformedVerts[i].tmuvtx[0].sow *= xformedVerts[i].oow; xformedVerts[i].tmuvtx[0].tow *= xformedVerts[i].oow; SNAP_COORD( xformedVerts[i].x ); SNAP_COORD( xformedVerts[i].y ); } switch ( ccFnc ) { case GR_COLORCOMBINE_ITRGB: grColorCombine( GR_COMBINE_FUNCTION_LOCAL, GR_COMBINE_FACTOR_NONE, GR_COMBINE_LOCAL_ITERATED, GR_COMBINE_OTHER_NONE, FXFALSE ); break; case GR_COLORCOMBINE_DECAL_TEXTURE: grColorCombine( GR_COMBINE_FUNCTION_SCALE_OTHER, GR_COMBINE_FACTOR_ONE, GR_COMBINE_LOCAL_NONE, GR_COMBINE_OTHER_TEXTURE, FXFALSE ); break; case GR_COLORCOMBINE_TEXTURE_TIMES_ITRGB: grColorCombine( GR_COMBINE_FUNCTION_SCALE_OTHER, GR_COMBINE_FACTOR_LOCAL, GR_COMBINE_LOCAL_ITERATED, GR_COMBINE_OTHER_TEXTURE, FXFALSE ); break; } /* grLfbBypassMode(GR_LFBBYPASS_ENABLE); */ if (render == FXTRUE) { ++frameNum; if ((frameNum % NFRAMES) == 0) { if (printPerf) { if (!firstTime) { GrSstPerfStats_t pStats; FxU32 lfbWritePixels, nFrames = frameNum - lastFrame, fillPixels = nFrames * screenFulls[resolution], totFail; lastFrame = frameNum; grGet(GR_STATS_PIXELS_IN, 4, &pStats.pixelsIn); grGet(GR_STATS_PIXELS_CHROMA_FAIL, 4, &pStats.chromaFail); grGet(GR_STATS_PIXELS_DEPTHFUNC_FAIL, 4, &pStats.zFuncFail); grGet(GR_STATS_PIXELS_AFUNC_FAIL, 4, &pStats.aFuncFail); grGet(GR_STATS_PIXELS_OUT, 4, &pStats.pixelsOut); grGet(GR_STATS_TRIANGLES_IN, 4, &trisProcessed); grGet(GR_STATS_TRIANGLES_OUT, 4, &trisDrawn); totFail = pStats.chromaFail + pStats.zFuncFail + pStats.aFuncFail; lfbWritePixels = pStats.pixelsOut - pStats.pixelsIn - fillPixels; tlConOutput("In the last %d frames:\n", nFrames); tlConOutput(" Pixels Processed: %d\n", pStats.pixelsIn); tlConOutput(" Chroma Failures: %d\n", pStats.chromaFail); tlConOutput(" Z Compare Failures: %d\n", pStats.zFuncFail); tlConOutput(" Alpha Compare Failures: %d\n", pStats.aFuncFail); tlConOutput(" Fast Fill Pixels: %d\n", fillPixels); tlConOutput(" LFB Write Pixels: %d\n", lfbWritePixels); tlConOutput(" Total Pixels Drawn: %d\n", pStats.pixelsOut); tlConOutput(" Triangles Processed %d\n", trisProcessed); tlConOutput(" Triangles Drawn %d\n", trisDrawn); if ( (pStats.pixelsOut - lfbWritePixels - fillPixels - pStats.pixelsIn) != totFail) tlConOutput("Error: %d != %d\n", pStats.pixelsOut - lfbWritePixels - fillPixels, totFail); grReset(GR_STATS_PIXELS); } else { lastFrame = frameNum; grReset(GR_STATS_PIXELS); firstTime = 0; } } } grBufferClear( 0xffffffff, 0, (FxU16)wrange[1] ); if (background == FXTRUE) { texVerts[0].x = 0.f; texVerts[0].y = 0.f; texVerts[1].x = scrWidth; texVerts[1].y = 0.f; texVerts[1].x = scrWidth; texVerts[1].y = 0.f; texVerts[2].x = scrWidth; texVerts[2].y = scrHeight; texVerts[3].x = 0.f; texVerts[3].y = scrHeight; grGlideGetState(oldState); grVertexLayout(GR_PARAM_Q, GR_VERTEX_OOW_OFFSET << 2, GR_PARAM_ENABLE); grVertexLayout(GR_PARAM_ST0, GR_VERTEX_SOW_TMU0_OFFSET << 2, GR_PARAM_ENABLE); grAlphaBlendFunction( GR_BLEND_ONE, GR_BLEND_ZERO, GR_BLEND_ONE, GR_BLEND_ZERO); grColorCombine( GR_COMBINE_FUNCTION_SCALE_OTHER, GR_COMBINE_FACTOR_ONE, GR_COMBINE_LOCAL_NONE, GR_COMBINE_OTHER_TEXTURE, FXFALSE ); grTexSource( GR_TMU0, bgDecalAddress, GR_MIPMAPLEVELMASK_BOTH, &bgDecal ); for (i = 0; i < NTRIS; i++) { grDrawTriangle(&texVerts[0], &texVerts[1], &texVerts[2]); grDrawTriangle(&texVerts[2], &texVerts[3], &texVerts[0]); } grGlideSetState(oldState); grClipWindow(0, 0, (FxU32) scrWidth, (FxU32) scrHeight); } if (texturing == FXTRUE) grTexSource( GR_TMU0, bgDecalAddress, GR_MIPMAPLEVELMASK_BOTH, &bgDecal ); if (texturing) grTexSource( GR_TMU0, triDecalAddress, GR_MIPMAPLEVELMASK_BOTH, &triDecal ); if (antialias == FXTRUE) { grEnable(GR_AA_ORDERED); if (lines == FXTRUE) { grDrawLine(&xformedVerts[0], &xformedVerts[1]); grDrawLine(&xformedVerts[1], &xformedVerts[2]); grDrawLine(&xformedVerts[2], &xformedVerts[0]); } else { grAADrawTriangle( &xformedVerts[0], &xformedVerts[1], &xformedVerts[2], FXTRUE, FXTRUE, FXTRUE ); } } else { grDisable(GR_AA_ORDERED); if (lines == FXTRUE) { grDrawLine(&xformedVerts[0], &xformedVerts[1]); grDrawLine(&xformedVerts[1], &xformedVerts[2]); grDrawLine(&xformedVerts[2], &xformedVerts[0]); } else { grDrawTriangle( &xformedVerts[0], &xformedVerts[1], &xformedVerts[2] ); } } if (plugging) grSplash(0.f, 0.f, scrWidth / 5.f, scrHeight / 5.f, frameNum); if (backbuffer) { tlConRender(); grBufferSwap( swapDelay ); } } if (tlKbHit()) { char c = (char) tlGetCH(); switch (c) { case 'a': case 'A': if (antialias == FXFALSE) { tlConOutput("Turning ON Antialiasing\n"); antialias = FXTRUE; } else { tlConOutput("Turning OFF Antialiasing\n"); antialias = FXFALSE; } break; case 'B': case 'b': if (bilinear == FXFALSE) { bilinear = FXTRUE; tlConOutput("Turning ON BiLinear blending\n"); grTexFilterMode ( GR_TMU0, GR_TEXTUREFILTER_BILINEAR, GR_TEXTUREFILTER_BILINEAR ); } else { bilinear = FXFALSE; tlConOutput("Turning OFF BiLinear blending\n"); grTexFilterMode ( GR_TMU0, GR_TEXTUREFILTER_POINT_SAMPLED, GR_TEXTUREFILTER_POINT_SAMPLED ); } break; case 'c': case 'C': if (blend == FXTRUE) { int i; blend = FXFALSE; for(i=0;i<VERT_COUNT;i++) localVerts[i].a = 255.0f; } else { int i; blend = FXTRUE; for(i=0;i<VERT_COUNT;i++) localVerts[i].a = alpha; } break; case 'd': case 'D': tlConOutput("vtxa = (%.2f, %.2f), vtxb = (%.2f, %.2f), vtxc = (%.2f, %.2f)\n", xformedVerts[0].x, xformedVerts[0].y, xformedVerts[1].x, xformedVerts[1].y, xformedVerts[2].x, xformedVerts[2].y ); break; case 'f': case 'F': if (backbuffer == FXTRUE) { backbuffer = FXFALSE; grRenderBuffer(GR_BUFFER_FRONTBUFFER); } else { backbuffer = FXTRUE; grRenderBuffer(GR_BUFFER_BACKBUFFER); } break; case 'g': case 'G': #if 0 grLfbBegin(); grLfbWriteMode(GR_LFBWRITEMODE_565); grLfbOrigin(GR_ORIGIN_UPPER_LEFT); grLfbGetReadPtr(GR_BUFFER_FRONTBUFFER); tlConOutput("Press a key to get front buffer\n"); while (!tlKbHit()); c = (char) tlGetCH(); guFbReadRegion(0,0,(int)wWidth,(int)scrHeight,scrnImage,(int)wWidth * sizeof(FxU16)); tlConOutput("Press a key to put image in back buffer and swap\n"); while (!tlKbHit()); tlGetCH(); grLfbGetWritePtr(GR_BUFFER_BACKBUFFER); guFbWriteRegion(0,0,(int)wWidth,(int)scrHeight,scrnImage,(int)wWidth * sizeof(FxU16)); grBufferSwap(swapDelay); tlConOutput("Press a key to continue...\n"); while (!tlKbHit()); tlGetCH(); grLfbEnd(); #endif break; case 'h': case 'H': case '?': doHelp(); break; case 'i': case 'I': if (background == FXTRUE) { background = FXFALSE; tlConOutput("Turning off background\n"); } else { tlConOutput("Turning on background\n"); background = FXTRUE; } break; case 'l': case 'L': if (lines == FXTRUE) { lines = FXFALSE; tlConOutput("Turning OFF lines\n"); } else { lines = FXTRUE; tlConOutput("Turning ON lines\n"); } break; case 'm': case 'M': ccFnc = GR_COLORCOMBINE_TEXTURE_TIMES_ITRGB; break; case 'n': case 'N': if (printPerf == FXFALSE) { printPerf = FXTRUE; firstTime = 1; grReset(GR_STATS_PIXELS); grReset(GR_STATS_TRIANGLES); } else { printPerf= FXFALSE; } break; case 'o': case 'O': if (origin == GR_ORIGIN_LOWER_LEFT) origin = GR_ORIGIN_UPPER_LEFT; else origin = GR_ORIGIN_LOWER_LEFT; grSstOrigin(origin); break; case 'p': case 'P': if (render == FXTRUE) render = FXFALSE; else render = FXTRUE; break; case 'q': case 'Q': case 27: grGlideShutdown(); exit(0); break; case 'r': case 'R': tlConOutput("Screen Resolution is %s\n", tlGetResolutionString( resolution ) ); break; case 'S': case 's': if (cullMode == GR_CULL_DISABLE) { cullMode = GR_CULL_NEGATIVE; tlConOutput("Turning ON backface culling (hidden Surface removal)\n"); } else { cullMode = GR_CULL_DISABLE; tlConOutput("Turning OFF backface culling (hidden Surface removal)\n"); } grCullMode(cullMode); break; case 'T': case 't': if (texturing == FXFALSE) { tlConOutput("Turning ON texturing\n"); ccFnc = GR_COLORCOMBINE_DECAL_TEXTURE; texturing = FXTRUE; grVertexLayout(GR_PARAM_Q, GR_VERTEX_OOW_OFFSET << 2, GR_PARAM_ENABLE); grVertexLayout(GR_PARAM_ST0, GR_VERTEX_SOW_TMU0_OFFSET << 2, GR_PARAM_ENABLE); } else { tlConOutput("Turning OFF texturing\n"); ccFnc = GR_COLORCOMBINE_ITRGB; texturing = FXFALSE; grVertexLayout(GR_PARAM_Q, GR_VERTEX_OOW_OFFSET << 2, GR_PARAM_DISABLE); grVertexLayout(GR_PARAM_ST0, GR_VERTEX_SOW_TMU0_OFFSET << 2, GR_PARAM_DISABLE); } break; case 'u': case 'U': if (plugging == FXTRUE) { plugging = FXFALSE; grDisable(GR_SHAMELESS_PLUG); } else { plugging = FXTRUE; grEnable(GR_SHAMELESS_PLUG); } break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '0': { char str[256]; swapDelay = (int) c - 0x30; sprintf(str, "Swapdelay = %d\n", swapDelay); tlConOutput(str); } break; } } if (render) { y_angle += 2.f; if( y_angle > 360.0f ) y_angle -= 360.0f; } frameCount++; if(frameCount < 0) frameCount = 0; if(frames == frameCount) break; } grGlideShutdown(); }
BLOCK_MEM allocate(int threadId, bool toBePassed) { LOG_PROLOG(); Chunk *stolenChunk; BLOCK_MEM block = NULL; int threadToBeHelped; Donor *donor; //Helper *announceOfThreadToBeHelped; ReferenceIntegerPair *announceOfThreadToBeHelped; //LOG_INFO("allocate: threadID = %d\n", threadId); if (toBePassed) { donor = getDonorEntry(threadId); donor->numOfPassed++; if (donor->numOfPassed % memory->c == 1) { LOG_INFO("allocate: setting addInFreePoolC true"); donor->addInFreePoolC = true; } } Chunk* chunk = getFromLocalPool(memory->localPool, threadId); if (!IS_CHUNK_EMPTY(chunk)) { block = getFromChunkUncontended(chunk); setBlockThreadIndex(block, threadId); LOG_EPILOG(); return block; } else { Chunk* chunk = removeFromLocalPool(memory->localPool, threadId); LOG_INFO("allocate: chunk in localPool is empty"); donor = getDonorEntry(threadId); if (donor->addInFreePoolC) { //LOG_INFO("allocate: threadId = %d: putting in freePoolC\n", threadId); putInFreePoolC(memory->freePoolC, threadId, chunk); donor->addInFreePoolC = false; } else { putInFreePoolUC(memory->freePoolUC, threadId, chunk); } while (true) { // handling call to allocate again if (isFullPoolEmpty(memory->fullPool,threadId)) { LOG_INFO("allocate: *****fullPool is empty******"); //getHelperEntry(threadId)->needHelp = true; *(bool*)getHelperEntry(threadId)->atomicRef->reference = true; stolenChunk = NULL; for(int i = 1; i <= memory->n; i++) { threadToBeHelped = (threadId + i) % memory->n; announceOfThreadToBeHelped = setHazardPointer(globalHPStructure, threadId, getHelperEntry(threadToBeHelped)->atomicRef); if(*(bool*)announceOfThreadToBeHelped->reference) { LOG_INFO("allocate: going to help thread %d", threadToBeHelped); assert(globalHPStructure->topPointers[threadId] == 1); stolenChunk = doHelp(threadId, threadToBeHelped, stolenChunk, announceOfThreadToBeHelped); assert(globalHPStructure->topPointers[threadId] == 0); } else { assert(globalHPStructure->topPointers[threadId] == 1); clearHazardPointer(globalHPStructure, threadId); assert(globalHPStructure->topPointers[threadId] == 0); } } if (stolenChunk != NULL) { LOG_INFO("allocate: threadId = %d: stolenChunk was not null. Putting in own fullPool\n", threadId); putInOwnFullPool(memory->fullPool, threadId, stolenChunk); LOG_INFO("allocate: threadId = %d: stolenChunk was not null. Putting in own fullPool successful\n", threadId); } } while(true) { LOG_INFO("allocate: threadId = %d, isFullPoolEmpty = %d\n", threadId, isFullPoolEmpty(memory->fullPool,threadId)); chunk = getFromOwnFullPool(memory->fullPool,threadId); LOG_INFO("allocate: threadId = %d, after removing a chunk, isFullPoolEmpty = %d\n", threadId, isFullPoolEmpty(memory->fullPool,threadId)); assert(globalHPStructure->topPointers[threadId] == 0); if (chunk != NULL) { assert(globalHPStructure->topPointers[threadId] == 0); if (getDonorEntry(threadId)->noOfOps != memory->C) { LOG_INFO("allocate: threadId = %d: noOfOps = %d\n", threadId,getDonorEntry(threadId)->noOfOps); getDonorEntry(threadId)->noOfOps++; putInLocalPool(memory->localPool, threadId, chunk); block = getFromChunkUncontended(chunk); setBlockThreadIndex(block, threadId); LOG_EPILOG(); return block; } else { assert(globalHPStructure->topPointers[threadId] == 0); getDonorEntry(threadId)->noOfOps = 0; if (!donate(threadId, chunk)) { putInLocalPool(memory->localPool, threadId, chunk); block = getFromChunkUncontended(chunk); setBlockThreadIndex(block, threadId); LOG_EPILOG(); return block; } else { break; } } } } // while(true) LOG_INFO("allocate: calling allocate again"); //return allocate(threadId); } } }
int main (int argc, char *argv[]) { if (!_isterm(1)) ANSI = 0; if (DosCreateMutexSem("\\SEM32\\CONSOLE.RUN", &ConsoleSem, DC_SEM_SHARED, TRUE) != NO_ERROR) { if (DosOpenMutexSem("\\SEM32\\CONSOLE.RUN", &ConsoleSem) != NO_ERROR) Stop(3, NULL); if (DosRequestMutexSem(ConsoleSem, SEM_INDEFINITE_WAIT) != NO_ERROR) Stop(3, NULL); } atexit(ReleaseINI); doInitialize(); ParseCmdLine(getenv("CONSOLE"), OptH, StrH); optCount = 0; cmdLine = CmdLine(argc, argv); ParseCmdLine(cmdLine, OptH, StrH); free(cmdLine); if (!fNewSession && (optCount > 0) && !fQueryCommand) fQuiet = TRUE; doHeader(); if (fQueryCommand) doShowCommand(); if ((fConsoleSize || fSetBorder || (fSetFlash && fFlashWindow)) && fNewSession && (sd.SessionType == SSF_TYPE_WINDOWABLEVIO)) { char *p,*n; int nl = 64; if (progname) nl += strlen(progname); if (progargs) nl += strlen(progargs); p = malloc(nl); sprintf(p, "-s%d,%d ", Console.W, Console.H); if (fSetBorder) sprintf(&p[strlen(p)], "-b%d,%d ", Border.W, Border.H); if (fSetFlash && fFlashWindow) strcat(&p[strlen(p)], "-of "); if (fExplicitSize) sprintf(&p[strlen(p)], "-p,,%d,%d ", ConsolePos.W, ConsolePos.H); if ((sd.PgmControl & SSF_CONTROL_INVISIBLE) == 0) { strcat(&p[strlen(p)], "-ov "); sd.PgmControl |= SSF_CONTROL_INVISIBLE; } if (!progname || !progname[0]) n = getenv("COMSPEC"); else n = progname; sprintf(&p[strlen(p)], "%s ", n); if (progargs) strcat(p, progargs); if (progname) free(progname); progname = SourceName(); progargs = p; } if (!optCount) doHelp(); else { if (fNewSession) doNewSession(); else doSameSession(); } if (!fQuiet) { SetColor(colBLUE, colSAME); printf("À´ Done\n"); SetColor(colCYAN, colSAME); } return 0; }
void main( int argc, char **argv) { char match, **remArgs, *args = "nrd", filename[256]; int frames = -1, rv; float scrWidth = 640.f, scrHeight = 480.f; FxBool scrgrab = FXFALSE; GrScreenResolution_t resolution = GR_RESOLUTION_640x480; FxI32 listType = -1; FxBool aaenable = FXFALSE; FxBool packedrgb = FXFALSE; FxBool varraycont = FXFALSE; GrVertex vtxList[4]; void *vtxListArray[6]; GrVertex vtxListCont[6]; FxU32 wrange[2]; /* Initialize Glide */ grGlideInit(); assert( hwconfig = tlVoodooType() ); /* Process Command Line Arguments */ while( rv = tlGetOpt( argc, argv, args, &match, &remArgs ) ) { if ( rv == -1 ) { printf( "Unrecognized command line argument\n" ); printf( "%s %s\n", name, usage ); printf( "Available resolutions:\n%s\n", tlGetResolutionList() ); return; } switch( match ) { case 'n': frames = atoi( remArgs[0] ); break; case 'r': resolution = tlGetResolutionConstant( remArgs[0], &scrWidth, &scrHeight ); break; case 'd': scrgrab = FXTRUE; frames = 1; strcpy(filename, remArgs[0]); break; } } tlSetScreen( scrWidth, scrHeight ); version = grGetString( GR_VERSION ); printf( "%s:\n%s\n", name, purpose ); printf( "%s\n", version ); printf( "Resolution: %s\n", tlGetResolutionString( resolution ) ); if ( frames == -1 ) { printf( "Press A Key To Begin Test.\n" ); tlGetCH(); } grSstSelect( 0 ); assert( grSstWinOpen(tlGethWnd(), resolution, GR_REFRESH_60Hz, GR_COLORFORMAT_ABGR, GR_ORIGIN_UPPER_LEFT, 2, 1 ) ); tlConSet( 0.f, 0.f, 1.f, 1.f, 60, 30, 0xffffff ); /* Set up Render State - gouraud shading */ grVertexLayout(GR_PARAM_XY, GR_VERTEX_X_OFFSET << 2, GR_PARAM_ENABLE); grVertexLayout(GR_PARAM_RGB, GR_VERTEX_R_OFFSET << 2, GR_PARAM_ENABLE); grGet(GR_WDEPTH_MIN_MAX, 8, wrange); grColorCombine( GR_COMBINE_FUNCTION_LOCAL, GR_COMBINE_FACTOR_NONE, GR_COMBINE_LOCAL_ITERATED, GR_COMBINE_OTHER_NONE, FXFALSE ); grCullMode(GR_CULL_DISABLE); if(frames == -1) { doHelp(); } /* ** data */ { vtxList[0].x = tlScaleX( 0.3f ), vtxList[0].y = tlScaleY( 0.3f ); vtxList[0].r = 255.f, vtxList[0].g = 0.f, vtxList[0].b = 0.f, vtxList[0].a = 255.f; vtxList[1].x = tlScaleX( 0.8f ), vtxList[1].y = tlScaleY( 0.4f ); vtxList[1].r = 0.f, vtxList[1].g = 255.f, vtxList[1].b = 0.f, vtxList[1].a = 255.f; vtxList[2].x = tlScaleX( 0.5f ), vtxList[2].y = tlScaleY( 0.8f ); vtxList[2].r = 0.f, vtxList[2].g = 0.f, vtxList[2].b = 255.f, vtxList[2].a = 255.f; vtxList[3].x = tlScaleX( 0.9f ), vtxList[3].y = tlScaleY( 0.8f ); vtxList[3].r = 0.f, vtxList[3].g = 0.f, vtxList[3].b = 255.f, vtxList[3].a = 255.f; vtxListCont[0] = vtxList[0]; vtxListCont[1] = vtxList[1]; vtxListCont[2] = vtxList[2]; vtxListCont[3] = vtxList[3]; } while( frames-- && tlOkToRender()) { tlConClear(); tlConOutput( "Press a key to quit\n" ); if (aaenable) tlConOutput("Antialiasing ON\n"); else tlConOutput("Antialiasing OFF\n"); if (packedrgb) tlConOutput("Packed Color ON\n"); else tlConOutput("Packed Color OFF\n"); if (listType >= 0) { if (varraycont) tlConOutput("grDrawVertexArrayContiguous\n"); else tlConOutput("grDrawVertexArray\n"); switch (listType) { case GR_POINTS: tlConOutput("POINTS\n"); break; case GR_LINE_STRIP: tlConOutput("LINE STRIP\n"); break; case GR_LINES: tlConOutput("LINES\n"); break; case GR_POLYGON: tlConOutput("POLYGON\n"); break; case GR_TRIANGLE_STRIP: tlConOutput("TRIANGLE STRIP\n"); break; case GR_TRIANGLE_FAN: tlConOutput("TRIANGLE FAN\n"); break; case GR_TRIANGLES: tlConOutput("TRIANGLES\n"); break; } } else tlConOutput("grDrawTriangle\n"); if (hwconfig == TL_VOODOORUSH) { tlGetDimsByConst(resolution, &scrWidth, &scrHeight ); grClipWindow(0, 0, (FxU32) scrWidth, (FxU32) scrHeight); } grRenderBuffer( GR_BUFFER_BACKBUFFER ); grBufferClear( 0x00, 0, wrange[1] ); switch (listType) { case GR_POINTS: case GR_LINE_STRIP: case GR_LINES: case GR_POLYGON: case GR_TRIANGLE_STRIP: case GR_TRIANGLE_FAN: if (varraycont) grDrawVertexArrayContiguous(listType, 4, vtxListCont, sizeof(GrVertex)); else grDrawVertexArray(listType, 4, vtxListArray); break; case GR_TRIANGLES: if (varraycont) grDrawVertexArrayContiguous(listType, 6, vtxListCont, sizeof(GrVertex)); else grDrawVertexArray(listType, 6, vtxListArray); break; default: if (aaenable) grAADrawTriangle(vtxList, vtxList+1, vtxList+2, FXTRUE, FXTRUE, FXTRUE); else grDrawTriangle(vtxList, vtxList+1, vtxList+2); } tlConRender(); grBufferSwap( 1 ); /* grab the frame buffer */ if (scrgrab) { if (!tlScreenDump(filename, (FxU16)scrWidth, (FxU16)scrHeight)) printf( "Cannot open %s\n", filename); scrgrab = FXFALSE; } while( tlKbHit() ) { FxU32 key; switch( key = tlGetCH() ) { case 'c': case 'C': varraycont = !varraycont; break; case 't': case 'T': listType = -1; break; case 'a': case 'A': aaenable = !aaenable; if (aaenable) { grAlphaCombine( GR_COMBINE_FUNCTION_LOCAL, GR_COMBINE_FACTOR_NONE, GR_COMBINE_LOCAL_ITERATED, GR_COMBINE_OTHER_NONE, FXFALSE ); grAlphaBlendFunction( GR_BLEND_SRC_ALPHA, GR_BLEND_ONE_MINUS_SRC_ALPHA, GR_BLEND_ZERO, GR_BLEND_ZERO ); grEnable(GR_AA_ORDERED); if (!packedrgb) grVertexLayout(GR_PARAM_A, GR_VERTEX_A_OFFSET << 2, GR_PARAM_ENABLE); } else { grAlphaCombine(GR_COMBINE_FUNCTION_SCALE_OTHER, GR_COMBINE_FACTOR_ONE, GR_COMBINE_LOCAL_NONE, GR_COMBINE_OTHER_CONSTANT, FXFALSE); grAlphaBlendFunction(GR_BLEND_ONE , GR_BLEND_ZERO, GR_BLEND_ONE, GR_BLEND_ZERO); grDisable(GR_AA_ORDERED); if (!packedrgb) grVertexLayout(GR_PARAM_A, GR_VERTEX_A_OFFSET << 2, GR_PARAM_DISABLE); } break; case 'p': case 'P': packedrgb = !packedrgb; if (packedrgb) { grVertexLayout(GR_PARAM_PARGB, GR_VERTEX_R_OFFSET << 2, GR_PARAM_ENABLE); *(FxU32*)&vtxList[0].r = 0xff0000ff; *(FxU32*)&vtxList[1].r = 0xff00ff00; *(FxU32*)&vtxList[2].r = 0xffff0000; *(FxU32*)&vtxList[3].r = 0xffff0000; *(FxU32*)&vtxList[4].r = 0xff00ff00; *(FxU32*)&vtxList[5].r = 0xff0000ff; } else { grVertexLayout(GR_PARAM_RGB, GR_VERTEX_R_OFFSET << 2, GR_PARAM_ENABLE); if (aaenable) grVertexLayout(GR_PARAM_A, GR_VERTEX_A_OFFSET << 2, GR_PARAM_ENABLE); vtxList[0].r = 255.f, vtxList[0].g = 0.f, vtxList[0].b = 0.f, vtxList[0].a = 255.f; vtxList[1].r = 0.f, vtxList[1].g = 255.f, vtxList[1].b = 0.f, vtxList[1].a = 255.f; vtxList[2].r = 0.f, vtxList[2].g = 0.f, vtxList[2].b = 255.f, vtxList[2].a = 255.f; vtxList[3].r = 0.f, vtxList[3].g = 0.f, vtxList[3].b = 255.f, vtxList[3].a = 255.f; vtxList[4].r = 0.f, vtxList[4].g = 255.f, vtxList[4].b = 0.f, vtxList[4].a = 255.f; vtxList[5].r = 0.f, vtxList[5].g = 0.f, vtxList[5].b = 255.f, vtxList[5].a = 255.f; } switch (listType) { case 0: case 1: case 2: case 4: vtxListCont[0] = vtxList[0]; vtxListCont[1] = vtxList[1]; vtxListCont[2] = vtxList[2]; vtxListCont[3] = vtxList[3]; break; case 3: case 5: vtxListCont[0] = vtxList[1]; vtxListCont[1] = vtxList[0]; vtxListCont[2] = vtxList[2]; vtxListCont[3] = vtxList[3]; break; case 6: vtxListCont[0] = vtxList[1]; vtxListCont[1] = vtxList[0]; vtxListCont[2] = vtxList[2]; vtxListCont[3] = vtxList[1]; vtxListCont[4] = vtxList[2]; vtxListCont[5] = vtxList[3]; break; } break; case '0': case '1': case '2': case '4': listType = key - '0'; vtxListArray[0] = (void *)&vtxList[0]; vtxListArray[1] = (void *)&vtxList[1]; vtxListArray[2] = (void *)&vtxList[2]; vtxListArray[3] = (void *)&vtxList[3]; vtxListCont[0] = vtxList[0]; vtxListCont[1] = vtxList[1]; vtxListCont[2] = vtxList[2]; vtxListCont[3] = vtxList[3]; break; case '3': case '5': listType = key - '0'; vtxListArray[0] = (void *)&vtxList[1]; vtxListArray[1] = (void *)&vtxList[0]; vtxListArray[2] = (void *)&vtxList[2]; vtxListArray[3] = (void *)&vtxList[3]; vtxListCont[0] = vtxList[1]; vtxListCont[1] = vtxList[0]; vtxListCont[2] = vtxList[2]; vtxListCont[3] = vtxList[3]; break; case '6': listType = key - '0'; vtxListArray[0] = (void *)&vtxList[1]; vtxListArray[1] = (void *)&vtxList[0]; vtxListArray[2] = (void *)&vtxList[2]; vtxListArray[3] = (void *)&vtxList[1]; vtxListArray[4] = (void *)&vtxList[2]; vtxListArray[5] = (void *)&vtxList[3]; vtxListCont[0] = vtxList[1]; vtxListCont[1] = vtxList[0]; vtxListCont[2] = vtxList[2]; vtxListCont[3] = vtxList[1]; vtxListCont[4] = vtxList[2]; vtxListCont[5] = vtxList[3]; break; default: frames = 0; break; } } } grGlideShutdown(); return; } /* main */
char doRegular(char expand, char c) { char toReturn; int i; int done = 0; label doorinfo; toReturn = FALSE; for (i = 0; !expand && i < MAXEXTERN && extCmd[i].name[0]; ++i) { if (c == toupper(extCmd[i].name[0]) && (onConsole || !extCmd[i].local)) { done = 1; mPrintf("\b%s", extCmd[i].name); doCR(); if (changedir(cfg.aplpath) == ERROR) { mPrintf(" -- Can't find application directory.\n\n"); changedir(cfg.homepath); } /* apsystem(extCmd[i].command); */ sprintf(doorinfo, "DORINFO%d.DEF", onConsole ? 0 : userdat.apl_com); extFmtRun(extCmd[i].command, doorinfo); } } if (!done) { switch (c) { case 'S': if (gl_user.sysop && expand) { mPrintf("\b\bSysop Menu"); doCR(); doSysop(); } else { toReturn = TRUE; } break; case 'A': if (gl_user.aide) { doAide(expand, 'E'); } else { toReturn = TRUE; } break; case 'C': doChat(expand, '\0'); break; case 'D': doDownload(expand); break; case 'E': doEnter(expand, 'm'); break; case 'F': doRead(expand, 'f'); break; case 'G': doGoto(expand, FALSE); break; case 'H': doHelp(expand); break; case 'I': doIntro(); break; case 'J': mPrintf("\bJump back to "); unGotoRoom(); break; case 'K': doKnown(expand, 'r'); break; case 'L': if (!loggedIn) { doLogin(expand); } else { if (!getYesNo(confirm, 0)) break; doLogout(expand, 's'); doLogin(expand); } break; case 'N': case 'O': case 'R': doRead(expand, tolower(c)); break; case 'B': doGoto(expand, TRUE); break; case 'T': doLogout(expand, 'q'); break; case 'U': doUpload(expand); break; case 'X': if (!expand) { doEnter(expand, 'x'); } else { doXpert(); } break; case '=': case '+': doNext(); break; case '\b': mPrintf(" "); case '-': doPrevious(); break; case ']': case '>': doNextHall(); break; case '[': case '<': doPreviousHall(); break; case '~': mPrintf("\bAnsi %s\n ", gl_term.ansiOn ? gl_str.off : gl_str.on); gl_term.ansiOn = !gl_term.ansiOn; break; case '!': mPrintf("\bIBM Graphics %s\n ", gl_term.IBMOn ? gl_str.off:gl_str.on); gl_term.IBMOn = !gl_term.IBMOn; break; case '?': nextmenu("mainopt", &(cfg.cnt.mainopttut), 1); listExterns(); break; case 0: /* never gets here in shell mode... */ if (newCarrier) { greeting(); if (cfg.forcelogin) { doCR(); doCR(); i = 0; while (!loggedIn && gotCarrier()) { doLogin(2); if (++i > 3) { Initport(); toReturn = TRUE; break; } } } newCarrier = FALSE; } if (logBuf.lbflags.NODE && loggedIn) { net_slave(); haveCarrier = FALSE; modStat = FALSE; newCarrier = FALSE; justLostCarrier = FALSE; onConsole = FALSE; disabled = FALSE; callout = FALSE; delay(2000); Initport(); cfg.callno++; terminate(FALSE, FALSE); } if (justLostCarrier || ExitToMsdos) { justLostCarrier = FALSE; if (loggedIn) terminate(FALSE, FALSE); } break; /* irrelevant value */ default: toReturn = TRUE; break; } } /* if they get unverified online */ if (logBuf.VERIFIED) terminate(FALSE, FALSE); /* update25(); */ do_idle(0); return toReturn; }
// the main function void _main(void) { unsigned int difficulty = NORMAL; short int key=0; short int keys[8]; unsigned int level_num = 1; unsigned short int score = 0; int done = 0; unsigned int money = 0; int cannon_level = 1; int missile_level = 0; char map[12][MAP_SIZE]; // seed the random numbers randomize(); // get the key masks getKeyMasks(keys); INT_HANDLER interrupt1 = GetIntVec(AUTO_INT_1); // this will save auto int 1 // draw title screen and wait for keypress GrayOn(); drawTitle(2); ngetchx(); //draw background title screen and menu drawTitle(1); drawWords(difficulty); POSITION pointer = {10,0}; drawPointer(pointer); // the menu loop while (1) { key = ngetchx(); if (key == KEY_ENTER && pointer.y != OPTIONS) { if (pointer.y == PLAY) break; if (pointer.y == HIGH_SCORES) printHiScores(); if (pointer.y == HELP) doHelp(); if (pointer.y == ABOUT) { SetIntVec(AUTO_INT_1,interrupt1); GrayOff(); exit(0); } GraySetAMSPlane(LIGHT_PLANE); clrscr(); GraySetAMSPlane(DARK_PLANE); clrscr(); drawTitle(1); drawWords(difficulty); pointer=(POSITION) { 10,0 }; drawPointer(pointer); } if (key == KEY_LEFT && pointer.y == OPTIONS && difficulty < VERY_EASY) { difficulty+=1; GraySetAMSPlane(LIGHT_PLANE); clrscr(); GraySetAMSPlane(DARK_PLANE); clrscr(); drawTitle(1); drawPointer(pointer); drawWords(difficulty); } if (key == KEY_RIGHT && pointer.y == OPTIONS && difficulty > IMPOSSIBLE) { difficulty-=1; GraySetAMSPlane(LIGHT_PLANE); clrscr(); GraySetAMSPlane(DARK_PLANE); clrscr(); drawTitle(1); drawPointer(pointer); drawWords(difficulty); } if (key == KEY_UP || key == KEY_DOWN) drawPointer(pointer); if (key == KEY_UP && pointer.y > 0) pointer.y--; if (key == KEY_DOWN && pointer.y < 4) pointer.y++; if (key == KEY_UP || key == KEY_DOWN) drawPointer(pointer); } key = 0; // turn off gray, so we can destroy auto-int-1 and not mess it up GrayOff(); // DESTROY auto-interrupt 1 so as not to mess up _rowread SetIntVec(AUTO_INT_1,DUMMY_HANDLER); // turn gray back on GrayOn(); // randomize the map randomMap(difficulty, map, level_num); //the main game loop while (!quit() && !done) { done = 0; int fin = 0; int win = 0; int forward = 0; int map_x_location = 0; int laser = 0; int justLaser = 0; int missile = 0; int justMissile = 0; int missileSlow = 2; POSITION laserPos; POSITION oldLaserPos; POSITION missilePos; POSITION oldMissilePos; POSITION oldShip; POSITION ShipPos = {0,5}; // we need to disable gray temporarily to do the shop screen... GrayOff(); SetIntVec(AUTO_INT_1, interrupt1); shop(&money, &cannon_level, &missile_level); SetIntVec(AUTO_INT_1, DUMMY_HANDLER); GrayOn(); // draws the level Draw_Map(map_x_location, map, ShipPos, laserPos, laser, missilePos, missile); // the loop for the action in the level while (!quit()) { // if the user has a missile out, deal with it if (missile && missileSlow == 2) { missileSlow = 1; oldMissilePos = missilePos; missilePos.x++; missilePos.y+=missile; if (missilePos.x > map_x_location + 20) missile = 0; if (missilePos.y < 0 || missilePos.y > 12) { missile = 0; eraseMissile(missilePos, map_x_location); } if (blowWall(missilePos,map)) { if (map[missilePos.y][missilePos.x] < 4) { map[missilePos.y][missilePos.x]-=3; if (map[missilePos.y][missilePos.x] == 0) { score++; money+=BLOCK_VALUE; } } if (map[missilePos.y][missilePos.x] < 0) map[missilePos.y][missilePos.x] = 0; missile = 0; justMissile = 0; Draw_Map(map_x_location,map,ShipPos,laserPos,laser,missilePos,missile); } // if the shot was just fired, then there wont be one to erase if (!justMissile && missile == 1) { moveMissile(oldMissilePos,missilePos,map_x_location); } else if (missile == 1) { drawMissile(missilePos,map_x_location); justMissile = 0; } else if (!justMissile && missile == -1) { moveUpMissile(oldMissilePos, missilePos, map_x_location); } else if (missile == -1) { drawUpMissile(missilePos, map_x_location); justMissile = 0; } } else { missileSlow++; } // if the user has a laser shot that is still going, continue it if (laser) { oldLaserPos = laserPos; laserPos.x++; if (laserPos.x > map_x_location + 20) laser=0; if (blowWall(laserPos,map)) { if (map[laserPos.y][laserPos.x] < 4) { map[laserPos.y][laserPos.x]-=cannon_level; if (map[laserPos.y][laserPos.x] <= 0) { score++; money+=BLOCK_VALUE; map[laserPos.y][laserPos.x] = 0; } } else if (map[laserPos.y][laserPos.x] == 4 && cannon_level == 4) { map[laserPos.y][laserPos.x] = 1; } laser = 0; justLaser = 0; Draw_Map(map_x_location,map,ShipPos,laserPos,laser, missilePos, missile); } // if the shot was just fired, then there wont be one to erase if (!justLaser && laser) { moveLaser(oldLaserPos,laserPos,map_x_location); } else if (laser) { drawLaser(laserPos,map_x_location); justLaser = 0; } } // scroll the screen forward one block every (difficulty) time through the main loop if (forward == difficulty) { map_x_location++; ShipPos.x++; forward = 0; if (map_x_location >= MAP_SIZE - 20) { win = 1; level_num++; break; } // if you ran into a wall, quit if (detectWall(ShipPos,map)) { win = 1; score /= 2 ; break; } Draw_Map(map_x_location,map,ShipPos,laserPos,laser, missilePos, missile); } else { forward++; } // if you ran into a wall, quit if (detectWall(ShipPos,map)) { win = 1; score = 0; break; } if (_rowread(~((short)(1<<1))) & (1<<6) && _rowread(~((short)(1<<2))) & (1<<6)) { win = 1; level_num++; break; } // get keypresses key = _rowread(ARROW_ROW); // if the user pressed right, move the ship right if (key & keys[RIGHT]) { oldShip = ShipPos; ShipPos.x++; if (ShipPos.x > map_x_location + 18) ShipPos.x--; if (!detectWall(ShipPos,map)) { moveShip(oldShip,ShipPos,map_x_location); } else { win = 1; score = 0; break; } } // If the user pressed left, move the ship left if (key & keys[LEFT]) { oldShip = ShipPos; ShipPos.x--; if (ShipPos.x < map_x_location) ShipPos.x++; if (!detectWall(ShipPos,map)) { moveShip(oldShip,ShipPos,map_x_location); } else { win = 1; score = 0; break; } } // if the user pressed up, move the ship up if (key & keys[UP]) { oldShip = ShipPos; if (ShipPos.y - 1 < 0) { ShipPos.y = 0; } else { ShipPos.y--; } if (!detectWall(ShipPos,map)) { moveShip(oldShip,ShipPos,map_x_location); } else { win = 1; score = 0; break; } } // if the user pressed down, move the ship down if (key & keys[DOWN]) { oldShip = ShipPos; ShipPos.y++; if (ShipPos.y > 10) ShipPos.y = 10; if (!detectWall(ShipPos,map)) { moveShip(oldShip,ShipPos,map_x_location); } else { win = 1; score = 0; break; } } // if 2nd was pushed, fire the laser if (key & keys[SECOND]) { if (!laser) { justLaser = 1; laser = 1; laserPos.x = ShipPos.x + 1; laserPos.y = ShipPos.y; } } // if diamond was pushed fire the downward missiles if (key & keys[DIAMOND]) { if (missile_level == 3 || missile_level == 1) { if (!missile) { justMissile = 1; missile = 1; missileSlow = 2; missilePos.x = ShipPos.x; missilePos.y = ShipPos.y; } } } // if shift was pushed fire the upward missiles if (key & keys[SHIFT]) { if (missile_level == 2 || missile_level == 3) { if (!missile) { justMissile = 1; missile = -1; missileSlow = 2; missilePos.x = ShipPos.x; missilePos.y = ShipPos.y; } } } /*if (key & keys[ALPHA]) { score += 10; }*/ // slow down the program because _rowread is too fast delay(); } // back to the overall game loop if (win) { if (level_num <= LEVEL_NUM) { won(difficulty, map, level_num); } else { fin = 1; break; } } } // the user left, either by winning or quitting, so make sure everything is reset so the calc will be fine GrayOff(); SetIntVec(AUTO_INT_1,interrupt1); hiScoresGo(score, difficulty, level_num); }
int main (int argc,char *argv []) { int argPos, argNum = argc, numGrpNames = 0, i = 0; char **groupnames, *rename = (char *) NULL, *tableName = (char *) NULL; bool ascii = false; FieldOptions *head = (FieldOptions *) NULL, *p = (FieldOptions *) NULL, *temp = (FieldOptions *) NULL; Groups **groups = (Groups **) NULL; FILE *outFile = (FILE *) NULL; DBObjData *inData, *outData; DBObjTable *inTable, *outTable; DBObjTableField *field; DBObjRecord *inRecord, *outRecord; DBObjectLIST<DBObjTableField> *fields; if(argc <= 2) { doHelp(false,argv[0]); return(DBSuccess); } outData = new DBObjData("Untitled", DBTypeTable); outTable = outData->Table(DBrNItems); head = new FieldOptions(BAD,"","", (FieldOptions *) NULL); groupnames = (char **) malloc(sizeof(char *)); for (argPos = 1;argPos < argNum;) { if (CMargTest(argv[argPos],"-f","--field")) { if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) { CMmsgPrint (CMmsgUsrError,"Missing operation and field after -f!"); return (CMfailed); } if(!strcmp(argv[argPos],"pct")) { if (argNum <= argPos + 2) { CMmsgPrint (CMmsgUsrError,"Missing field and/or percentage after -f pct!"); return (CMfailed); } p = FOHierarchy(argv[argPos],argv[argPos+1],rename,atoi(argv[argPos+2]),head); argNum = CMargShiftLeft(argPos,argv,argNum); argNum = CMargShiftLeft(argPos,argv,argNum); } else if(!strcmp(argv[argPos],"num")) { char *num = new char[4]; strcpy(num,"Num"); p = FOHierarchy(argv[argPos],num,rename,-1,head); } else { if (argNum < argPos + 1) { CMmsgPrint (CMmsgUsrError,"Missing operation or field after -f %s!",argv[argPos]); return (CMfailed); } p = FOHierarchy(argv[argPos],argv[argPos+1],rename,-1,head); argNum = CMargShiftLeft(argPos,argv,argNum); } p->setPrint(true); rename = (char *) NULL; if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-g","--group")) { if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) { CMmsgPrint (CMmsgUsrError,"Missing groupname!"); return (CMfailed); } if((groupnames = (char **) realloc(groupnames,(numGrpNames + 1) * sizeof(char *))) == (char **) NULL) { CMmsgPrint (CMmsgSysError, "Memory allocation error in: %s %d",__FILE__,__LINE__); return(DBFault); } groupnames[numGrpNames] = argv[argPos]; numGrpNames++; if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-h","--help")) { argNum = CMargShiftLeft (argPos,argv,argNum); if(CMargTest(argv[argPos],"e","extend")) { doHelp(true,argv[0]); argNum = CMargShiftLeft (argPos,argv,argNum); } else doHelp(false,argv[0]); } if (CMargTest(argv[argPos],"-c","--ascii")) { ascii = true; if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-a","--table")) { if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) { CMmsgPrint (CMmsgUsrError,"Missing table name!"); return (CMfailed); } tableName = argv[argPos]; if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-r","--rename")) { if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) { CMmsgPrint (CMmsgUsrError,"Missing field after -r!"); return (CMfailed); } rename = argv[argPos]; if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-o","--output")) { if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) { CMmsgPrint (CMmsgUsrError,"Missing output filename!"); return (CMfailed); } if((outFile = fopen(argv[argPos],"w")) == (FILE *) NULL) { CMmsgPrint (CMmsgUsrError,"Cannot open file %s",argv[argPos]); return (CMfailed); } if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-t","--title")) { if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) { CMmsgPrint (CMmsgUsrError,"Missing title!"); return (CMfailed); } outData->Name(argv[argPos]); if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-s","--subject")) { if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) { CMmsgPrint (CMmsgUsrError,"Missing subject!"); return (CMfailed); } outData->Document(DBDocSubject,argv[argPos]); if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-d","--domain")) { if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) { CMmsgPrint (CMmsgUsrError,"Missing domain!"); return (CMfailed); } outData->Document(DBDocGeoDomain,argv[argPos]); if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-v","--version")) { if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) { CMmsgPrint (CMmsgUsrError,"Missing version!"); return (CMfailed); } outData->Document(DBDocVersion,argv[argPos]); if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) break; continue; } if ((argv[argPos][0] == '-') && (strlen (argv[argPos]) > 1)) { CMmsgPrint (CMmsgUsrError, "Unknown option: %s!",argv[argPos]); return (CMfailed); } argPos++; } if(outFile == (FILE *) NULL) outFile = stdout; if(head->next == (FieldOptions *) NULL) return(DBSuccess); inData = new DBObjData(); if ((argNum > 1) && (strcmp(argv[1],"-") != 0)) inData->Read(argv[1]); else inData->Read(stdin); if (outData->Name() == (char *) NULL) outData->Name("Untitled"); if (outData->Document(DBDocSubject) == (char *) NULL) outData->Document(DBDocSubject,inData->Document(DBDocSubject)); if (outData->Document(DBDocGeoDomain) == (char *) NULL) outData->Document(DBDocGeoDomain,inData->Document(DBDocGeoDomain)); if (outData->Document(DBDocVersion) == (char *) NULL) outData->Document(DBDocVersion,inData->Document(DBDocVersion)); if(tableName == (char *) NULL) tableName = DBrNItems; if((inTable = inData->Table(tableName)) == (DBObjTable *) NULL) { CMmsgPrint (CMmsgUsrError,"Invalid table!"); delete inData; return (CMfailed); } if((groups = (Groups **) malloc(numGrpNames * sizeof(Groups *))) == (Groups **) NULL) { CMmsgPrint (CMmsgSysError, "Memory allocation error in: %s %d",__FILE__,__LINE__); return(DBFault); } for(i = 0; i < numGrpNames; i++) { if((field = inTable->Field(groupnames[i])) == (DBObjTableField *) NULL) { CMmsgPrint (CMmsgUsrError, "Invalid group name: %s",groupnames[i]); return (CMfailed); } if(DBTableFieldIsCategory(field)) { groups[i] = new Groups(); groups[i]->srcFLD = field; groups[i]->dstFLD = new DBObjTableField(*field); outTable->AddField(groups[i]->dstFLD); // CMmsgPrint (CMmsgUsrError, "Added Group: %s",groups[i]->dstFLD->Name()); } else CMmsgPrint (CMmsgUsrError, "Group %s is not Category!",groupnames[i]); } delete groupnames; p = head->next; temp = head; while(p->next) { FieldOptions *duplicate = (FieldOptions *) NULL, *prev = p; if(!p->getPrint() && FLDExists(p,p->getOldName(),p->getFunc(),&duplicate)) { temp->next = p->next; delete p; p = temp->next; continue; } while(FLDExists(prev,prev->getOldName(),prev->getFunc(),&prev,&duplicate) && !duplicate->getPrint()) { prev->next = duplicate->next; delete duplicate; } temp = p; p = p->next; } // p = head->next; // while(p) { CMmsgPrint (CMmsgUsrError, "Added: o:%s n:%s p:",p->getOldName(),p->getNewName()); if(p->getPrint()) CMmsgPrint (CMmsgUsrError, "true"); else CMmsgPrint (CMmsgUsrError, "false"); p = p->next; } fields = inTable->Fields(); p = head->next; while(p) { field = fields->Item (p->getOldName()); if (p->getFunc() == MIN || p->getFunc() == MAX) p->field = new DBObjTableField(p->getNewName(),field->Type(),field->Format(),field->Length()); else if(p->getFunc() == NUM || p->getFunc() == NONNULL) p->field = new DBObjTableField(p->getNewName(), DBTableFieldInt, DBHiddenField, sizeof (DBInt)); else p->field = new DBObjTableField(p->getNewName(), DBTableFieldFloat, DBHiddenField, sizeof(DBFloat)); if(p->getFunc() != NUM && p->getFunc() != NONNULL) { // if ((field = inTable->Field(p->getOldName())) == (DBObjTableField *) NULL) if (field == (DBObjTableField *) NULL) { CMmsgPrint (CMmsgUsrError, "Invalid field name: %s",p->getOldName()); return(DBFault); } if (!DBTableFieldIsNumeric(field)) { CMmsgPrint (CMmsgUsrError, "Field is not Numeric: %s",p->getOldName()); return(DBFault); } } outTable->AddField(p->field); p = p->next; } // MAKE SURE TO TEST FOR SPEED BY DECLARING INTS OUTSIDE OF FOR LOOPS!!! for (int inRecID = 0;inRecID < inTable->ItemNum();++inRecID) { inRecord = inTable->Item(inRecID); if ((outRecord = FindMatch(inRecord, outTable,(const Groups**) groups, numGrpNames)) != (DBObjRecord *) NULL) { p = head->next; while(p) { field = fields->Item (p->getOldName()); switch(p->getFunc()) { default: break; case NUM: p->field->Int(outRecord,p->field->Int(outRecord) + 1); break; case NONNULL: if (p->isInt()) { if (field->Int(inRecord) != field->IntNoData()) p->field->Int(outRecord,p->field->Int(outRecord) + 1); } else { if (!CMmathEqualValues(field->Float(inRecord),field->FloatNoData())) p->field->Int(outRecord,p->field->Int(outRecord) + 1); } break; case MIN: if (p->isInt()) { if(field->Int(inRecord) != field->IntNoData()) { if (p->field->Int(outRecord) != p->field->IntNoData()) { if (field->Int(inRecord) < p->field->Int(outRecord)) p->field->Int(outRecord,field->Int(inRecord)); } else { p->field->Int(outRecord,field->Int(inRecord)); } } } else { if (!CMmathEqualValues(field->Float(inRecord),field->FloatNoData())) { if (!CMmathEqualValues(p->field->Float(inRecord),p->field->FloatNoData())) { if (field->Float(inRecord) < p->field->Float(outRecord)) p->field->Float(outRecord,field->Float(inRecord)); } else { p->field->Float(outRecord,field->Float(inRecord)); } } } break; case MAX: if (p->isInt()) { if(field->Int(inRecord) != field->IntNoData()) { if (p->field->Int(outRecord) != p->field->IntNoData()) { if (field->Int(inRecord) > p->field->Int(outRecord)) p->field->Int(outRecord,field->Int(inRecord)); } else { p->field->Int(outRecord,field->Int(inRecord)); } } } else { if (!CMmathEqualValues(field->Float(inRecord),field->FloatNoData())) { if (!CMmathEqualValues(p->field->Float(inRecord),p->field->FloatNoData())) { if (field->Float(inRecord) > p->field->Float(outRecord)) p->field->Float(outRecord,field->Float(inRecord)); } else { p->field->Float(outRecord,field->Float(inRecord)); } } } break; case SUM: if (p->isInt()) { if(field->Int(inRecord) != field->IntNoData()) p->field->Int(outRecord,p->field->Int(outRecord) + field->Int(inRecord)); } else { if (!CMmathEqualValues(field->Float(inRecord),field->FloatNoData())) p->field->Float(outRecord,p->field->Float(outRecord) + field->Float(inRecord)); } break; case DEV: case PCT: case MED: p->tailVal = p->tailVal->next = new Values(); p->tailVal->val = field->Float(inRecord); p->tailVal->next = 0; break; case MOD: Values *cur = p->getHead(); while(cur->next && !CMmathEqualValues(cur->val,field->Float(inRecord))) cur = cur->next; if(cur->next) cur->occur++; else { p->tailVal->val = field->Float(inRecord); p->tailVal->occur = 1; p->tailVal = p->tailVal->next = new Values(); } break; } p = p->next; } } else { outRecord = outTable->Add(); for(i = 0; i < numGrpNames; i++) { switch (groups[i]->srcFLD->Type()) { default: case DBTableFieldString: groups[i]->dstFLD->String(outRecord,groups[i]->srcFLD->String(inRecord)); break; case DBTableFieldInt: groups[i]->dstFLD->Int(outRecord,groups[i]->srcFLD->Int(inRecord)); break; } } p = head->next; while(p) { field = fields->Item (p->getOldName()); switch(p->getFunc()) { default: case BAD: break; case NUM: p->setInt(); p->field->Int(outRecord,1); break; case NONNULL: if (field->Type() == DBTableFieldInt) { p->setInt(); if (field->Int(inRecord) != field->IntNoData()) p->field->Int(outRecord,1); else p->field->Int(outRecord,0); } else { if (!CMmathEqualValues(field->Float(inRecord),field->FloatNoData())) p->field->Int(outRecord,1); else p->field->Int(outRecord,0); } break; case MIN: if (field->Type() == DBTableFieldInt) { p->setInt(); if (field->Int(inRecord) != field->IntNoData()) p->field->Int(outRecord,field->Int(inRecord)); } else { if(!CMmathEqualValues(field->Float(inRecord),field->FloatNoData())) p->field->Float(outRecord,field->Float(inRecord)); } break; case MAX: if (field->Type() == DBTableFieldInt) { p->setInt(); if (field->Int(inRecord) != field->IntNoData()) p->field->Int(outRecord,field->Int(inRecord)); } else { if(!CMmathEqualValues(field->Float(inRecord),field->FloatNoData())) p->field->Float(outRecord,field->Float(inRecord)); } break; case SUM: if (field->Type() == DBTableFieldInt) { p->setInt(); if (field->Int(inRecord) != field->IntNoData()) p->field->Int(outRecord,field->Int(inRecord)); else p->field->Int(outRecord,0); } else { if(!CMmathEqualValues(field->Float(inRecord),field->FloatNoData())) p->field->Float(outRecord,field->Float(inRecord)); else p->field->Float(outRecord,0.0); } break; case DEV: case PCT: case MED: p->tailVal = p->tailVal->next = new Values(); p->tailVal->val = field->Float(inRecord); p->tailVal->next = 0; break; case MOD: p->tailVal->val = field->Float(inRecord); p->tailVal->occur = 1; p->tailVal = p->tailVal->next = new Values(); break; } p = p->next; } } } for(int outRecID = 0; outRecID < outTable->ItemNum();++outRecID) { outRecord = outTable->Item(outRecID); p = head->next; FieldOptions *sum, *num; DBFloat mod; int occurrance; float i; bool mult; Values *cur; while(p) { field = fields->Item (p->getOldName()); switch(p->getFunc()) { case AVG: if((FLDExists(head,p->getOldName(),SUM,&sum)) && (FLDExists(head,p->getOldName(),NONNULL,&num))) p->field->Float(outRecord,sum->field->Float(outRecord) / (DBFloat) (num->field->Int(outRecord))); else CMmsgPrint (CMmsgUsrError, "Program Error! Could not find SUM or NONNULL in linked list! Please contact the GHAAS developers group!"); break; case NAVG: if((FLDExists(head,p->getOldName(),SUM,&sum)) && (FLDExists(head,"NUM",NUM,&num))) p->field->Float(outRecord,sum->field->Float(outRecord) / (DBFloat) (num->field->Int(outRecord))); else CMmsgPrint (CMmsgUsrError, "Program Error! Could not find SUM or NUM in linked list! Please contact the GHAAS developers group!"); break; case PCT: case MED: i = (float) (inTable->ItemNum() * p->getHead()->occur * 0.01) - 1; cur = p->getHead()->next; while(i > 0) { cur = cur->next; i--; } p->field->Float(outRecord,(cur->val + cur->next->val) / 2); break; case MOD: mod = 0.0; occurrance = 0; mult = false; cur = p->getHead(); while(cur) { if(cur->occur > occurrance) { mod = cur->val; occurrance = cur->occur; mult = false; } else if(cur->occur == occurrance) mult = true; cur = cur->next; } if(mult) CMmsgPrint (CMmsgUsrError, "** Warning, multiple answers for MOD, listing first found!"); p->field->Float(outRecord,mod); break; default: break; } p = p->next; } } p = head->next; while(p) { if(p->getFunc() == DEV) { FieldOptions *avg, *num; field = fields->Item (p->getOldName()); if((FLDExists(head,p->getOldName(),AVG,&avg)) && (FLDExists(head,"NUM",NUM,&num))) { for(int outRecID = 0; outRecID < outTable->ItemNum();++outRecID) { outRecord = outTable->Item(outRecID); DBFloat sum = 0.0; Values *cur = p->getHead()->next; while(cur) { // sum += (DBFloat) (pow((cur->val - avg->field->Float(outRecord)),2)); DBFloat add = (cur->val - avg->field->Float(outRecord)); sum += (DBFloat) (add * add); cur = cur->next; } sum = sqrt(sum /(DBFloat) num->field->Int(outRecord)); p->field->Float(outRecord,sum); } } else CMmsgPrint (CMmsgUsrError, "Program Error! Could not find AVG or NUM in linked list! Please contact the GHAAS developers group!"); } p = p->next; } // DELETE unnecessary fields which were for temp storage fields = outTable->Fields(); p = head->next; while(p) { if(!p->getPrint()) outTable->DeleteField(fields->Item(p->getNewName())); p = p->next; } p = head->next; while(p) { if ((strcmp(p->field->Format(),DBHiddenField) == 0) && p->getPrint()) { if(p->isInt()) { int maxval = 0; for(int outRecID = 0; outRecID < outTable->ItemNum();++outRecID) { int val = p->field->Int(outTable->Item(outRecID)); if (maxval < val) maxval = val; else if (maxval < -val) maxval = -val; } p->field->Format(DBMathIntAutoFormat(maxval)); } else { float maxval = 0.0; for(int outRecID = 0; outRecID < outTable->ItemNum();++outRecID) { float val = p->field->Float(outTable->Item(outRecID)); if (maxval < val) maxval = val; else if (maxval < -val) maxval = -val; } p->field->Format(DBMathFloatAutoFormat(maxval)); } } // CMmsgPrint (CMmsgUsrError, "Format(%s)%d,%d: '%s'",p->getFuncName(),p->isInt(),p->getPrint(),p->field->Format()); p = p->next; } DBObjectLIST<DBObjTableField> *list = new DBObjectLIST<DBObjTableField> ("Sorted Field List"); for(i = 0; i < numGrpNames; i++) list->Add(groups[i]->dstFLD); outTable->ListSort(list); if (ascii) DBExportASCIITable(outTable,outFile); else outData->Write(outFile); /* CLEANUP ************************************************/ if(outFile != stdout) fclose(outFile); for(i = 0; i < numGrpNames; i++) delete groups[i]->dstFLD; delete groups; p = head; while(p) { head = head->next; delete p; p = head; } return(DBSuccess); }
int main(int argc, char** argv) { plString inputFile, outputFile; bool exVtx = false, exTex = false; PlasmaVer inVer = PlasmaVer::pvUnknown; plString objName; short objType = -1; if (argc == 1) { doHelp(argv[0]); return 0; } for (int i=1; i<argc; i++) { if (strcmp(argv[i], "-o") == 0 || strcmp(argv[i], "--out") == 0) { if (++i >= argc) { fprintf(stderr, "Error: expected filename\n"); return 1; } outputFile = argv[i]; } else if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--ver") == 0) { if (++i >= argc) { fprintf(stderr, "Error: expected version specifier\n"); return 1; } plString ver = plString(argv[i]).toLower(); if (ver == "prime") inVer = PlasmaVer::pvPrime; else if (ver == "pots") inVer = PlasmaVer::pvPots; else if (ver == "moul") inVer = PlasmaVer::pvMoul; else if (ver == "eoa") inVer = PlasmaVer::pvEoa; else if (ver == "hex") inVer = PlasmaVer::pvHex; else if (ver == "universal") inVer = PlasmaVer::pvUniversal; else { fprintf(stderr, "Error: unrecognized version: %s\n", ver.cstr()); return 1; } } else if (strcmp(argv[i], "-x") == 0 || strcmp(argv[i], "--extract") == 0) { if (++i >= argc) { fprintf(stderr, "Error: expected object specifier"); return 1; } plString objSpec = argv[i]; plString type = objSpec.beforeFirst(':'); objType = plFactory::ClassIndex(type); if (objType == -1) objType = type.toInt(); objName = objSpec.afterLast(':'); if (objName.startsWith("\"")) { do { if (++i >= argc) { fprintf(stderr, "Error: Unterminated string"); return 1; } objName += plString(" ") + argv[i]; } while (!objName.endsWith("\"")); objName = objName.mid(1, objName.len() - 2); } } else if (strcmp(argv[i], "--notex") == 0) { exTex = true; fprintf(stderr, "Warning: omitting texture data; output files wil be incomplete\n"); } else if (strcmp(argv[i], "--novtx") == 0) { exVtx = true; fprintf(stderr, "Warning: omitting vertex data; output files wil be incomplete\n"); } else if (strcmp(argv[i], "-?") == 0 || strcmp(argv[i], "--help") == 0) { doHelp(argv[0]); return 0; } else if (argv[i][0] == '-') { fprintf(stderr, "Warning: unrecognized option %s\n", argv[i]); } else { if (inputFile.empty()) inputFile = argv[i]; else fprintf(stderr, "Warning: ignoring extra parameter %s\n", argv[i]); } } if (outputFile.empty()) outputFile = "out.prc"; if (!inVer.isValid() && inputFile.afterLast('.') != "prp" && inputFile.afterLast('.') != "age") { fprintf(stderr, "Error: Plasma version must be specified for object decompilation\n"); return 1; } plDebug::Init(plDebug::kDLAll); plResManager rm; rm.setVer(inVer, true); hsFileStream out; out.open(outputFile, fmCreate); pfPrcHelper prc(&out); if (exTex) prc.exclude(pfPrcHelper::kExcludeTextureData); if (exVtx) prc.exclude(pfPrcHelper::kExcludeVertexData); try { if (inputFile.afterLast('.') == "prp") { plPageInfo* page = rm.ReadPage(inputFile); if (objType == -1) { rm.WritePagePrc(&prc, page); } else { std::vector<plKey> keys = rm.getKeys(page->getLocation(), objType); bool found = false; for (std::vector<plKey>::iterator it = keys.begin(); it != keys.end(); it++) { if ((*it)->getName() == objName && (*it)->getObj() != NULL) { (*it)->getObj()->prcWrite(&prc); found = true; break; } } if (!found) fprintf(stderr, "Object %s:%s does not exist\n", plFactory::ClassName(objType), objName.cstr()); } } else if (inputFile.afterLast('.') == "age") { plAgeInfo* age = rm.ReadAge(inputFile, false); rm.WriteAgePrc(&prc, age); } else { hsFileStream in; if (!in.open(inputFile, fmRead)) { fprintf(stderr, "Error opening input file\n"); return 1; } in.setVer(inVer); plCreatable* cre = rm.ReadCreatable(&in); cre->prcWrite(&prc); } } catch (hsException& e) { fprintf(stderr, "%s:%lu: %s\n", e.File(), e.Line(), e.what()); return 1; } catch (std::exception& e) { fprintf(stderr, "Caught Exception: %s\n", e.what()); return 1; } printf("Successfully decompiled %s!\n", inputFile.cstr()); return 0; }
int main (int argc,char *argv []) { int argPos, argNum = argc, ncid, varid; double range[2]; char *title = NULL, *type = NULL, *domain = NULL, *subject = NULL, *ref = NULL, *inst = NULL, *source = NULL, *comments = NULL; VarNode_t *head, *last; if((last = head = malloc(sizeof(VarNode_t))) == (VarNode_t *) NULL) { CMmsgPrint (CMmsgAppError, "Memory allocation error in: %s %d",__FILE__,__LINE__); return(NCfailed); } for (argPos = 1;argPos < argNum;) { if (CMargTest(argv[argPos],"-h","--help")) { if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) { doHelp(CMfileName(argv[0]),0); break; } else doHelp(CMfileName(argv[0]),(strcmp(argv[argPos],"extend") == 0) || (strcmp(argv[argPos],"e") == 0)); continue; } if (CMargTest(argv[argPos],"-l","--longname")) { if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) { CMmsgPrint (CMmsgUsrError, "Missing variable Name!"); return (CMfailed); } last->text = true; last->var = argv[argPos]; if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) { CMmsgPrint (CMmsgUsrError, "Missing Long Name!"); return (CMfailed); } last->dat = argv[argPos]; last->attrib = NCnameVALongName; if((last = last->next = malloc(sizeof(VarNode_t))) == NULL) { CMmsgPrint (CMmsgSysError, "Memory allocation error in: %s %d",__FILE__,__LINE__); return(NCfailed); } last->dat = last->dat2 = (char *) NULL; if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-n","--standardname")) { if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) { CMmsgPrint (CMmsgUsrError, "Missing variable Name!"); return (CMfailed); } last->text = true; last->var = argv[argPos]; if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) { CMmsgPrint (CMmsgUsrError, "Missing Standard Name!"); return (CMfailed); } last->dat = argv[argPos]; last->attrib = NCnameVAStandardName; if((last = last->next = malloc(sizeof(VarNode_t))) == NULL) { CMmsgPrint (CMmsgSysError, "Memory allocation error in: %s %d"); return(CMfailed); } last->dat = last->dat2 = (char *) NULL; if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-U","--units")) { if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) { CMmsgPrint (CMmsgUsrError, "Missing variable!"); return (CMfailed); } last->text = true; last->var = argv[argPos]; if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) { CMmsgPrint (CMmsgUsrError, "Missing Units!"); return (CMfailed); } last->dat = argv[argPos]; last->attrib = NCnameVAUnits; if((last = last->next = malloc(sizeof(VarNode_t))) == NULL) { CMmsgPrint (CMmsgSysError, "Memory allocation error in: %s %d",__FILE__,__LINE__); return(NCfailed); } last->dat = last->dat2 = (char *) NULL; if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-v","--validrange")) { if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) { CMmsgPrint (CMmsgUsrError, "Missing variable!"); return (CMfailed); } // ******************** CHECK HERE!!! ************************ last->text = false; last->var = argv[argPos]; if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) { CMmsgPrint (CMmsgUsrError, "Missing upper range!"); return (CMfailed); } last->dat = argv[argPos]; if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) { CMmsgPrint (CMmsgUsrError, "Missing lower range!"); return (CMfailed); } last->dat2 = argv[argPos]; last->attrib = NCnameVAValidRange; if((last = last->next = malloc(sizeof(VarNode_t))) == NULL) { CMmsgPrint (CMmsgSysError, "Memory allocation error in: %s %d",__FILE__,__LINE__); return(NCfailed); } last->dat = last->dat2 = (char *) NULL; if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-o","--offset")) { if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) { CMmsgPrint (CMmsgUsrError, "Missing variable!"); return (CMfailed); } last->text = false; last->var = argv[argPos]; if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) { CMmsgPrint (CMmsgUsrError, "Missing offset!"); return (CMfailed); } last->dat = argv[argPos]; last->attrib = NCnameVAAddOffset; if((last = last->next = malloc(sizeof(VarNode_t))) == NULL) { CMmsgPrint (CMmsgSysError, "Memory allocation error in: %s %d",__FILE__,__LINE__); return(CMfailed); } last->dat = last->dat2 = (char *) NULL; if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-s","--scalefactor")) { if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) { CMmsgPrint (CMmsgUsrError,"Missing variable!"); return (CMfailed); } last->text = false; last->var = argv[argPos]; if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) { CMmsgPrint (CMmsgUsrError,"Missing scale factor!"); return (CMfailed); } last->dat = argv[argPos]; last->attrib = NCnameVAScaleFactor; if((last = last->next = malloc(sizeof(VarNode_t))) == NULL) { CMmsgPrint (CMmsgSysError, "Memory allocation error in: %s %d",__FILE__,__LINE__); return(NCfailed); } last->dat = last->dat2 = (char *) NULL; if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-t","--title")) { if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) { CMmsgPrint (CMmsgUsrError, "Missing Title!"); return (CMfailed); } title = argv[argPos]; if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-y","--type")) { if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) { CMmsgPrint (CMmsgUsrError, "Missing Type!"); return (CMfailed); } type = argv[argPos]; if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-d","--domain")) { if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) { CMmsgPrint (CMmsgUsrError, "Missing Domain!"); return (CMfailed); } domain = argv[argPos]; if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-s","--subject")) { if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) { CMmsgPrint (CMmsgUsrError, "Missing Subject!"); return (CMfailed); } subject = argv[argPos]; if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-r","--references")) { if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) { CMmsgPrint (CMmsgUsrError, "Missing References!"); return (CMfailed); } ref = argv[argPos]; if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-i","--institution")) { if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) { CMmsgPrint (CMmsgUsrError, "Missing Institution!"); return (CMfailed); } inst = argv[argPos]; if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-s","--source")) { if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) { CMmsgPrint (CMmsgUsrError, "Missing Source!"); return (CMfailed); } source = argv[argPos]; if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-c","--comments")) { if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) { CMmsgPrint (CMmsgUsrError, "Missing Comment!"); return (CMfailed); } comments = argv[argPos]; if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) break; continue; } if ((argv[argPos][0] == '-') && (strlen (argv[argPos]) > 1)) { CMmsgPrint (CMmsgUsrError, "Unknown option: %s!",argv[argPos]); return (NCfailed); } argPos++; } last->next = (VarNode_t *) NULL; if ((argNum > 1) && (strcmp(argv[1],"-") != 0)) { if(nc_open(argv[1],NC_WRITE,&ncid) != NC_NOERR) { CMmsgPrint (CMmsgUsrError, "Error opening file: %s!",argv[1]); return (NCfailed); } } else doHelp(CMfileName(argv[0]),1); if(nc_redef(ncid) != NC_NOERR) { CMmsgPrint (CMmsgUsrError, "Cannot place into redef mode!"); return (NCfailed); } last = head; while(last->next != (VarNode_t *) NULL) { if(nc_inq_varid(ncid,last->var,&varid) != NC_NOERR) { CMmsgPrint (CMmsgUsrError, "Error finding %s variable",last->var); return (NCfailed); } if(last->text) { if(nc_put_att_text(ncid, varid, last->attrib,strlen(last->dat), last->dat) != NC_NOERR) { CMmsgPrint (CMmsgUsrError, "Error changing attribute: %s!", last->attrib); return (NCfailed); } } else { if(last->dat2 != (char *) NULL) { range[0] = atof(last->dat); range[1] = atof(last->dat2); if(nc_put_att_double(ncid, varid, last->attrib,NC_DOUBLE, 2, range) != NC_NOERR) { CMmsgPrint (CMmsgUsrError, "Error changing attribute: %s!", last->attrib); return (NCfailed); } } else { range[0] = atof(last->dat); if(nc_put_att_double(ncid, varid, last->attrib,NC_DOUBLE, 1, range) != NC_NOERR) { CMmsgPrint (CMmsgUsrError, "Error changing attribute: %s!", last->attrib); return (NCfailed); } } } last = last->next; } if((title != NULL) && (nc_put_att_text(ncid, NC_GLOBAL, NCnameGATitle,strlen(title), title) != NC_NOERR)) { CMmsgPrint (CMmsgUsrError, "Error changing attribute: title!"); return (NCfailed); } if(type != NULL) if(nc_put_att_text(ncid, NC_GLOBAL, NCnameGADataType,strlen(type), type) != NC_NOERR) { CMmsgPrint (CMmsgUsrError, "Error changing attribute; type!"); return (NCfailed); } if((domain != NULL) && (nc_put_att_text(ncid, NC_GLOBAL, NCnameGADomain, strlen(domain), domain) != NC_NOERR)) { CMmsgPrint (CMmsgUsrError, "Error changing attribute: domain!"); return (NCfailed); } if((subject != NULL) && (nc_put_att_text(ncid, NC_GLOBAL, NCnameGASubject, strlen(subject), subject) != NC_NOERR)) { CMmsgPrint (CMmsgUsrError, "Error changing attribute: subject!"); return (NCfailed); } if((ref != NULL) && (nc_put_att_text(ncid, NC_GLOBAL, NCnameGAReferences, strlen(ref), ref) != NC_NOERR)) { CMmsgPrint (CMmsgUsrError, "Error changing attribute: references!"); return (NCfailed); } if((inst != NULL) && (nc_put_att_text(ncid, NC_GLOBAL, NCnameGAInstitution, strlen(inst), inst) != NC_NOERR)) { CMmsgPrint (CMmsgUsrError, "Error changing attribute: institution!"); return (NCfailed); } if((source != NULL) && (nc_put_att_text(ncid, NC_GLOBAL, NCnameGASource, strlen(source), source) != NC_NOERR)) { CMmsgPrint (CMmsgUsrError, "Error changing attribute: source!"); return (NCfailed); } if((comments != NULL) && (nc_put_att_text(ncid, NC_GLOBAL, NCnameGAComments, strlen(comments), comments) != NC_NOERR)) { CMmsgPrint (CMmsgUsrError, "Error changing attribute: comments!"); return (NCfailed); } if(nc_close(ncid) != NC_NOERR) { CMmsgPrint (CMmsgUsrError, "Error commiting changes to file!"); return (NCfailed); } return 0; }
void doInitialPage() /* Put up page with search box that explains program and * some good things to search on. */ { char *listSpec = NULL; webStartWrapperDetailedNoArgs(cart, NULL, "", "VisiGene Image Browser", FALSE, FALSE, FALSE, TRUE); printf("<FORM ACTION=\"%s\" METHOD=GET>\n", hgVisiGeneCgiName()); puts("<P>VisiGene is a virtual microscope for viewing <em>in situ</em> images. \n" "These images show where a gene is used in an organism, sometimes down to \n" "cellular resolution. With VisiGene users can retrieve images that meet specific " "search criteria, then interactively zoom and scroll across the collection.</P>\n"); printf("<CENTER>"); listSpec = cartUsualString(cart, hgpListSpec, ""); cgiMakeTextVar(hgpListSpec, listSpec, 30); cgiMakeButton(hgpDoSearch, "search"); printf("<BR>\n"); printf("</CENTER>"); puts( "<P>Good search terms include gene symbols, authors, years, body parts,\n" "organisms, GenBank and UniProt accessions, Known Gene descriptive terms,\n" "<A HREF=\"http://genex.hgu.mrc.ac.uk/Atlas/intro.html\" \n" "TARGET=_blank>Theiler</A> stages for mice, and \n" "<A HREF=\"http://www.xenbase.org/atlas/NF/NF-all.html\" \n" "TARGET=_blank>Nieuwkoop/Faber</A> stages for frogs. The wildcard characters\n" "* and ? work with gene symbols; otherwise the full word must match.</P>\n" "<P> \n" "<H3>Sample queries</H3> \n" "<TABLE border=0 CELLPADDING=0 CELLSPACING=0> \n" " <TR><TD VALIGN=Top NOWRAP><B>Request:</B><BR></TD> \n" " <TD VALIGN=Top COLSPAN=2><B> VisiGene Response:</B><BR></TD> \n" " </TR> \n" // " <TR><TD VALIGN=Top><BR></TD></TR> \n" " <TR><TD VALIGN=Top NOWRAP>nkx2-2</TD> \n" " <TD WIDTH=14></TD> \n" " <TD VALIGN=Top>Displays images associated with the gene nkx2-2</TD>\n" " </TR> \n" " <TR><TD VALIGN=Top NOWRAP>hoxa*</TD> \n" " <TD WIDTH=14></TD> \n" " <TD VALIGN=Top>Displays images of all genes in the Hox-A cluster (Note: * works only at the end of the word)</TD>\n" " </TR> \n" " <TR><TD VALIGN=Top NOWRAP>NM_007492</TD> \n" " <TD WIDTH=14></TD> \n" " <TD VALIGN=Top>Displays images associated with accession NM_007492</TD> \n" " </TR> \n" " <TR><TD VALIGN=Top NOWRAP>theiler 22</TD> \n" " <TD WIDTH=14></TD> \n" " <TD VALIGN=Top>Displays all images that show Theiler stage 22</TD> \n" " </TR> \n" " <TR><TD VALIGN=Top NOWRAP>vgPrb_16</TD> \n" " <TD WIDTH=14></TD> \n" " <TD VALIGN=Top>Displays images associated with VisiGene probe ID 16</TD> \n" " </TR> \n" " <TR><TD VALIGN=Top NOWRAP>allen institute</TD> \n" " <TD WIDTH=14></TD> \n" " <TD VALIGN=Top>Displays all images from the Allen Brain Atlas</TD> \n" " </TR> \n" " <TR><TD VALIGN=Top NOWRAP>mouse</TD> \n" " <TD WIDTH=14></TD> \n" " <TD VALIGN=Top>Displays all mouse images </TD> \n" " </TR> \n" " <TR><TD VALIGN=Top NOWRAP>xenopus</TD> \n" " <TD WIDTH=14></TD> \n" " <TD VALIGN=Top>Displays all images associated with frogs of genus Xenopus </TD>\n" " </TR> \n" " <TR><TD VALIGN=Top NOWRAP>mouse midbrain</TD> \n" " <TD WIDTH=14></TD> \n" " <TD VALIGN=Top>Displays mouse images that show expression in the " "midbrain</TD> \n" " </TR> \n" " <TR><TD VALIGN=Top NOWRAP>smith jc 1994</TD> \n" " <TD WIDTH=14></TD> \n" " <TD VALIGN=Top>Displays images contributed by scientist J.C. Smith " "in 1994</TD> \n" " </TR> \n" "</TABLE> \n" ); printf("</FORM>\n"); doHelp(); webEnd(); }
int main(int argc, char* argv[]) { char *filename = (char *) NULL, *rename = (char *) NULL, *varname = (char *) NULL; int argPos = 0, argNum = argc, interval = NONE, ncid = 0, *dimIDs = (int *) NULL; // NCdsHandle_t *dsHandle; if(argNum == 1) { doHelp(CMfileName(argv[0])); return (NCsucceeded); } if ((argNum == 2) && (argv[1][0] == '-')) { if (CMargTest (argv[1],"-d","--debug")) SetDebug(); doHelp(CMfileName(argv[0])); return (NCsucceeded); } initMemInfo(); for(argPos = 1; argPos < argNum;) { if (CMargTest(argv[argPos],"-d","--debug")) { SetDebug(); CMargShiftLeft(argPos,argv,argc); argNum--; continue; } if (CMargTest(argv[argPos],"-h","--help")) { doHelp(CMfileName(argv[0])); cleanup(NCsucceeded); } if (CMargTest(argv[argPos],"-f","--file")) { if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) { CMmsgPrint (CMmsgUsrError,"Missing file!"); return (CMfailed); } filename = argv[argPos]; if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-r","--rename")) { if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) { CMmsgPrint (CMmsgUsrError,"Missing name!"); return (CMfailed); } if(rename == (char *) NULL) rename = argv[argPos]; else { CMmsgPrint (CMmsgUsrError, "Output field name defined twice!"); cleanup(NCfailed); } if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) break; continue; } if (CMargTest(argv[argPos],"-s","--set")) { if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) { CMmsgPrint (CMmsgUsrError,"Time step!"); return (CMfailed); } if(interval != NONE) { CMmsgPrint (CMmsgUsrError, "Interval already set!"); cleanup(NCfailed); } if(NCmathIsNumber(argv[argPos])) interval = atoi(argv[argPos]); else if (strcmp(argv[argPos],"hour") == 0) interval = HOUR; else if (strcmp(argv[argPos],"day") == 0) interval = DAY; else if (strcmp(argv[argPos],"month") == 0) interval = MONTH; else if (strcmp(argv[argPos],"year") == 0) interval = YEAR; else { CMmsgPrint (CMmsgUsrError, "Undefined time interval '%s'",argv[argPos]); cleanup(NCfailed); } if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) { CMmsgPrint (CMmsgUsrError,"Missing variable!"); return (CMfailed); } if(varname == (char *) NULL) varname = argv[argPos]; else { CMmsgPrint (CMmsgUsrError, "Input field name defined twice!"); cleanup(NCfailed); } if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) break; continue; } if ((argv[argPos][0] == '-') && (strlen (argv[argPos]) > 1)) { CMmsgPrint (CMmsgUsrError, "Unknown option: %s!",argv[argPos]); cleanup(NCfailed); } argPos++; } if(interval == NONE) { CMmsgPrint (CMmsgUsrError, "Invalid interval!"); cleanup(NCfailed); } if (filename != (char *) NULL) { if(nc_open(filename,NC_WRITE,&ncid) != NC_NOERR) { CMmsgPrint (CMmsgAppError, "Error opening file: %s!",filename); return (NCfailed); } } else if ((argNum > 1) && (strcmp(argv[1],"-") != 0)) { if(nc_open(argv[1],NC_WRITE,&ncid) != NC_NOERR) { CMmsgPrint (CMmsgUsrError, "Error opening file: %s!",argv[1]); return (NCfailed); } } else doHelp(CMfileName(argv[0])); // dsHandle = NCdsHandleOpenById (ncid); /* if((nc_inq_varid(ncid,varname,&inVar)) != NC_NOERR) { CMmsgPrint (CMmsgUsrError, "NC: Error getting varID!"); cleanup(NCfailed); } if(nc_inq_ndims(ncid,&ndims) != NC_NOERR) { CMmsPrint (CMmsgAppError, "Cannot get the ndims!",__FILE__,__LINE__); cleanup(NCfailed); } dimIDs = malloc(sizeof(int) * ndims); if((nc_inq_vardimid(ncid,inVar,dimIDs)) != NC_NOERR) { CMmsgPrint (CMmsgUsrError, "NC: Error getting dimIDs!"); cleanup(NCfailed); } if(nc_redef(ncid) != NC_NOERR) { CMmsgPrint (CMmsgAppError, "Cannot place into redef mode!"); cleanup(NCfailed); } CMmsgPrint (CMmsgUsrError, "id=%d ndims=%d, dimIDs[0]=%d dimIDs[1]=%d dimIDs[2]=%d",ncid,ndims, dimIDs[0],dimIDs[1],dimIDs[2]); if(rename == (char *) NULL) { if((nc_def_var(ncid,"Aggregate",NC_DOUBLE,ndims,dimIDs,&outVar)) != NC_NOERR) { CMmsgPrint (CMmsgUsrError, "NC: Error creating new variable!"); cleanup(NCfailed); } } else { if((nc_def_var(ncid,rename,NC_DOUBLE,ndims,dimIDs,&outVar)) != NC_NOERR) { CMmsgPrint (CMmsgUsrError, "NC: Error creating new variable!"); cleanup(NCfailed); } } CMmsgPrint (CMmsgUsrError, "id=%d ndims=%d, dimIDs[0]=%d dimIDs[1]=%d dimIDs[2]=%d",ncid,ndims, dimIDs[0],dimIDs[1],dimIDs[2]); //if(nc_enddef(ncid) != NC_NOERR) { CMmsgPrint (CMmsgAppError, "Cannot get out of redef mode!"); cleanup(NCfailed); } cleanup(NCsucceeded); if((nc_inq_dimlen(ncid,dimIDs[0],&bLen)) != NC_NOERR) { CMmsgPrint (CMmsgUsrError, "NC: Error getting length of dimension!"); cleanup(NCfailed); } for(i = 0; i < bLen; i++) { idx[0] = i; if(nc_get_var1_double(ncid,inVar,idx, &val) != NC_NOERR) { CMmsgPrint (CMmsgUsrError, "NC: There's a problem getting a value!"); cleanup(NCfailed); } printf("inVar: %d, outVar: %d, val: %f",inVar,outVar,val); }*/ // for (i = 0; i < dsHandle->ColNum * dsHandle->RowNum * dsHandle->TimeNum; i++) printf("i: %f",data[i]); cleanup(NCsucceeded); }
int main(int argc, char* argv[]) { if (argc < 2) { doHelp(argv[0]); return 1; } OperationMode mode = kModeUpdate; std::list<plString> addPaths; std::list<plString> delPaths; std::list<plString> sumFiles; for (int i = 1; i < argc; i++) { if (argv[i][0] == '-') { if (strcmp(argv[i], "-L") == 0) { mode = kModeList; } else if (strcmp(argv[i], "-i") == 0) { mode = kModeManual; if (++i >= argc) { fprintf(stderr, "Error: Expected filename\n"); return 1; } addPaths.push_back(argv[i]); } else if (strcmp(argv[i], "-d") == 0) { mode = kModeManual; if (++i >= argc) { fprintf(stderr, "Error: Expected filename\n"); return 1; } delPaths.push_back(argv[i]); } else if (strcmp(argv[i], "-c") == 0) { s_createFile = true; } else if (strcmp(argv[i], "-y") == 0) { s_autoYes = true; } else if (strcmp(argv[i], "-old") == 0) { s_oldFormat = true; } else if (strcmp(argv[i], "--help") == 0) { doHelp(argv[0]); return 0; } else { fprintf(stderr, "Error: Unrecognized option %s\n", argv[i]); return 1; } } else { sumFiles.push_back(argv[i]); } } if (sumFiles.empty()) { fprintf(stderr, "Error: No sum files specified\n"); return 1; } if (s_createFile && mode == kModeList) { fprintf(stderr, "Error: -c and -L options cannot be combined\n"); return 1; } switch (mode) { case kModeUpdate: for (std::list<plString>::iterator fn = sumFiles.begin(); fn != sumFiles.end(); fn++) { if (UpdateSums(*fn)) printf("Successfully updated %s\n", fn->cstr()); } break; case kModeList: for (std::list<plString>::iterator fn = sumFiles.begin(); fn != sumFiles.end(); fn++) { printf("%s:\n", fn->cstr()); try { plEncryptedStream S; if (!S.open(*fn, fmRead, plEncryptedStream::kEncAuto)) { fprintf(stderr, "Could not open file %s\n", fn->cstr()); continue; } SumFile sum; sum.read(&S); S.close(); std::vector<SumEntry>::iterator it; for (it = sum.fEntries.begin(); it != sum.fEntries.end(); it++) PrintFile(*it, ' '); printf("\n"); } catch (hsException& e) { fprintf(stderr, "%s:%ld: %s\n", e.File(), e.Line(), e.what()); return 1; } catch (...) { fprintf(stderr, "An unknown error occured\n"); return 1; } } break; case kModeManual: if (sumFiles.size() != 1) { fprintf(stderr, "Error: You must specify exactly ONE sumfile for\n"); fprintf(stderr, "-i and -d operations\n"); return 1; } try { bool isUpdated = false; SumFile sum; plEncryptedStream S; plEncryptedStream::EncryptionType eType = plEncryptedStream::kEncXtea; if (!s_createFile) { if (!S.open(sumFiles.front(), fmRead, plEncryptedStream::kEncAuto)) { fprintf(stderr, "Could not open file %s\n", sumFiles.front().cstr()); return 1; } eType = S.getEncType(); sum.read(&S); S.close(); } else { isUpdated = true; } std::list<plString>::iterator pi; std::vector<SumEntry>::iterator it; for (pi = delPaths.begin(); pi != delPaths.end(); pi++) { bool found = false; it = sum.fEntries.begin(); while (it != sum.fEntries.end()) { if (it->fPath == *pi) { PrintFile(*it, '-'); it = sum.fEntries.erase(it); found = true; isUpdated = true; } else { ++it; } } if (!found) fprintf(stderr, "Warning: path '%s' not found\n", pi->cstr()); } for (pi = addPaths.begin(); pi != addPaths.end(); pi++) { hsFileStream* IS = FindFilePath(*pi, ""); if (IS == NULL) { fprintf(stderr, "Warning: path '%s' not found\n", pi->cstr()); continue; } SumEntry ent; ent.fPath = GetInternalName(*pi); ent.fHash = plMD5::hashStream(IS); ent.fTimestamp = IS->getModTime(); bool found = false; it = sum.fEntries.begin(); while (it != sum.fEntries.end()) { if (it->fPath == *pi) { found = true; if (it->fHash != ent.fHash) { PrintFile(*it, '*'); it->fHash = ent.fHash; it->fTimestamp = ent.fTimestamp; isUpdated = true; } else { PrintFile(*it, ' '); } } ++it; } if (!found) { PrintFile(ent, '+'); sum.fEntries.push_back(ent); if (IS != NULL) delete IS; isUpdated = true; } } if (isUpdated) { if (!S.open(sumFiles.front(), fmWrite, eType)) { fprintf(stderr, "Error: Could not open %s for writing!\n", sumFiles.front().cstr()); return 1; } sum.write(&S); S.close(); printf("Successfully %s %s\n", s_createFile ? "created" : "updated", sumFiles.front().cstr()); } } catch (hsException& e) { fprintf(stderr, "%s:%ld: %s\n", e.File(), e.Line(), e.what()); return 1; } catch (...) { fprintf(stderr, "An unknown error occured\n"); return 1; } break; } return 0; }
int main(int argc, char* argv[]) { if (argc < 2 || argc > 3) { doHelp(); return 0; } eDirection direction = kRepack; ST::string filename = argv[1]; ST_ssize_t dotLoc = filename.find_last('.'); if (argc == 3) { if (strcmp(argv[1], "-c") == 0) direction = kCreate; else if (strcmp(argv[1], "-x") == 0) direction = kExtract; else if (strcmp(argv[1], "-r") == 0) direction = kRepack; else { doHelp(); return 1; } filename = argv[2]; } else if (dotLoc >= 0 && filename.substr(dotLoc) == ".prd") { direction = kCreate; } plResManager rm; hsFileStream S, OS; if (!S.open(filename, fmRead)) { ST::printf(stderr, "Error opening {} for reading!", filename); return 1; } plPageInfo* page = new plPageInfo(); //int len; short maj = 63, min = 11; unsigned int i, j; if (direction == kExtract || direction == kRepack) { S.close(); delete page; page = rm.ReadPage(filename, true); OS.open(filenameConvert(filename, kExtract), fmCreate); OS.write(4, "PRD"); OS.writeShort(page->getAge().size()); OS.writeStr(page->getAge()); OS.writeShort(page->getPage().size()); OS.writeStr(page->getPage()); if (rm.getVer().isUniversal()) { maj = 0x7FFF; min = 0x7FFF; } else if (rm.getVer().isEoa()) { maj = -1; min = 1; } else if (rm.getVer().isHexIsle()) { maj = -1; min = 2; } else { maj = rm.getVer().revMajor(); min = rm.getVer().revMinor(); } OS.writeShort(maj); OS.writeShort(min); plLocation loc = page->getLocation(); loc.write(&OS); OS.close(); std::vector<short> types = rm.getTypes(loc); #ifdef _WIN32 CreateDirectoryW(getOutputDir(filename, page).to_wchar().data(), NULL); #else mkdir(getOutputDir(filename, page).c_str(), S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH); #endif for (i=0; i<types.size(); i++) { std::vector<plKey> objs = rm.getKeys(loc, types[i]); for (j=0; j<objs.size(); j++) { ST::string po_file = ST::format("{}[{04X}]{}.po", getOutputDir(filename, page), types[i], CleanFileName(objs[j]->getName())); OS.open(po_file, fmCreate); OS.setVer(rm.getVer()); rm.WriteCreatable(&OS, objs[j]->getObj()); OS.close(); } } } if (direction == kRepack) { filename = filenameConvert(filename, kExtract); S.open(filename, fmRead); } if (direction == kCreate || direction == kRepack) { OS.open(filenameConvert(filename, kCreate), fmCreate); char sig[4]; S.read(4, sig); if (strncmp(sig, "PRD", sizeof(sig)) != 0) { fputs("Error: Invalid input file!\n", stderr); OS.close(); S.close(); return 1; } ST::string ageName = S.readStr(S.readShort()); ST::string pageName = S.readStr(S.readShort()); page->setAge(ageName); page->setPage(pageName); maj = S.readShort(); min = S.readShort(); if (maj == 0x7FFF) { OS.setVer(PlasmaVer::pvUniversal); } else if (maj == -1) { if (min == 1) OS.setVer(PlasmaVer::pvEoa); else if (min == 2) OS.setVer(PlasmaVer::pvHex); } else if (maj == 70) { OS.setVer(PlasmaVer::pvMoul); } else if (maj == 63) { if (min == 11) OS.setVer(PlasmaVer::pvPrime); if (min == 12) OS.setVer(PlasmaVer::pvPots); } else { ST::printf(stderr, "Error: Invalid Plasma version: {}.{}\n", maj, min); OS.close(); S.close(); return 1; } S.setVer(OS.getVer()); plLocation loc; loc.read(&S); page->setLocation(loc); page->setReleaseVersion(0); page->setFlags(plPageInfo::kBasicChecksum); S.close(); std::vector<ST::string> inFiles; std::vector<short> inClasses; hsFileStream PS; PS.setVer(OS.getVer()); #ifdef _WIN32 ST::string pattern = ST::format("{}*.po", getOutputDir(filename, page)); WIN32_FIND_DATAW fd; HANDLE fr = FindFirstFileW(pattern.to_wchar().data(), &fd); if (fr != NULL) { do { ST::string po_file = getOutputDir(filename, page) + fd.cFileName; inFiles.push_back(po_file); PS.open(po_file, fmRead); short classType = PS.readShort(); PS.close(); bool haveClass = false; for (j=0; j<inClasses.size(); j++) if (inClasses[j] == classType) { haveClass = true; } if (!haveClass) inClasses.push_back(classType); } while (FindNextFileW(fr, &fd)); FindClose(fr); } #else dirent** des; unsigned int nEntries = scandir(getOutputDir(filename, page).c_str(), &des, &selPO, &alphasort); for (i=0; i<nEntries; i++) { ST::string po_file = getOutputDir(filename, page) + des[i]->d_name; inFiles.push_back(po_file); PS.open(po_file, fmRead); short classType = PS.readShort(); PS.close(); bool haveClass = false; for (j=0; j<inClasses.size(); j++) if (inClasses[j] == classType) { haveClass = true; } if (!haveClass) inClasses.push_back(classType); } #endif page->setClassList(inClasses); page->write(&OS); page->setDataStart(OS.pos()); plKeyCollector keys; for (i=0; i<inFiles.size(); i++) { plKey key = new plKeyData(); PS.open(inFiles[i], fmRead); PS.setVer(S.getVer()); unsigned int poLen = PS.size(); uint8_t* objBuf = new uint8_t[poLen]; key->setFileOff(OS.pos()); key->setObjSize(poLen); PS.read(poLen, objBuf); OS.write(poLen, objBuf); delete[] objBuf; PS.seek(2); key->readUoid(&PS); PS.close(); keys.add(key); } page->setIndexStart(OS.pos()); keys.sortKeys(page->getLocation()); std::vector<short> types = keys.getTypes(page->getLocation()); //if (types != inClasses) // throw "Wtf, mate?"; OS.writeInt(types.size()); for (i=0; i<types.size(); i++) { std::vector<plKey> kList = keys.getKeys(page->getLocation(), types[i]); OS.writeShort(pdUnifiedTypeMap::MappedToPlasma(types[i], OS.getVer())); unsigned int lenPos = OS.pos(); if (!OS.getVer().isUruSP() && !OS.getVer().isUniversal()) { OS.writeInt(0); OS.writeByte(0); } OS.writeInt(kList.size()); for (j=0; j<kList.size(); j++) kList[j]->write(&OS); if (!OS.getVer().isUruSP() && !OS.getVer().isUniversal()) { unsigned int nextPos = OS.pos(); OS.seek(lenPos); OS.writeInt(nextPos - lenPos - 4); OS.seek(nextPos); } } if (OS.getVer().isNewPlasma()) page->setChecksum(OS.pos()); else page->setChecksum(OS.pos() - page->getDataStart()); page->writeSums(&OS); OS.close(); } // Delete temp files with the repack option if (direction == kRepack) { #ifdef _WIN32 ST::string pattern = ST::format("{}*.po", getOutputDir(filename, page)); WIN32_FIND_DATAW rfd; HANDLE rfr = FindFirstFileW(pattern.to_wchar().data(), &rfd); if (rfr != NULL) { do { ST::string po_file = getOutputDir(filename, page) + rfd.cFileName; DeleteFileW(po_file.to_wchar().data()); } while (FindNextFileW(rfr, &rfd)); FindClose(rfr); } RemoveDirectoryW(getOutputDir(filename, page).to_wchar().data()); DeleteFileW(filename.to_wchar().data()); #else dirent** rdes; unsigned int nEntries = scandir(getOutputDir(filename, page).c_str(), &rdes, &selAll, &alphasort); for (i=0; i<nEntries; i++) { ST::string po_file = getOutputDir(filename, page) + rdes[i]->d_name; unlink(po_file.c_str()); } rmdir(getOutputDir(filename, page).c_str()); unlink(filename.c_str()); #endif } return 0; }
int main(int argc, char** argv) { if (argc < 2) { doHelp(); return 0; } std::vector<plString> fFiles; plDebug::Init(plDebug::kDLAll); plResManager rm; plPageInfo* page; plString outDir, outFile; bool exVtx = true, exTex = true, noHdr = false; for (int i=1; i<argc; i++) { if (argv[i][0] == '-') { if (argv[i][1] == '-') argv[i]++; if (strcmp(argv[i], "-help") == 0) { doHelp(); return 0; } else if (strcmp(argv[i], "-vtx") == 0) { exVtx = false; fprintf(stderr, "Warning: Including Vertex data\n"); } else if (strcmp(argv[i], "-tex") == 0) { exTex = false; fprintf(stderr, "Note: Texture data unsupported. -tex will " "be ignored for this export\n"); } else if (strcmp(argv[i], "-nohdr") == 0) { noHdr = true; } else { fprintf(stderr, "Error: Unrecognized option %s\n", argv[i]); return 1; } } else { fFiles.push_back(plString(argv[i])); } } for (size_t i=0; i<fFiles.size(); i++) { try { page = rm.ReadPage(fFiles[i]); } catch (hsException& e) { fprintf(stderr, "%s:%lu: %s\n", e.File(), e.Line(), e.what()); return 1; } catch (std::exception& e) { fprintf(stderr, "PrcExtract Exception: %s\n", e.what()); return 1; } catch (...) { fprintf(stderr, "Undefined error!\n"); return 1; } outDir = getOutputDir(fFiles[i], page); outFile = outDir + filenameConvert(fFiles[i]); #ifdef WIN32 CreateDirectory(outDir.cstr(), NULL); #else mkdir(outDir.cstr(), S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH); #endif printf("Writing %s\n", outFile.cstr()); hsFileStream* S = new hsFileStream(); if (!S->open(outFile, fmWrite)) { fprintf(stderr, "Error opening %s for writing!\n", outFile.cstr()); delete S; return 1; } S->setVer(rm.getVer()); pfPrcHelper* prc = new pfPrcHelper(S); if (exVtx) prc->exclude(pfPrcHelper::kExcludeVertexData); if (exTex) prc->exclude(pfPrcHelper::kExcludeTextureData); if (!noHdr) { prc->writeComment("Generator: PrcExtract"); prc->writeComment(plString("Source: ") + fFiles[i]); time_t ts = time(NULL); char buf[256]; strftime(buf, 256, "Created: %Y/%m/%d %H:%M:%S", localtime(&ts)); prc->writeComment(buf); S->writeStr("\n"); } try { rm.WritePagePrc(prc, page); } catch (hsException& e) { fprintf(stderr, "%s:%lu: %s\n", e.File(), e.Line(), e.what()); return 1; } catch (std::exception& e) { fprintf(stderr, "PrcExtract Exception: %s\n", e.what()); return 1; } catch (...) { fprintf(stderr, "Undefined error!\n"); return 1; } delete prc; S->close(); delete S; } return 0; }
int main(int argc, char** argv) { if (argc < 2) { doHelp(argv[0]); return 0; } plDebug::Init(plDebug::kDLAll); const char* filename = argv[1]; plString outfile = filenameConvert(filename, ".obj"); plString mtlfile = filenameConvert(filename, ".mtl"); hsTArray<plString> objects; for (int i=2; i<argc; i++) { if (argv[i][0] == '-') { if (strcmp(argv[i], "-o") == 0) { if (i+1 >= argc) { printf("No output filename supplied\n"); return 0; } else { outfile = argv[++i]; } } else if (strcmp(argv[i], "-m") == 0) { if (i+1 >= argc) { printf("No material filename supplied\n"); return 0; } else { mtlfile = argv[++i]; } } else if (strcmp(argv[i], "--help") == 0) { doHelp(argv[0]); return 0; } else { printf("Unrecognized option: %s\n", argv[i]); } } else { objects.append(argv[i]); } } plResManager rm; plPageInfo* page; try { page = rm.ReadPage(filename); } catch (const hsException& e) { plDebug::Error("%s:%lu: %s", e.File(), e.Line(), e.what()); return 1; } catch (const std::exception& e) { plDebug::Error("%s", e.what()); return 1; } catch (...) { plDebug::Error("Undefined error!"); return 1; } hsFileStream OS; if (!OS.open(mtlfile, fmCreate)) { fprintf(stderr, "Error opening %s for writing!\n", mtlfile.cstr()); return 1; } OS.writeStr("#Generated by Prp2Obj\n"); try { std::vector<plKey> MObjs = rm.getKeys(page->getLocation(), kGMaterial); for (size_t i = 0; i < MObjs.size(); i++) { hsGMaterial* mat = hsGMaterial::Convert(rm.getObject(MObjs[i])); WriteMat(mat, &OS); } } catch (const hsException& e) { plDebug::Error("%s:%lu: %s", e.File(), e.Line(), e.what()); return 1; } OS.close(); if (!OS.open(outfile, fmCreate)) { fprintf(stderr, "Error opening %s for writing!\n", outfile.cstr()); return 1; } OS.writeStr("#Generated by Prp2Obj\n"); OS.writeStr(plString::Format("mtllib %s\n", mtlfile.cstr())); size_t nObjects = 0; try { std::vector<plKey> SObjs = rm.getKeys(page->getLocation(), kSceneObject); for (size_t i = 0; i < SObjs.size(); i++) { if (objects.empty() || objects.find(SObjs[i]->getName()) != (size_t)-1) { plSceneObject* obj = plSceneObject::Convert(rm.getObject(SObjs[i])); if (obj->getDrawInterface().Exists()) WriteObj(obj, &OS, objects.empty()); nObjects++; } } } catch (const hsException& e) { plDebug::Error("%s:%lu: %s", e.File(), e.Line(), e.what()); return 1; } OS.close(); printf("Successfully wrote %u objects\n", (unsigned int)nObjects); return 0; }