示例#1
0
// Initialize GLUT & OpenSG and set up the scene
int main (int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    // GLUT init
    glutInit(&argc, argv);
    glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
    int winid = glutCreateWindow("OpenSG");
    glutReshapeFunc(reshape);
    glutDisplayFunc(display);
    glutIdleFunc(idle);
    glutMouseFunc(mouse);
    glutMotionFunc(motion);
    glutKeyboardFunc(key);

    // the connection between GLUT and OpenSG
    GLUTWindowPtr gwin= GLUTWindow::create();
    gwin->setId(winid);
    gwin->init();

    // create the scene

    const char *fileName = (argc > 1) ? argv[1] : "test.raw";

    SceneFileHandler::the().print();

    // As default the SceneFileHandler sets a PathHandler for geo and image files,
    // but it is also possible use your own PathHandler.
    /*
    // set image and scene path handler to find relative texture and scene paths.
    PathHandler pathHandler;
    pathHandler.push_frontCurrentDir();
    pathHandler.setBaseFile(fileName);
    ImageFileHandler::the().setPathHandler(&pathHandler);
    SceneFileHandler::the().setPathHandler(&pathHandler);
    */

    // set a callback for reading progress.
    SceneFileHandler::the().setReadProgressCB(progress);
#if 0
    // stream test.
    std::ifstream in(fileName, std::ios::binary);
    // The last parameter is the filetype e.g. "bin", "osg" but it is
    // also possible to use the filename with a extension.
    scene = SceneFileHandler::the().read(in, fileName);
    in.close();
#else
    scene = SceneFileHandler::the().read(fileName);
#endif

    if(scene == NullFC)
    {
        std::cerr << "Error loading " << fileName << "!" << std::endl;
        scene = makeTorus( .5, 2, 16, 16 );
    }

    //scene.dump();

#if 0
    // stream test.
    std::ofstream out("test.bin", std::ios::binary);
    SceneFileHandler::the().write(scene, out, "bin");
    out.close();
#endif

    // create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    mgr->setWindow( gwin );
    mgr->setRoot( scene );

    mgr->showAll();

    webInterface = new WebInterface();
    webInterface->setRoot(scene);

    // GLUT main loop
    glutMainLoop();

    return 0;
}
示例#2
0
//--Main
int main(int argc, char **argv)
{
    //set config data
    simConfig.setWindow(800, 1280);

    // Initialize glut
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
    glutInitWindowSize( simConfig.getWindowWidth(), simConfig.getWindowHeight());
    glutInitWindowPosition( 100, 100);
    // Name and create the Window
    glutCreateWindow("Air Hockey");
    glutFullScreen();

    // Now that the window is created the GL context is fully set up
    // Because of that we can now initialize GLEW to prepare work with shaders
    GLenum status = glewInit();
    if( status != GLEW_OK)
    {
        std::cerr << "[F] GLEW NOT INITIALIZED: ";
        std::cerr << glewGetErrorString(status) << std::endl;
        return -1;
    }

    // Set all of the callbacks to GLUT that we need
    //glutSetKeyRepeat(GLUT_KEY_REPEAT_OFF); //disable key spamming for now
    glutDisplayFunc(render);// Called when its time to display
    glutReshapeFunc(reshape);// Called if the window is resized
    glutIdleFunc(update);// Called if there is nothing else to do
    glutMouseFunc(mouse);// Called if there is mouse input
    glutMotionFunc(mouseChange);
    glutPassiveMotionFunc(mouseChange);
    glutKeyboardFunc(keyPressed);// Called if there is keyboard input
    glutKeyboardUpFunc(keyUp);// Called if there is keyboard anti-input
    glutSpecialFunc(keyboardPlus);// for stuff without ascii access characters like arrow keys

    //setup inputs
    menuID = glutCreateMenu(menu_test);
    glutAddMenuEntry("Resume", 4);
    glutAddMenuEntry("Pause", 3);
    glutAddMenuEntry("Restart", 2);
    glutAddMenuEntry("Quit", 1);
    glutAttachMenu(GLUT_RIGHT_BUTTON);

    //misc setup
    simEntities.simConfig = &simConfig;

    // Initialize all of our resources(config, geometry)
    bool init = initialize();

    //load model data
    #ifdef TESTING
    simEntities.loadData("../bin/data/test_load_list.dat"); // don't want to load all those machines if I'm just testing
    #else
    simEntities.loadData("../bin/data/load_list.dat");
    #endif

    //run our shader loader now
    init = init && simShaderManager.loadShaders(argc,argv);

    //call some other resources to initialize after the shader, separately
    init = init && postInitialize();

    if(init)
    {
        t1 = std::chrono::high_resolution_clock::now();
        glutMainLoop();
    }

    // Clean up after ourselves
    cleanUp();
    return 0;
}
示例#3
0
int RenderEngine::init() {


		p_camera = vec3(16,10,0);
		//Camera lookAt
		l_camera = vec3(0,0,0);
		//Camera up
		u_camera = vec3(0,1,0);
		//Light position
		p_light = vec3(110,60,0);
		//Light lookAt
		l_light = vec3(0,0,0);
		//Light Scatter Physical Light Location (used for demonstrations like title screen, where illumination is not same place as physical light in light scatter render)
		p_light_scatter = vec3(110,60,0);
		//Sky Color
		skyColor = vec4(0,0,0,0);
		//Trippy Light Scattering Mode
		deathScatter = false;

		FreeImage_Initialise();

		// set some lights
		{
				//float ambient[4] = { .5f, .5f, .5f, 1.f };
				float diffuse[4] = { 1.0f, 1.0f, 1.0f, 1.f };
				float pos[4] = { p_light[0], p_light[1], p_light[2], 0 };
				//glLightfv(GL_LIGHT0, GL_AMBIENT, ambient);
				glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);
				glLightfv(GL_LIGHT0, GL_POSITION, pos);
				glEnable(GL_LIGHT0);
		}

		glEnable(GL_DEPTH_TEST);
		glClearColor(0,0,0,1.0f);
		glEnable(GL_CULL_FACE);
		glFrontFace(GL_CCW);
		glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST);

		this->activate();	

		glutDisplayFunc(renderFunction);
		glutIdleFunc(renderFunction);


		glewInit();

		if (GLEW_ARB_vertex_shader && GLEW_ARB_fragment_shader)
				printf("Ready for GLSL\n");
		else {
				printf("No GLSL support\n");
				exit(1);
		}

		//Generate FBOs
		generateShadowFBO();
		generateBlurFBO();
		generateLightFBO();

		//Load Shaders
		shade = new ShadowShader("shaders/MainVertexShader.c", "shaders/MainFragmentShader.c");
		blurShade = new BlurShader("shaders/GaussianBlurVertexShader.c", "shaders/GaussianBlurFragmentShader.c");
		depthShade = new GeometryShader("shaders/DepthVertexShader.c", "shaders/DepthFragmentShader.c");
		scatterShade = new ScatterShader("shaders/ScatteringVertexShader.c", "shaders/ScatteringFragmentShader.c");
		darkShade = new GeometryShader("shaders/SimpleDarkVertexShader.c", "shaders/SimpleDarkFragmentShader.c");

		return 0;


}
示例#4
0
int main (int argc, char *argv[]) {
  post("PROTO v%s%s (%s) (Developed by MIT Space-Time Programming Group 2005-2008)\n",
      PROTO_VERSION,
#if USE_NEOCOMPILER
      "[neo]",
#else
      "[paleo]",
#endif
      KERNEL_VERSION);
  Args *args = new Args(argc,argv); // set up the arg parser

  // initialize randomness  [JAH: fmod added for OS X bug]
  unsigned int seed = (unsigned int)
    (args->extract_switch("-seed") ? args->pop_number()
    : fmod(get_real_secs()*1000, RAND_MAX));
  post("Using random seed %d\n", seed);
  srand(seed);

  process_app_args(args);
  bool headless = args->extract_switch("-headless") || DEFAULT_HEADLESS;
  if(!headless) {
    vis = new Visualizer(args); // start visualizer
  } else {
#ifdef WANT_GLUT
    palette = Palette::default_palette;
#endif // WANT_GLUT
  }

  computer = new SpatialComputer(args,!test_mode);
  if(opcode_file != "") {
     post("reading opcodes from: %s\n", opcode_file.c_str());
     // read from file
     int len = -1;
     uint8_t* s = read_script(opcode_file,&len);
     //post("script[%d]=\n",len);
     //for(unsigned int i=0; i<len; ++i)
     //   post("%d\n", s[i]);
     if(len > 0 && s != NULL) {
        computer->load_script(s,len);
     }
     else
        uerror("Problem loading opcode file: %s", opcode_file.c_str());
     if(!headless) {
       vis->set_bounds(computer->vis_volume); // connect to computer
       register_app_colors();
     }
  } else {
     // use a compiler
#if USE_NEOCOMPILER
     compiler = new NeoCompiler(args);  // first the compiler
     compiler->emitter = new ProtoKernelEmitter(compiler,args);
#else
     compiler = new PaleoCompiler(args);  // first the compiler
#endif
     string defops;
     computer->appendDefops(defops);
     compiler->setDefops(defops);
     if(!headless) {
        vis->set_bounds(computer->vis_volume); // connect to computer
        register_app_colors();
     }
     // next the forwarder for the motes, if desired
     if(args->extract_switch("-motelink")) motelink = new MoteLink(args);
     // load the script
     int len;
     if(args->argc==1) {
        uerror("No program specified: all arguments consumed.");
     } else {
        uint8_t* s = compiler->compile(args->argv[args->argc-1],&len);
        computer->load_script(s,len);
        if(args->argc>2) {
           post("WARNING: %d unhandled arguments:",args->argc-2);
           for(int i=2;i<args->argc;i++) post(" '%s'",args->argv[i-1]);
           post("\n");
        }
     }
  }
  // if in test mode, swap the C++ file for a C file for the SpatialComputer
  if(test_mode) {
    delete cpout;
    computer->dump_file = fopen(dump_name,"a");
  }
  // and start!
  if(headless) {
    if(stop_time==INFINITY) 
      uerror("Headless runs must set an end time with -stop-after N");
    while(1) idle();
  } else {
#ifdef WANT_GLUT
    // set up callbacks for user interface and idle
    glutMouseFunc(on_mouse_button);
    glutMotionFunc(on_mouse_motion);
    glutPassiveMotionFunc(on_mouse_motion);
    glutDisplayFunc(render);
    glutReshapeFunc(resize);
    glutIdleFunc(idle);
    glutKeyboardFunc(keyboard_handler);
    glutSpecialFunc(special_handler);
    // finally, hand off control to the glut event-loop
    glutMainLoop(); 
#endif
  }
}
int main(int argc, char *argv[])
#endif
{
#ifdef USE_SDL
    if (SDL_Init(SDL_INIT_VIDEO) < 0)
    {
        report("Can't initialize SDL\n");
        return 1;
    }
// TODO fullscreen + get screen size
#ifndef __ANDROID__
    width=height=700;
#else
    width=320;
    height=480;
//     const SDL_VideoInfo* vinfo=SDL_GetVideoInfo();    
//     width = vinfo->current_w;
//     height = vinfo->current_h;
//     report("Detected %dx%d resolution.\n",width,height);
#endif

    window = SDL_CreateWindow("Bezier Fragment Shader Demo", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_RESIZABLE | SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);

    if(window == NULL)
    {
        report("Can't create window: %s\n", SDL_GetError());
        return -1;
    }

    glcontext = SDL_GL_CreateContext(window);

    if(glcontext == NULL)
    {
        report("Can't create context: %s\n", SDL_GetError());
        return -1;
    }

    SDL_GL_MakeCurrent(window, glcontext);
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
#else
    glutInit(&argc,argv);
    glutInitWindowSize(700,700);
    glutInitDisplayMode(GLUT_RGB|GLUT_DOUBLE|GLUT_DEPTH);
    glutCreateWindow("Bezier Fragment Shader Demo");
#endif
    

    glViewport(0, 0, width, height);

    glClearColor(0.0, 0.0, 0.0, 0.0);

    glEnable(GL_DEPTH_TEST);

    fshader = loadShader("bezier.glsl",GL_FRAGMENT_SHADER);
    vshader = loadShader("bezier-vertex.glsl",GL_VERTEX_SHADER);

    if (!(fshader&&vshader))
    {
        report("One of shaders failed, aborting.\n");
        return -1;
    }

    program = glCreateProgram();
    glAttachShader(program, fshader);
    glAttachShader(program, vshader);
    glBindAttribLocation(program, 0, "vertexPos");
    glBindAttribLocation(program, 1, "bezCoordsAttr");
    glLinkProgram(program);

    glGetProgramiv(program, GL_LINK_STATUS, &linked);

    if (!linked)
    {
        report("Can't link the shader\n");
        return -1;
    }

    glUseProgram(program);

    glUniform1i(glGetUniformLocation(program, "drawFill"), 1);
    glUniform1i(glGetUniformLocation(program, "useBezier"), 1);
    glUniform1i(glGetUniformLocation(program, "drawStroke"), 1);

#ifndef __ANDROID__
//     glEnableClientState(GL_VERTEX_ARRAY); // Why don't they work like glEnable(A|B) did before? or am I dumb?
//     glEnableClientState(GL_TEXTURE_COORD_ARRAY);
#endif

    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);
    createShapes();
    
#ifdef USE_SDL
    int running = 1;
    timemark=SDL_GetTicks();

    while(running)
    {
        if ( SDL_PollEvent(&event) > 0 )
        {
//         SDL_WaitEvent(&event);

            switch(event.type)
            {
                case SDL_KEYDOWN:
                    switch(event.key.keysym.sym)
                    {
                        #ifdef __ANDROID__
                        case SDLK_AC_SEARCH:
                        #endif  
                        case SDLK_F1: performanceReport(); break;
                        
                        #ifndef __ANDROID__
                            case SDLK_ESCAPE: running = 0;          break;
                        #else
                            case SDLK_AC_BACK: running = 0;         break;
                        #endif

                        case SDLK_LEFT:   Camera.beta += M_PI / 36; camera(); break;
                        case SDLK_RIGHT:  Camera.beta -= M_PI / 36; camera(); break;
                        case SDLK_UP:    Camera.alpha += M_PI / 36; camera(); break;
                        case SDLK_DOWN:  Camera.alpha -= M_PI / 36; camera(); break;
                        default: keyb(event.key.keysym.scancode);   break;
                    }
                break;

                case SDL_MOUSEWHEEL:
                    Camera.dist*= (event.wheel.y < 0)? 1.1 : 0.9;
                    camera();
                break;

                case SDL_MOUSEMOTION:
                    if(event.motion.state == 1) motion(event.motion.xrel, event.motion.yrel);
                break;

                // Note, the first frame flickers, TODO workaround
                // TODO: track the real sequence of WINDOWEVENT_ENTER and WINDOWEVENT_SIZE_CHANGED events 
                case SDL_WINDOWEVENT:
                    if (event.window.event==SDL_WINDOWEVENT_SIZE_CHANGED)
                        size(event.window.data1, event.window.data2);
                    camera();
                break;

                // handle touch events here

                case SDL_QUIT:
                    running = 0;
                break;
            }
        }

        draw();
    }
    
    performanceReport();
    
    SDL_GL_MakeCurrent(NULL, NULL);
    SDL_GL_DeleteContext(glcontext);
    SDL_DestroyWindow(window);
    SDL_Quit();
#else
    glutReshapeFunc(size);
    glutDisplayFunc(draw);
    glutIdleFunc(draw);
    glutMouseFunc(mouse);
    glutMotionFunc(motion);
    glutSpecialFunc(keybs);
    glutKeyboardFunc(keyb);
    glutTimerFunc(TIMER_RESOLUTION,timer,0);
    glutMainLoop();
#endif
    
    return 0;
}
示例#6
0
int main(int argc, char *argv[])
{
  if (argc == 1) {
    // program called with no arguments.  Show info
    show_general_help();
    return 0;
  } else if (argc == 2 && 
	     (std::string(argv[1]) == "hotkeys" || std::string(argv[1]) == "HOTKEYS")) {
    show_hotkey_help();
    return 0;
  }
  xscale=yscale=zscale=1.0;
  int i;

  
  for (i=0; i<MAX_SURFACES; i++)
    {
      surface[i]=NULL;
      normal[i]=NULL;
    }
  for (i=0; i<MAX_CURVES; i++)
    curve[i]=NULL;

  for (i=0; i<MAX_CURVES; i++)
    discr_curve[i]=NULL;

  read_curves_and_surfaces(argc, argv);
  
  {
    int tx=32, ty=32;	// gl_init needs variables, but doesn't do
    // anything when texfile==NULL.
#ifdef _MSC_VER
    gl_init(argc, argv, 500, 500, 180, 100, true,
#else
	    gl_init(argc, argv, 1100, 1100, 460, 20, true,
#endif
		    1, GL_TRUE, 1, GL_TRUE,
		    xtrans, ytrans, ztrans,
		    // xscale, yscale, zscale, tx, ty, NULL);
		    xscale, yscale, zscale, tx, ty,
		    // GL_MODULATE,
		    // GL_BLEND,
		    GL_DECAL,
		    NULL			// NULL produces a frame.
		    // "greyclouds3.pgm"	// A texture.
	      );
	    }
  
    //
    // This will have the same effect as pressing 'tab'+'d'.
    //
    if (surfaces>0)
      {
	int i;
      
	selected_surface=0;
	for (i=0; i<surfaces; i++)
	  surf_enabled[i]= 1 ; //(i==selected_surface);
      }

    //
    // This will have the same effect as pressing 'space'+'ctrl-d'.
    //
    if (curves>0)
      {
	int i;
      
	selected_curve=0;
	for (i=0; i<curves; i++)
	  curve_enabled[i]=1; // (i==selected_curve);
      }

    glPolygonOffset(1.0, 1.0);
    glEnable(GL_POLYGON_OFFSET_POINT);
    glEnable(GL_POLYGON_OFFSET_LINE);
    glEnable(GL_POLYGON_OFFSET_FILL);
  
    glutReshapeFunc(Reshape);
    glutKeyboardFunc(Key);
    glutMotionFunc(MouseRotate);
    glutMouseFunc(Mouse);
    glutDisplayFunc(draw);
    glutIdleFunc(idle_func);

    scale(0.5, 0.5, 0.5);
    glEnable(GL_NORMALIZE);


    parse_keys(0,
	       (const unsigned char *)init_key_string,
	       strlen(init_key_string));

    // making sure loaded object is centered
    //parse_keys('o'); // doesn't work as expected


    glutMainLoop();
  
    return 0;
  }
int main( int argc, char *argv[] )
{
    osgInit(argc, argv);

    glutInit(&argc, argv);
    glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
    glutCreateWindow("OpenSG");
    glutKeyboardFunc(key);
    // glutReshapeFunc(resize);
    glutDisplayFunc(display);
    // glutMouseFunc(mouse);
    // glutMotionFunc(motion);

    glutIdleFunc(display);

    pImage = Image::create();

    // create the dummy structures

    // the window is needed for the chunks that access GLObjects

    win = GLUTWindow::create();
    win->frameInit(); // test for preliminary calls not messing up GLexts
    win->init();
    
    dact = DrawAction::create();
    dact->setWindow(get_pointer(win));

    win->init();

    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    gluPerspective( 60, 1, 0.1, 10 );
    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();
    gluLookAt( 3, 3, 3,  0, 0, 0,   0, 1, 0 );

    glEnable( GL_DEPTH_TEST );
    glEnable( GL_LIGHTING );
    glEnable( GL_LIGHT0 );
    glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );

    dlid = glGenLists( 1 );
    glNewList( dlid, GL_COMPILE );
    glutSolidSphere( .8, 24, 24 );
    glEndList();

    dlid2 = glGenLists( 1 );
    glNewList( dlid2, GL_COMPILE );
    glBegin( GL_POLYGON );
    glNormal3f( 0, 1, 0 );
    glColor3f( 1, 1, 1 );
    glTexCoord3f( 0, 0, 0 );
    glVertex3f( -1.5, -1, -1.5 );
    glTexCoord3f( 2, 0, 0 );
    glVertex3f(  1.5, -1, -1.5 );
    glTexCoord3f( 2, 2, 2 );
    glVertex3f(  1.5, -1,  1.5 );
    glTexCoord3f( 0, 2, 2 );
    glVertex3f( -1.5, -1,  1.5 );
    glEnd();
    glEndList();


    Matrix m;

    tchunk1 = TransformChunk::create();
    m.setTranslate( 0, 1, 0 );
    tchunk1->setMatrix( m );

    tchunk2 = TransformChunk::create();
    tchunk2->setMatrix( Matrix::identity() );


    mchunk1 = MaterialChunk::create();
    mchunk1->setDiffuse( Color4f( 1,0,0,0 ) );
    mchunk1->setAmbient( Color4f( 1,0,0,0 ) );
    mchunk1->setShininess( 20 );

    mchunk2 = MaterialChunk::create();
    mchunk2->setDiffuse( Color4f( 0,1,0,0 ) );
    mchunk2->setAmbient( Color4f( 0,1,0,0 ) );
    mchunk2->setShininess( 50 );

    // Texture chunk

//  UChar8 imgdata[] =
//      {  255,0,0,0,  0,255,0,0,  0,0,255,255,  255,255,255,255 };
    UChar8 imgdata[] =
        {  255,0,0,  255,0,0,  255,0,255,
           255,0,0,  255,0,0,  255,0,255,
           255,255,0,  255,255,0,  255,255,255,
           255,255,0,  255,255,0,  255,255,255, };
//  UChar8 limgdata[] =
//      {  0, 128, 64, 255 };
    pImage->set( Image::OSG_RGB_PF, 2, 2, 1, 1, 1, 0, imgdata );

    if ( argc > 1 )
        pImage->read( argv[1] );

    xchunk1 = TextureChunk::create();
    beginEditCP(xchunk1);
    xchunk1->setImage( pImage );
    xchunk1->setMinFilter( GL_LINEAR );
    xchunk1->setMagFilter( GL_NEAREST );
    xchunk1->setWrapS( GL_REPEAT );
    xchunk1->setWrapT( GL_REPEAT );
    xchunk1->setEnvMode( GL_REPLACE );
    xchunk1->setScale( false );
    endEditCP(xchunk1);

    xchunk1->imageContentChanged();

    beginEditCP(xchunk1);
    xchunk1->setImage( pImage );
    xchunk1->setLodBias( 10 );
    endEditCP(xchunk1);

    UChar8 imgdata2[] =
    {  255,0,0,  0,255,0,  0,0,255,  255,255,255 };

    ImagePtr pImage2 = Image::create();
    pImage2->set(Image::OSG_RGB_PF, 2, 2, 1, 1, 1, 0, imgdata2);

    xchunk2 = TextureChunk::create();
    beginEditCP(xchunk2);
    xchunk2->setImage( pImage2 );
    xchunk2->setMinFilter( GL_LINEAR );
    xchunk2->setMagFilter( GL_NEAREST );
    xchunk2->setWrapS( GL_REPEAT );
    xchunk2->setWrapT( GL_REPEAT );
    xchunk2->setEnvMode( GL_MODULATE );
    xchunk2->setLodBias( 10 );
    endEditCP(xchunk2);
    
    // Cube Texture chunk
    
    UChar8 negz[] = {  255,0,0,  128,0,0,  64,0,0,   255,255,255 },
           posz[] = {  0,255,0,  0,128,0,  0,64,0,  255,255,255 },
           negy[] = {  0,0,255,  0,0,128,  0,0,64,  255,255,255 },
           posy[] = {  255,255,0,  128,128,0,  64,64,0,  255,255,255 },
           negx[] = {  255,0,255,  128,0,128,  64,0,64,  255,255,255 },
           posx[] = {  0,255,255,  0,128,128,  0,64,64,  255,255,255 };
    
    ImagePtr inegz = Image::create();
    ImagePtr iposz = Image::create();
    ImagePtr inegy = Image::create();
    ImagePtr iposy = Image::create();
    ImagePtr inegx = Image::create();
    ImagePtr iposx = Image::create();

    inegz->set( Image::OSG_RGB_PF, 2, 2, 1, 1, 1, 0, negz );
    iposz->set( Image::OSG_RGB_PF, 2, 2, 1, 1, 1, 0, posz );
    inegy->set( Image::OSG_RGB_PF, 2, 2, 1, 1, 1, 0, negy );
    iposy->set( Image::OSG_RGB_PF, 2, 2, 1, 1, 1, 0, posy );
    inegx->set( Image::OSG_RGB_PF, 2, 2, 1, 1, 1, 0, negx );
    iposx->set( Image::OSG_RGB_PF, 2, 2, 1, 1, 1, 0, posx );
        
    cchunk1 = CubeTextureChunk::create();
    beginEditCP(cchunk1);
    cchunk1->setImage( inegz );
    cchunk1->setPosZImage( iposz );
    cchunk1->setPosYImage( iposy );
    cchunk1->setNegYImage( inegy );
    cchunk1->setPosXImage( iposx );
    cchunk1->setNegXImage( inegx );
    cchunk1->setMinFilter( GL_LINEAR );
    cchunk1->setMagFilter( GL_NEAREST );
    cchunk1->setWrapS( GL_REPEAT );
    cchunk1->setWrapT( GL_REPEAT );
    cchunk1->setEnvMode( GL_MODULATE );
    cchunk1->setLodBias( 10 );
    endEditCP(cchunk1);
    
    gchunk1 = TexGenChunk::create();
    beginEditCP(gchunk1);
    gchunk1->setGenFuncS(GL_REFLECTION_MAP_ARB);
    gchunk1->setGenFuncT(GL_REFLECTION_MAP_ARB);
    gchunk1->setGenFuncR(GL_REFLECTION_MAP_ARB);
    endEditCP(gchunk1);
    
    // blend chunk

    blchunk = BlendChunk::create();
#ifndef WIN32
//    blchunk->setSrcFactor( GL_CONSTANT_ALPHA );
//    blchunk->setDestFactor( GL_ONE_MINUS_CONSTANT_ALPHA );
#endif
    blchunk->setColor( Color4f( 1,1,1,0.1 ) );

    // texture transform chunk

    txchunk = TextureTransformChunk::create();
    beginEditCP(txchunk);
//    txchunk->setMatrix( Matrix(4,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1) );
    endEditCP(txchunk);

    glutMainLoop();

    return 0;
}
示例#8
0
// Função para o teclado
void keyboard_Frostbite(unsigned char key, int x, int y){
    // Funções do teclado no modo controle
    if (camera == 1){
        switch(key){
            // Troca o modo da camera
            case 'm':
            case 'M':
                if(camera == 1) camera = 0;
                else camera = 1;

                rotX = 0;
                rotY = 0;
                rotZ = 0;
            break;

            // Controle em perspectiva
            case 'w':
            case 'W':
                if(character == 0){
                    moveFoward_WarmachineKiwi();
                    glutIdleFunc(walk_WarmachineKiwi);
                }else if(character == 1){
                    moveFoward_WarmachineBLD();
                    glutIdleFunc(walk_WarmachineBLD);
                }
            break;

            case 's':
            case 'S':
                if(character == 0){
                    moveBackward_WarmachineKiwi();
                    glutIdleFunc(walk_WarmachineKiwi);
                }else if(character == 1){
                    moveBackward_WarmachineBLD();
                    glutIdleFunc(walk_WarmachineBLD);
                }
            break;

            case 'd':
            case 'D':
                if(character == 0){
                    turnRight_WarmachineKiwi();
                    glutIdleFunc(walk_WarmachineKiwi);
                }else if(character == 1){
                    turnRight_WarmachineBLD();
                    glutIdleFunc(walk_WarmachineBLD);
                }
            break;

            case 'a':
            case 'A':
                if (character == 0) {
                    turnLeft_WarmachineKiwi();
                    glutIdleFunc(walk_WarmachineKiwi);
                }else if(character == 1){
                    turnLeft_WarmachineBLD();
                    glutIdleFunc(walk_WarmachineBLD);
                }
            break;

            default:
            break;
        }
    }
    // Funções de controle no modo mapa
    else if(camera == 0){
    switch(key){
            // Troca o modo da camera
            case 'm':
            case 'M':
                if(camera == 1) camera = 0;
                else camera = 1;

                rotX = 0;
                rotY = 0;
                rotZ = 0;
            break;

            // Controle em perspectiva
            case 'w':
            case 'W':
                if(character == 0) panY_WarmachineKiwi--;
                else if(character == 1) panY_WarmachineBLD--;
            break;

            case 's':
            case 'S':
                if(character == 0) panY_WarmachineKiwi++;
                else if(character == 1) panY_WarmachineBLD++;
            break;

            case 'd':
            case 'D':
                if(character == 0) panX_WarmachineKiwi--;
                else if(character == 1) panX_WarmachineBLD--;
            break;

            case 'a':
            case 'A':
                if(character == 0) panX_WarmachineKiwi++;
                else if(character == 1) panX_WarmachineBLD++;
            break;

            // Controle de Dia-Noite
            case 'L': // Dia
                glDisable(GL_LIGHT0);
                glDisable(GL_LIGHT1);
                glEnable(GL_LIGHT2);

                glClearColor(0.0, 0.7, 0.93, 1.0);
            break;

            case 'l': // Noite
                glEnable(GL_LIGHT0);
                glEnable(GL_LIGHT1);
                glDisable(GL_LIGHT2);

                glClearColor(0.0, 0.0, 0.0, 1.0);
            break;

            default:
            break;
        }
    }
    glutPostRedisplay();
}
示例#9
0
void keyboardUp_Frostbite(unsigned char key, int x, int y){
    glutIdleFunc(NULL);
    glutPostRedisplay();
}
示例#10
0
void SetupGL(int argc, char *argv[])
{
	//Parameter handling
	glShadeModel(GL_SMOOTH);

	// Accept fragment if it closer to the camera than the former one
	glDepthFunc(GL_LESS);
	// polygon rendering mode
	glEnable(GL_COLOR_MATERIAL);
	glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);

	//Set up light source
	GLfloat light_position[] = {0.0, 30.0, -50.0, 0.0};

	glLightfv(GL_LIGHT0, GL_POSITION, light_position);
	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT0);

	// Black background
	glClearColor(0.0f, 0.0f, 0.0f, 1.0f);   // Black background

	// Register GLUT callbacks
	glutDisplayFunc(DisplayGL);
	glutKeyboardFunc(KeyboardGL);
	glutSpecialFunc(Specialkey);
	glutReshapeFunc(ReshapeGL);

	//Call to the drawing function
	glutIdleFunc(Idle);
	last_time = glutGet(GLUT_ELAPSED_TIME);

	// Setup initial GL State
	glClearDepth(1.0f);

	//
	// Init GLEW

	// Setup initial GL State
	glClearDepth(1.0f);

	if ( glewInit() != GLEW_OK )
	{
		std::cerr << "Failed to initialize GLEW." << std::endl;
		exit(-1);
	}
	if (!GLEW_VERSION_1_1)
	{
		std::cerr << "Failed to set the correct version" << std::endl;
		exit(1);
	}
	std::cout << "Initialise OpenGL: Success!" << std::endl;

	//VAO
	//        glGenVertexArrays(1, &VertexArrayID);
	//        glBindVertexArray(VertexArrayID);

	// Create and compile our GLSL program from the shaders
	std::string vertex = ttl::file2str("TransformVertexShader.vs");
	std::string fragment = ttl::file2str("ColorFragmentShader.fs");

	oglProgram = LoadShaders(vertex.c_str(), fragment.c_str());

	static const GLfloat g_vertex_buffer_data_cube[] = {
		// Front face
		1.f, -1.f, 1.f,
		-1.f, 1.f, 1.f,
		-1.f, -1.f, 1.f,
		1.f, -1.f, 1.f,
		1.f, 1.f, 1.f,
		-1.f, 1.f, 1.f,

		// Head
		1.f, 1.f, -1.f,
		-1.f, 1.f, 1.f,
		-1.f, 1.f, -1.f,
		1.f, 1.f, -1.f,
		1.f, 1.f, 1.f,
		-1.f, 1.f, 1.f,

		// Bottom
		1.f, -1.f, -1.f,
		-1.f, -1.f, 1.f,
		-1.f, -1.f, -1.f,
		1.f, -1.f, -1.f,
		1.f, -1.f, 1.f,
		-1.f, -1.f, 1.f,

		// Left
		-1.f, 1.f, 1.f,
		-1.f, 1.f, -1.f,
		-1.f, -1.f, -1.f,
		-1.f, -1.f, -1.f,
		-1.f, -1.f, 1.f,
		-1.f, 1.f, 1.f,
		// Right
		1.f, 1.f, 1.f,
		1.f, 1.f, -1.f,
		1.f, -1.f, -1.f,
		1.f, -1.f, -1.f,
		1.f, -1.f, 1.f,
		1.f, 1.f, 1.f,

		// Back face
		-1.f, -1.f, -1.f,
		-1.f, 1.f, -1.f,
		1.f, -1.f, -1.f,
		-1.f, 1.f, -1.f,
		1.f, 1.f, -1.f,
		1.f, -1.f, -1.f,
	};

	static const GLfloat g_vertex_buffer_data_cube_color_checker[] = {
		// Red side
		54/255.f, 54/255.f, 54/255.f,
		54/255.f, 54/255.f, 54/255.f,
		54/255.f, 54/255.f, 54/255.f,
		54/255.f, 54/255.f, 54/255.f,
		54/255.f, 54/255.f, 54/255.f,
		54/255.f, 54/255.f, 54/255.f,

		// Purple side
		138/255.f, 43/255.f, 226/255.f,
		138/255.f, 43/255.f, 226/255.f,
		138/255.f, 43/255.f, 226/255.f,
		138/255.f, 43/255.f, 226/255.f,
		138/255.f, 43/255.f, 226/255.f,
		138/255.f, 43/255.f, 226/255.f,

		// Orange side
		238/255.f, 118/255.f, 36/255.f,
		238/255.f, 118/255.f, 36/255.f,
		238/255.f, 118/255.f, 36/255.f,
		238/255.f, 118/255.f, 36/255.f,
		238/255.f, 118/255.f, 36/255.f,
		238/255.f, 118/255.f, 36/255.f,

		// Blue side
		127/255.f, 186/255.f, 0.f,
		127/255.f, 186/255.f, 0.f,
		127/255.f, 186/255.f, 0.f,
		127/255.f, 186/255.f, 0.f,
		127/255.f, 186/255.f, 0.f,
		127/255.f, 186/255.f, 0.f,

		// Blue side
		0.f, 100/255.f, 0.f,
		0.f, 100/255.f, 0.f,
		0.f, 100/255.f, 0.f,
		0.f, 100/255.f, 0.f,
		0.f, 100/255.f, 0.f,
		0.f, 100/255.f, 0.f,

		// Back (red) face
		127/255.f, 186/255.f, 0.f,
		127/255.f, 186/255.f, 0.f,
		127/255.f, 186/255.f, 0.f,
		127/255.f, 186/255.f, 0.f,
		127/255.f, 186/255.f, 0.f,
		127/255.f, 186/255.f, 0.f,
	};

	static const GLfloat g_vertex_buffer_data_cube_color[] = {
		// Red side
		0.7f, 0.078f, 0.14f,
		0.7f, 0.078f, 0.14f,
		0.7f, 0.078f, 0.14f,
		0.7f, 0.078f, 0.14f,
		0.7f, 0.078f, 0.14f,
		0.7f, 0.078f, 0.14f,

		// Blue side
		0.184f, 0.34f, 0.55f,
		0.184f, 0.34f, 0.55f,
		0.184f, 0.34f, 0.55f,
		0.184f, 0.34f, 0.55f,
		0.184f, 0.34f, 0.55f,
		0.184f, 0.34f, 0.55f,

		// Blue side
		0.184f, 0.34f, 0.55f,
		0.184f, 0.34f, 0.55f,
		0.184f, 0.34f, 0.55f,
		0.184f, 0.34f, 0.55f,
		0.184f, 0.34f, 0.55f,
		0.184f, 0.34f, 0.55f,

		// Blue side
		0.184f, 0.34f, 0.55f,
		0.184f, 0.34f, 0.55f,
		0.184f, 0.34f, 0.55f,
		0.184f, 0.34f, 0.55f,
		0.184f, 0.34f, 0.55f,
		0.184f, 0.34f, 0.55f,

		// Blue side
		0.184f, 0.34f, 0.75f,
		0.184f, 0.34f, 0.75f,
		0.184f, 0.34f, 0.75f,
		0.184f, 0.34f, 0.75f,
		0.184f, 0.34f, 0.75f,
		0.184f, 0.34f, 0.75f,

		// Back (red) face
		0.7f, 0.078f, 0.14f,
		0.7f, 0.078f, 0.14f,
		0.7f, 0.078f, 0.14f,
		0.7f, 0.078f, 0.14f,
		0.7f, 0.078f, 0.14f,
		0.7f, 0.078f, 0.14f,
	};

	static const GLfloat g_vertex_buffer_data_circle[] = {
		0.f, 0.f, 1.f,
		1.00000000000000f, 0.000000000000000f, 0.f,
		0.987688340595138f, 0.156434465040231f, 0.f,
		0.951056516295154f, 0.309016994374947f, 0.f,
		0.891006524188368f, 0.453990499739547f, 0.f,
		0.809016994374947f, 0.587785252292473f, 0.f,
		0.707106781186548f, 0.707106781186548f, 0.f,
		0.587785252292473f, 0.809016994374947f, 0.f,
		0.453990499739547f, 0.891006524188368f, 0.f,
		0.309016994374947f, 0.951056516295154f, 0.f,
		0.156434465040231f, 0.987688340595138f, 0.f,
		0.000000000000000f, 1.00000000000000f, 0.f,
		-0.156434465040231f, 0.987688340595138f, 0.f,
		-0.309016994374947f, 0.951056516295154f, 0.f,
		-0.453990499739547f, 0.891006524188368f, 0.f,
		-0.587785252292473f, 0.809016994374947f, 0.f,
		-0.707106781186548f, 0.707106781186548f, 0.f,
		-0.809016994374947f, 0.587785252292473f, 0.f,
		-0.891006524188368f, 0.453990499739547f, 0.f,
		-0.951056516295154f, 0.309016994374947f, 0.f,
		-0.987688340595138f, 0.156434465040231f, 0.f,
		-1.00000000000000f, 0.000000000000000f, 0.f,
		-0.987688340595138f, -0.156434465040231f, 0.f,
		-0.951056516295154f, -0.309016994374947f, 0.f,
		-0.891006524188368f, -0.453990499739546f, 0.f,
		-0.809016994374947f, -0.587785252292473f, 0.f,
		-0.707106781186548f, -0.707106781186548f, 0.f,
		-0.587785252292473f, -0.809016994374947f, 0.f,
		-0.453990499739547f, -0.891006524188368f, 0.f,
		-0.309016994374947f, -0.951056516295154f, 0.f,
		-0.156434465040231f, -0.987688340595138f, 0.f,
		0.000000000000000f, -1.00000000000000f, 0.f,
		0.156434465040231f, -0.987688340595138f, 0.f,
		0.309016994374947f, -0.951056516295154f, 0.f,
		0.453990499739547f, -0.891006524188368f, 0.f,
		0.587785252292473f, -0.809016994374947f, 0.f,
		0.707106781186548f, -0.707106781186548f, 0.f,
		0.809016994374947f, -0.587785252292473f, 0.f,
		0.891006524188368f, -0.453990499739547f, 0.f,
		0.951056516295154f, -0.309016994374947f, 0.f,
		0.987688340595138f, -0.156434465040231f, 0.f,
		1.f, 0.f, 0.f,
	};

	static const GLfloat g_vertex_buffer_data_circle_color[] = {
		0.f, 0.f, 1.f,
		1.00000000000000f, 0.000000000000000f, 0.f,
		0.987688340595138f, 0.156434465040231f, 0.f,
		0.951056516295154f, 0.309016994374947f, 0.f,
		0.891006524188368f, 0.453990499739547f, 0.f,
		0.809016994374947f, 0.587785252292473f, 0.f,
		0.707106781186548f, 0.707106781186548f, 0.f,
		0.587785252292473f, 0.809016994374947f, 0.f,
		0.453990499739547f, 0.891006524188368f, 0.f,
		0.309016994374947f, 0.951056516295154f, 0.f,
		0.156434465040231f, 0.987688340595138f, 0.f,
		0.000000000000000f, 1.00000000000000f, 0.f,
		-0.156434465040231f, 0.987688340595138f, 0.f,
		-0.309016994374947f, 0.951056516295154f, 0.f,
		-0.453990499739547f, 0.891006524188368f, 0.f,
		-0.587785252292473f, 0.809016994374947f, 0.f,
		-0.707106781186548f, 0.707106781186548f, 0.f,
		-0.809016994374947f, 0.587785252292473f, 0.f,
		-0.891006524188368f, 0.453990499739547f, 0.f,
		-0.951056516295154f, 0.309016994374947f, 0.f,
		-0.987688340595138f, 0.156434465040231f, 0.f,
		-1.00000000000000f, 0.000000000000000f, 0.f,
		-0.987688340595138f, -0.156434465040231f, 0.f,
		-0.951056516295154f, -0.309016994374947f, 0.f,
		-0.891006524188368f, -0.453990499739546f, 0.f,
		-0.809016994374947f, -0.587785252292473f, 0.f,
		-0.707106781186548f, -0.707106781186548f, 0.f,
		-0.587785252292473f, -0.809016994374947f, 0.f,
		-0.453990499739547f, -0.891006524188368f, 0.f,
		-0.309016994374947f, -0.951056516295154f, 0.f,
		-0.156434465040231f, -0.987688340595138f, 0.f,
		0.000000000000000f, -1.00000000000000f, 0.f,
		0.156434465040231f, -0.987688340595138f, 0.f,
		0.309016994374947f, -0.951056516295154f, 0.f,
		0.453990499739547f, -0.891006524188368f, 0.f,
		0.587785252292473f, -0.809016994374947f, 0.f,
		0.707106781186548f, -0.707106781186548f, 0.f,
		0.809016994374947f, -0.587785252292473f, 0.f,
		0.891006524188368f, -0.453990499739547f, 0.f,
		0.951056516295154f, -0.309016994374947f, 0.f,
		0.987688340595138f, -0.156434465040231f, 0.f,
		1.f, 0.f, 0.f,
	};

	static const GLfloat g_vertex_buffer_data_arrow[] = {
		0.f, -1.f, 0.f,
		-0.5f, 1.f, 0.f,
		0.5f, 1.f, 0.f,
	};

	static const GLfloat g_vertex_buffer_data_arrow_color[] = {
		1.f, 0.f, 1.f,
		1.f, 0.f, 1.f,
		1.f, 0.f, 1.f,
	};

	// Set up the buffer data for the cube
	glGenBuffers(1, &cubebuffer);
	glBindBuffer(GL_ARRAY_BUFFER, cubebuffer);
	glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data_cube),
		g_vertex_buffer_data_cube, GL_STATIC_DRAW);

	glGenBuffers(1, &cubebuffercolor);
	glBindBuffer(GL_ARRAY_BUFFER, cubebuffercolor);
	glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data_cube_color),
		g_vertex_buffer_data_cube_color, GL_STATIC_DRAW);

	glGenBuffers(1, &cubebuffercolor_checker);
	glBindBuffer(GL_ARRAY_BUFFER, cubebuffercolor_checker);
	glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data_cube_color_checker),
		g_vertex_buffer_data_cube_color_checker, GL_STATIC_DRAW);

	glGenBuffers(1, &circlebuffer);
	glBindBuffer(GL_ARRAY_BUFFER, circlebuffer);
	glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data_circle),
		g_vertex_buffer_data_circle, GL_STATIC_DRAW);

	glGenBuffers(1, &circlebuffer_color);
	glBindBuffer(GL_ARRAY_BUFFER, circlebuffer_color);
	glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data_circle_color),
		g_vertex_buffer_data_circle_color, GL_STATIC_DRAW);

	glGenBuffers(1, &arrowbuffer);
	glBindBuffer(GL_ARRAY_BUFFER, arrowbuffer);
	glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data_arrow),
		g_vertex_buffer_data_arrow, GL_STATIC_DRAW);

	glGenBuffers(1, &arrowbuffer_color);
	glBindBuffer(GL_ARRAY_BUFFER, arrowbuffer_color);
	glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data_arrow_color),
		g_vertex_buffer_data_arrow_color, GL_STATIC_DRAW);

	// May as well just add the vertex data.
	lex(ttl::file2str(std::string(argv[1]) + "1"), red);
	lex(ttl::file2str(std::string(argv[1]) + "2"), white);
}
示例#11
0
文件: glutiv.cpp 项目: Alexpux/Coin3D
int
main(int argc, char ** argv)

#endif

{
  // initialize Coin and glut libraries

  SoDB::init();
  SoNodeKit::init();
  SoInteraction::init();

#ifdef _WIN32
  int argc = 1;
  char * argv[] = { "glutiv.exe", (char *) NULL };
  glutInit(&argc, argv);
#else
  glutInit(&argc, argv);
#endif
  glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);

  // Note: _don't_ use SoGroup, as TGS' Inventor has a bug where
  // lightsource contribution will get accumulated over runs.
  SoSeparator * root[SCENEWINDOWS];

  for (unsigned int i=0; i < SCENEWINDOWS; i++) {
    // set up individual parts of scenegraph

    root[i] = new SoSeparator;
    root[i]->ref();
    SoPerspectiveCamera * camera = new SoPerspectiveCamera;
    root[i]->addChild(camera);
    root[i]->addChild(new SoDirectionalLight);
    SoDrawStyle * drawstyle = new SoDrawStyle;
    drawstyle->style.setValue(i % 3);
    root[i]->addChild(drawstyle);
    root[i]->addChild(commongraph());

    // initialize scenemanager instance

    scenemanager[i] = new SoSceneManager;
    scenemanager[i]->setRenderCallback(redraw_cb, (void *)i);
    scenemanager[i]->setBackgroundColor(SbColor(0.2f, 0.2f, i * 0.2f));
    scenemanager[i]->activate();
    camera->viewAll(root[i], scenemanager[i]->getViewportRegion());
    scenemanager[i]->setSceneGraph(root[i]);

    // glut window initialization

    glutInitWindowSize(512, 400);
    SbString title("window ");
    title += (char)(i + 0x30);
    glutwin[i] = glutCreateWindow(title.getString());
    glutDisplayFunc(expose_cb);
    glutReshapeFunc(reshape_cb);
  }

  SoDB::setRealTimeInterval(1/120.0);

  // start main loop processing (with an idle callback)

  glutIdleFunc(idle_cb);
  glutMainLoop();

  // clean up Coin resource use

  for (int j=0; j < SCENEWINDOWS; j++) {
    root[j]->unref();
    delete scenemanager[j];
  }

  return 0;
}
示例#12
0
/**
 * Acciones de las teclas
 */
static void keyboard(unsigned char key, int x, int y) {
	
	switch (key) {
			
		case 'w':	// Movimiento hacia adelante
		case 'W':
			if(andando){
				setAlturaPj();
			}
			dollyCamera( DEF_dollyStepSize, 0.0 );
			break;
			
			case 's':	// Movimiento hacia atras
			case 'S':
			if(andando){
				setAlturaPj();
			}
			dollyCamera( DEF_dollyStepSize, 180.0 );
			break;
			
			case 'a':	// Strafe hacia la izquierda
			case 'A':
			if(andando){
				setAlturaPj();
			}
			dollyCamera( DEF_dollyStepSize, 90.0 );
			break;
			
			case 'd':	// Strafe derecha
			case 'D':
			if(andando){
				setAlturaPj();
			}
			dollyCamera( DEF_dollyStepSize, 270.0 );
			break;
			
			case 'f':	// Fullscreen
			case 'F':
			if(fullscreen){
				fullscreen = 0;
			}else{
				fullscreen = 1;
			}
			if(fullscreen){
				glutFullScreen();
			}else{
				glutReshapeWindow(800,600);
			}
			break;
			
			case 'z':	//Mirar abajo
			camPitch -= 1.0;
			clampCamera();
			break;
			
			case 'Z':	// Mirar arriba
			camPitch += 1.0;
			clampCamera();
			break;
			
			
			case ' ': // Cambia modos de visualizado
			switch(modoRender){
				case glLINE:
					modoRender = glPOINT;
					real_renderMode = GL_POINT;
					break;
				case glPOINT:
					modoRender = glFLAT;
					real_renderMode = GL_FILL;
					glShadeModel(GL_FLAT);
					break;
				case glFLAT:
					modoRender = glSMOOTH;
					real_renderMode = GL_FILL;
					glShadeModel(GL_SMOOTH);
					break;
				case glSMOOTH:
					modoRender = glLINE;
					real_renderMode = GL_LINE;
					break;
				default: break;
			}
			break;
			
			
			case 27:	//Esc salir
			glutIdleFunc(NULL);
			exit(0);
			break;
			
			case '+': case '.': // Zoom in
			if(zoomFactor > 0.1)
				zoomFactor -= 0.1;
			break;
			
			case '-': case ',': // Zoom out
			if(zoomFactor < 2.4)
				zoomFactor += 0.1;
			break;
			
			case '0': // Zoom reset
			zoomFactor = 1.0;
			break;
			
			case '1': // Avanzar 1 hora
			horas++;
			actualizaSol(true);
			break;
			
			case '2': // Retroceder 1 hora
			horas--;
			if (horas == -1)
				horas = 23;
			actualizaSol(true);
			break;
			
			case 'p': case 'P': // Cambia entre andar y flotar
			andando = !andando;
			if(andando){
				setAlturaPj();
			}
			break;
			
			case 'o': case 'O': // Activar paso del tiempo
			animar = !animar;
			break;
			
			case 't':// Aumentar la velocidad del tiempo
			velocidad *= 2;
			if (velocidad > 500 ) velocidad = 512;
			cout << "v: " << velocidad << endl;
			break;
			
			case 'T':// Disminuir la velocidad del tiempo
			velocidad /= 2;
			if (velocidad < .125 ) velocidad = .125;
			break;	

			case 'M': // Deformación positiva
				realizarDeformacion(1);
			break;	

			case 'm': // Deformación negativa
				realizarDeformacion(-1);
			break;

			case 'x': case 'X': // Animación cámara
				animarCamara = !animarCamara;
				estadoAnimCamara = INICIO_SUAVE;
			break;
			
			default: break;
	}
	glutPostRedisplay();
}
示例#13
0
int main(int argc,char **argv)
{

   
   DIR  *dip, *dic;
   struct dirent *dit;
   int n,i;
   char *dir_and_file[2][MAX_PIC];
   
   for (i = 0; i< 2; i ++)
   {
     switch(i)
     {
     case 0: strcpy(dirString, "lf/"); break;
     case 1: strcpy(dirString, "land/"); break;
     case 2: strcpy(dirString, "path/"); break;
     default: strcpy(dirString, "lf/"); break;
     }
     
   if ((dip = opendir(dirString)) == NULL || (dic = opendir(".")) == NULL)
   {
     fprintf(stderr, "can't open directory %s\n", dirString);
     return 1;
   }
   
   
   NUM_PIC[i] = 0;
   
   while ((dit = readdir(dip)) != NULL)
   {
     if(strstr(dit->d_name, ".JPG") != NULL || strstr(dit->d_name, ".jpg") != NULL || strstr(dit->d_name, ".jpeg") != NULL || strstr(dit->d_name, ".JPEG") != NULL)
     {
       int index = NUM_PIC[i];
       dir_and_file[i][index] = malloc(100);
       strcpy(dir_and_file[i][index], dirString);
       strcat(dir_and_file[i][index], dit->d_name);
//       fd[NUM_PIC] = fopen(dir_and_file, "rb"); // Opens up the files in arbitiary order, no good
       NUM_PIC[i]++;
//       printf("READ %s %d\n", dir_and_file[NUM_PIC-1], NUM_PIC - 1);
     }

   }

   n = 0;

  sort_files(dir_and_file[i], NUM_PIC[i]);

//  for(n=0; n<NUM_PIC; n++);
   while(n<NUM_PIC[i])
   {
     fd[i][n] = fopen(dir_and_file[i][n], "rb");
//     printf("OPEN %s %d\n", dir_and_file[n], n);
     n++;
   }
   closedir(dip);

//   printf("%s %d\n", "done", NUM_PIC - 1);
 }
    
   glutInit(&argc, argv);
  

   // To see OpenGL drawing, take out the GLUT_DOUBLE request.
   glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
   glutInitWindowSize(Window_Width, Window_Height);

   // Open a window
   Window_ID = glutCreateWindow( "Light Field Viewer" );

   // Register the callback function to do the drawing.
   glutDisplayFunc(&cbRenderScene);

   // If there's nothing to do, draw.
   glutIdleFunc(&cbRenderScene);

   // It's a good idea to know when our window's resized.
   glutReshapeFunc(&cbResizeScene);


   //glutSpecialFunc(&cbSpecialKeyPressed);
   glutMouseFunc(&cbMouseClick);

   // OK, OpenGL's ready to go.  Let's call our own init function.
   ourInit(Window_Width, Window_Height);

   // Print out a bit of help dialog.
   printf("Light Field Viewer\n");

   // Pass off control to OpenGL.
   // Above functions are called as appropriate.
   glutMainLoop();

   return 1;
}
示例#14
0
void userSettings(void)
{
  lighting(currentLighting);
  materials(currentMaterials);

  if ( lightingEnabled ) {
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
  } else {
    glDisable(GL_LIGHTING);
    glDisable(GL_LIGHT0);
  }

  if ( smoothEnabled ) {
    glShadeModel(GL_SMOOTH);
  } else {
    glShadeModel(GL_FLOAT);
  }

  if ( idleSpin ) {
    glutIdleFunc(spinCube);
  } else {
    glutIdleFunc(NULL);
  }

  if ( texEnabled ) {
    glEnable(GL_TEXTURE_2D);
  } else {
    glDisable(GL_TEXTURE_2D);
  }

  if ( fastTexture ) {
    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
  } else {
    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
  }

  if ( mipmapEnabled ) {
    glTexParameterf(GL_TEXTURE_2D, 
      GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST);
  } else {
    glTexParameterf(GL_TEXTURE_2D, 
      GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  }

  if ( fogEnabled )
  {
    float fogColor[] = {0.7, 0.6, 0.6, 1.0};

    glClearColor(fogColor[0], fogColor[1], fogColor[2], fogColor[3]);
    glEnable(GL_FOG);
    glFogi(GL_FOG_MODE, GL_LINEAR);
    glFogf(GL_FOG_DENSITY, 1.0);
    glFogf(GL_FOG_START, zNear);
    glFogf(GL_FOG_END, zFar);
    glFogfv(GL_FOG_COLOR, fogColor);
  }
  else
  {
    glDisable(GL_FOG);
    glClearColor(0.0, 0.0, 0.0, 1.0 );
  }

  if ( lineAAEnabled )
    glEnable(GL_BLEND);
  else
    glDisable(GL_BLEND);

  if ( lineAAEnabled ) {
    glEnable( GL_LINE_SMOOTH );
    glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
  } else {
    glDisable( GL_LINE_SMOOTH );
  }

  if ( depthEnabled )
    glEnable(GL_DEPTH_TEST);
  else
    glDisable(GL_DEPTH_TEST);

  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();

  if ( perspectiveXform ) {
    glFrustum(-1.25, 1.25, -1.25, 1.25, zNear, zFar);
    viewxform_z = -5.0;
  } else {
    glOrtho(-2.0, 2.0, -2.0, 2.0, zNear, zFar);
    viewxform_z = -5.0;
  }
  glMatrixMode(GL_MODELVIEW);
}
示例#15
0
bool COGLWin::Init()
{
	// OpenGL rendering context exists at this point.
	m_pWindow->callback((Fl_Callback *) COGLWin::CB_Quit, this);

	glutIdleFunc(CallIdleFunc);
/*
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluOrtho2D(0, m_iOutSizeX, m_iOutSizeY, 0);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
*/
	glutSetWindow(m_iHWin);
	////////////////////////////////////////////////////

	//COGLBitmapText::InitFonts();

	// Lighting has to be enabled BEFORE
	// you call CGLUTBase::Init() !!!
	EnableLighting();

	// Initialize OpenGL settings.
	CCLUDrawBase::Init();

	m_dlSpace.Create();

	// Can change sensitivity of mouse
	// for rotation...
	SetRotFac(0.5f); // default = 1.0

	// and for translation
	SetTransFac(0.02f);  // default = 0.05

	// Enable lighting for filter
	m_Filter.EnableLighting();

	// Reduce sensitivity
	m_Filter.SetSensitivity(1e-5);//1e-4);

	// Initialize Settings for E3Filter
	m_Filter.Init();

	// Initialize Parser
	if (!m_Parse.Init())
		return false;

	m_Parse.SetMVFilter(&m_Filter);
	m_Parse.SetTransform(&m_mTransform);
	m_Parse.SetFrameRotor(&m_vRMain);
	m_Parse.SetCLUDrawBase((CCLUDrawBase *) this);
	m_Parse.InitBitmapFont();

	InitScriptListWindow();

	//AddToolSlider("Mouse Mode", 0, 9, 1, 0, true, "Set the mouse mode here.");
	//AddToolSlider("Test2", -10, 2, 0.02, "World");

	SetTitle();

	return true;
}
示例#16
0
文件: test.cpp 项目: mkkellogg/GTE
int main(int argc, char **argv) {
    
   /* glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
    glutInitWindowPosition(100,100);
    glutInitWindowSize(320,320);

  
    if(!glutGet(GLUT_DISPLAY_MODE_POSSIBLE))
    {
       exit(1);
    }

    glutCreateWindow("Lighthouse3D");
    glutDisplayFunc(renderScene);
    glutIdleFunc(renderScene);
    glutReshapeFunc(changeSize);
    glutKeyboardFunc(processNormalKeys);
 
    glewInit();
    if (glewIsSupported("GL_VERSION_2_0"))
        printf("Ready for OpenGL 2.0\n");
    else {
        printf("OpenGL 2.0 not supported\n");
        exit(1);
    }
 
    glEnable(GL_DEPTH_TEST);
    glClearColor(1.0,1.0,1.0,1.0);
 
    p = setupShaders(); 
    setupBuffers(); 
 
    glutMainLoop(); 
 
    return(0); */

    glutInit(&argc, argv);

    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
    glutInitWindowSize(640, 480);

    if(!glutGet(GLUT_DISPLAY_MODE_POSSIBLE))
    {
       exit(1);
    }

    (void)glutCreateWindow("GLUT Program");

    glewExperimental = GL_TRUE; 
    glewInit();
    if (glewIsSupported("GL_VERSION_2_0"))
        printf("Ready for OpenGL 2.0\n");
    else {	
        printf("OpenGL 2.0 not supported\n");
        exit(1);
    }

    p = setupShaders(); 
    setupBuffers(); 

    glutDisplayFunc(renderScene);
    glutIdleFunc(renderScene);
    glutReshapeFunc(changeSize);
    glutKeyboardFunc(processNormalKeys);

    glEnable(GL_DEPTH_TEST);
    glClearColor(1.0,1.0,1.0,1.0);

    glutMainLoop(); 

    return EXIT_SUCCESS;
}
示例#17
0
文件: Lab9.cpp 项目: frazeeat/CSE287
// To keep the console open on shutdown, start the project with Ctrl+F5 instead of just F5.
int main(int argc, char** argv)
{
	// freeGlut and Window initialization ***********************

	// Pass any applicable command line arguments to GLUT. These arguments
	// are platform dependent.
	glutInit(&argc, argv);

	// Set the initial display mode.
	glutInitDisplayMode(GLUT_RGBA | GLUT_SINGLE);

	// Set the initial window size
	glutInitWindowSize(winWidth, winHeight);

	// Create a window using a string and make it the current window.
	GLuint world_Window = glutCreateWindow("Viewing Transformations");

	// Indicate to GLUT that the flow of control should return to the program after
	// the window is closed and the GLUTmain loop is exited.
	glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS);

	// Callback for window redisplay
	glutDisplayFunc(RenderSceneCB);
	glutReshapeFunc(ResizeCB);
	glutKeyboardFunc(KeyboardCB);
	glutSpecialFunc(SpecialKeysCB);
	glutIdleFunc(animate);

	// Create polygon submenu
	int menu1id = glutCreateMenu(viewMenu);
	// Specify menu items and integer identifiers
	glutAddMenuEntry("View 0", 1);
	glutAddMenuEntry("View 1", 2);
	glutAddMenuEntry("View 2", 3);
	glutAddMenuEntry("View 3", 4);
	glutAddMenuEntry("Quit", 0);

	// Attach menu to right mouse button
	glutAttachMenu(GLUT_RIGHT_BUTTON);

	// Request that the window be made full screen
	//glutFullScreenToggle();

	color blue(0.498f, 1.000f, 0.831f, 1.0f);

	// Set red, green, blue, and alpha to which the color buffer is cleared.
	colorBuffer.setClearColor(blue);
	
	// Set the initial viewing tranformation for the scene
	p = glm::vec3(0.0f, 0.0f, 12.0f);
	d = glm::vec3(0.0f, 0.0f, -1.0f);
	u = glm::vec3(0.0f, 1.0f, 0.0f);

	camera.setPositionDirectionUp(p,d,u);
	a = camera.getWorldCoordinateViewPosition();
	viewingTransformation = camera.getViewingTransformation();
	std::cout << "{"
		<< a.x << " " << a.y << " " << a.z
		<< "}";
	//viewingTransformation = glm::translate( glm::vec3(0.0f, 0.0f, -12.0) );

	// Enter the GLUT main loop. Control will not return until the window is closed.
	glutMainLoop();

	return 0;

} // end main
示例#18
0
/**
 * Main Programme
 */
int main(int argc, char** argv)
{
    glutInit(&argc, argv);

    // Framebuffer setup
    glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH );

    // Positioning and size of window
    glutInitWindowPosition(200, 100);
    glutInitWindowSize(WindowSize_X,WindowSize_Y);
    glutCreateWindow(argv[0]);	

    // Initialize viewpoint
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glTranslatef(0,0,-4);
    tbInitTransform();     // This is for the trackball, please ignore
    tbHelp();             // idem
	MyCameraPosition=getCameraPosition();

	// Activate the light following the camera
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glEnable(GL_COLOR_MATERIAL);
    int LightPos[4] = {0,0,2,0};
    int MatSpec [4] = {1,1,1,1};
    glLightiv(GL_LIGHT0,GL_POSITION,LightPos);

	// Normals will be normalized in the graphics pipeline
	glEnable(GL_NORMALIZE);
    // Clear color of the background is black.
	glClearColor (0.0, 0.0, 0.0, 0.0);

	
	// Activate rendering modes
    // Activate depth test
	glEnable( GL_DEPTH_TEST ); 
    // Araw front-facing triangles filled
	// and back-facing triangles as wires
    glPolygonMode(GL_FRONT,GL_FILL);
    glPolygonMode(GL_BACK,GL_LINE);
    // Interpolate vertex colors over the triangles
	glShadeModel(GL_SMOOTH);


	// Glut setup... to ignore
    glutReshapeFunc(reshape);
    glutKeyboardFunc(keyboard);
    glutDisplayFunc(display);
    glutMouseFunc(tbMouseFunc);    // trackball
    glutMotionFunc(tbMotionFunc);  // uses mouse
    glutIdleFunc( animate);


	init();

    
	// Main loop for glut... this just runs your application
    glutMainLoop();
        
    return 0;  // execution never reaches this point
}
示例#19
0
int init(int argc, char **argv)	//initialization function
{
	printf("Beginning initialization\n");

	vectorUp.x=0;			//assign the up vector to (0,1,0)
	vectorUp.y=1;
	vectorUp.z=0;

	cameraDefault.location.x=0;	//set up a default camera
	cameraDefault.location.y=0;
	cameraDefault.location.z=5;
	cameraDefault.target.x=0;
	cameraDefault.target.y=0;
	cameraDefault.target.z=-1;

	cameraCurrent = &cameraDefault;	//set the default camera as the current camera

	windowTitle = &defaultTitle;	//set the window title to be the default
	windowMain.x = 50;				//set up initial window shape
	windowMain.y = 50;
	windowMain.width = 640;
	windowMain.height = 480;

	stateFullScreen = 0;	//default is to start in window mode
							//to start in fullscreen mode do NOT
							//change this value, instead call
							//toggleFullScreen() after the window
							//has been created

	frame = 0;				//set up counters
	timebase = 0;
	
	incps = 30;				//this value represents the number of
							//animation increments per second
							//change if you want to do more or less
							//every second
	mspinc = 1000/incps;

	//GLUT initialization follows, don't worry about it
	glutInit(&argc, argv);
	glutInitWindowPosition(windowMain.x, windowMain.y);
	glutInitWindowSize(windowMain.width, windowMain.height);
	glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
	printf("Creating window \"%s\"\n", windowTitle);
	glutCreateWindow(windowTitle);
	glutDisplayFunc(draw);
	glutIdleFunc(draw);
	glutReshapeFunc(resize);
	glutKeyboardFunc(normalKey);
	glutSpecialFunc(specialKey);
	glutMouseFunc(mouse);
	glutMotionFunc(mouseActive);
	glutPassiveMotionFunc(mousePassive);
	glutEntryFunc(mouseEntry);

	//initialize timers
	time = glutGet(GLUT_ELAPSED_TIME);
	timepassed = 0;

	printf("Initialization complete\n");

	return 0;
}
int main(int argc, char **argv) {
	char serialport[256];
    int n;

    if (argc==1) {
        exit(EXIT_SUCCESS);
    }

    // Parse options from the command line.
    int option_index = 0, opt;
    static struct option loptions[] = {
    	{"port", required_argument, 0, 'p'},		// Command line for setting port: -p /dev/tty.usbmodem####
	    {"delay", required_argument, 0, 'd'}		// Command line for zero delay: -d 0
	};

    while(1) {
    	opt = getopt_long(argc, argv, "hp:b:s:rn:d:", loptions, &option_index);
    	if (opt==-1) break;
    	switch (opt) {
			case '0': break;
	        case 'd':
	            n = strtol(optarg,NULL,10);
	            usleep(n * 1000); 									// Delay (sleep in milliseconds).
	            break;
	        case 'p':
	            strcpy(serialport,optarg);
	            fd = serialport_init(optarg, baudrate);
	            if(fd==-1) return -1;
	            break;
    	}
    }
	
	// Opens MATLAB engine, creates matrices & pointers for visual and timing samples.
	ep = engOpen(NULL);
	cppVisualSamples = mxCreateDoubleMatrix(numberOfSamples, 1, mxREAL);
	cppTimingSamples = mxCreateDoubleMatrix(numberOfSamples, 1, mxREAL);
	dataSetVisual = mxGetPr(cppVisualSamples);
	dataSetTiming = mxGetPr(cppTimingSamples);
    glutInit(&argc,argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
	glutInitWindowSize(window_width,window_height);					// Window size (in pixels).
	glutInitWindowPosition(100,100);								// Window position (from upper left).
	glutCreateWindow("Torquometer Visual Field");					// Window title.
	init();
	glutKeyboardFunc(myKeyboardFunc);								// Handles "normal" ascii symbols (letters).
	glutSpecialFunc(mySpecialKeyFunc);								// Handles "special" keyboard keys (up, down).
	glutDisplayFunc(display);										// Default display mode.
	glutIdleFunc(idleDisplay);										// Used with glutSwapBuffers();
	glEnable(GL_DEPTH_TEST);
	//glEnable(GL_TEXTURE_2D);
	makeCheckImage();												// Generates the gradient pattern in the background.
	glGenTextures(1, &texName);
	glBindTexture(GL_TEXTURE_2D, texName);
	//glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_BLEND);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, checkImageWidth, checkImageHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, checkImage);
	glutMainLoop();
}
示例#21
0
int
maininit(int argc, char **argv)
{
  float fogcolor[4]={0.025,0.025,0.025,1.0};

  fprintf(stderr,"Teapot V1.2\nWritten by David Bucciarelli ([email protected])\n");

  /*
    if(!SetPriorityClass(GetCurrentProcess(),REALTIME_PRIORITY_CLASS)) {
    fprintf(stderr,"Error setting the process class.\n");
    return 0;
    }

    if(!SetThreadPriority(GetCurrentThread(),THREAD_PRIORITY_TIME_CRITICAL)) {
    fprintf(stderr,"Error setting the process priority.\n");
    return 0;
    }
    */

  glutInitWindowPosition(0,0);
  glutInitWindowSize(WIDTH,HEIGHT);
  glutInit(&argc,argv);

  glutInitDisplayMode(GLUT_RGB|GLUT_DEPTH|GLUT_DOUBLE);

  if(!(win=glutCreateWindow("Teapot"))) {
    fprintf(stderr,"Error, couldn't open window\n");
       exit(1);
  }

  reshape(WIDTH,HEIGHT);

  glShadeModel(GL_SMOOTH);
  glEnable(GL_DEPTH_TEST);
  glEnable(GL_CULL_FACE);
  glEnable(GL_TEXTURE_2D);

  glEnable(GL_FOG);
  glFogi(GL_FOG_MODE,GL_EXP2);
  glFogfv(GL_FOG_COLOR,fogcolor);

  glFogf(GL_FOG_DENSITY,0.04);
  glHint(GL_FOG_HINT,GL_NICEST);
  glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);

  calcposobs();

  inittextures();
  initlight();

  initdlists();

  glClearColor(fogcolor[0],fogcolor[1],fogcolor[2],fogcolor[3]);

  glutReshapeFunc(reshape);
  glutDisplayFunc(draw);
  glutKeyboardFunc(key);
  glutSpecialFunc(special);
  glutIdleFunc(draw);

  glutMainLoop();

  return 0;
}
示例#22
0
//////////////////////////////////////////////////////////////////////////////
// Program main
//////////////////////////////////////////////////////////////////////////////
int
main( int argc, char** argv) 
{
    printf("Run \"nbody -benchmark [-n=<numBodies>]\" to measure perfomance.\n\n");
    
    bool benchmark = 
        (cutCheckCmdLineFlag(argc, (const char**) argv, "benchmark") != 0);

    bool compareToCPU = 
        ((cutCheckCmdLineFlag(argc, (const char**) argv, "compare") != 0) ||
        !(cutCheckCmdLineFlag(argc, (const char**) argv, "noqatest")  != 0));

    bool regression = 
        (cutCheckCmdLineFlag(argc, (const char**) argv, "regression") != 0);

    int devID;
    cudaDeviceProp props;

    // nBody has a mode that allows it to be run without using GL interop
    if (benchmark || compareToCPU || regression) {
				/*
        if( cutCheckCmdLineFlag(argc, (const char**)argv, "device") ) {
            cutilDeviceInit(argc, argv);
        } else {
            devID = cutGetMaxGflopsDeviceId();
            cudaSetDevice( devID );
        } */
    } 
    else 
    { 
        // This mode shows the OpenGL results rendered
        // First initialize OpenGL context, so we can properly set the GL for CUDA.
        // This is necessary in order to achieve optimal performance with OpenGL/CUDA interop.
        glutInit(&argc, argv);
        glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
        glutInitWindowSize(720, 480);
        glutCreateWindow("CUDA n-body system");

        GLenum err = glewInit();
        if (GLEW_OK != err)
        {
            printf("GLEW Error: %s\n", glewGetErrorString(err));
        }
        else
        {
#if   defined(WIN32)
            wglSwapIntervalEXT(0);
#elif defined(LINUX)
            glxSwapIntervalSGI(0);
#endif      
        }
    	
        initGL();
        initParameters();
    	
        if( cutCheckCmdLineFlag(argc, (const char**)argv, "device") ) {
            cutilGLDeviceInit(argc, argv);
        } else {
            devID = cutGetMaxGflopsDeviceId();
            cudaGLSetGLDevice( devID );
        }
    }


    // get number of SMs on this GPU
    cutilSafeCall(cudaGetDevice(&devID));
    cutilSafeCall(cudaGetDeviceProperties(&props, devID));

    numIterations = 0;
    int p = 256;
    int q = 1;

    cutGetCmdLineArgumenti(argc, (const char**) argv, "i", &numIterations);
    cutGetCmdLineArgumenti(argc, (const char**) argv, "p", &p);
    cutGetCmdLineArgumenti(argc, (const char**) argv, "q", &q);


    // default number of bodies is #SMs * 4 * CTA size
    numBodies = compareToCPU ? 4096 : p*q*4*props.multiProcessorCount;

    cutGetCmdLineArgumenti(argc, (const char**) argv, "n", &numBodies);

    switch (numBodies)
    {
    case 1024:
        activeParams.m_clusterScale = 1.52f;
        activeParams.m_velocityScale = 2.f;
        break;
    case 2048:
        activeParams.m_clusterScale = 1.56f;
        activeParams.m_velocityScale = 2.64f;
        break;
    case 4096:
        activeParams.m_clusterScale = 1.68f;
        activeParams.m_velocityScale = 2.98f;
        break;
    case 8192:
        activeParams.m_clusterScale = 1.98f;
        activeParams.m_velocityScale = 2.9f;
        break;
    default:
    case 16384:
        activeParams.m_clusterScale = 1.54f;
        activeParams.m_velocityScale = 8.f;
        break;
    case 32768:
        activeParams.m_clusterScale = 1.44f;
        activeParams.m_velocityScale = 11.f;
        break;
    }

    if (q * p > 256)
    {
        p = 256 / q;
        printf("Setting p=%d, q=%d to maintain %d threads per block\n", p, q, 256);
    }

    if (q == 1 && numBodies < p)
    {
        p = numBodies;
    }

    init(numBodies, p, q, !(benchmark || compareToCPU));
    
    reset(nbody, numBodies, NBODY_CONFIG_SHELL, !(benchmark || compareToCPU));


    if (benchmark)
    {
        if (numIterations <= 0) 
            numIterations = 100;
        runBenchmark(numIterations);
    }
    else if (compareToCPU || regression)
    {
        compareResults(regression, numBodies);
    }
    else
    {
        glutDisplayFunc(display);
        glutReshapeFunc(reshape);
        glutMouseFunc(mouse);
        glutMotionFunc(motion);
        glutKeyboardFunc(key);
        glutSpecialFunc(special);
        glutIdleFunc(idle);

        cutilSafeCall(cudaEventRecord(startEvent, 0));
        glutMainLoop();
    }

    if (nbodyCPU)
        delete nbodyCPU;
    if (nbodyCUDA)
        delete nbodyCUDA;

    if (hPos)
        delete [] hPos;
    if (hVel)
        delete [] hVel;
    if (hColor)
        delete [] hColor;

    cutilSafeCall(cudaEventDestroy(startEvent));
    cutilSafeCall(cudaEventDestroy(stopEvent));
    cutilCheckError(cutDeleteTimer(demoTimer));

    return 0;
}
示例#23
0
/**
 * Create or load a particle system and simulate a number of time steps.
 */
int main(int argc, char *argv[]) {
	// Create particles and springs.
	particles.reserve(dimx * dimy * dimz);
	for (size_t z = 0; z < dimz; ++z) {
		for (size_t y = 0; y < dimy; ++y) {
			for (size_t x = 0; x < dimx; ++x) {
				Length3D p;
				p[0] = (x / float(dimx > 1 ? dimx - 1 : 1) - 0.5) * m - 1 * m;// - 6 * m;
				p[1] = (y / float(dimy > 1 ? dimy - 1 : 1) - 0.5) * 0.005 * m - 1.7 * m;// + 5 * m;
				p[2] = (z / float(dimz > 1 ? dimz - 1 : 1) - 0.5) * m;
				particles.push_back(Particle(mass, p, Velocity3D()));
				// create connections to all existing neighbors
				std::vector<size_t> other_xs, other_ys, other_zs;
				if (z > 0) other_zs.push_back(z - 1);
				if (y > 0) other_ys.push_back(y - 1);
				if (x > 0) other_xs.push_back(x - 1);
				other_zs.push_back(z);
				other_ys.push_back(y);
				other_xs.push_back(x);
				if (z + 1 < dimz) other_zs.push_back(z + 1);
				if (y + 1 < dimy) other_ys.push_back(y + 1);
				if (x + 1 < dimx) other_xs.push_back(x + 1);
				for (std::vector<size_t>::const_iterator oz = other_zs.begin(); oz != other_zs.end(); ++oz) {
					for (std::vector<size_t>::const_iterator oy = other_ys.begin(); oy != other_ys.end(); ++oy) {
						for (std::vector<size_t>::const_iterator ox = other_xs.begin(); ox != other_xs.end(); ++ox) {
							size_t idx = *oz * dimy * dimx + *oy * dimx + *ox;
							if (idx < particles.size() - 1) {
								springs.push_back(Spring(particles[idx], particles.back(), stiffness, springDamping, shrinkage));
							}
						}
					}
				}
			}
		}
	}

	// Create obstacles.
	/*Number3D plane_normal;
	plane_normal[0] = 0.5; plane_normal[1] = 1.0; plane_normal[2] = 0.0;
	obstacles.push_back(new Plane(plane_normal / norm(plane_normal), -1.0 * m, bounciness, friction));
	plane_normal[0] = 0.0; plane_normal[1] = 1.0; plane_normal[2] = 0.0;
	obstacles.push_back(new Plane(plane_normal / norm(plane_normal), -1.5 * m, bounciness, friction));
	plane_normal[0] = -1.0; plane_normal[1] = 0.0; plane_normal[2] = 0.0;
	obstacles.push_back(new Plane(plane_normal / norm(plane_normal), -5.0 * m, bounciness, friction));
	*/

	Number3D table_normal;
	table_normal[0] = 0.0; table_normal[1] = 1.0; table_normal[2] = 0.0;
	Length table_radius = 0.35 * m;
	Length3D table_origin;
	table_origin[0] = -1.0 * m; table_origin[1] = -2.0 * m; table_origin[2] = 0.0 * m;
	obstacles.push_back(new Table(table_origin, table_normal, table_radius, bounciness, friction));
	table_origin[0] =  -1.15 * m; table_origin[1] =  -1.9 * m;
	obstacles.push_back(new Table(table_origin, table_normal, table_radius, bounciness, friction));
	table_origin[0] =  -0.85 * m; table_origin[1] =  -2.1 * m;
	obstacles.push_back(new Table(table_origin, table_normal, table_radius, bounciness, friction));

	// Create a particle system.
	particle_system = new MassSpringSystem(particles, springs, obstacles, particleDamping);

	// Create a solver.
	solver = new RungeKuttaSolver(particle_system);

	quadObj = gluNewQuadric();
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
	glutInitWindowPosition(0, 0);
	glutInitWindowSize(windowWidth, windowHeight);
	glutCreateWindow("Particle System");
	glutIdleFunc(idle);
	glutDisplayFunc(display);
	glutReshapeFunc(reshape);
	glutMouseFunc(mouse);
	glutMotionFunc(motion);
	glutKeyboardFunc(keyboard);
	glEnable(GL_DEPTH_TEST);
	glutMainLoop();

	return 0;
}
示例#24
0
// Initialize GLUT & OpenSG and set up the scene
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    // GLUT init
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);

    int winid = glutCreateWindow("OpenSG CGFX Shader");

    // the connection between GLUT and OpenSG
    _gwin = GLUTWindow::create();
    _gwin->setId(winid);
    _gwin->setSize( 800, 800 );
    _gwin->init();

    // init callbacks
    glutSetWindow(winid);
    glutReshapeFunc(reshape);
    glutDisplayFunc(display);
    glutIdleFunc(display);
    glutMouseFunc(mouse);
    glutMotionFunc(motion);
    glutKeyboardFunc(keyboard);

    const char *effectFile = "BumpGlossedShiny.fx";

    if(argc > 1)
    {
        effectFile = argv[1];
    }

    _cgfxmat = CGFXMaterial::create();
    beginEditCP(_cgfxmat);
        _cgfxmat->setEffectFile(effectFile);
        // this multipass technique leads to a render bug, I have no idea what's wrong :-(
        //_cgfxmat->setTechnique(1);
    endEditCP(_cgfxmat);

    ChunkMaterialPtr mat2 = ChunkMaterial::create();
    MaterialChunkPtr matc = MaterialChunk::create();
    beginEditCP(matc);
        matc->setDiffuse(Color4f(1, 0, 0, 1));
    endEditCP(matc);
    beginEditCP(mat2);
        mat2->addChunk(matc);
        //mat2->addChunk(texc);
    endEditCP(mat2);

    // create root node
    _scene = Node::create();

    GeometryPtr geo1 = makeLatLongSphereGeo(50, 50, 1.0f);
    
    OSG::calcVertexTangents(geo1, 0, Geometry::TexCoords1FieldId, Geometry::TexCoords2FieldId);

    beginEditCP( geo1, Geometry::MaterialFieldMask);
        geo1->setMaterial(_cgfxmat);
    endEditCP(geo1, Geometry::MaterialFieldMask);

    NodePtr sphere1 = Node::create();
    beginEditCP(sphere1, Node::CoreFieldMask);
        sphere1->setCore(geo1);
    endEditCP(sphere1, Node::CoreFieldMask);

    TransformPtr trans1 = Transform::create();
    beginEditCP(trans1);
        trans1->getMatrix().setTranslate(-2 , 0, 0);
    endEditCP(trans1);
    NodePtr transn1 = Node::create();
    beginEditCP(transn1);
        transn1->setCore(trans1);
        transn1->addChild(sphere1);
    beginEditCP(transn1);

    //
    GeometryPtr geo2 = makeLatLongSphereGeo(50, 50, 1.0f);
    
    beginEditCP( geo2, Geometry::MaterialFieldMask);
        geo2->setMaterial(mat2);
    endEditCP(geo2, Geometry::MaterialFieldMask);

    NodePtr sphere2 = Node::create();
    beginEditCP(sphere2, Node::CoreFieldMask);
        sphere2->setCore(geo2);
    endEditCP(sphere2, Node::CoreFieldMask);

    TransformPtr trans2 = Transform::create();
    beginEditCP(trans2);
        trans2->getMatrix().setTranslate(2 , 0, 0);
    endEditCP(trans2);
    NodePtr transn2 = Node::create();
    beginEditCP(transn2);
        transn2->setCore(trans2);
        transn2->addChild(sphere2);
    beginEditCP(transn2);

    beginEditCP(_scene);
        _scene->setCore(Group::create());
        _scene->addChild(transn1);
        _scene->addChild(transn2);
    endEditCP(_scene);

    // create the SimpleSceneManager
    _mgr = new SimpleSceneManager;

    // tell the manager what to manage
    _mgr->setWindow(_gwin);

    _mgr->setRoot(_scene);

    // show the whole scene
    _mgr->showAll();

    // create a gradient background.
    GradientBackgroundPtr gback = GradientBackground::create();
    beginEditCP(gback, GradientBackground::LineFieldMask);
        gback->clearLines();
        gback->addLine(Color3f(0.7, 0.7, 0.8), 0);
        gback->addLine(Color3f(0.0, 0.1, 0.3), 1);
    endEditCP(gback, GradientBackground::LineFieldMask);

    WindowPtr win = _mgr->getWindow();
    beginEditCP(win);
        for(int i=0;i<win->getPort().size();++i)
        {
            ViewportPtr vp = win->getPort()[i];
            beginEditCP(vp);
                vp->setBackground(gback);
            endEditCP(vp);
        }
    endEditCP(win);


    // GLUT main loop
    glutMainLoop();

    return 0;
}
示例#25
0
文件: xldemo.c 项目: Aye1/RVProject
int main(int argc, char *argv[])
{
	ALenum format;
	ALsizei size, freq;
	ALvoid *data;


	/* setup camera position and orientation */
	cameraAngle = 0.0f;
	
	cameraPosition[0] = 0.0f;
	cameraPosition[1] = 0.8f;
	cameraPosition[2] = 0.0f;

	cameraOrientation[0] = cos(2.0 * M_PI * cameraAngle / 360.0);
	cameraOrientation[1] = 0.0f;
	cameraOrientation[2] = sin(2.0 * M_PI * cameraAngle / 360.0);
	
	cameraOrientation[3] = 0.0f;
	cameraOrientation[4] = 1.0f;
	cameraOrientation[5] = 0.0f;


	/* setup radar and phase position */
	radarPosition[0] = 5.0f;
	radarPosition[1] = 0.0f;
	radarPosition[2] = 0.0f;
	
	phaserPosition[0] = 2.0f;
	phaserPosition[1] = 0.0f;
	phaserPosition[2] = 0.0f;

	radarLightAngle = 0.0f;
	phaserPlaying = AL_FALSE;


	/* initialize GLUT */
	glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
	glutInitWindowPosition(200, 100);
	glutInitWindowSize(320, 240);
	glutCreateWindow("XL Demo");
	
	glutDisplayFunc(display);
	glutKeyboardFunc(keyboard);
	glutSpecialFunc(special);
	glutReshapeFunc(reshape);
	glutIdleFunc(idle);

	glEnable(GL_CULL_FACE);

	
	/* initialize ALUT */
	alutInit(&argc, argv);


   	/* set up the buffers */
   	alGenBuffers(1, &radarBuffer);
   	alGenBuffers(1, &phaserBuffer);
   	
   	alutLoadWAV(kRadarFileName, &format, &data, &size, &freq);
   	alBufferData(radarBuffer, format, data, size, freq);
	free(data);

   	alutLoadWAV(kPhaserFileName, &format, &data, &size, &freq);
   	alBufferData(phaserBuffer, format, data, size, freq);
	free(data);


   	/* set up the sources */
   	alGenSources(1, &radarSource);
   	alGenSources(1, &phaserSource);

	alSourcefv(radarSource, AL_POSITION, radarPosition);
	alSourcef(radarSource, AL_GAIN, 1.0f);
	alSourcef(radarSource, AL_PITCH, 1.0f);
	alSourcei(radarSource, AL_BUFFER, radarBuffer);
	alSourcei(radarSource, AL_LOOPING, AL_TRUE);
	
	alSourcefv(phaserSource, AL_POSITION, phaserPosition);
	alSourcef(phaserSource, AL_GAIN, 1.0f);
	alSourcef(phaserSource, AL_PITCH, 1.0f);
	alSourcei(phaserSource, AL_BUFFER, phaserBuffer);
	alSourcei(phaserSource, AL_LOOPING, AL_FALSE);

	/* start the radar */
	alSourcePlay(radarSource);


	/* GLUT event loop */
	glutMainLoop();
	
	
	/* shutdown alut */
	alutExit();

	return 0;
}
示例#26
0
int
main(int ac, char **av)
{
   int i;

   fprintf(stderr,
	   "Fire V1.5\nWritten by David Bucciarelli ([email protected])\n");

   /* Default settings */

   np = 800;
   eject_r = -0.65;
   dt = 0.015;
   eject_vy = 4;
   eject_vl = 1;
   shadows = 1;
   ridtri = 0.25;

   maxage = 1.0 / dt;

   if (ac == 2) {
      np = atoi(av[1]);
      if (np <= 0 || np > 1000000) {
         fprintf(stderr, "Invalid input.\n");
         exit(-1);
      }
   }

   if (ac == 4) {
      WIDTH = atoi(av[2]);
      HEIGHT = atoi(av[3]);
   }

   glutInitWindowSize(WIDTH, HEIGHT);
   glutInit(&ac, av);

   glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);

   if (!(win = glutCreateWindow("Fire"))) {
      fprintf(stderr, "Error opening a window.\n");
      exit(-1);
   }

   reshape(WIDTH, HEIGHT);

   inittextures();

   glShadeModel(GL_FLAT);
   glEnable(GL_DEPTH_TEST);

   glEnable(GL_BLEND);
   glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

   glEnable(GL_FOG);
   glFogi(GL_FOG_MODE, GL_EXP);
   glFogfv(GL_FOG_COLOR, fogcolor);
   glFogf(GL_FOG_DENSITY, 0.1);

   assert(np > 0);
   p = (part *) malloc(sizeof(part) * np);
   assert(p);

   for (i = 0; i < np; i++)
      setnewpart(&p[i]);

   inittree();

   glutKeyboardFunc(key);
   glutSpecialFunc(special);
   glutDisplayFunc(drawfire);
   glutIdleFunc(idle);
   glutReshapeFunc(reshape);
   glutMainLoop();

   return (0);
}
示例#27
0
static void InitializeGlutCallbacks()
{
    glutDisplayFunc(RenderSceneCB);
    glutIdleFunc(RenderSceneCB);
}
示例#28
0
void
menu(int option)
{
  switch (option) {
  case 0:
    makePointList();
    break;
#if GL_EXT_point_parameters
  case 1:
    if (hasPointParameters) {
      glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT, constant);
    }
    break;
  case 2:
    if (hasPointParameters) {
      glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT, linear);
    }
    break;
  case 3:
    if (hasPointParameters) {
      glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT, quadratic);
    }
    break;
#endif
  case 4:
    glEnable(GL_BLEND);
    break;
  case 5:
    glDisable(GL_BLEND);
    break;
#if GL_EXT_point_parameters
  case 6:
    if (hasPointParameters) {
      glPointParameterfEXT(GL_POINT_FADE_THRESHOLD_SIZE_EXT, 1.0);
    }
    break;
  case 7:
    if (hasPointParameters) {
      glPointParameterfEXT(GL_POINT_FADE_THRESHOLD_SIZE_EXT, 10.0);
    }
    break;
#endif
  case 8:
    glEnable(GL_POINT_SMOOTH);
    break;
  case 9:
    glDisable(GL_POINT_SMOOTH);
    break;
  case 10:
    glPointSize(2.0);
    break;
  case 11:
    glPointSize(4.0);
    break;
  case 12:
    glPointSize(8.0);
    break;
  case 18:
    glPointSize(16.0);
    break;
  case 13:
    spin = 1 - spin;
    if (animate && (spin || motion)) {
      glutIdleFunc(idle);
    } else {
      glutIdleFunc(NULL);
    }
    break;
  case 14:
    numPoints = 200;
    break;
  case 15:
    numPoints = 500;
    break;
  case 16:
    numPoints = 1000;
    break;
  case 17:
    numPoints = 2000;
    break;
  case 19:
    useTexture = !useTexture;
    break;
  case 666:
    exit(0);
  }
  glutPostRedisplay();
}
示例#29
0
void GLUTDisplay2::run(PathTracer &pt) {
	ptr = &pt;

	unsigned int buffer_width = 960;
	unsigned int buffer_height = 540;
	glutInitWindowSize(buffer_width, buffer_height);
	glutInitWindowPosition(100, 100);
	glutCreateWindow("test");

	// Initialize GLEW
	if (glewInit() != GLEW_OK) {
		cerr << "Failed to initialize GLEW" << endl;
		return;
	}

	try {
		// Set up scene
		cout << "setup camera" << endl;
		//SampleScene::InitialCameraData camera_data;

		// todo: get camera
		//ptr->initScene(camera_data);

		// Initialize camera according to scene params
		//m_camera = new PinholeCamera(camera_data.eye, camera_data.lookat,
		//		camera_data.up, -1.0f, // hfov is ignored when using keep vertical
		//		camera_data.vfov, PinholeCamera::KeepVertical);
	} catch (optix::Exception& e) {
		sutilReportError(e.getErrorString().c_str());
		exit(2);
	}

	//cout << "make renderer" << endl;
	//renderer = new GLrenderer( pt.getOutputBuffer()->getGLBOId() );

	cout << "init texture" << endl;
	glGenTextures(1, &m_texId);
	glBindTexture(GL_TEXTURE_2D, m_texId);

	// Change these to GL_LINEAR for super- or sub-sampling
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

	// GL_CLAMP_TO_EDGE for linear filtering, not relevant for nearest.
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

	glBindTexture(GL_TEXTURE_2D, 0);

	// Initialize state
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(0, 1, 0, 1, -1, 1);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glViewport(0, 0, buffer_width, buffer_height);

	cout << "begin glut loop" << endl;
	glutDisplayFunc(display);
	glutIdleFunc(idle);
	glutShowWindow();
	glutReshapeWindow( buffer_width, buffer_height );
	glutMainLoop();
}
示例#30
0
文件: menu.c 项目: netscruff/ceiba
//void animateRotationToNode(OglTree T, node n, enum FlagTypes rotateTo, float x, float y, float z) // move to node, but offset by xyz
void animateRotationToObject(struct PickableObject *p)
/*
On menu selection of double click, animate a rotation that brings either a leaf node or a fan into the foreground at a nice position.
Responding to a menu driven taxon name selection, with ROTATE_TO_NODE we move until the leaf's node position is centered on the screen and "close".
Responding to a double click on a visible fan, with ROTATE_TO_TREE we move until the center of the fan is centered on the screen and close.
Close is determined by 'finalEyeDistance', currently set to a fraction of the root tree's radius.

*/

{
extern float theta[3], theta0[3];
area A, Athis,Aanc;
int i;
extern double gRadiusOfOriginalCircle;
extern float xStep,yStep,thetaStep,zStep,theta0step;
extern int animSteps;
extern node gTreeRoot;
OglTree t;
float startTheta,endTheta,curTheta,startZ,endZ,startTheta0,endTheta0,diff0,diffTheta, radius;

float x,z;

OglTree T=p->tree;
float y=-p->height/2.0;
node n=p->nd;
enum ObjectType objType=p->objType;


// if the node is part of a subtree, find the marked ancestor node, and use its coordinates

float finalEyeDistance; // the distance from eye to tree or node after animation is over.
float deltaX=0.0, deltaY=0.0, angle;


switch (objType)
	{
	case LABEL: // rotate to make a label on any kind of tree front and center
		t=T;
		if (t)
		while (t->layout == circle)
			{
			A = (area)(n->data); // this will recurse through the leaf's ancestors.
			angle = A->theta_center - t->upDirection;  // what about petiole???
			deltaX += -sin(angle)*(t->outerRadius+t->petioleLength);
			deltaY += cos(angle)*(t->outerRadius+t->petioleLength); // sin and cos are backwards from intuition; remember the fans go 
			n = t->parentNode;
			//printf ("%f %f %f %f\n",toDegs(angle),deltaX, deltaY,t->upDirection);
		
			t=t->anc;
			}
		A=(area)(n->data); 
		finalEyeDistance = t->radius/10.0; // for example
		radius = A->r_center + finalEyeDistance;
		break;

	case IMAGE:
		switch (T->layout)
			{
			case circle:
				return;
			case solid_cone:
					A=(area)(n->data); 
					finalEyeDistance = T->radius/10.0; // for example
					//y=-0.2*T->outerRadius; // for taxon name, zoom to leaf node position 
					radius = A->r_center + finalEyeDistance;
			}
		break;

	case FAN: // rotate to make fan front and center
		if (T->layout == fanlet) return;
		if (T->anc)
			switch (T->anc->layout)
				{
				case solid_cone:
					A=(area)(T->parentNode->data);
					finalEyeDistance = T->anc->radius/10.0; // for example
					radius = A->r_center + finalEyeDistance;
					break;
				case circle:
					break;
				}
		break;
	}

#define ANIM_STEPS_FACTOR 3000 // bigger is smoother and slower
animSteps = ANIM_STEPS_FACTOR/gTreeRoot->numdescEffective + 1; // scale the number of animation steps to be fewer in large trees...

startTheta=theta[2];
diffTheta= - (90 + theta[2] +  toDegs(A->theta_center)  ); // took a lot of peering to get this right
	if ( diffTheta > 180 ) diffTheta -= 360; 
	if ( diffTheta < -180 ) diffTheta += 360; 

//printf("Initial theta = %f target theta = %f adjusted diff = %f\n",startTheta,endTheta,diffTheta);

thetaStep=diffTheta/animSteps;


extern OglTree gCurrOglTree;
zStep=(radius-gP->Z)/animSteps;

yStep=(A->z-gP->Y - y + deltaY)/animSteps;

xStep= (-gP->X + deltaX)/animSteps; // put the viewer back lined up with x=0 

startTheta0=theta[0];  // this is putting the tree back to its completely vertical original pos
endTheta0=theta0[0];
diff0 = endTheta0 - startTheta0; 
	if ( diff0 > 180 ) diff0 -= 360; 
	if ( diff0 < -180 ) diff0 += 360; 

theta0step = diff0/animSteps; 
    
glutIdleFunc(animateTwist);
}