bool ProjectileManager::readRecord(ESM::ESMReader &reader, uint32_t type) { if (type == ESM::REC_PROJ) { ESM::ProjectileState esm; esm.load(reader); ProjectileState state; state.mActorId = esm.mActorId; state.mBowId = esm.mBowId; state.mVelocity = esm.mVelocity; state.mIdArrow = esm.mId; state.mAttackStrength = esm.mAttackStrength; std::string model; try { MWWorld::ManualRef ref(MWBase::Environment::get().getWorld()->getStore(), esm.mId); MWWorld::Ptr ptr = ref.getPtr(); model = ptr.getClass().getModel(ptr); } catch(...) { return true; } createModel(state, model, osg::Vec3f(esm.mPosition), osg::Quat(esm.mOrientation), false, false, osg::Vec4(0,0,0,0)); mProjectiles.push_back(state); return true; } else if (type == ESM::REC_MPRJ) { ESM::MagicBoltState esm; esm.load(reader); MagicBoltState state; state.mSourceName = esm.mSourceName; state.mIdMagic.push_back(esm.mId); state.mSpellId = esm.mSpellId; state.mActorId = esm.mActorId; state.mStack = esm.mStack; std::string texture = ""; state.mEffects = getMagicBoltData(state.mIdMagic, state.mSoundIds, state.mSpeed, texture, esm.mEffects); state.mSpeed = esm.mSpeed; // speed is derived from non-projectile effects as well as // projectile effects, so we can't calculate it from the save // file's effect list, which is already trimmed of non-projectile // effects. We need to use the stored value. std::string model; try { MWWorld::ManualRef ref(MWBase::Environment::get().getWorld()->getStore(), state.mIdMagic.at(0)); MWWorld::Ptr ptr = ref.getPtr(); model = ptr.getClass().getModel(ptr); } catch(...) { return true; } osg::Vec4 lightDiffuseColor = getMagicBoltLightDiffuseColor(esm.mEffects); createModel(state, model, osg::Vec3f(esm.mPosition), osg::Quat(esm.mOrientation), true, true, lightDiffuseColor, texture); MWBase::SoundManager *sndMgr = MWBase::Environment::get().getSoundManager(); for (size_t soundIter = 0; soundIter != state.mSoundIds.size(); soundIter++) { state.mSounds.push_back(sndMgr->playSound3D(esm.mPosition, state.mSoundIds.at(soundIter), 1.0f, 1.0f, MWBase::SoundManager::Play_TypeSfx, MWBase::SoundManager::Play_Loop)); } mMagicBolts.push_back(state); return true; } return false; }
int main( int argc, char **argv ) { osg::notify(osg::WARN) << "\n\n" << osgAudio::getLibraryName() << " demo" << std::endl; osg::notify(osg::WARN) << "Version: " << osgAudio::getVersion() << "\n\n" << std::endl; osg::notify(osg::WARN) << "Demonstrates how to create and destroy soundsources on the fly" << std::endl; try { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // set up the usage document, in case we need to print out how to use this program. arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" demonstrates the use of the osgAudio toolkit for spatial sound."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ..."); arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information"); // initialize the viewer. osgViewer::Viewer viewer(arguments); osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator; keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() ); viewer.setCameraManipulator( keyswitchManipulator.get() ); // add the window size toggle handler viewer.addEventHandler(new osgViewer::WindowSizeHandler); // add the stats handler viewer.addEventHandler(new osgViewer::StatsHandler); // add the help handler viewer.addEventHandler(new osgViewer::HelpHandler(arguments.getApplicationUsage())); // get details on keyboard and mouse bindings used by the viewer. viewer.getUsage(*arguments.getApplicationUsage()); // if user request help write it out to cout. if (arguments.read("-h") || arguments.read("--help")) { arguments.getApplicationUsage()->write(std::cout); return 1; } // any option left unread are converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); arguments.getApplicationUsage()->addKeyboardMouseBinding("RETURN", "Play a sound"); // report any errors if they have occured when parsing the program aguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } int num_hw_soundsources = 10; osgAudio::SoundManager::instance()->init(num_hw_soundsources); osgAudio::SoundManager::instance()->getEnvironment()->setDistanceModel(osgAudio::InverseDistance); osgAudio::SoundManager::instance()->getEnvironment()->setDopplerFactor(1); // load the nodes from the commandline arguments. osg::Node* model = createModel(); if (!model) { return 1; } // tilt the scene so the default eye position is looking down on the model. osg::MatrixTransform* rootnode = new osg::MatrixTransform; rootnode->setMatrix(osg::Matrix::rotate(osg::inDegrees(30.0f),1.0f,0.0f,0.0f)); rootnode->addChild(model); // Make use of a few sound samples std::vector<std::string> wave_vector; wave_vector.push_back("a.wav"); wave_vector.push_back("high-e.wav"); wave_vector.push_back("low-e.wav"); // Create ONE (only one, otherwise the transformation of the listener and update for SoundManager will be // called several times, which is not catastrophic, but unnecessary) // SoundRoot that will make sure the listener is updated and // to keep the internal state of the SoundManager updated // This could also be done manually, this is just a handy way of doing it. osg::ref_ptr<osgAudio::SoundRoot> sound_root = new osgAudio::SoundRoot; sound_root->setCamera( viewer.getCamera() ); // The position in the scenegraph of this node is not important. // Just as long as the cull traversal should be called after any changes to the SoundManager are made. rootnode->addChild(sound_root.get()); // Create a transformation node onto we will attach a soundnode osg::ref_ptr<osg::PositionAttitudeTransform> sound_transform = new osg::PositionAttitudeTransform; rootnode->addChild(sound_transform.get()); sound_transform->setPosition(osg::Vec3(0,-100,50)); // Create a sphere so we can "see" the sound osg::ref_ptr<osg::Geode> geode = new osg::Geode; osg::TessellationHints* hints = new osg::TessellationHints; hints->setDetailRatio(0.5f); geode->addDrawable(new osg::ShapeDrawable(new osg::Sphere(osg::Vec3(0.0f,0.0f,0.0f),1),hints)); sound_transform->addChild(geode.get()); #ifdef USE_SOUNDNODE osg::ref_ptr<osgAudio::SoundNode> sound_node = new osgAudio::SoundNode; sound_transform->addChild(sound_node.get()); #else osg::ref_ptr< osgAudio::SoundUpdateCB > soundCB = new osgAudio::SoundUpdateCB; geode->setUpdateCallback( soundCB.get() ); #endif osg::Timer_t curr, start = osg::Timer::instance()->tick(); double interval = 2; // 2 seconds interval unsigned int n = 0; // run optimization over the scene graph osgUtil::Optimizer optimizer; optimizer.optimize(rootnode); // set the scene to render viewer.setSceneData(rootnode); // create the windows and run the threads. viewer.realize(); osgViewer::Viewer::Windows windows; viewer.getWindows(windows); windows[0]->setWindowRectangle( 10, 10, 1024, 768 ); windows[0]->setWindowDecoration( true ); while( !viewer.done() ) { // wait for all cull and draw threads to complete. //viewer.sync(); // update the scene by traversing it with the the update visitor which will // call all node update callbacks and animations. //viewer.update(); // For every interval seconds, we will remove the current soundstate and create a new one, // with the next sample sounds curr = osg::Timer::instance()->tick(); if (osg::Timer::instance()->delta_s(start, curr) > interval) { start = curr; std::string file = wave_vector[n%wave_vector.size()]; osgAudio::SoundManager::instance()->removeSoundState(file); n++; // Create a sample, load a .wav file. file = wave_vector[n%wave_vector.size()]; bool add_to_cache = true; osg::ref_ptr<osgAudio::Sample> sample = osgAudio::SoundManager::instance()->getSample(file.c_str(), add_to_cache); osg::notify(osg::WARN) << "Loading sample: " << file << std::endl; // Create a new soundstate, give it the name of the file we loaded. osg::ref_ptr<osgAudio::SoundState> sound_state = new osgAudio::SoundState(file); sound_state->setSample(sample.get()); sound_state->setGain(1.0f); sound_state->setReferenceDistance(60); sound_state->setRolloffFactor(3); sound_state->setPlay(true); sound_state->setLooping(true); // Allocate a hardware soundsource to this soundstate (priority 10) sound_state->allocateSource(10, false); // Add the soundstate to the sound manager, so we can find it later on if we want to osgAudio::SoundManager::instance()->addSoundState(sound_state.get()); #ifdef USE_SOUNDNODE sound_node->setSoundState(sound_state.get()); #else soundCB->setSoundState( sound_state.get() ); #endif } // fire off the cull and draw traversals of the scene. viewer.frame(); } } catch (std::exception& e) { osg::notify(osg::WARN) << "Caught: " << e.what() << std::endl; } // Very important to call this before end of main. // Otherwise OpenAL will do all sorts of strange things after end of main // in the destructor of soundmanager. if (osg::Referenced::getDeleteHandler()) { osg::Referenced::getDeleteHandler()->setNumFramesToRetainObjects(0); osg::Referenced::getDeleteHandler()->flushAll(); } osgAudio::SoundManager::instance()->shutdown(); return 0; }
virtual void SetUp() { ros::Time::init(); createModel(); createTask(); }
int main( int argc, char * argv[] ) { osg::ArgumentParser arguments( &argc, argv ); osgViewer::Viewer viewer; viewer.setUpViewInWindow( 10, 30, 800, 600 ); osgGA::TrackballManipulator * tb = new osgGA::TrackballManipulator(); tb->setHomePosition( osg::Vec3( 5, -12, 12 ), osg::Vec3( -7, 0, -10 ), osg::Vec3( 0, 0, 1 ) ); viewer.setCameraManipulator( tb ); osg::ref_ptr< osg::Group > root = new osg::Group; viewer.setSceneData( root.get() ); osgDB::getDataFilePathList().push_back( "C:\\OpenSceneGraph\\Data" ); btDynamicsWorld * dynamicsWorld = initPhysics(); root->addChild( createModel( dynamicsWorld ) ); /* BEGIN: Create environment boxes */ osg::MatrixTransform * ground; btRigidBody * groundBody; float thin = .01; ground = createOSGBox( osg::Vec3( 10, 10, thin ) ); root->addChild( ground ); groundBody = createBTBox( ground, osg::Vec3( 0, 0, -10 ) ); dynamicsWorld->addRigidBody( groundBody ); ground = createOSGBox( osg::Vec3( 10, thin, 5 ) ); root->addChild( ground ); groundBody = createBTBox( ground, osg::Vec3( 0, 10, -5 ) ); dynamicsWorld->addRigidBody( groundBody ); ground = createOSGBox( osg::Vec3( 10, thin, 5 ) ); root->addChild( ground ); groundBody = createBTBox( ground, osg::Vec3( 0, -10, -5 ) ); dynamicsWorld->addRigidBody( groundBody ); ground = createOSGBox( osg::Vec3( thin, 10, 5 ) ); root->addChild( ground ); groundBody = createBTBox( ground, osg::Vec3( 10, 0, -5 ) ); dynamicsWorld->addRigidBody( groundBody ); ground = createOSGBox( osg::Vec3( thin, 10, 5 ) ); root->addChild( ground ); groundBody = createBTBox( ground, osg::Vec3( -10, 0, -5 ) ); dynamicsWorld->addRigidBody( groundBody ); /* END: Create environment boxes */ /* BEGIN: Create animated box */ /* OSG Code */ osg::MatrixTransform * box = createOSGBox( osg::Vec3( .3, .3, .3 ) ); osg::AnimationPathCallback * apc = new osg::AnimationPathCallback( createAnimationPath( osg::Vec3( 0, 0, -9.25 ), 9.4, 6 ), 0, 1 ); box->setUpdateCallback( apc ); root->addChild( box ); /* Bullet Code */ btRigidBody * boxBody = createBTBox( box, osg::Vec3( -9, -3, -9 ) ); boxBody->setCollisionFlags( boxBody->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT ); boxBody->setActivationState( DISABLE_DEACTIVATION ); dynamicsWorld->addRigidBody( boxBody ); /* osgBullet Code */ osgbCollision::RefBulletObject< btRigidBody >* boxRigid = new osgbCollision::RefBulletObject< btRigidBody >( boxBody ); box->setUserData( boxRigid ); osgbDynamics::RigidBodyAnimation * rba = new osgbDynamics::RigidBodyAnimation; apc->setNestedCallback( rba ); /* END: Create animated box */ // bonus geometry root->addChild( osgDB::readNodeFiles( arguments ) ); double currSimTime = viewer.getFrameStamp()->getSimulationTime();; double prevSimTime = viewer.getFrameStamp()->getSimulationTime(); viewer.realize(); while( !viewer.done() ) { currSimTime = viewer.getFrameStamp()->getSimulationTime(); dynamicsWorld->stepSimulation( currSimTime - prevSimTime ); prevSimTime = currSimTime; viewer.frame(); } return( 0 ); }
TileGrass::TileGrass(int x, int y) : Tile(x, y) { createModel("res/tileGrass.3DS", "res/tileGrass.png", x, y); walkable = true; }
int main(int argc, char * argv[]) { #if USE_GTK == 1 GtkWidget *window; GtkWidget *drawing_area; GdkGLConfig *gl_config; gtk_init(&argc, &argv); gtk_gl_init(&argc, &argv); #else glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_DEPTH); #endif model = createModel(); if(model == NULL) { printf("Failed to create model :(\n"); exit(1); } #if USE_GTK == 1 window = gtk_window_new (GTK_WINDOW_TOPLEVEL); gtk_window_set_default_size (GTK_WINDOW (window), DEFAULT_WIN_WIDTH, DEFAULT_WIN_HEIGHT); drawing_area = gtk_drawing_area_new(); gtk_container_add( GTK_CONTAINER( window ), drawing_area ); g_signal_connect_swapped (window, "destroy", G_CALLBACK (gtk_main_quit), NULL); gtk_widget_set_events(drawing_area, GDK_EXPOSURE_MASK); gl_config = gdk_gl_config_new_by_mode(GDK_GL_MODE_RGB | GDK_GL_MODE_DEPTH | GDK_GL_MODE_DOUBLE); if (!gl_config) { printf("Messed up the config :(\n"); exit(1); } if (!gtk_widget_set_gl_capability(drawing_area, gl_config, NULL, TRUE, GDK_GL_RGBA_TYPE)) { printf("Couldn't get capabilities we needed :(\n"); exit(1); } g_signal_connect(drawing_area, "configure-event", G_CALLBACK(configure), NULL); g_signal_connect(drawing_area, "expose-event", G_CALLBACK(expose), NULL); gtk_widget_show_all(window); /* turned rotation off */ /*g_timeout_add(ROTATION_SPEED_MS, rotate_callback, drawing_area);*/ #else glutInitWindowSize(DEFAULT_WIN_WIDTH, DEFAULT_WIN_HEIGHT); glutInitWindowPosition(100, 100); glutCreateWindow("Simple 3D Collision Detection"); glutDisplayFunc(display); glutReshapeFunc(reshape); /* turned rotation off */ /*glutTimerFunc(ROTATION_SPEED_MS, rotate_callback, 0 );*/ glutTimerFunc(1000/MAX_MOVEMENT_SPEED, move_dude_callback, 0); #endif glEnable(GL_DEPTH_TEST); glFrontFace(GL_CCW); glCullFace(GL_BACK); glEnable(GL_CULL_FACE); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); glEnable(GL_LIGHTING); glEnable(GL_COLOR_MATERIAL); glShadeModel(GL_SMOOTH); light_0_enable(); #if USE_GTK == 1 gtk_main(); #else glutMainLoop(); #endif glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); destroyModel(model); return 0; }
int timeModel<type,type2>::Solve(const Problem<type>& P,Solution<type,type2> &s,double time_limit,int ERIneq) { try{ IloNum start,time_exec; const int n= P.nbTask; IloInt cptCut=0; IloEnv env; IloModel model(env); IloNumVarMatrix x(env,n); IloNumVarMatrix y(env,n); IloNumVarMatrix b(env,n); IloNumVarMatrix w(env,n); createModel(P,env,model,x,y,b,w); IloCplex cplex(model); if (ERIneq==1) { std::cout << " Starting resolution with ER inequalities at root node\n"; addERinequalities(P,env,model,x,y); } if (ERIneq==2) { std::cout << " Starting resolution with ER inequalities in tree <10\n"; IloInt nodeDepth=0; IloInt maxDepth=10; cplex.use(depth(env,nodeDepth)); cplex.use(energyCuts(env,P,x,y, 0.01, cptCut,nodeDepth,maxDepth)); } else std::cout << " Starting resolution without ER inequalities\n"; cplex.setParam(IloCplex::TiLim, time_limit); cplex.setParam(IloCplex::Threads,2); cplex.setOut(env.getNullStream()); start= cplex.getCplexTime(); IloInt cpt=0; cplex.use(getFirstSolInfo(env,cpt,start)); // solve ! if (cplex.solve()) { time_exec=cplex.getCplexTime()-start; std::cout << "Final status: \t"<< cplex.getStatus() << " en " << time_exec << std::endl; std:: cout << "Final objective: " << cplex.getObjValue() <<"\nFinal gap: \t" << cplex.getMIPRelativeGap() << std::endl; if (ERIneq==2) std::cout << "number of preemp cuts: " << cptCut << "\n"; modelToSol(P,s,cplex,x,y,b); env.end(); return 0; } else if (cplex.getStatus()==IloAlgorithm::Infeasible){ time_exec=cplex.getCplexTime()-start; if (ERIneq==2) std::cout << "number of ER cuts: " << cptCut << "\n"; std::cout << "status: "<< cplex.getStatus() << " en " << time_exec << std::endl; } env.end(); return 1; } catch (IloException &e) { std::cout << "Iloexception in solve" << e << std::endl; e.end(); return 1; } catch (...){ std::cout << "Error unknown\n"; return 1; } }
MODEL *QWzmViewer::loadPIE(QString inputFile) { const bool swapYZ = false; const bool reverseWinding = false; const bool invertUV = false; const bool assumeAnimation = false; int num, x, y, z, levels, level, pieVersion; char s[200]; QByteArray inFile = inputFile.toAscii(); const char *input = inFile.constData(); MODEL *psModel = NULL; FILE *fp = fopen(input, "r"); if (!fp) { qWarning("Cannot open \"%s\" for reading: %s", input, strerror(errno)); return NULL; } num = fscanf(fp, "PIE %d\n", &pieVersion); if (num != 1) { qWarning("Bad PIE file %s\n", input); fclose(fp); freeModel(psModel); return NULL; } num = fscanf(fp, "TYPE %x\n", &x); // ignore if (num != 1) { qWarning("Bad TYPE directive in %s\n", input); fclose(fp); freeModel(psModel); return NULL; } num = fscanf(fp, "TEXTURE %d %s %d %d\n", &z, s, &x, &y); if (num != 4) { qWarning("Bad TEXTURE directive in %s\n", input); fclose(fp); freeModel(psModel); return NULL; } num = fscanf(fp, "LEVELS %d\n", &levels); if (num != 1) { qWarning("Bad LEVELS directive in %s\n", input); fclose(fp); freeModel(psModel); return NULL; } psModel = createModel(levels, 0); if (!psModel) { qFatal("Out of memory"); fclose(fp); exit(EXIT_FAILURE); } strcpy(psModel->texPath, s); for (level = 0; level < levels; level++) { MESH *psMesh = &psModel->mesh[level]; int j, points, faces, facesWZM, faceCount, pointsWZM, pointCount, textureArrays = 1; WZ_FACE *faceList; WZ_POSITION *posList; num = fscanf(fp, "\nLEVEL %d\n", &x); if (num != 1 || level + 1 != x) { qWarning("Bad LEVEL directive in %s, was %d should be %d.\n", input, x, level + 1); fclose(fp); freeModel(psModel); return NULL; } num = fscanf(fp, "POINTS %d\n", &points); if (num != 1) { qWarning("Bad POINTS directive in %s, level %d.\n", input, level); fclose(fp); freeModel(psModel); return NULL; } posList = (WZ_POSITION*)malloc(sizeof(WZ_POSITION) * points); for (j = 0; j < points; j++) { if (swapYZ) { num = fscanf(fp, "%f %f %f\n", &posList[j].x, &posList[j].z, &posList[j].y); } else { num = fscanf(fp, "%f %f %f\n", &posList[j].x, &posList[j].y, &posList[j].z); } if (num != 3) { qWarning("Bad POINTS entry level %d, number %d\n", level, j); fclose(fp); freeModel(psModel); return NULL; } } num = fscanf(fp, "POLYGONS %d", &faces); if (num != 1) { qWarning("Bad POLYGONS directive in %s, level %d.\n", input, level); fclose(fp); freeModel(psModel); return NULL; } facesWZM = faces; // for starters faceList = (WZ_FACE*)malloc(sizeof(WZ_FACE) * faces); pointsWZM = 0; for (j = 0; j < faces; ++j) { int k; unsigned int flags; num = fscanf(fp, "\n%x", &flags); if (num != 1) { qWarning("Bad POLYGONS texture flag entry level %d, number %d\n", level, j); fclose(fp); freeModel(psModel); return NULL; } if (!(flags & iV_IMD_TEX)) { qWarning("Bad texture flag entry level %d, number %d - no texture flag!\n", level, j); fclose(fp); freeModel(psModel); return NULL; } if (flags & iV_IMD_XNOCUL) { faceList[j].cull = true; facesWZM++; // must add additional face that is faced in the opposite direction } else { faceList[j].cull = false; } num = fscanf(fp, "%u", &faceList[j].vertices); if (num != 1 || faceList[j].vertices < 0) { qWarning("Bad POLYGONS vertices entry level %d, number %d\n", level, j); fclose(fp); freeModel(psModel); return NULL; } assert(faceList[j].vertices <= MAX_POLYGON_SIZE); // larger polygons not supported assert(faceList[j].vertices >= VERTICES_PER_TRIANGLE); // points and lines not supported if (faceList[j].vertices > VERTICES_PER_TRIANGLE) { // since they are triangle fans already, we get to do easy tessellation facesWZM += (faceList[j].vertices - VERTICES_PER_TRIANGLE); if (faceList[j].cull) { facesWZM += (faceList[j].vertices - VERTICES_PER_TRIANGLE); // double the number of extra faces needed } } pointsWZM += faceList[j].vertices; // Read in vertex indices and texture coordinates for (k = 0; k < faceList[j].vertices; k++) { num = fscanf(fp, "%d", &faceList[j].index[k]); if (num != 1) { qWarning("Bad vertex position entry level %d, number %d\n", level, j); fclose(fp); freeModel(psModel); return NULL; } } if (flags & iV_IMD_TEXANIM) { num = fscanf(fp, "%d %d %f %f", &faceList[j].frames, &faceList[j].rate, &faceList[j].width, &faceList[j].height); if (num != 4) { qWarning("Bad texture animation entry level %d, number %d.\n", level, j); fclose(fp); freeModel(psModel); return NULL; } if (faceList[j].frames <= 1) { qWarning("Level %d, polygon %d has a single animation frame. That makes no sense.\n", level, j); } if (textureArrays < faceList[j].frames) { textureArrays = faceList[j].frames; } } else { faceList[j].frames = 0; faceList[j].rate = 0; faceList[j].width = 0; faceList[j].height = 0; } for (k = 0; k < faceList[j].vertices; k++) { num = fscanf(fp, "%f %f", &faceList[j].texCoord[k][0], &faceList[j].texCoord[k][1]); if (num != 2) { qWarning("Bad texture coordinate entry level %d, number %d\n", level, j); fclose(fp); freeModel(psModel); return NULL; } } } if (textureArrays == 8 && !assumeAnimation) // guesswork { psMesh->teamColours = true; } else { psMesh->teamColours = false; } // Calculate position list. Since positions hold texture coordinates in WZM, unlike in Warzone, // we need to use some black magic to transfer them over here. pointCount = 0; psMesh->vertices = pointsWZM; psMesh->faces = facesWZM; psMesh->vertexArray = (GLfloat*)malloc(sizeof(GLfloat) * psMesh->vertices * VERTICES_PER_TRIANGLE); psMesh->indexArray = (GLuint*)malloc(sizeof(GLuint) * psMesh->vertices * VERTICES_PER_TRIANGLE); psMesh->textureArrays = textureArrays; for (j = 0; j < textureArrays; j++) { psMesh->textureArray[j] = (GLfloat*)malloc(sizeof(GLfloat) * psMesh->vertices * 2); } for (z = 0, j = 0; j < faces; j++) { for (int k = 0; k < faceList[j].vertices; k++, pointCount++) { int pos = faceList[j].index[k]; // Generate new position psMesh->vertexArray[z++] = posList[pos].x; psMesh->vertexArray[z++] = posList[pos].y; psMesh->vertexArray[z++] = posList[pos].z; // Use the new position faceList[j].index[k] = pointCount; } } // Handle texture animation or team colours. In either case, add multiple texture arrays. for (z = 0; z < textureArrays; z++) { for (x = 0, j = 0; j < faces; j++) { for (int k = 0; k < faceList[j].vertices; k++) { double u; double v; // Fix for division by zero in pie 2 int framesPerLine = OLD_TEXTURE_SIZE_FIX; if (pieVersion == 3) { if(faceList[j].width != 0) { framesPerLine = 1/ faceList[j].width; } else { // Fix for division by zero in pie 3 framesPerLine = 1; } } else if (faceList[j].width != 0) // else pieVersion ==2 { framesPerLine = OLD_TEXTURE_SIZE_FIX / faceList[j].width; } int frameH = z % framesPerLine; /* * This works because wrap around is only permitted if you start the animation at the * left border of the texture. What a horrible hack this was. * Note: It is done the same way in the Warzone source. */ int frameV = z / framesPerLine; double width = faceList[j].texCoord[k][0] + faceList[j].width * frameH; double height = faceList[j].texCoord[k][1] + faceList[j].height * frameV; if (pieVersion == 2) { u = width / OLD_TEXTURE_SIZE_FIX; v = height / OLD_TEXTURE_SIZE_FIX; } else if (pieVersion == 3) { u = width; v = height; } if (invertUV) { v = 1.0f - v; } psMesh->textureArray[z][x++] = u; psMesh->textureArray[z][x++] = v; } } } faceCount = 0; for (z = 0, j = 0; j < faces; j++) { int k, key, previous; key = faceList[j].index[0]; previous = faceList[j].index[2]; faceCount++; if (reverseWinding || faceList[j].cull) { GLuint *v = &psMesh->indexArray[z]; z += 3; v[0] = key; v[1] = previous; v[2] = faceList[j].index[1]; } if (!reverseWinding || faceList[j].cull) { GLuint *v = &psMesh->indexArray[z]; z += 3; v[0] = key; v[2] = previous; v[1] = faceList[j].index[1]; } // Generate triangles from the Warzone triangle fans (PIEs, get it?) for (k = VERTICES_PER_TRIANGLE; k < faceList[j].vertices; k++) { if (reverseWinding || faceList[j].cull) { GLuint *v = &psMesh->indexArray[z]; z += 3; v[0] = key; v[2] = previous; v[1] = faceList[j].index[k]; } if (!reverseWinding || faceList[j].cull) { GLuint *v = &psMesh->indexArray[z]; z += 3; v[0] = key; v[1] = previous; v[2] = faceList[j].index[k]; } previous = faceList[j].index[k]; } } // We only handle texture animation here, so leave bone heap animation out of it for now. if (textureArrays == 1 || (textureArrays == 8 && !assumeAnimation)) { psMesh->frames = 0; } else { psMesh->frames = textureArrays; psMesh->frameArray = (FRAME*)malloc(sizeof(FRAME) * psMesh->frames); for (j = 0; j < textureArrays; j++) { FRAME *psFrame = &psMesh->frameArray[j]; psFrame->timeSlice = (float)faceList[j].rate; psFrame->textureArray = j; psFrame->translation.x = 0; psFrame->translation.y = 0; psFrame->translation.z = 0; psFrame->rotation.x = 0; psFrame->rotation.y = 0; psFrame->rotation.z = 0; } } num = fscanf(fp, "\nCONNECTORS %d", &psMesh->connectors); if (num == 1 && psMesh->connectors > 0) { psMesh->connectorArray = (CONNECTOR *)malloc(sizeof(CONNECTOR) * psMesh->connectors); for (j = 0; j < psMesh->connectors; j++) { CONNECTOR *conn = &psMesh->connectorArray[j]; GLfloat a, b, c; num = fscanf(fp, "\n%f %f %f", &a, &b, &c); if (num != 3) { qWarning("Bad CONNECTORS directive in %s entry level %d, number %d\n", input, level, j); fclose(fp); freeModel(psModel); return NULL; } conn->pos.x = a; conn->pos.y = b; conn->pos.z = c; conn->type = 0; // generic type of connector, only type supported in PIE } } free(faceList); free(posList); } fclose(fp); return psModel; }
MODEL *QWzmViewer::load3DS(QString input) { const bool swapYZ = true; const bool reverseWinding = true; const bool invertUV = true; const float scaleFactor = 1.0f; Lib3dsFile *f = lib3ds_file_load(input.toAscii().constData()); Lib3dsMaterial *material = f->materials; int meshes = 0; Lib3dsMesh *m; int meshIdx; MODEL *psModel; if (!f) { qWarning("Loading 3DS file %s failed", input.toAscii().constData()); return NULL; } for (meshes = 0, m = f->meshes; m; m = m->next, meshes++) ; // count the meshes psModel = createModel(meshes, 0); if (!psModel) { qFatal("Out of memory"); } // Grab texture name for (int j = 0; material; material = material->next, j++) { Lib3dsTextureMap *texture = &material->texture1_map; QString texName(texture->name); if (j > 0) { qWarning("Texture %d %s: More than one texture currently not supported!", j, texture->name); continue; } strcpy(psModel->texPath, texName.toLower().toAscii().constData()); } // Grab each mesh for (meshIdx = 0, m = f->meshes; m; m = m->next, meshIdx++) { MESH *psMesh = &psModel->mesh[meshIdx]; psMesh->vertices = m->points; psMesh->faces = m->faces; psMesh->vertexArray = (GLfloat*)malloc(sizeof(GLfloat) * psMesh->vertices * 3); psMesh->indexArray = (GLuint*)malloc(sizeof(GLuint) * psMesh->faces * 3); psMesh->textureArrays = 1; // only one supported from 3DS psMesh->textureArray[0] = (GLfloat*)malloc(sizeof(GLfloat) * psMesh->vertices * 2); for (unsigned int i = 0; i < m->points; i++) { Lib3dsVector pos; lib3ds_vector_copy(pos, m->pointL[i].pos); if (swapYZ) { psMesh->vertexArray[i * 3 + 0] = pos[0] * scaleFactor; psMesh->vertexArray[i * 3 + 1] = pos[2] * scaleFactor; psMesh->vertexArray[i * 3 + 2] = pos[1] * scaleFactor; } else { psMesh->vertexArray[i * 3 + 0] = pos[0] * scaleFactor; psMesh->vertexArray[i * 3 + 1] = pos[1] * scaleFactor; psMesh->vertexArray[i * 3 + 2] = pos[2] * scaleFactor; } } for (unsigned int i = 0; i < m->points; i++) { GLfloat *v = &psMesh->textureArray[0][i * 2]; v[0] = m->texelL[i][0]; if (invertUV) { v[1] = 1.0f - m->texelL[i][1]; } else { v[1] = m->texelL[i][1]; } } for (unsigned int i = 0; i < m->faces; ++i) { Lib3dsFace *face = &m->faceL[i]; GLuint *v = &psMesh->indexArray[i * 3]; if (reverseWinding) { v[0] = face->points[2]; v[1] = face->points[1]; v[2] = face->points[0]; } else { v[0] = face->points[0]; v[1] = face->points[1]; v[2] = face->points[2]; } } } lib3ds_file_free(f); return psModel; }
int main( int argc, char **argv ) { bool overlay = false; osg::ArgumentParser arguments(&argc,argv); while (arguments.read("--overlay")) overlay = true; osgSim::OverlayNode::OverlayTechnique technique = osgSim::OverlayNode::OBJECT_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY; while (arguments.read("--object")) { technique = osgSim::OverlayNode::OBJECT_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY; overlay=true; } while (arguments.read("--ortho") || arguments.read("--orthographic")) { technique = osgSim::OverlayNode::VIEW_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY; overlay=true; } while (arguments.read("--persp") || arguments.read("--perspective")) { technique = osgSim::OverlayNode::VIEW_DEPENDENT_WITH_PERSPECTIVE_OVERLAY; overlay=true; } // initialize the viewer. osgViewer::Viewer viewer; // load the nodes from the commandline arguments. osg::ref_ptr<osg::Group> model = createModel(overlay, technique); if (!model) { return 1; } // tilt the scene so the default eye position is looking down on the model. osg::ref_ptr<osg::MatrixTransform> rootnode = new osg::MatrixTransform; rootnode->setMatrix(osg::Matrix::rotate(osg::inDegrees(30.0f),1.0f,0.0f,0.0f)); rootnode->addChild(model); // run optimization over the scene graph osgUtil::Optimizer optimzer; optimzer.optimize(rootnode); // set the scene to render viewer.setSceneData(rootnode); viewer.setCameraManipulator(new osgGA::TrackballManipulator()); // viewer.setUpViewOnSingleScreen(1); #if 0 // use of custom simulation time. viewer.realize(); double simulationTime = 0.0; while (!viewer.done()) { viewer.frame(simulationTime); simulationTime += 0.001; } return 0; #else // normal viewer usage. return viewer.run(); #endif }
MODEL *readModel(const char *filename, int now) { FILE *fp = fopen(filename, "r"); int num, x, meshes, mesh, version; char s[200]; MODEL *psModel; if (!fp) { fprintf(stderr, "Cannot open \"%s\" for reading: %s", filename, strerror(errno)); return NULL; } num = fscanf(fp, "WZM %d\n", &version); if (num != 1) { fprintf(stderr, "Bad WZM file or wrong version: %s\n", filename); fclose(fp); return NULL; } if (version != 1 && version != 2) { fprintf(stderr, "Bad WZM version %d in %s\n", version, filename); fclose(fp); return NULL; } num = fscanf(fp, "TEXTURE %s\n", s); if (num != 1) { fprintf(stderr, "Bad TEXTURE directive in %s\n", filename); fclose(fp); return NULL; } num = fscanf(fp, "MESHES %d", &meshes); if (num != 1) { fprintf(stderr, "Bad MESHES directive in %s\n", filename); fclose(fp); return NULL; } psModel = createModel(meshes, now); strcpy(psModel->texPath, s); for (mesh = 0; mesh < meshes; mesh++) { MESH *psMesh = &psModel->mesh[mesh]; int j; num = fscanf(fp, "\nMESH %s\n", s); if (num != 1) { fprintf(stderr, "Bad MESH directive in %s, was \"%s\".\n", filename, s); fclose(fp); freeModel(psModel); return NULL; } num = fscanf(fp, "TEAMCOLOURS %d\n", &x); if (num != 1 || x > 1 || x < 0) { fprintf(stderr, "Bad TEAMCOLOURS directive in %s, mesh %d.\n", filename, mesh); fclose(fp); freeModel(psModel); return NULL; } psMesh->teamColours = x; num = fscanf(fp, "VERTICES %d\n", &x); if (num != 1 || x < 0) { fprintf(stderr, "Bad VERTICES directive in %s, mesh %d.\n", filename, mesh); fclose(fp); freeModel(psModel); return NULL; } psMesh->vertices = x; psMesh->vertexArray = malloc(sizeof(GLfloat) * x * 3); num = fscanf(fp, "FACES %d\n", &x); if (num != 1) { fprintf(stderr, "Bad VERTICES directive in %s, mesh %d.\n", filename, mesh); fclose(fp); freeModel(psModel); return NULL; } psMesh->faces = x; psMesh->indexArray = malloc(sizeof(GLuint) * x * 3); num = fscanf(fp, "VERTEXARRAY"); if (num == EOF) { fprintf(stderr, "No VERTEXARRAY directive in %s, mesh %d.\n", filename, mesh); fclose(fp); freeModel(psModel); return NULL; } for (j = 0; j < psMesh->vertices; j++) { GLfloat *v = &psMesh->vertexArray[j * 3]; num = fscanf(fp, "%f %f %f\n", &v[0], &v[1], &v[2]); if (num != 3) { fprintf(stderr, "Bad VERTEXARRAY entry mesh %d, number %d\n", mesh, j); fclose(fp); freeModel(psModel); return NULL; } } num = fscanf(fp, "TEXTUREARRAYS %d", &x); if (num != 1 || x < 0) { fprintf(stderr, "Bad TEXTUREARRAYS directive in %s, mesh %d.\n", filename, mesh); fclose(fp); freeModel(psModel); return NULL; } psMesh->textureArrays = x; for (j = 0; j < psMesh->textureArrays; j++) { int k; num = fscanf(fp, "\nTEXTUREARRAY %d", &x); if (num != 1 || x < 0 || x != j) { fprintf(stderr, "Bad TEXTUREARRAY directive in %s, mesh %d, array %d.\n", filename, mesh, j); fclose(fp); freeModel(psModel); return NULL; } psMesh->textureArray[j] = malloc(sizeof(GLfloat) * psMesh->vertices * 2); for (k = 0; k < psMesh->vertices; k++) { GLfloat *v = &psMesh->textureArray[j][k * 2]; num = fscanf(fp, "\n%f %f", &v[0], &v[1]); if (num != 2) { fprintf(stderr, "Bad TEXTUREARRAY entry mesh %d, array %d, number %d\n", mesh, j, k); fclose(fp); freeModel(psModel); return NULL; } } } num = fscanf(fp, "\nINDEXARRAY"); if (num == EOF) { fprintf(stderr, "No INDEXARRAY directive in %s, mesh %d.\n", filename, mesh); fclose(fp); freeModel(psModel); return NULL; } for (j = 0; j < psMesh->faces; j++) { GLuint *v = &psMesh->indexArray[j * 3]; num = fscanf(fp, "\n%u %u %u", &v[0], &v[1], &v[2]); if (num != 3) { fprintf(stderr, "Bad INDEXARRAY entry in mesh %d, number %d\n", mesh, j); fclose(fp); freeModel(psModel); return NULL; } } // Read animation frames num = fscanf(fp, "\nFRAMES %d", &psMesh->frames); if (num != 1 || psMesh->frames < 0) { fprintf(stderr, "Bad FRAMES directive in mesh %d\n", mesh); fclose(fp); freeModel(psModel); return NULL; } if (psMesh->frames) { psMesh->frameArray = malloc(sizeof(FRAME) * psMesh->frames); } for (j = 0; j < psMesh->frames; j++) { FRAME *psFrame = &psMesh->frameArray[j]; num = fscanf(fp, "\n%f %d %f %f %f %f %f %f", &psFrame->timeSlice, &psFrame->textureArray, &psFrame->translation.x, &psFrame->translation.y, &psFrame->translation.z, &psFrame->rotation.x, &psFrame->rotation.y, &psFrame->rotation.z); if (num != 8) { fprintf(stderr, "Bad FRAMES entry in mesh %d, number %d\n", mesh, j); fclose(fp); freeModel(psModel); return NULL; } } // Read connectors num = fscanf(fp, "\nCONNECTORS %d", &psMesh->connectors); if (num != 1 || psMesh->connectors < 0) { fprintf(stderr, "Bad CONNECTORS directive in mesh %d\n", mesh); fclose(fp); freeModel(psModel); return NULL; } if (psMesh->connectors) { psMesh->connectorArray = malloc(sizeof(CONNECTOR) * psMesh->connectors); } for (j = 0; j < psMesh->connectors; j++) { CONNECTOR *conn = &psMesh->connectorArray[j]; int angle, angler1, angler2; if (version == 1) { num = fscanf(fp, "\n%f %f %f %d", &conn->pos.x, &conn->pos.y, &conn->pos.z, &conn->type); } else if (version == 2) { num = fscanf(fp, "\n%s %f %f %f %d %d %d", s, &conn->pos.x, &conn->pos.y, &conn->pos.z, &angle, &angler1, &angler2); conn->type = 0; // TODO } if (num != 4) { fprintf(stderr, "Bad CONNECTORS entry in mesh %d, number %d\n", mesh, j); fclose(fp); freeModel(psModel); return NULL; } } } return psModel; }
ImageListModelProxy::ImageListModelProxy(QObject *parent) : QObject(parent) { createModel(); }
//@Override /*public*/ QWidget* AbstractTableTabAction::getPanel() { if (!init) createModel(); return dataPanel; }
int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // set up the usage document, in case we need to print out how to use this program. arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates how to create a scene programmatically, in this case a hang gliding flying site."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ..."); arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information"); // construct the viewer. osgViewer::Viewer viewer; // if user requests help write it out to cout. if (arguments.read("-h") || arguments.read("--help")) { arguments.getApplicationUsage()->write(std::cout); return 1; } bool customWindows = false; while(arguments.read("-2")) customWindows = true; if (customWindows) { osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface(); if (!wsi) { osg::notify(osg::NOTICE)<<"View::setUpViewAcrossAllScreens() : Error, no WindowSystemInterface available, cannot create windows."<<std::endl; return 0; } osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits; traits->x = 250; traits->y = 200; traits->width = 800; traits->height = 600; traits->windowDecoration = true; traits->doubleBuffer = true; traits->sharedContext = 0; traits->readDISPLAY(); traits->setUndefinedScreenDetailsToDefaultScreen(); osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get()); if (gc.valid()) { // need to ensure that the window is cleared make sure that the complete window is set the correct colour // rather than just the parts of the window that are under the camera's viewports gc->setClearColor(osg::Vec4f(0.2f,0.2f,0.6f,1.0f)); gc->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } else { osg::notify(osg::NOTICE)<<" GraphicsWindow has not been created successfully."<<std::endl; } unsigned int numCameras = 2; double aspectRatioScale = 1.0; for(unsigned int i=0; i<numCameras;++i) { osg::ref_ptr<osg::Camera> camera = new osg::Camera; camera->setGraphicsContext(gc.get()); camera->setViewport(new osg::Viewport((i* traits->width)/numCameras,(i* traits->height)/numCameras, traits->width/numCameras, traits->height/numCameras)); GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT; camera->setDrawBuffer(buffer); camera->setReadBuffer(buffer); viewer.addSlave(camera.get(), osg::Matrixd(), osg::Matrixd::scale(aspectRatioScale,1.0,1.0)); } } else { viewer.setUpViewAcrossAllScreens(); } // set up the camera manipulation with our custom manipultor viewer.setCameraManipulator(new GliderManipulator()); // pass the scene graph to the viewer viewer.setSceneData( createModel() ); return viewer.run(); }
Model *Model::create(int argc, char **argv) { return createModel(argc, argv); }
TransferFileModel::TransferFileModel(QObject *parent) : QObject(parent) { createModel(); }
Model *Model::create(const char *arg) { return createModel(arg); }
int main(int argc, char *argv[]){ WDTCTL = WDTPW | WDTHOLD;// Stop watchdog timer P1DIR |= 0x01;// Set P1.0 to output direction P1OUT = 0x01;// Toggle P1.0 using exclusive-OR if( *whichTrainingExample < 0 || *whichTrainingExample > NUM_SAMPLES * NUM_FEATURES ){ *whichTrainingExample = 0; } ACCEL_setup(); ACCEL_SetReg(0x2D,0x02); P4DIR |= BIT5;// Set P4.5 to output direction unsigned tmpx = ACCEL_getX(); unsigned tmpy = ACCEL_getY(); unsigned tmpz = ACCEL_getZ(); /*newFeaturizableData allocates memory -- assume this is in NV*/ featurizableData *X = (featurizableData*)newFeaturizableData();//Defined in Accelerometer featureVector *features = newFeatureVector(NUM_FEATURES);//Defined in FeatureVector createModel(NUM_CLASSES, NUM_FEATURES);//in NormalDistributionModel unsigned sampleTimer = SAMPLE_INTERVAL; while(1){ if( P4IN & BIT6 ){ /*pushbutton on 4.6 is pressed. This should be interrupt driven, but it's like this for now*/ P4OUT |= BIT5; sampler_init(); P4OUT &= ~BIT5; } getNextSample(X);//in Accelerometer if(samplesReady(X)){ featurize(X,features); //in CUEAR -- Accelerometer and CUEAR agree on this if( --sampleTimer == 0 ){ sampleTimer = SAMPLE_INTERVAL; /*Do this for the first 1000 samples*/ if( *whichTrainingExample < NUM_SAMPLES * features->numFeatures ){ int i; for(i = 0; i < features->numFeatures; i++){ trainingExamples[ (*whichTrainingExample) + i ] = features->features[i]; } *whichTrainingExample = *whichTrainingExample + features->numFeatures; }else{ P1OUT &= ~(0x01);//LED off means sampling is done } } } } }
bool ProjectileManager::readRecord(ESM::ESMReader &reader, int32_t type) { if (type == ESM::REC_PROJ) { ESM::ProjectileState esm; esm.load(reader); ProjectileState state; state.mActorId = esm.mActorId; state.mBowId = esm.mBowId; state.mVelocity = esm.mVelocity; state.mId = esm.mId; std::string model; try { MWWorld::ManualRef ref(MWBase::Environment::get().getWorld()->getStore(), esm.mId); MWWorld::Ptr ptr = ref.getPtr(); model = ptr.getClass().getModel(ptr); } catch(...) { return true; } state.mNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(esm.mPosition, esm.mOrientation); createModel(state, model); mProjectiles.push_back(state); return true; } else if (type == ESM::REC_MPRJ) { ESM::MagicBoltState esm; esm.load(reader); MagicBoltState state; state.mSourceName = esm.mSourceName; state.mId = esm.mId; state.mSpellId = esm.mSpellId; state.mActorId = esm.mActorId; state.mSpeed = esm.mSpeed; state.mStack = esm.mStack; state.mEffects = esm.mEffects; std::string model; try { MWWorld::ManualRef ref(MWBase::Environment::get().getWorld()->getStore(), esm.mId); MWWorld::Ptr ptr = ref.getPtr(); model = ptr.getClass().getModel(ptr); } catch(...) { return true; } state.mNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(esm.mPosition, esm.mOrientation); createModel(state, model); MWBase::SoundManager *sndMgr = MWBase::Environment::get().getSoundManager(); state.mSound = sndMgr->playManualSound3D(esm.mPosition, esm.mSound, 1.0f, 1.0f, MWBase::SoundManager::Play_TypeSfx, MWBase::SoundManager::Play_Loop); state.mSoundId = esm.mSound; mMagicBolts.push_back(state); return true; } return false; }
void CustomModel::createModel() { createModel(false); }