示例#1
1
/**
 * @fn main()
 * @brief The main method.
 */ 
int main(int argc, char **argv)
{
  // optionally set the resolution at startup
  if (argc > 1)
  {
    g_iFloWidth = g_iFloHeight = atoi(argv[1]);
  }

  // Window size.
  const int width = 512, height = 512;

  glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_ALPHA);
  glutInitWindowPosition(50, 50);
  glutInitWindowSize(width, height);
  glutCreateWindow("Mark's Fluid Simulator");

  glutIdleFunc(Idle);
  glutDisplayFunc(Display);
  glutKeyboardFunc(Keyboard);
  glutMotionFunc(Motion);
  glutMouseFunc(Mouse);
  glutReshapeFunc(Reshape);
  glutSpecialFunc(Special);

  Reshape(width, height); 

  // Init the simulation, UI, and graphics state.
  Initialize();

  // Print some instructions.
  system("cls");
  printf("\nFlo: Mark's GPU Fluid Simulator\n\n");
  printf("Keys:\n");
  printf("[`]: (tilde key) Display parameter sliders\n"
         "[t]: Cycle display mode (Velocity, Scalar, Pressure).\n"
		 "[T]: Toggle display (turn it off for more accurate \n"
		 "     simulation timing.\n"
         "[r]: Reset fluid simulation\n"
         "[b]: Toggle bilinear interpolation in fragment program.\n"
		 "     (High Quality, Lower Performance)\n"
		 "[m]: Toggle interpolated texture generation.\n"
		 "     (Lower Quality, Higher Performance)\n"
		 "[v]: Toggle vorticity confinement.\n"
         "[a]: Toggle arbitrary boundaries.\n"
         "[c]: Toggle clearing of pressure each iteration. \n"
         "     (With this off, solution requires fewer iterations, but\n"
         "     has more oscillatory behavior.)\n"
         "[L]: Time 100 iterations and print out the result.\n"
         "[q]/[ESC]: Quit\n"
         "\n"
         "Mouse:\n"
         "Left Button: Inject Ink and perturb the fluid.\n"
         "Right Button: perturb the fluid w/o injecting Ink.\n"
         "CTRL + Left Button: Draw boundaries.\n"
         "\n\n\n"
        );

  // start the framerate timer.
  g_timer.Start();

  // Go!
  glutMainLoop();

  return 0;
}
示例#2
0
int main(int argc, char *argv[]) {
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH |
		GLUT_STENCIL);
	if((argc > 1) && (strcmpi(argv[1], "--helmet") == 0)) {
		/*left eye*/
		glutInitWindowPosition(0,0);
		glutInitWindowSize(640, 480);
		left_eye = glutCreateWindow("Escher World - Left Eye");

		glutSetWindow(left_eye);
		set_window_size(640, 480);
		glutDisplayFunc(displayleft);
		glutKeyboardFunc(keyfunc);
		glutMouseFunc(mouse_button);
		glutPassiveMotionFunc(passive_mouse_motion);
		glutMotionFunc(passive_mouse_motion);
		glutReshapeFunc(set_window_size);
/*		glutTimerFunc(10,child,1);*/

		/* right eye */
		glutInitWindowPosition(641,0);
		glutInitWindowSize(640, 480);
		right_eye = glutCreateWindow("Escher World - Right Eye");

		glutSetWindow(right_eye);
		set_window_size(640, 480);
		glutDisplayFunc(displayright);
		glutKeyboardFunc(keyfunc);
		glutMouseFunc(mouse_button);
		glutPassiveMotionFunc(passive_mouse_motion);
		glutMotionFunc(passive_mouse_motion);
		glutReshapeFunc(set_window_size);

		glutSetWindow(left_eye);
		create_menus();
		init();
		/* Initialize the scene */
		init_scene(FILENAME);

		glutSetWindow(right_eye);
		create_menus();
		create_menus();
		init();
		/* Initialize the scene */
		init_scene(FILENAME);

#ifdef USE_HELMET
/*		main_helmet();
		signal(SIGUSR1, cleanup);
*/		birdinit();
/*		glutTimerFunc(10,child,1);*/
#endif

	} else {
		glutInitWindowPosition(64,64);

		glutInitWindowSize(768, 832);
		glut_window = glutCreateWindow("Escher World");

		glutSetWindow(glut_window);
		set_window_size(768, 832);
		helmet = !helmet;
		glutDisplayFunc(displaymid);
		glutKeyboardFunc(keyfunc);
		glutMouseFunc(mouse_button);
		glutPassiveMotionFunc(passive_mouse_motion);
		glutMotionFunc(passive_mouse_motion);
		glutReshapeFunc(set_window_size);
		create_menus();
		init();
		/* Initialize the scene */
		init_scene(FILENAME);
	}

	glutMainLoop();

	return 0;
}
示例#3
0
int
main(int argc, char** argv)
{
    int buffering = GLUT_DOUBLE;
    struct dirent* direntp;
    DIR* dirp;
    int models;

    glutInitWindowSize(512, 512);
    glutInit(&argc, argv);

    while (--argc) {
	if (strcmp(argv[argc], "-sb") == 0)
	    buffering = GLUT_SINGLE;
	else
	    model_file = argv[argc];
    }

    if (!model_file) {
	model_file = "data/dolphins.obj";
    }

    glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | buffering);
    glutCreateWindow("Smooth");
  
    glutReshapeFunc(reshape);
    glutDisplayFunc(display);
    glutKeyboardFunc(keyboard);
    glutMouseFunc(mouse);
    glutMotionFunc(motion);

    models = glutCreateMenu(menu);
    dirp = opendir(DATA_DIR);
    if (!dirp) {
	fprintf(stderr, "%s: can't open data directory.\n", argv[0]);
    } else {
	while ((direntp = readdir(dirp)) != NULL) {
	    if (strstr(direntp->d_name, ".obj")) {
		entries++;
		glutAddMenuEntry(direntp->d_name, -entries);
	    }
	}
	closedir(dirp);
    }

    glutCreateMenu(menu);
    glutAddMenuEntry("Smooth", 0);
    glutAddMenuEntry("", 0);
    glutAddSubMenu("Models", models);
    glutAddMenuEntry("", 0);
    glutAddMenuEntry("[w]   Toggle wireframe/filled", 'w');
    glutAddMenuEntry("[c]   Toggle culling on/off", 'c');
    glutAddMenuEntry("[n]   Toggle face/smooth normals", 'n');
    glutAddMenuEntry("[b]   Toggle bounding box on/off", 'b');
    glutAddMenuEntry("[p]   Toggle frame rate on/off", 'p');
    glutAddMenuEntry("[t]   Toggle model statistics", 't');
    glutAddMenuEntry("[m]   Toggle color/material/none mode", 'm');
    glutAddMenuEntry("[r]   Reverse polygon winding", 'r');
    glutAddMenuEntry("[s]   Scale model smaller", 's');
    glutAddMenuEntry("[S]   Scale model larger", 'S');
    glutAddMenuEntry("[o]   Weld redundant vertices", 'o');
    glutAddMenuEntry("[+]   Increase smoothing angle", '+');
    glutAddMenuEntry("[-]   Decrease smoothing angle", '-');
    glutAddMenuEntry("[W]   Write model to file (out.obj)", 'W');
    glutAddMenuEntry("", 0);
    glutAddMenuEntry("[Esc] Quit", 27);
    glutAttachMenu(GLUT_RIGHT_BUTTON);
  
    init();
  
    glutMainLoop();
    return 0;
}
示例#4
0
int                /* O - Exit status */
main(int  argc,    /* I - Number of command-line arguments */
     char *argv[]) /* I - Command-line arguments */
    {
    glutInit(&argc, argv);
#ifdef BOOK_COVER
    glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE | GLUT_DEPTH);
#else
    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
#endif /* BOOK_COVER */
    glutInitWindowSize(792, 573);
    glutCreateWindow("Terrain Using Vertex Culling Extension");
    glutDisplayFunc(Redraw);
    if (glutDeviceGet(GLUT_HAS_JOYSTICK))
        glutJoystickFunc(Joystick, 200);
    glutKeyboardFunc(Keyboard);
    glutMotionFunc(Motion);
    glutMouseFunc(Mouse);
    glutReshapeFunc(Resize);
    glutSpecialFunc(Special);

    BuildF16();

    LandTexture = TextureLoad("land.bmp", GL_FALSE, GL_LINEAR_MIPMAP_LINEAR,
                              GL_LINEAR, GL_REPEAT);
    SkyTexture  = TextureLoad("sky.bmp", GL_FALSE, GL_LINEAR, GL_LINEAR,
                              GL_CLAMP);

    LoadTerrain(36, -112);

    puts("QUICK HELP:");
    puts("");
    puts("ESC - Quit");
    puts("',' - Slow down, '<' - Slowest");
    puts("'.' - Speed up, '>' - Fastest");
    puts("'3' - Toggle terrain");
    puts("'a' - Toggle aircraft");
    puts("'f' - Toggle fog");
    puts("'l' - Toggle lighting");
    puts("'s' - Toggle sky/clouds");
    puts("'t' - Toggle texturing");
    puts("'w' - Toggle water");
    puts("'W' - Toggle wireframe");

    printf("GL_EXTENSIONS = %s\n", glGetString(GL_EXTENSIONS));

    if (strstr(glGetString(GL_EXTENSIONS), "EXT_cull_vertex") != NULL)
        {
        UseCullVertex        = 1;
	glCullParameterfvEXT = wglGetProcAddress("glCullParameterfvEXT");
	}
    else if (strstr(glGetString(GL_EXTENSIONS), "SGI_cull_vertex") != NULL)
        {
        UseCullVertex        = 1;
	glCullParameterfvEXT = wglGetProcAddress("glCullParameterfvSGI");
	}
    else
        UseCullVertex = 0;

    glutMainLoop();

    return (0);
    }
// Main program
//*****************************************************************************
int main(int argc, char** argv) 
{
	// Locals used with command line args
    int p = 256;            // workgroup X dimension
    int q = 1;              // workgroup Y dimension

	pArgc = &argc;
	pArgv = argv;

    shrQAStart(argc, argv);

    // latch the executable path for other funcs to use
    cExecutablePath = argv[0];

    // start logs and show command line help
	shrSetLogFileName ("oclNbody.txt");
    shrLog("%s Starting...\n\n", cExecutablePath);
    shrLog("Command line switches:\n");
	shrLog("  --qatest\t\tCheck correctness of GPU execution and measure performance)\n");
	shrLog("  --noprompt\t\tQuit simulation automatically after a brief period\n");
    shrLog("  --n=<numbodies>\tSpecify # of bodies to simulate (default = %d)\n", numBodies);
	shrLog("  --double\t\tUse double precision floating point values for simulation\n");
	shrLog("  --p=<workgroup X dim>\tSpecify X dimension of workgroup (default = %d)\n", p);
	shrLog("  --q=<workgroup Y dim>\tSpecify Y dimension of workgroup (default = %d)\n\n", q);

	// Get command line arguments if there are any and set vars accordingly
    if (argc > 0)
    {
        shrGetCmdLineArgumenti(argc, (const char**)argv, "p", &p);
        shrGetCmdLineArgumenti(argc, (const char**)argv, "q", &q);
        shrGetCmdLineArgumenti(argc, (const char**)argv, "n", &numBodies);
	    bDouble = (shrTRUE == shrCheckCmdLineFlag(argc, (const char**)argv, "double"));
        bNoPrompt = shrCheckCmdLineFlag(argc, (const char**)argv, "noprompt");
        bQATest = shrCheckCmdLineFlag(argc, (const char**)argv, "qatest");
    }

    //Get the NVIDIA platform
    cl_int ciErrNum = oclGetPlatformID(&cpPlatform);
    oclCheckErrorEX(ciErrNum, CL_SUCCESS, pCleanup);
    shrLog("clGetPlatformID...\n\n"); 
	
	if (bDouble)
	{
		shrLog("Double precision execution...\n\n");
	}
	else
	{
		shrLog("Single precision execution...\n\n");
	}

	flopsPerInteraction = bDouble ? 30 : 20; 
    
	//Get all the devices
    shrLog("Get the Device info and select Device...\n");
    ciErrNum = clGetDeviceIDs(cpPlatform, CL_DEVICE_TYPE_GPU, 0, NULL, &uiNumDevices);
    oclCheckErrorEX(ciErrNum, CL_SUCCESS, pCleanup);
    cdDevices = (cl_device_id *)malloc(uiNumDevices * sizeof(cl_device_id) );
    ciErrNum = clGetDeviceIDs(cpPlatform, CL_DEVICE_TYPE_GPU, uiNumDevices, cdDevices, NULL);
    oclCheckErrorEX(ciErrNum, CL_SUCCESS, pCleanup);

    // Set target device and Query number of compute units on uiTargetDevice
    shrLog("  # of Devices Available = %u\n", uiNumDevices); 
    if(shrGetCmdLineArgumentu(argc, (const char**)argv, "device", &uiTargetDevice)== shrTRUE) 
    {
        uiTargetDevice = CLAMP(uiTargetDevice, 0, (uiNumDevices - 1));
    }
    shrLog("  Using Device %u, ", uiTargetDevice); 
    oclPrintDevName(LOGBOTH, cdDevices[uiTargetDevice]);  
    cl_uint uiNumComputeUnits;        
    clGetDeviceInfo(cdDevices[uiTargetDevice], CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(uiNumComputeUnits), &uiNumComputeUnits, NULL);
    shrLog("  # of Compute Units = %u\n", uiNumComputeUnits); 

    //Create the context
    shrLog("clCreateContext...\n"); 
    cxContext = clCreateContext(0, uiNumDevsUsed, &cdDevices[uiTargetDevice], NULL, NULL, &ciErrNum);
    oclCheckErrorEX(ciErrNum, CL_SUCCESS, pCleanup);

    // Create a command-queue 
    shrLog("clCreateCommandQueue...\n\n"); 
    cqCommandQueue = clCreateCommandQueue(cxContext, cdDevices[uiTargetDevice], CL_QUEUE_PROFILING_ENABLE, &ciErrNum);
    oclCheckErrorEX(ciErrNum, CL_SUCCESS, pCleanup);

    // Log and config for number of bodies
    shrLog("Number of Bodies = %d\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 7680:
        case 8192:
            activeParams.m_clusterScale = 1.98f;
            activeParams.m_velocityScale = 2.9f;
            break;
        default:
        case 15360:
        case 16384:
            activeParams.m_clusterScale = 1.54f;
            activeParams.m_velocityScale = 8.f;
            break;
        case 30720:
        case 32768:
            activeParams.m_clusterScale = 1.44f;
            activeParams.m_velocityScale = 11.f;
            break;
    }

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

    if ((q == 1) && (numBodies < p))
    {
        p = numBodies;
        shrLog("Setting p=%d because # of bodies < p\n", p);
    }
    shrLog("Workgroup Dims = (%d x %d)\n\n", p, q); 

    // Initialize OpenGL items if using GL 
    if (bQATest == shrFALSE)
    {
	    shrLog("Calling InitGL...\n"); 
	    InitGL(&argc, argv);
    }
    else 
    {
	    shrLog("Skipping InitGL...\n"); 
    }
	
    // CL/GL interop disabled
    bUsePBO = (false && (bQATest == shrFALSE));
    InitNbody(cdDevices[uiTargetDevice], cxContext, cqCommandQueue, numBodies, p, q, bUsePBO, bDouble);
    ResetSim(nbody, numBodies, NBODY_CONFIG_SHELL, bUsePBO);

    // init timers
    shrDeltaT(DEMOTIME); // timer 0 is for timing demo periods
    shrDeltaT(FUNCTIME); // timer 1 is for logging function delta t's
    shrDeltaT(FPSTIME);  // timer 2 is for fps measurement   

    // Standard simulation
    if (bQATest == shrFALSE)
    {
        shrLog("Running standard oclNbody simulation...\n\n"); 
        glutDisplayFunc(DisplayGL);
        glutReshapeFunc(ReshapeGL);
        glutMouseFunc(MouseGL);
        glutMotionFunc(MotionGL);
        glutKeyboardFunc(KeyboardGL);
        glutSpecialFunc(SpecialGL);
        glutIdleFunc(IdleGL);
        glutMainLoop();
    }


    // Compare to host, profile and write out file for regression analysis
    if (bQATest == shrTRUE) {
	    bool bTestResults = false;
        shrLog("Running oclNbody Results Comparison...\n\n"); 
        bTestResults = CompareResults(numBodies);

        shrLog("Profiling oclNbody...\n\n"); 
        RunProfiling(100, (unsigned int)(p * q));  // 100 iterations

		shrQAFinish(argc, (const char **)argv, bTestResults ? QA_PASSED : QA_FAILED);
    } else {
        // Cleanup/exit 
	    bNoPrompt = shrTRUE;
        shrQAFinish2(false, *pArgc, (const char **)pArgv, QA_PASSED);
    }
    Cleanup(EXIT_SUCCESS);
}
示例#6
0
// main function
int main(int argc,char *argv[])
   {
   int i;

   int argc_regular;

   int argv_type;
   char *argv_ext;

   // count regular arguments
   for (argc_regular=0,i=1; i<argc; i++)
      if (*argv[i]!='-') argc_regular++;

   // process command line options
   for (i=1; i<argc; i++)
      if (strcmp(argv[i],"-s")==0) sw_stereo=1;
      else if (strcmp(argv[i],"-a")==0) sw_anaglyph=1;
      else if (strcmp(argv[i],"-f")==0) sw_full=1;
      else if (strcmp(argv[i],"-m")==0) sw_multi=1;
      else if (strcmp(argv[i],"-r")==0) sw_reset=1;
      else if (strcmp(argv[i],"-c")==0) sw_autos3tc=1;
      else if (strcmp(argv[i],"-b")==0) sw_bricks=1;
      else if (strcmp(argv[i],"-B")==0) sw_bricks=sw_mpass=1;

   // check arguments
   if ((sw_multi==0 && argc_regular!=1 && argc_regular!=2 && argc_regular!=4) ||
       (sw_multi!=0 && argc_regular<1))
      {
      printf("short usage: %s <url> {<options>}\n",argv[0]);
      printf("regular usage: %s <elev.ini> <imag.ini> {<options>}\n",argv[0]);
      printf("long usage: %s <url> <tileset.path> <elevation.subpath> <imagery.subpath> {<options>}\n",argv[0]);
      printf("multi usage: %s -m {<url> [<detail.db>]} {<options>}\n",argv[0]);
      printf("options: -s=stereo -a=anaglyph -f=full-screen -r=reset-cache -c=auto-s3tc\n");
      exit(1);
      }

   // path setup for elevation and imagery
   if (sw_multi==0)
      if (argc_regular==4)
         {
         if (*argv[1]=='-' || sscanf(argv[1],"%s",baseurl)!=1) exit(1);
         if (*argv[2]=='-' || sscanf(argv[2],"%s",baseid)!=1) exit(1);
         if (*argv[3]=='-' || sscanf(argv[3],"%s",basepath1)!=1) exit(1);
         if (*argv[4]=='-' || sscanf(argv[4],"%s",basepath2)!=1) exit(1);
         }
      else if (argc_regular==2)
         {
         if (*argv[1]=='-' || sscanf(argv[1],"%s",elev)!=1) exit(1);
         if (*argv[2]=='-' || sscanf(argv[2],"%s",imag)!=1) exit(1);
         }
      else
         if (*argv[1]=='-' || sscanf(argv[1],"%s",shorturl)!=1) exit(1);

   // open window with GLUT:

   winwidth=VIEWER_WINWIDTH;
   winheight=VIEWER_WINHEIGHT;

   glutInit(&argc,argv);
   glutInitWindowSize(winwidth,winheight);
   if (sw_stereo!=0 && sw_anaglyph==0) glutInitDisplayMode(GLUT_RGB|GLUT_DEPTH|GLUT_STENCIL|GLUT_DOUBLE|GLUT_STEREO);
   else glutInitDisplayMode(GLUT_RGB|GLUT_DEPTH|GLUT_STENCIL|GLUT_DOUBLE);
   if (sw_full==0) winid=glutCreateWindow(VIEWER_WINTITLE);
   else glutEnterGameMode();

   glutDisplayFunc(displayfunc);
   glutReshapeFunc(reshapefunc);
   glutMouseFunc(NULL);
   glutMotionFunc(NULL);
   glutKeyboardFunc(keyboardfunc);
   glutSpecialFunc(NULL);
   glutIdleFunc(displayfunc);

   // print unsupported OpenGL extensions
   miniOGL::print_unsupported_glexts();

   // create the viewer object
   viewer=new miniview;

   // initialize the viewing parameters
   initparams();

   // get a reference to the viewing parameters
   params=viewer->get();

   // get a reference to the earth parameters
   eparams=viewer->getearth()->get();

   // get a reference to the terrain parameters
   tparams=viewer->getearth()->getterrain()->get();

   // load tileset (short version)
   if (sw_multi==0 && argc_regular==1)
      if (!viewer->getearth()->load(shorturl,TRUE,sw_reset))
         {
         printf("unable to load tileset at url=%s\n",shorturl);
         exit(1);
         }

   // load tileset (regular version)
   if (sw_multi==0 && argc_regular==2)
      if (!viewer->getearth()->load(elev,imag,TRUE,sw_reset))
         {
         printf("unable to load tileset from %s (resp. %s)\n",elev,imag);
         exit(1);
         }

   // load tileset (long version)
   if (sw_multi==0 && argc_regular==4)
      if (!viewer->getearth()->load(baseurl,baseid,basepath1,basepath2,TRUE,sw_reset))
         {
         printf("unable to load tileset at url=%s%s%s (resp. %s)\n",baseurl,baseid,basepath1,basepath2);
         exit(1);
         }

   // load tileset (multi version)
   if (sw_multi!=0)
      for (i=1; i<argc; i++)
         if (*argv[i]!='-')
            {
            argv_type=0;
            argv_ext=strrchr(argv[i],'.');

            if (argv_ext!=NULL)
               if (strlen(argv_ext)<=4)
                  if (strcmp(argv_ext,".db")==0) argv_type=1;

            // identified tileset
            if (argv_type==0)
               if (!viewer->getearth()->loadLTS(argv[i],TRUE,sw_reset,VIEWER_LEVELS))
                  {
                  printf("unable to load tileset at url=%s\n",argv[i]);
                  exit(1);
                  }

            // identified detail
            if (argv_type==1)
               viewer->getearth()->loaddetailtex(argv[i]);
            }

   // load optional features
   viewer->getearth()->loadopts();

   // initialize VIS bathy map
   initVISbathymap();

   // initialize NPR bathy map
   initNPRbathymap();

   // initialize camera
   cam=new minicam(viewer->getearth());

   // tell actual camera
   viewer->set_camera(cam);

   // load settings
   loadsettings();

   // initialize waypoint addons
   initaddons();

   // enter event loop
   glutMainLoop();

   // never reached
   return(0);
   }
示例#7
0
int main(int argc, char* argv[])
{
    
    XnBool bChooseDevice = false;
	const char* csRecordingName = NULL;
    
	if (argc > 1)
	{
		if (strcmp(argv[1], "-devices") == 0)
		{
			bChooseDevice = TRUE;
		}
		else
		{
			csRecordingName = argv[1];
		}
	}
    
	if (csRecordingName != NULL)
	{
		// check if running from a different directory. If so, we need to change directory
		// to the real one, so that path to INI file will be OK (for log initialization, for example)
		if (0 != changeDirectory(argv[0]))
		{
			return(ERR_DEVICE);
		}
	}
    
	// Xiron Init
	XnStatus rc = XN_STATUS_OK;
	EnumerationErrors errors;
    
	if (csRecordingName != NULL)
	{
		xnLogInitFromXmlFile(SAMPLE_XML_PATH);
		rc = openDeviceFile(argv[1]);
	}
	else if (bChooseDevice)
	{
		rc = openDeviceFromXmlWithChoice(SAMPLE_XML_PATH, errors);
	}
	else
	{
		rc = openDeviceFromXml(SAMPLE_XML_PATH, errors);
	}
    
	if (rc == XN_STATUS_NO_NODE_PRESENT)
	{
		XnChar strError[1024];
		errors.ToString(strError, 1024);
		printf("%s\n", strError);
		closeSample(ERR_DEVICE);
		return (rc);
	}
	else if (rc != XN_STATUS_OK)
	{
		printf("Open failed: %s\n", xnGetStatusString(rc));
		closeSample(ERR_DEVICE);
	}
    
	captureInit();
	statisticsInit();
    
	//reshaper.zNear = 1;
	//reshaper.zFar = 100;
	//glut_add_interactor(&reshaper);
    
	//cb.mouse_function = MouseCallback;
	//cb.motion_function = MotionCallback;
	//cb.passive_motion_function = MotionCallback;
	//cb.keyboard_function = KeyboardCallback;
	//cb.reshape_function = ReshapeCallback;
	//glut_add_interactor(&cb);
    
    glutInit(&argc, argv);
	glutInitDisplayString("stencil double rgb");
	glutInitWindowSize(WIN_SIZE_X, WIN_SIZE_Y);
	glutCreateWindow("OpenNI Viewer");
	//glutFullScreen();
	glutSetCursor(GLUT_CURSOR_NONE);
    
    glutMouseFunc(MouseCallback);
    glutMotionFunc(MotionCallback);
    
    init_opengl();
    
    glutIdleFunc(IdleCallback);
	glutDisplayFunc(drawFunctionMain);
    glutPassiveMotionFunc(MotionCallback);
    
	//createKeyboardMap();
	//createMenu();

    atexit(onExit);
    
    //Use built in hand tracker class to handle all hand movements and gestures
    HandTracker mainHandTracker(g_Context);
    m_HandTracker = &mainHandTracker;
    
    drawInit(m_HandTracker);
    
    //mainHandTracker.Init();
    //mainHandTracker.Run();
    xn::ImageGenerator test;
    g_Context.FindExistingNode(XN_NODE_TYPE_IMAGE, test);
    xn::DepthGenerator depth;
    g_Context.FindExistingNode(XN_NODE_TYPE_DEPTH, depth);
    
    depth.GetAlternativeViewPointCap().SetViewPoint(test);
    
    glutMainLoop();
    
	return 0;
}
示例#8
0
int main(int argc, char **argv) {

//  GLUT initialization
	glutInit(&argc, argv);

	glutInitDisplayMode(GLUT_DEPTH|GLUT_DOUBLE|GLUT_RGBA|GLUT_MULTISAMPLE);

	glutInitContextVersion (3, 3);
	glutInitContextFlags (GLUT_COMPATIBILITY_PROFILE );

	glutInitWindowPosition(100,100);
	glutInitWindowSize(320,320);
	glutCreateWindow("Lighthouse3D - Assimp Demo");
		

//  Callback Registration
	glutDisplayFunc(renderScene);
	glutReshapeFunc(changeSize);
	glutIdleFunc(renderScene);

//	Mouse and Keyboard Callbacks
	glutKeyboardFunc(processKeys);
	glutMouseFunc(processMouseButtons);
	glutMotionFunc(processMouseMotion);
	
	glutMouseWheelFunc ( mouseWheel ) ;

//	Init GLEW
	//glewExperimental = GL_TRUE;
	glewInit();
	if (glewIsSupported("GL_VERSION_3_3"))
		printf("Ready for OpenGL 3.3\n");
	else {
		printf("OpenGL 3.3 not supported\n");
		return(1);
	}

//  Init the app (load model and textures) and OpenGL
	if (!init())
		printf("Could not Load the Model\n");

   printf ("Vendor: %s\n", glGetString (GL_VENDOR));
   printf ("Renderer: %s\n", glGetString (GL_RENDERER));
   printf ("Version: %s\n", glGetString (GL_VERSION));
   printf ("GLSL: %s\n", glGetString (GL_SHADING_LANGUAGE_VERSION));


   // return from main loop
	glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS);

//  GLUT main loop
	glutMainLoop();

	// cleaning up
	textureIdMap.clear();  

	// clear myMeshes stuff
	for (unsigned int i = 0; i < myMeshes.size(); ++i) {
			
		glDeleteVertexArrays(1,&(myMeshes[i].vao));
		glDeleteTextures(1,&(myMeshes[i].texIndex));
		glDeleteBuffers(1,&(myMeshes[i].uniformBlockIndex));
	}
	// delete buffers
	glDeleteBuffers(1,&matricesUniBuffer);

	return(0);
}
示例#9
0
int main(int argc, char *argv[])
{
	// inicjalizacja biblioteki GLUT
	glutInit(&argc, argv);

	// inicjalizacja bufora ramki
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);

	// rozmiary głównego okna programu
	glutInitWindowSize(500, 500);

	// utworzenie głównego okna programu
	glutCreateWindow("Zadanie 3");

	// dołączenie funkcji generującej scenę 3D
	glutDisplayFunc(DisplayScene);

	// dołączenie funkcji wywoływanej przy zmianie rozmiaru okna
	glutReshapeFunc(Reshape);

	// dołączenie funkcji obsługi klawiatury
	glutKeyboardFunc(Keyboard);

	// obsługa przycisków myszki
	glutMouseFunc(MouseButton);

	// obsługa ruchu kursora myszki
	glutMotionFunc(MouseMotion);

	// utworzenie podmenu - Planeta
	int MenuPlanet = glutCreateMenu(Menu);
	glutAddMenuEntry("Wenus", VENUS_TEX);
	glutAddMenuEntry("Ziemia", EARTH_TEX);
	glutAddMenuEntry("Mars", MARS_TEX);
	glutAddMenuEntry("Jowisz", JUPITER_TEX);

	// utworzenie podmenu - Filtr pomniejszający
	int MenuMinFilter = glutCreateMenu(Menu);
	glutAddMenuEntry("GL_NEAREST_MIPMAP_NEAREST", GL_NEAREST_MIPMAP_NEAREST);
	glutAddMenuEntry("GL_NEAREST_MIPMAP_LINEAR", GL_NEAREST_MIPMAP_LINEAR);
	glutAddMenuEntry("GL_LINEAR_MIPMAP_NEAREST", GL_LINEAR_MIPMAP_NEAREST);
	glutAddMenuEntry("GL_LINEAR_MIPMAP_LINEAR", GL_LINEAR_MIPMAP_LINEAR);

	// utworzenie podmenu - Aspekt obrazu
	int MenuAspect = glutCreateMenu(Menu);
#ifdef WIN32

	glutAddMenuEntry("Aspekt obrazu - całe okno", FULL_WINDOW);
#else

	glutAddMenuEntry("Aspekt obrazu - cale okno", FULL_WINDOW);
#endif

	glutAddMenuEntry("Aspekt obrazu 1:1", ASPECT_1_1);

	// menu główne
	glutCreateMenu(Menu);
	glutAddSubMenu("Planeta", MenuPlanet);

#ifdef WIN32

	glutAddSubMenu("Filtr pomniejszający", MenuMinFilter);
	glutAddSubMenu("Aspekt obrazu", MenuAspect);
	glutAddMenuEntry("Wyjście", EXIT);
#else

	glutAddSubMenu("Filtr pomniejszajacy", MenuMinFilter);
	glutAddSubMenu("Aspekt obrazu", MenuAspect);
	glutAddMenuEntry("Wyjscie", EXIT);
#endif

	// określenie przycisku myszki obsługującego menu podręczne
	glutAttachMenu(GLUT_RIGHT_BUTTON);

	// utworzenie tekstur
	GenerateTextures();

	// sprawdzenie i przygotowanie obsługi wybranych rozszerzeñ
	ExtensionSetup();

	// wprowadzenie programu do obsługi pętli komunikatów
	glutMainLoop();
	return 0;
}
示例#10
0
int main(int argc, char **argv)
{
    int i;

    if (argc > 1) {		/* make sure at least 2 args, program and file */
      strncpy(filename, argv[argc - 1], sizeof(filename));	/* get the last arg as the file always */

	for (i = 0; i < argc; i++) {	/* check for startup params */
	    if (strstr(argv[i], "-s"))
		stereo = 1;
	    if (strstr(argv[i], "-f"))
		full_screen = 1;
	}
    } else {			/* user only entered program name, help them */

	printf("Usage: %s [-s] [-f] <obj filename>\n", argv[0]);
	exit(0);
    }


    glutInit(&argc, argv);

	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);

    glutInitWindowSize(1024, 768);	/*  Window Size If We Start In Windowed Mode */
    glutCreateWindow("Wavefront Obj File Viewer");
    if (full_screen)
	glutFullScreen();


    glutDisplayFunc(Display);
    glutKeyboardFunc(Keyboard);
    getMatrix();
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glClearAccum(0.0, 0.0, 0.0, 0.0);
    glutReshapeFunc(Reshape);
    glutMouseFunc(Mouse);
    glutMotionFunc(Motion);
    glutIdleFunc(NULL);

    glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
    glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
    glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
    glLightfv(GL_LIGHT0, GL_POSITION, light_position);

    glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
    glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
    glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
    glMaterialfv(GL_FRONT, GL_SHININESS, high_shininess);

    if (lighting)
	glEnable(GL_LIGHTING);
    if (lighting)
	glEnable(GL_LIGHT0);
    glDepthFunc(GL_LESS);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_NORMALIZE);
    glEnable(GL_TEXTURE_2D);

	glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);

    if (!pmodel) {		/* load up the model */
	pmodel = glmReadOBJ(filename);
	if (!pmodel) {
	    printf("\nUsage: objviewV2 <-s> <obj filename>\n");
	    exit(0);
	}
	glmUnitize(pmodel);
	glmVertexNormals(pmodel, 90.0, GL_TRUE);
    }

    glutMainLoop();

    return 0;
}
示例#11
0
int main(int argc, char *argv[]) {
	double			pos;
    VideoState      *is;


    if(argc < 2) {
        fprintf(stderr, "Usage: test <file>\n");
        exit(1);
    }

#ifdef __MINGW32__
	ptw32_processInitialize();
	//ptw32_processTerminate();
#endif

	//XInitThreads();

    is = (VideoState *)av_mallocz(sizeof(VideoState));

	avcodec_register_all();
	//avdevice_register_all();
	avfilter_register_all();
    av_register_all();
	avformat_network_init();

	if (USE_EVENT_MULTI_THREAD)
	{
		if ( SDLMOD_StartEventLoop(SDLMOD_INIT_EVENTTHREAD) < 0 ) {
			fprintf(stderr, "Could not start SDLMOD event loop (multi thread)\n");
			exit(1);
		}
	}
	else
	{
		if ( SDLMOD_StartEventLoop(0) < 0 ) {
			fprintf(stderr, "Could not start SDLMOD event loop (main thread)\n");
			exit(1);
		}
	}
	if (SDLMOD_TimerInit() != 0)
	{
		fprintf(stderr, "SDLMOD_TimerInit failed\n");
		exit(1);
	}

	g_video_width = 640;
	g_video_height = 480;
	g_video_resized = 0;

	//screen = SDL_SetVideoMode(g_video_width, g_video_height, SDL_VIDEO_MODE_BPP, SDL_VIDEO_MODE_FLAGS);
	screen = SDLMOD_CreateRGBSurface(0,
		g_video_width, g_video_height, SDL_VIDEO_MODE_BPP,
		Rmask, Gmask, Bmask, Amask
		);
	if(!screen) {
		fprintf(stderr, "SDL: could not set video mode - exiting\n");
		exit(1);
	}

    screen_mutex = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t));
    pthread_mutex_init(screen_mutex, NULL);

    av_strlcpy(is->filename, argv[1], sizeof(is->filename));

	is->pictq_mutex = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t));
    pthread_mutex_init(is->pictq_mutex, NULL);
    is->pictq_cond = (pthread_cond_t *)malloc(sizeof(pthread_cond_t));
    pthread_cond_init(is->pictq_cond, NULL);
    
	schedule_refresh(is, 40);

	is->av_sync_type = AV_SYNC_VIDEO_MASTER;

    {
		int err;
		is->parse_tid = (pthread_t *)malloc(sizeof(pthread_t));
		err = pthread_create(is->parse_tid, NULL, decodeThread, is);
		if (err!=0)
		{
			free(is->parse_tid);
			printf("can't create thread: %s\n", strerror(err));
			exit(0);
		}
	}
    if (!is->parse_tid) {
        av_free(is);
        return -1;
    }

	av_init_packet(&flush_pkt);
	flush_pkt.data = (uint8_t*)"FLUSH";

#if USE_EVENT_LOOP_MT
	{
		pthread_t pid;
		pthread_create(&pid, NULL, event_loop, is);
		if (0)
		{
			pthread_join(pid, NULL);
		}
		else
		{
#if USE_GL
			glutInit(&argc, argv);
			glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGBA|GLUT_DEPTH);
			glutInitWindowSize(g_video_width, g_video_height);
			glutInitWindowPosition(0, 0);
			
			win = glutCreateWindow(TITLE);
			createMenu();

			glutDisplayFunc(display);
			glutReshapeFunc(reshape);
			glutMouseFunc(mouse);
			glutMotionFunc(motion);
			glutIdleFunc(idle);

			if (initEnvironment())
			{
				glutMainLoop();
			}
#else
			printf(">>>>>>Please input command (exit, quit, save):<<<<<<\n");
			char string[256];
			char* ret;
			while(1)
			{
				ret = gets(string);
				if (strcmp(string, "exit") == 0 || 
				    strcmp(string, "quit") == 0 ||
				    strcmp(string, "e") == 0 ||
				    strcmp(string, "q") == 0
				    )
				{
					break;
				}
				else if (strcmp(string, "save") == 0 ||
					strcmp(string, "s") == 0
				    )
				{
					save_bmp();
					printf("save_bmp() finish.\n");
				}
				else
				{
					printf("Please input command (exit, quit, save):\n");
				}
			}
#endif
		}
	}
#else
	event_loop(is);
#endif

    return 0;
}
示例#12
0
int main (int argc, char **argv)
{

/* **************************************************************************************************************************** */

 	/* Pointeurs vers l'application */
	glutInit(&argc, argv);         

  	/*  Activation des buffers :   
     	Double buffer 
     	RGBA color
     	Depth buffer */               
	glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH); 

  	/* Création de la fenêtre */
	glutInitWindowSize(1024, 768);

	/* Positionnement de la fenêtre */
	glutInitWindowPosition(100, 100);

	/* Ouverture de la fenêtre */  
	glutCreateWindow("TD_Animation_3D");

	/* Spécification de la fontion de dessin */
	glutDisplayFunc(display);

  	/* Spécification de la fontion de redimensionnement */
	glutReshapeFunc(reshape);

  	/* Spécification des fontions de gestion du clavier */
	glutKeyboardFunc(keyboardDown);
	glutKeyboardUpFunc(keyboardUp);
	glutSpecialFunc(keyboardSpecDown);
	glutSpecialUpFunc(keyboardSpecUp);

 	/* Spécification des fontions de gestion de la souris */
	glutMouseFunc(mouse);
	glutMotionFunc(motion);

 	/* Spécification de la fonction de mise-à-jour */
	glutIdleFunc(timeTick);

/* **************************************************************************************************************************** */

	/* Affichage des fonctions clavier */
	HelpMessage();

/* **************************************************************************************************************************** */

	/* Intitialisation des paramètres de l'affichage et de la fenêtre */
	GLInit();

	/* Intitialisation des paramètres du squelette */ 
	SkeletInit();

	/* Intitialisation de la scène cinématique */
	IKInit();

/* **************************************************************************************************************************** */

  	/* Lancement de la boucle OpenGL */  
	glutMainLoop();

/* **************************************************************************************************************************** */

	return 0;

/* **************************************************************************************************************************** */
}
示例#13
0
// Initialize GLUT & OpenSG and set up the scene
int main (int argc, char **argv)
{
    int i;
    float ca=-1,cb=-1,cc=-1;
    // OSG init
    osgInit(argc,argv);
    char *filename=NULL;

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

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

    // create the scene
    float x,y,z;
    scene = Node::create();
    beginEditCP(scene);
    scene->setCore(Group::create());
    endEditCP(scene);

    NodePtr file;

    for(i=1;i<argc;++i)
    {
        if(argv[i][0] =='-')
        {
            switch(argv[i][1])
            {
                case 'd':
                    useFaceDistribution=true;
                    break;
                case 'v':
                    viewVolume=true;
                    break;
                case 's':
                    serverCount=atoi(&argv[i][2]);
                    break;
                case 'l':
                    loop=atoi(&argv[i][2]);
                    break;
                case 'S':
                    simulateRendering=true;
                    break;
            }
        }
        else
        {
            if(argv[i][0] >='0' &&
               argv[i][0] <='9')
            {
                if(ca==-1)
                    ca=atoi(argv[i]);
                else
                    if(cb==-1)
                        cb=atoi(argv[i]);
                    else
                        if(cc==-1)
                            cc=atoi(argv[i]);
            }
            else
            {
                filename=argv[1];
            }
        }
    }
    if(ca == -1 && filename)
    {
        file = OSG::SceneFileHandler::the().read(filename);
        beginEditCP(scene);
        scene->addChild(file);
        endEditCP(scene);
    }
    else
    {
        if(ca==-1)
            ca=4;
        if(cb==-1)
            cb=ca;
        if(cc==-1)
            cc=cb;
        if(file == NullFC)
        {
            GeometryPtr geo=makeBoxGeo(.6,.6,.6,20,20,20);
            beginEditCP(geo);
            SimpleMaterialPtr mat=SimpleMaterial::create();
            beginEditCP(mat);
            mat->setAmbient(Color3f(.4,.4,.4));
            mat->setSpecular(Color3f(0,0,0));
            mat->setDiffuse(Color3f(1,1,1));
            endEditCP(mat);
            geo->setMaterial(mat);
            endEditCP(geo);
            NodePtr node;
            NodePtr geoNode;
            TransformPtr trans;
            for(x=-ca/2 ; x<ca/2 ; x++)
                for(y=-cb/2 ; y<cb/2 ; y++)
                    for(z=-cc/2 ; z<cc/2 ; z++)
                    {
                        trans=Transform::create();
                        node=Node::create();
                        geoNode=Node::create();
                        
                        beginEditCP(geoNode);
                        beginEditCP(trans);
                        beginEditCP(node);
                        
                        node->setCore(trans);
                        trans->getMatrix().setTranslate(x,y,z);
                        if(!filename)
                        {
                            geoNode=Node::create();
                            geoNode->setCore(geo);
                        }
                        else
                        {
                            geoNode = OSG::SceneFileHandler::the().read(filename);
                        }
                        node->addChild( geoNode );
                        beginEditCP(scene);
                        scene->addChild(node);
                        
                        endEditCP(geoNode);
                        endEditCP(scene);
                        endEditCP(trans);
                        endEditCP(node);
                    }
        }
    }
    // create the SimpleSceneManager helper
    mgr = new MySceneManager;

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

    mgr->showAll();

    // GLUT main loop
    if(loop)
        glutIdleFunc(display);
//    glutReshapeWindow(720,576);
    glutReshapeWindow(1152,864);
    glutMainLoop();

    return 0;
}
void initMouse() {
    glutMouseFunc(mouseOnPress);
    glutMotionFunc(mousePressedMotion);
}
示例#15
0
int
main(int argc, char **argv)
{
  static GLfloat lightpos[] =
  {25.f, 50.f, -50.f, 1.f};
  static GLfloat sphere_mat[] =
  {1.f, .5f, 0.f, 1.f};
  static GLfloat cone_mat[] =
  {0.f, .5f, 1.f, 1.f};
  GLUquadricObj *sphere, *cone, *base;

  glutInit(&argc, argv);
  glutInitWindowSize(512, 512);
  glutInitDisplayMode(GLUT_STENCIL | GLUT_DEPTH | GLUT_DOUBLE);
  (void) glutCreateWindow("csg");
  glutDisplayFunc(redraw);
  glutKeyboardFunc(key);
  glutSpecialFunc(special);
  glutMouseFunc(mouse);
  glutMotionFunc(motion);

  glutCreateMenu(menu);
  glutAddMenuEntry("A only", CSG_A);
  glutAddMenuEntry("B only", CSG_B);
  glutAddMenuEntry("A or B", CSG_A_OR_B);
  glutAddMenuEntry("A and B", CSG_A_AND_B);
  glutAddMenuEntry("A sub B", CSG_A_SUB_B);
  glutAddMenuEntry("B sub A", CSG_B_SUB_A);
  glutAttachMenu(GLUT_RIGHT_BUTTON);

  glEnable(GL_CULL_FACE);
  glEnable(GL_LIGHTING);
  glEnable(GL_LIGHT0);

  glLightfv(GL_LIGHT0, GL_POSITION, lightpos);
  glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);

  /* make display lists for sphere and cone; for efficiency */

  glNewList(SPHERE, GL_COMPILE);
  sphere = gluNewQuadric();
  glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, sphere_mat);
  gluSphere(sphere, 20.f, 64, 64);
  gluDeleteQuadric(sphere);
  glEndList();

  glNewList(CONE, GL_COMPILE);
  cone = gluNewQuadric();
  base = gluNewQuadric();
  glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, cone_mat);
  gluQuadricOrientation(base, GLU_INSIDE);
  gluDisk(base, 0., 15., 64, 1);
  gluCylinder(cone, 15., 0., 60., 64, 64);
  gluDeleteQuadric(cone);
  gluDeleteQuadric(base);
  glEndList();

  glMatrixMode(GL_PROJECTION);
  glOrtho(-50., 50., -50., 50., -50., 50.);
  glMatrixMode(GL_MODELVIEW);
  glutMainLoop();
  return 0;             /* ANSI C requires main to return int. */
}
示例#16
0
////////////////////////////////////////////////////////////////////////////////
// Program main
////////////////////////////////////////////////////////////////////////////////
int
main(int argc, char **argv)
{
#if defined(__linux__)
    setenv ("DISPLAY", ":0", 0);
#endif

    printf("%s Starting...\n\n", sSDKsample);

    numParticles = NUM_PARTICLES;
    uint gridDim = GRID_SIZE;
    numIterations = 0;

    if (argc > 1)
    {
        if (checkCmdLineFlag(argc, (const char **) argv, "n"))
        {
            numParticles = getCmdLineArgumentInt(argc, (const char **)argv, "n");
        }

        if (checkCmdLineFlag(argc, (const char **) argv, "grid"))
        {
            gridDim = getCmdLineArgumentInt(argc, (const char **) argv, "grid");
        }

        if (checkCmdLineFlag(argc, (const char **)argv, "file"))
        {
            getCmdLineArgumentString(argc, (const char **)argv, "file", &g_refFile);
            fpsLimit = frameCheckNumber;
            numIterations = 1;
        }
    }

    gridSize.x = gridSize.y = gridSize.z = gridDim;
    printf("grid: %d x %d x %d = %d cells\n", gridSize.x, gridSize.y, gridSize.z, gridSize.x*gridSize.y*gridSize.z);
    printf("particles: %d\n", numParticles);

    bool benchmark = checkCmdLineFlag(argc, (const char **) argv, "benchmark") != 0;

    if (checkCmdLineFlag(argc, (const char **) argv, "i"))
    {
        numIterations = getCmdLineArgumentInt(argc, (const char **) argv, "i");
    }

    if (g_refFile)
    {
        cudaInit(argc, argv);
    }
    else
    {
        if (checkCmdLineFlag(argc, (const char **)argv, "device"))
        {
            printf("[%s]\n", argv[0]);
            printf("   Does not explicitly support -device=n in OpenGL mode\n");
            printf("   To use -device=n, the sample must be running w/o OpenGL\n\n");
            printf(" > %s -device=n -file=<*.bin>\n", argv[0]);
            printf("exiting...\n");
            exit(EXIT_SUCCESS);
        }

        initGL(&argc, argv);
        cudaGLInit(argc, argv);
    }

    initParticleSystem(numParticles, gridSize, g_refFile==NULL);
    initParams();

    if (!g_refFile)
    {
        initMenus();
    }

    if (benchmark || g_refFile)
    {
        if (numIterations <= 0)
        {
            numIterations = 300;
        }

        runBenchmark(numIterations, argv[0]);
    }
    else
    {
        glutDisplayFunc(display);
        glutReshapeFunc(reshape);
        glutMouseFunc(mouse);
        glutMotionFunc(motion);
        glutKeyboardFunc(key);
        glutSpecialFunc(special);
        glutIdleFunc(idle);

        glutCloseFunc(cleanup);

        glutMainLoop();
    }

    if (psystem)
    {
        delete psystem;
    }

    // cudaDeviceReset causes the driver to clean up all state. While
    // not mandatory in normal operation, it is good practice.  It is also
    // needed to ensure correct operation when the application is being
    // profiled. Calling cudaDeviceReset causes all profile data to be
    // flushed before the application exits
    cudaDeviceReset();
    exit(g_TotalErrors > 0 ? EXIT_FAILURE : EXIT_SUCCESS);
}
示例#17
0
// Main
int main(int argc, char *argv[])
{
    glutInit( &argc, argv );
    glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH );
    glutInitWindowSize( 800, 600 );
    glutCreateWindow( "Font rendering advanced tweaking" );
    glutCreateMenu( NULL );

#ifndef __APPLE__
    GLenum err = glewInit();
    if (GLEW_OK != err)
    {
        /* Problem: glewInit failed, something is seriously wrong. */
        fprintf( stderr, "Error: %s\n", glewGetErrorString(err) );
        exit( EXIT_FAILURE );
    }
    fprintf( stderr, "Using GLEW %s\n", glewGetString(GLEW_VERSION) );
#endif

    glutDisplayFunc( display );
    glutReshapeFunc( reshape );
    atexit( terminate );
    TwInit( TW_OPENGL, NULL );
    glutMouseFunc( (GLUTmousebuttonfun)TwEventMouseButtonGLUT );
    glutMotionFunc( (GLUTmousemotionfun)TwEventMouseMotionGLUT );
    glutPassiveMotionFunc( (GLUTmousemotionfun)TwEventMouseMotionGLUT );
    glutKeyboardFunc( (GLUTkeyboardfun)TwEventKeyboardGLUT );
    glutSpecialFunc( (GLUTspecialfun)TwEventSpecialGLUT );
    TwGLUTModifiersFunc( glutGetModifiers );

    // Create a new tweak bar
    bar = TwNewBar("TweakBar");
    TwDefine("GLOBAL "
             "help = 'This example shows how to tune all font parameters.' ");
    TwDefine("TweakBar                      "
             "size          = '280 400'     "
             "position      = '500 20'      "
             "color         = '127 127 127' "
             "alpha         = 240           "
             "label         = 'Parameters'  "
             "resizable     = True          "
             "fontresizable = True          "
             "iconifiable   = True          ");

    {
        TwEnumVal familyEV[NUM_FONTS] = {
            {VERA,         "Vera"},
            {VERA_MONO,    "Vera Mono"},
            {LUCKIEST_GUY, "Luckiest Guy"},
            {SOURCE_SANS,  "Source Sans Pro"},
            {SOURCE_CODE,  "Source Code Pro"},
            {OLD_STANDARD, "Old Standard TT"},
            {LOBSTER,      "Lobster"} };
        TwType family_type = TwDefineEnum("Family", familyEV, NUM_FONTS);
        TwAddVarCB(bar, "Family", family_type, set_family, get_family, NULL, 
                   "label = 'Family'      "
                   "group = 'Font'        "
                   "help  = ' '           ");
    }
    TwAddVarCB(bar, "Size", TW_TYPE_FLOAT, set_size, get_size, NULL, 
               "label = 'Size' "
               "group = 'Font' "
               "min   = 6.0    "
               "max   = 24.0   "
               "step  = 0.05   "
               "help  = ' '    ");
    TwAddVarCB(bar, "LCD filtering", TW_TYPE_BOOL32, set_lcd_filtering, get_lcd_filtering, NULL, 
               "label = 'LCD filtering' "
              "group = 'Font'        "
               "help  = ' '             ");


    // Rendering
    TwAddVarCB(bar, "Kerning", TW_TYPE_BOOL32, set_kerning, get_kerning, NULL, 
               "label = 'Kerning'   "
               "group = 'Rendering' "
               "help  = ' '         ");
    TwAddVarCB(bar, "Hinting", TW_TYPE_BOOL32, set_hinting, get_hinting, NULL, 
               "label = 'Hinting'   "
               "group = 'Rendering' "
               "help  = ' '         ");

    // Color
    TwAddVarCB(bar, "Invert", TW_TYPE_BOOL32, set_invert, get_invert, NULL, 
               "label = 'Invert' "
               "group = 'Color'  "
               "help  = ' '      ");
    
    // Glyph
    TwAddVarCB(bar, "Width", TW_TYPE_FLOAT, set_width, get_width, NULL, 
               "label = 'Width' "
               "group = 'Glyph' "
               "min   = 0.75    "
               "max   = 1.25    " 
               "step  = 0.01    "
               "help  = ' '     ");

    TwAddVarCB(bar, "Interval", TW_TYPE_FLOAT, set_interval, get_interval, NULL, 
               "label = 'Spacing' "
               "group = 'Glyph'   "
               "min   = -0.2      "
               "max   = 0.2       "
               "step  = 0.01      "
               "help  = ' '       " );

    TwAddVarCB(bar, "Faux italic", TW_TYPE_FLOAT, set_faux_italic, get_faux_italic, NULL, 
               "label = 'Faux italic' "
               "group = 'Glyph'       "
               "min   = -30.0         "
               "max   =  30.0         "
               "step  = 0.1           "
               "help  = ' '           ");

    // Energy distribution
    TwAddVarCB(bar, "Primary", TW_TYPE_FLOAT, set_primary, get_primary, NULL,
               "label = 'Primary weight'      "
               "group = 'Energy distribution' "
               "min   = 0                     "
               "max   = 1                     "
               "step  = 0.01                  "
               "help  = ' '                   " );

    TwAddVarCB(bar, "Secondary", TW_TYPE_FLOAT, set_secondary, get_secondary, NULL,
               "label = 'Secondy weight'      "
               "group = 'Energy distribution' "
               "min   = 0                     "
               "max   = 1                     "
               "step  = 0.01                  "
               "help  = ' '                   " );

    TwAddVarCB(bar, "Tertiary", TW_TYPE_FLOAT, set_tertiary, get_tertiary, NULL,
               "label = 'Tertiary weight'      "
               "group = 'Energy distribution' "
               "min   = 0                     "
               "max   = 1                     "
               "step  = 0.01                  "
               "help  = ' '                   " );

    TwAddSeparator(bar, "",
                   "group = 'Energy distribution' " );

    TwAddVarCB(bar, "Gamma", TW_TYPE_FLOAT, set_gamma, get_gamma, NULL, 
               "label = 'Gamma correction'    "
               "group = 'Energy distribution' "
               "min   = 0.50                  "
               "max   = 2.5                   "
               "step  = 0.01                  "
               "help  = ' '                   ");

    TwAddSeparator(bar, "", "");
    TwAddButton(bar, "Reset", (TwButtonCallback) reset, NULL,
                "help='Reset all parameters to default values.'");
    TwAddSeparator(bar, "", "");
    TwAddButton(bar, "Quit", (TwButtonCallback) quit, NULL,
                "help='Quit.'");

    buffer_a = text_buffer_new( 1 ); 
    buffer_rgb = text_buffer_new( 3 ); 
    buffer = buffer_rgb;
    reset();

    glutTimerFunc( 1000.0/60.0, timer, 60 );

    mat4_set_identity( &projection );
    mat4_set_identity( &model );
    mat4_set_identity( &view );

    glutMainLoop();
    return EXIT_SUCCESS;
}
int doMain(int argc,char **argv)
{
    int                      i;
    char                    *opt;
    std::vector<std::string> filenames;
    std::vector<std::string> servers;
    std::string              connectionType = "StreamSock";
    std::string              connectionParameters;
    int                      rows=1;
    int                      cols=-1;
    char                     type='M';
    bool                     clientRendering=true;
    bool                     compose=false;

    std::string              composerType="";
    std::string              autostart;
    
    for(i=1;i<argc;i++)
    {
        if(strlen(argv[i])>1 && argv[i][0]=='-')
        {
            switch(argv[i][1])
            {
                case 'o':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    connectionParameters = opt;
                    printf("connectionParameters: '%s'\n", connectionParameters.c_str());
                    break;
                case 'A':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    autostart = opt;
                    break;
                case 'D':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    if(sscanf(opt,"%f,%f,%f",&ca,&cb,&cc)!=3)
                    {
                        std::cout << "Copy opton -D x,y,z" << std::endl;
                        return 1;
                    }
                    break;
                case 'b':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    serviceInterface.assign(opt);
                    serviceInterfaceValid = true;
                    break;
                case 'B':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    serviceAddress.assign(opt);
                    serviceAddressValid = true;
                    break;
                case 'f':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    filenames.push_back(opt);
                    printf("<%s>\n",opt);
                    break;
                case 'm':
                    connectionType="Multicast";
                    break;
                case 'r':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    if(sscanf(opt,"%d,%d",&rows,&cols) != 2)
                        sscanf(opt,"%d",&rows);
                    break;
                case 't':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    subtilesize=atoi(opt);
                    break;
#ifdef FRAMEINTERLEAVE
                case 'i':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    interleave=atoi(opt);
                    break;
#endif
                case 'C':
                    compose=true;
                    break;
                case 'F':
                    type='F';
                    break;
                case 'X':
                    type='X';
                    break;
                case 'P':
                    type='P';
                    break;
                case 'L':
                {
                    type='L';
                    int lpos=2;
                    while(argv[i][lpos])
                    {
                        if(argv[i][lpos] == 'B') 
                            composerType = "BinarySwapComposer";
                        if(argv[i][lpos] == 'P')
                            composerType = "PipelineComposer";
                        if(argv[i][lpos] == 'S')
                            composerType = "SepiaComposer";
                        if(argv[i][lpos] == 'p')
                            pipelinedBufferRead = true;
                        ++lpos;
                    }
                    break;
                }
                case 'M':
                    type='M';
                    break;
                case 'I':
                    type='I';
                    break;
                case 's':
                    stereoMode=1;
                    break;
                case 'c':
                    stereoMode=2;
                    break;
                case 'S':
                    info=true;
                    break;
                case 'e':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    sscanf(opt,"%f",&eyedistance);
                    break;
                case 'z':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    sscanf(opt,"%f",&zeroparallax);
                    break;
                case 'd':
                    clientRendering=false;
                    break;
                case 'v':
                    multiport=true;
                    break;
                case 'x':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    sscanf(opt,"%d",&serverx);
                    break;
                case 'y':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    sscanf(opt,"%d",&servery);
                    break;
                case 'a':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    animName=opt;
                    loadAnim();
                    animate=true;
                    break;
                case 'l':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    if(sscanf(opt,"%d,%d",&animLoops,&animLength) != 2)
                    {
                        animLength = 30;
                        if(sscanf(opt,"%d",&animLoops) != 1)
                        {
                            animLoops = -1;
                        }
                    }
                    break;
                case 'g':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    if(sscanf(opt,"%d,%d,%d,%d",
                              &winwidth,&winheight,&winx,&winy) != 4)
                        sscanf(opt,"%d,%d",&winwidth,&winheight);
                    break;
                case 'G':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    connectionDestination = opt;
                    break;
                case 'i':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    connectionInterface = opt;
                    break;
                default:
                    std::cout << argv[0] 
                              << "-ffile -m -rrows[,cols] -C -M"
                              << std::endl;
                    std::cout << "-m  use multicast" << std::endl
                              << "-G  multicast group" << std::endl
                              << "-i  interface" << std::endl
                              << "-b  service interface" << std::endl
                              << "-M  multi display" << std::endl
#ifdef FRAMEINTERLEAVE
                              << "-I  frame interleave" << std::endl
#endif
                              << "-r  number of display rows" << std::endl
                              << "-C  compose" << std::endl
                              << "-F  sort-first" << std::endl
                              << "-L  sort-last" << std::endl
                              << "-h  this msg" << std::endl
                              << "-s  stereo" << std::endl
                              << "-c  red/cyan stereo" << std::endl
                              << "-e  eye distance" << std::endl
                              << "-z  zero parallax" << std::endl
                              << "-d  disable client rendering"<<std::endl
                              << "-v  use two viewports" << std::endl
                              << "-x  server x resolution" << std::endl
                              << "-y  server y resolution" << std::endl
                              << "-t  subtile size for img composition" << std::endl
                              << "-D  x,y,z duplicate geometry" << std::endl
                              << "-A  Autostart command" << std::endl
                              << "-o  connection parameter string e.g. \"TTL=8\"" << std::endl;
                    return 0;
            }
        }
        else
        {
            servers.push_back(argv[i]);
        }
    }

    OSG::ChangeList::setReadWriteDefault(true);
    OSG::osgInit(argc, argv);
    glutInit(&argc, argv);
    glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
    if(winx >=0 && winy >=0)
        glutInitWindowPosition(winx,winy);
    glutInitWindowSize(winwidth,winheight);
    winid = glutCreateWindow("OpenSG Cluster Client");
    glutKeyboardFunc(key);
    glutReshapeFunc(reshape);
    glutDisplayFunc(display);     
    if(animate)
        glutIdleFunc(display);       
    glutMouseFunc(mouse);   
    glutMotionFunc(motion); 
    ract = OSG::RenderAction::create();
#ifdef OSG_OLD_RENDER_ACTION
    ract->setSortTrans(true);
    ract->setZWriteTrans(true);
    ract->setLocalLights(true);
    ract->setCorrectTwoSidedLighting(true);
#endif

    // clear changelist from prototypes
    OSG::Thread::getCurrentChangeList()->clear();
    
    // create cluster window
    switch(type)
    {
        case 'M': 
            multidisplay=OSG::MultiDisplayWindow::create();
            clusterWindow=multidisplay;
            break;
        case 'X': 
            balancedmultidisplay=OSG::BalancedMultiWindow::create();
            clusterWindow=balancedmultidisplay;
            break;
        case 'F':
            sortfirst=OSG::SortFirstWindow::create();
            if(compose)
                sortfirst->setCompose(true);
            else
                sortfirst->setCompose(false);
            clusterWindow=sortfirst;
            break;
        case 'L':
            sortlast=OSG::SortLastWindow::create();
            if(!composerType.empty())
            {
                OSG::FieldContainerUnrecPtr fcPtr = 
                    OSG::FieldContainerFactory::the()->
                    createContainer(composerType.c_str());
                OSG::ImageComposer *icPtr = 
                    dynamic_cast<OSG::ImageComposer *>(fcPtr.get());
                
                if(icPtr != NULL)
                {
                    if(dynamic_cast<OSG::PipelineComposer *>(icPtr) != NULL)
                    {
                        if(subtilesize>0)
                            dynamic_cast<OSG::PipelineComposer *>(icPtr)->setTileSize(subtilesize);
                        dynamic_cast<OSG::PipelineComposer *>(icPtr)->setPipelined(pipelinedBufferRead);
                    }
                    if(dynamic_cast<OSG::BinarySwapComposer *>(icPtr) != NULL)
                    {
                        if(subtilesize>0)
                            dynamic_cast<OSG::BinarySwapComposer *>(icPtr)->setTileSize(subtilesize);
                    }
                    icPtr->setStatistics(info);
//                        icPtr->setShort(false);
                    sortlast->setComposer(icPtr);
                }
            }
            clusterWindow=sortlast;
            break;
#ifdef FRAMEINTERLEAVE
        case 'I':
            frameinterleave=OSG::FrameInterleaveWindow::create();
            clusterWindow=frameinterleave;
            if(compose)
                frameinterleave->setCompose(true);
            else
                frameinterleave->setCompose(false);
            break;
#endif
        case 'P':
            sortfirst=OSG::SortFirstWindow::create();
            sortfirst->setCompose(false);
            clusterWindow=sortfirst;
            break;
    }
    
    if(!autostart.empty())
        clusterWindow->editMFAutostart()->push_back(autostart);
    
    for(i=0 ; i<int(servers.size()) ; ++i)
        clusterWindow->editMFServers()->push_back(servers[i]);
    if(cols < 0)
        cols = clusterWindow->getMFServers()->size32() / rows;
    switch(type)
    {
        case 'M': 
            multidisplay->setHServers(cols);
            multidisplay->setVServers(rows);
            break;
        case 'X': 
            balancedmultidisplay->setHServers(cols);
            balancedmultidisplay->setVServers(rows);
//                    balancedmultidisplay->setShowBalancing(true);
//            balancedmultidisplay->setShowBalancing(info);
            break;
    }
#ifdef FRAMEINTERLEAVE
    clusterWindow->setInterleave(interleave);
#endif
        
    // create client window
    clientWindow=OSG::GLUTWindow::create();
//        glutReshapeWindow(800,600);
    glutReshapeWindow(winwidth,winheight);
    clientWindow->setGlutId(winid);
    clientWindow->init();
    
    // init scene graph
    init(filenames);
    
    // init client
    clusterWindow->setConnectionType(connectionType);
    // needs to be called before init()!
    clusterWindow->setConnectionParams(connectionParameters);
    if(clientRendering)
    {
        clusterWindow->setClientWindow(clientWindow);
    }
    clusterWindow->setConnectionDestination(connectionDestination);
    clusterWindow->setConnectionInterface(connectionInterface);
    clusterWindow->init();
    if(serverx > 0)
        clusterWindow->resize(serverx,servery);
    else
        clusterWindow->resize(winwidth,winheight);
    clientWindow->resize(winwidth,winheight);

//    OSG::FieldContainerFactory::the()->dump();

    OSG::commitChanges();

    glutMainLoop();

    return 0;
}
示例#19
0
int
main(int argc, char **argv)
{
  int i;

  glutInitWindowSize(600,300);
  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH | GLUT_MULTISAMPLE);

  for (i=1; i<argc; i++) {
    if(!strcmp("-noms", argv[i])) {
      glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
      printf("forcing no multisampling\n");
    } else if(!strcmp("-nomipmaps", argv[i])) {
      useMipmaps = 0;
    } else if(!strcmp("-nearest", argv[i])) {
      linearFiltering = 0;
    }
  }
  glutCreateWindow("sprite blast");
  glewInit();
  glutReshapeFunc(reshape);
  glutDisplayFunc(redraw);
  glutMouseFunc(mouse);
  glutMotionFunc(mouseMotion);
  glutVisibilityFunc(visible);
  glutKeyboardFunc(key);
  glutCreateMenu(menu);
  glutAddMenuEntry("Reset time", 0);
  glutAddMenuEntry("Constant", 1);
  glutAddMenuEntry("Linear", 2);
  glutAddMenuEntry("Quadratic", 3);
  glutAddMenuEntry("Blend on", 4);
  glutAddMenuEntry("Blend off", 5);
  glutAddMenuEntry("Threshold 1", 6);
  glutAddMenuEntry("Threshold 10", 7);
  glutAddMenuEntry("Point smooth on", 8);
  glutAddMenuEntry("Point smooth off", 9);
  glutAddMenuEntry("Point size 16", 10);
  glutAddMenuEntry("Point size 32", 11);
  glutAddMenuEntry("Point size 64", 12);
  glutAddMenuEntry("Toggle spin", 13);
  glutAddMenuEntry("200 points ", 14);
  glutAddMenuEntry("500 points ", 15);
  glutAddMenuEntry("1000 points ", 16);
  glutAddMenuEntry("2000 points ", 17);
  glutAddMenuEntry("Quit", 666);
  glutAttachMenu(GLUT_RIGHT_BUTTON);

  makePointList();
  makeSprite();

  glShadeModel(GL_FLAT);
  glEnable(GL_DEPTH_TEST);
  glEnable(GL_POINT_SMOOTH);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  glPointSize(32.0);
#ifdef GL_ARB_point_parameters
  glPointParameterfvARB(GL_POINT_DISTANCE_ATTENUATION_ARB, theQuad);
#endif

  glutMainLoop();
  return 0;             /* ANSI C requires main to return int. */
}
示例#20
0
Window::Window(int x, int y, int w, int h, string title, int speed,
               double red, double green, double blue,
               bool read_keypresses_from_standard_input /* = false */
              )
{
  m_x = x;
  m_y = y;
  m_w = w;
  m_h = h;
  m_title = title;
  m_read_keypresses_from_standard_input = read_keypresses_from_standard_input;

  if (speed > 100)
    speed = 100;
  if (speed < 1)
    speed = 1;

  // This formula sets up the meaning of the speed
  // Speed is very machine dependent, this may have to be changed
  // for very fast or very slow machine

  // special case, low speeds are really slow for debugging
  if (speed <= 10)
    clock_tick = (11 - speed) * 1000;
  else clock_tick = ((103 - speed) * (103 - speed))/10;

  // glut can be controlled by command line arguments pass to glutInit().
  // In order to simplify argument parsing in gpl.cpp, command line
  // arguments are not passed to glutInit()
  int phony_argc = 1;
  char *phony_argv[2];
  phony_argv[0] = strdup("gpl");
  phony_argv[1] = 0;

  glutInit(&phony_argc,phony_argv);

  glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
  glutInitWindowSize(m_w,m_h);
  glutInitWindowPosition(m_x,m_y);

  glutCreateWindow(m_title.c_str());

  // if we are suppose to read characters from the command line
  // (this is a testing/debugging tool)
  if (m_read_keypresses_from_standard_input)
    // use an idle function to read the commands
    glutIdleFunc(read_keypresses_from_standard_input_callback);

  // redraws all objects if window is changed by windowing system
  glutReshapeFunc(window_reshape_callback);
  glutVisibilityFunc(window_visibility_callback);

  glutDisplayFunc(draw_callback);
  glutTimerFunc(clock_tick, timer_callback, 0);
  glutKeyboardFunc(keyboard_callback);
  glutSpecialFunc(special_callback);

  glutMouseFunc(mouse_callback);
  glutMotionFunc(motion_callback);
  glutPassiveMotionFunc(passive_motion_callback);

  glViewport(0, 0, m_w, m_h);

  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  gluOrtho2D(0, m_w, 0, m_h);
  glClearColor (red, green, blue, 0.0);
}
示例#21
0
文件: curvature.c 项目: xtmacbook/SGI
main(int argc, char *argv[]) {
    GLUquadric *quad;

    glutInit(&argc, argv);
    glutInitWindowSize(winWidth, winHeight);
    glutInitDisplayMode(GLUT_RGBA|GLUT_DEPTH|GLUT_DOUBLE);
    (void)glutCreateWindow("locate");
    glutDisplayFunc(redraw);
    glutReshapeFunc(reshape);
    glutMouseFunc(mouse);
    glutMotionFunc(motion);
    glutKeyboardFunc(key);
    create_menu();

    glClearColor(0.0f, 0.3f, 0.0f, 0.f);
    /* draw a perspective scene */
    glMatrixMode(GL_PROJECTION);
    glFrustum(-100., 100., -100., 100., 300., 600.); 
    glMatrixMode(GL_MODELVIEW);
    /* look at scene from (0, 0, 450) */
    gluLookAt(0., 0., 450., 0., 0., 0., 0., 1., 0.);
    {
    int i;
    float mat[16];
    glGetFloatv(GL_MODELVIEW_MATRIX, mat);
    for(i = 0; i < 4; i++)
	printf("%f %f %f %f\n", mat[4*i+0], mat[4*i+1], mat[4*i+2], mat[4*i+3]);
    }

    glEnable(GL_DEPTH_TEST);

    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glEnable(GL_COLOR_MATERIAL);
    
    glCullFace(GL_BACK);
    glReadBuffer(GL_BACK);
    glDisable(GL_DITHER);

    CHECK_ERROR("end of main");

    glNewList(1, GL_COMPILE);
    glutSolidCube(50.f);
    glEndList();

    glNewList(2, GL_COMPILE);
    glutSolidTeapot(50.f);
    glEndList();

    quad = gluNewQuadric();
    gluQuadricTexture(quad, GL_TRUE);

    glNewList(3, GL_COMPILE);
    gluSphere(quad, 70., 20, 20);
    glEndList();

    gluDeleteQuadric(quad);

    glNewList(4, GL_COMPILE);
    glutSolidTorus(20, 50, 20, 20);
    glEndList();

    glNewList(5, GL_COMPILE);
    glPushMatrix();
    glTranslatef(0.f, -80.f, 0.f);
    cylinder(40, 3, 20, 160);
    glTranslatef(0.f, 20.f, 0.f);
    cylinder(40, 3, 60, 20);
    glTranslatef(0.f, 20.f, 0.f);
    cylinder(40, 3, 30, 20);
    glTranslatef(0.f, 60.f, 0.f);
    cylinder(40, 3, 30, 20);
    glTranslatef(0.f, 20.f, 0.f);
    cylinder(40, 3, 60, 20);
    glPopMatrix();
    glEndList();

    glNewList(6, GL_COMPILE);
    glPushMatrix();
    glTranslatef(0.f, -80.f, 0.f);
    cylinder(40, 3, 80, 160);
    glPopMatrix();
    glEndList();

    maxobject = 6;
    {
    GLubyte* tex;
    int texwid, texht, texcomps;
    tex = (GLubyte*)read_texture("../../data/spheremap.rgb", &texwid, &texht, &texcomps);
    glBindTexture(GL_TEXTURE_2D, 1);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, texwid, texht, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    free(tex);
    }
    {

    GLubyte tex2[1024];
    int i;
    for(i = 0; i < 1024; i++) {
	if ((i/10)&1)
	    tex2[i] = 0;
	else tex2[i] = 255;
    }
    glBindTexture(GL_TEXTURE_2D, 2);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, 1024, 1, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, tex2);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    }

    glutMainLoop();
    return 0;
}
示例#22
0
int	main(int argc, char *argv[])
{
	// Print a summary of the user-interface.
	printf("Welcome to the Adaptive Quadtree Meshing demo.\n");
	printf("by Thatcher Ulrich <[email protected]> Copyright 2000\n\n");
	printf("Use the mouse and keyboard to control the program.  Here's a summary:\n");
	printf(" * mouse-left plus mouse-move rotates the view orientation\n");
	printf(" * mouse-right plus mouse-move moves the viewpoint\n");
	printf(" * both mouse buttons plus mouse-move moves the viewpoint differently\n");
	printf(" * 'w' toggles wireframe mode.  Good for checking out the LOD\n");
	printf(" * '0'-'9' controls the speed of viewpoint motion\n");
	printf(" * 't' toggles texturing (off by default).  Please try it\n");
	printf(" * 'c' toggles backface culling\n");
	printf(" * 'p' fixes the viewpoint at a certain altitude above the terrain\n");
	printf(" * 'm' toggles motion mode\n");
	printf(" * 'd' runs a 1-second benchmark and displays some performance data\n");
	printf(" * '=' increases terrain detail\n");
	printf(" * '-' decreases terrain detail\n");
	printf("\n");
	
	int	i;
	
	root = new quadsquare(&RootCornerData);

/*
	// Sample heightmap data.
	HeightMapInfo	hm;
	hm.XOrigin = 30001;
	hm.ZOrigin = 30001;
	hm.XSize = 50;
	hm.ZSize = 50;
	hm.RowWidth = hm.XSize;
	hm.Scale = 0;
	hm.Data = new float[hm.XSize * hm.ZSize];

	int	i, j;
	for (j = 0; j < hm.ZSize; j++) {
		for (i = 0; i < hm.XSize; i++) {
			if (i == 0 || j == 0 || i == hm.XSize-1 || j == hm.ZSize - 1) hm.Data[i + j * hm.XSize] = 0;	// Force boundary to 0.
			else hm.Data[i + j * hm.XSize] = sin(i * 0.1) * sin(j * 0.1) * 10;
		}
	}

	// Put some heightmap data in the quadtree.
	hm.Scale = 0;
	root->AddHeightMap(RootCornerData, hm);

	hm.Scale = 2;
	hm.XOrigin &= ~((1 << hm.Scale) - 1);
	hm.ZOrigin &= ~((1 << hm.Scale) - 1);
	root->AddHeightMap(RootCornerData, hm);
	
	hm.Scale = 6;
	hm.XOrigin &= ~((1 << hm.Scale) - 1);
	hm.ZOrigin &= ~((1 << hm.Scale) - 1);
	root->AddHeightMap(RootCornerData, hm);
*/

	LoadData();
	
	// Debug info.
	printf("nodes = %d\n", root->CountNodes());
	printf("max error = %g\n", root->RecomputeErrorAndLighting(RootCornerData));

	// Get rid of unnecessary nodes in flat-ish areas.
	printf("Culling unnecessary nodes (detail factor = 25)...\n");
	root->StaticCullData(RootCornerData, 25);

	// Post-cull debug info.
	printf("nodes = %d\n", root->CountNodes());
	printf("max error = %g\n", root->RecomputeErrorAndLighting(RootCornerData));


	// Run the update function a few times before we start rendering
	// to disable unnecessary quadsquares, so the first frame won't
	// be overloaded with tons of triangles.
	for (i = 0; i < 10; i++) {
		root->Update(RootCornerData, (const float*) ViewerLoc, Detail);
	}

	
	//
	// Set up glut.
	//
	glutInit(&argc, argv);

	glutInitWindowSize(640, 480);
	glutInitWindowPosition(0, 0);

	glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);

	int	win_id = glutCreateWindow(argv[0]);
	if (win_id < 0) {
		printf("could not create window...exiting\n");
		exit(1);
	}

	glutReshapeFunc(DisplayReshape);
	glutKeyboardFunc(KeyHandler);
	glutSpecialFunc(SpecialKeyHandler);
	glutMouseFunc(MouseHandler);
	glutMotionFunc(MotionHandler);
	glutIdleFunc(Idle);
	glutDisplayFunc(Display);

	glutMainLoop();

	delete root;

	return 0;
}
示例#23
0
__NS_GLK_END
int      main(int argc, char* argv[])
{
//	gltSetWorkingDirectory(argv[0]);
#ifdef  __USE_GLFW_MM__
#else
	glutInit(&argc, argv);
#endif
	glk::GLContext	 *_context = glk::GLContext::getInstance();
	GLMainEntrySetting(_context);
#ifdef __USE_GLFW_MM__
	glfwInit();
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
	glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

	Size    _size = _context->getWinSize();
	GLFWwindow* window = glfwCreateWindow(_size.width, _size.height, "Learn-OpenGL", nullptr, nullptr);
	if ( ! window )
	{
		printf("Failed to create GLFW window\n");
		glfwTerminate();
		return -1;
	}
	glfwMakeContextCurrent(window);
	glfwSetKeyCallback(window, key_callback);
	int width, height;
	glfwGetFramebufferSize(window, &width, &height);
#else
	glutInitDisplayMode(_context->displayMode);
	glutInitWindowSize((int)_context->winSize.width,(int)_context->winSize.height);
	glutInitWindowPosition((int)_context->winPosition.x,(int)_context->winPosition.y);
	glutCreateWindow("FPS: 0");
	glutReshapeFunc(glk::_static_onChangeSize);
	glutDisplayFunc(glk::_static_OnDraw);
	//鼠标按下释放事件
	glutMouseFunc(glk::_static_mousePressCallback);
	glutMotionFunc(glk::_static_mouseMotionCallback);
	//键盘事件
	glutKeyboardFunc(glk::_static_keyPressCallback);
	glutKeyboardUpFunc(glk::_static_keyReleaseCallback);
	glutSpecialFunc(glk::_static_keySpecialPressCallback);
	glutSpecialUpFunc(glk::_static_keySpecialReleaseCallback);
#endif
	glewExperimental = GL_TRUE;
	GLenum err = glewInit();
	if (GLEW_OK != err) {
		fprintf(stderr, "GLEW Error: %s\n", glewGetErrorString(err));
		return 1;
	}
#ifdef __USE_GLFW_MM__
	glViewport(0, 0, width, height);
#endif
//init函数必须实现,必须调用初始化函数
	_context->init(_context);
#ifdef __USE_GLFW_MM__
	float            _origin_time = glfwGetTime();
	glBindVertexArray(0);
	while (!glfwWindowShouldClose(window))
	{
		float      _now_time = glfwGetTime();
		float      _elapse_time = _now_time - _origin_time;
		_origin_time = _now_time;
		glfwPollEvents();
		_context->update(_context,_elapse_time);
		_context->draw(_context);
		glfwSwapBuffers(window);
	}
#else
	glutTimerFunc(34, glk::_static_OnUpdate, 0);

	glutMainLoop();
#endif
	if (_context->finalize)//程序退出时的清理
		       _context->finalize(_context);
	if (_context->userObject)//释放申请的内存
		      free(_context->userObject);
	glk::GLCacheManager::getInstance()->~GLCacheManager();
	glk::EventManager::getInstance()->~EventManager();
#ifdef __USE_GLFW_MM__
	glfwTerminate();
	return 0;
#endif
	return 0;
}
示例#24
0
int main(int argc, char **argv)
{
    int array_size_2d,totpoints,i;
    float rcol,gcol,bcol;

    FILE *fp_col;

    // The following parameters are usually read from a file, but
    // hard code them for the demo:
    ni=320;
    nj=112;
    vxin=0.04;
    roout=1.0;
    tau=0.51;
    // End of parameter list

    // Write parameters to screen
    printf ("ni = %d\n", ni);
    printf ("nj = %d\n", nj);
    printf ("vxin = %f\n", vxin);
    printf ("roout = %f\n", roout);
    printf ("tau = %f\n", tau);
    

    totpoints=ni*nj;    
    array_size_2d=ni*nj*sizeof(float);

    // Allocate memory for arrays
    
    f0 = malloc(array_size_2d);
    f1 = malloc(array_size_2d);
    f2 = malloc(array_size_2d);
    f3 = malloc(array_size_2d);
    f4 = malloc(array_size_2d);
    f5 = malloc(array_size_2d);
    f6 = malloc(array_size_2d);
    f7 = malloc(array_size_2d);
    f8 = malloc(array_size_2d);

    tmpf0 = malloc(array_size_2d);
    tmpf1 = malloc(array_size_2d);
    tmpf2 = malloc(array_size_2d);
    tmpf3 = malloc(array_size_2d);
    tmpf4 = malloc(array_size_2d);
    tmpf5 = malloc(array_size_2d);
    tmpf6 = malloc(array_size_2d);
    tmpf7 = malloc(array_size_2d);
    tmpf8 = malloc(array_size_2d);

    plotvar = malloc(array_size_2d);
    
    plot_rgba = malloc(ni*nj*sizeof(unsigned int));

    solid = malloc(ni*nj*sizeof(int));

    //
    // Some factors used to calculate the f_equilibrium values
    // 
    faceq1 = 4.f/9.f;
    faceq2 = 1.f/9.f;
    faceq3 = 1.f/36.f;


    //
    // Initialise f's by setting them to the f_equilibirum values assuming
    // that the whole domain is at velocity vx=vxin vy=0 and density ro=roout
    //
    for (i=0; i<totpoints; i++) {
	f0[i] = faceq1 * roout * (1.f                             - 1.5f*vxin*vxin);
	f1[i] = faceq2 * roout * (1.f + 3.f*vxin + 4.5f*vxin*vxin - 1.5f*vxin*vxin);
	f2[i] = faceq2 * roout * (1.f                             - 1.5f*vxin*vxin);
	f3[i] = faceq2 * roout * (1.f - 3.f*vxin + 4.5f*vxin*vxin - 1.5f*vxin*vxin);
	f4[i] = faceq2 * roout * (1.f                             - 1.5f*vxin*vxin);
	f5[i] = faceq3 * roout * (1.f + 3.f*vxin + 4.5f*vxin*vxin - 1.5f*vxin*vxin);
	f6[i] = faceq3 * roout * (1.f - 3.f*vxin + 4.5f*vxin*vxin - 1.5f*vxin*vxin);
	f7[i] = faceq3 * roout * (1.f - 3.f*vxin + 4.5f*vxin*vxin - 1.5f*vxin*vxin);
	f8[i] = faceq3 * roout * (1.f + 3.f*vxin + 4.5f*vxin*vxin - 1.5f*vxin*vxin);
	plotvar[i] = vxin;
	solid[i] = 1;
    }

    //
    // Read in colourmap data for OpenGL display 
    //
    fp_col = fopen("cmap.dat","r");
    if (fp_col==NULL) {
	printf("Error: can't open cmap.dat \n");
	return 1;
    }
    // allocate memory for colourmap (stored as a linear array of int's)
    fscanf (fp_col, "%d", &ncol);
    cmap_rgba = (unsigned int *)malloc(ncol*sizeof(unsigned int));
    // read colourmap and store as int's
    for (i=0;i<ncol;i++){
	fscanf(fp_col, "%f%f%f", &rcol, &gcol, &bcol);
	cmap_rgba[i]=((int)(255.0f) << 24) | // convert colourmap to int
	    ((int)(bcol * 255.0f) << 16) |
	    ((int)(gcol * 255.0f) <<  8) |
	    ((int)(rcol * 255.0f) <<  0);
    }
    fclose(fp_col);


    //
    // Iinitialise OpenGL display - use glut
    //
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
    glutInitWindowSize(ni, nj);      // Window of ni x nj pixels
    glutInitWindowPosition(50, 50);  // position
    glutCreateWindow("2D LB");       // title

    // Check for OpenGL extension support 
    printf("Loading extensions: %s\n", glewGetErrorString(glewInit()));
    if(!glewIsSupported(
                        "GL_VERSION_2_0 " 
                        "GL_ARB_pixel_buffer_object "
                        "GL_EXT_framebuffer_object "
                        )){
        fprintf(stderr, "ERROR: Support for necessary OpenGL extensions missing.");
        fflush(stderr);
        return;
    }

    // Set up view
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0,ni,0.,nj, -200.0, 200.0);


    // Create texture which we use to display the result and bind to gl_Tex
    glEnable(GL_TEXTURE_2D);
    glGenTextures(1, &gl_Tex);                     // Generate 2D texture
    glBindTexture(GL_TEXTURE_2D, gl_Tex);          // bind to gl_Tex
    // texture properties:
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, ni, nj, 0, 
                 GL_RGBA, GL_UNSIGNED_BYTE, NULL);


    // Create pixel buffer object and bind to gl_PBO. We store the data we want to
    // plot in memory on the graphics card - in a "pixel buffer". We can then 
    // copy this to the texture defined above and send it to the screen
    glGenBuffers(1, &gl_PBO);
    glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, gl_PBO);
    printf("Buffer created.\n");
    

    // Set the call-back functions and start the glut loop
    printf("Starting GLUT main loop...\n");
    glutDisplayFunc(display);
    glutReshapeFunc(resize);
    glutIdleFunc(display);
    glutMouseFunc(mouse);
    glutMotionFunc(mouse_motion); 
    glutMainLoop();

    return 0;
}
示例#25
0
void main(int argc, char **argv)
{
  // init glut

  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH | GLUT_MULTISAMPLE);

  // create the window

  glutCreateWindow("PQP Demo - Falling");

  // set OpenGL graphics state -- material props, perspective, etc.

  init_viewer_window();

  // set the callbacks

  glutDisplayFunc(cb_display);
  glutMouseFunc(cb_mouse);
  glutMotionFunc(cb_motion);  
  glutKeyboardFunc(cb_keyboard);
  glutIdleFunc(cb_idle);

  // create models

  FILE *fp;
  int ntris, i;
  double a,b,c;
  PQP_REAL p1[3],p2[3],p3[3];

  // model 1

  torus1_drawn = new Model("torus1.tris");

  torus1_tested = new PQP_Model();

  fp = fopen("torus1.tris","r");
  fscanf(fp,"%d",&ntris);

  torus1_tested->BeginModel();
  for (i = 0; i < ntris; i++)
  {
    fscanf(fp,"%lf %lf %lf",&a,&b,&c);
    p1[0] = (PQP_REAL)a;
    p1[1] = (PQP_REAL)b;
    p1[2] = (PQP_REAL)c;
    fscanf(fp,"%lf %lf %lf",&a,&b,&c);
    p2[0] = (PQP_REAL)a;
    p2[1] = (PQP_REAL)b;
    p2[2] = (PQP_REAL)c;
    fscanf(fp,"%lf %lf %lf",&a,&b,&c);
    p3[0] = (PQP_REAL)a;
    p3[1] = (PQP_REAL)b;
    p3[2] = (PQP_REAL)c;
    torus1_tested->AddTri(p1,p2,p3,i);
  }
  torus1_tested->EndModel();  

  fclose(fp);

  // model 2

  torus2_drawn = new Model("torus2.tris");

  torus2_tested = new PQP_Model();

  fp = fopen("torus2.tris","r");
  fscanf(fp,"%d",&ntris);

  torus2_tested->BeginModel();
  for (i = 0; i < ntris; i++)
  {
    fscanf(fp,"%lf %lf %lf",&a,&b,&c);
    p1[0] = (PQP_REAL)a;
    p1[1] = (PQP_REAL)b;
    p1[2] = (PQP_REAL)c;
    fscanf(fp,"%lf %lf %lf",&a,&b,&c);
    p2[0] = (PQP_REAL)a;
    p2[1] = (PQP_REAL)b;
    p2[2] = (PQP_REAL)c;
    fscanf(fp,"%lf %lf %lf",&a,&b,&c);
    p3[0] = (PQP_REAL)a;
    p3[1] = (PQP_REAL)b;
    p3[2] = (PQP_REAL)c;
    torus2_tested->AddTri(p1,p2,p3,i);
  }
  torus2_tested->EndModel();  

  fclose(fp);

  // load paths

  LoadPath(R1,T1,"torus1.path");
  LoadPath(R2,T2,"torus2.path");

  // print instructions

  printf("PQP Demo - Falling:\n"
         "Press:\n"
         "0 - no proximity query, just animation\n"
         "1 - collision query\n"
         "    overlapping triangles shown in red.\n"
         "2 - distance query\n"
         "    closest points connected by a line.\n"
         "3 - tolerance query\n"
         "    reduce/increase tolerance with -/= keys.\n"
         "    models turn blue when closer than the tolerance.\n"
         "any other key to toggle animation on/off\n");

  // Enter the main loop.

  glutMainLoop();
}
示例#26
0
// Main
int main(int argc, char *argv[])
{
    TwBar *bar; // Pointer to the tweak bar
    float axis[] = { 0.7f, 0.7f, 0.0f }; // initial model rotation
    float angle = 0.8f;

    // Initialize GLUT
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
    glutInitWindowSize(640, 480);
    glutCreateWindow("AntTweakBar simple example using GLUT");
    glutCreateMenu(NULL);

    // Set GLUT callbacks
    glutDisplayFunc(Display);
    glutReshapeFunc(Reshape);
    atexit(Terminate);  // Called after glutMainLoop ends

    // Initialize AntTweakBar
    TwInit(TW_OPENGL, NULL);

    // Set GLUT event callbacks
    // - Directly redirect GLUT mouse button events to AntTweakBar
    glutMouseFunc((GLUTmousebuttonfun)TwEventMouseButtonGLUT);
    // - Directly redirect GLUT mouse motion events to AntTweakBar
    glutMotionFunc((GLUTmousemotionfun)TwEventMouseMotionGLUT);
    // - Directly redirect GLUT mouse "passive" motion events to AntTweakBar (same as MouseMotion)
    glutPassiveMotionFunc((GLUTmousemotionfun)TwEventMouseMotionGLUT);
    // - Directly redirect GLUT key events to AntTweakBar
    glutKeyboardFunc((GLUTkeyboardfun)TwEventKeyboardGLUT);
    // - Directly redirect GLUT special key events to AntTweakBar
    glutSpecialFunc((GLUTspecialfun)TwEventSpecialGLUT);
    // - Send 'glutGetModifers' function pointer to AntTweakBar;
    //   required because the GLUT key event functions do not report key modifiers states.
    TwGLUTModifiersFunc(glutGetModifiers);

    // Create some 3D objects (stored in display lists)
    glNewList(SHAPE_TEAPOT, GL_COMPILE);
    glutSolidTeapot(1.0);
    glEndList();
    glNewList(SHAPE_TORUS, GL_COMPILE);
    glutSolidTorus(0.3, 1.0, 16, 32);
    glEndList();
    glNewList(SHAPE_CONE, GL_COMPILE);
    glutSolidCone(1.0, 1.5, 64, 4);
    glEndList();

    // Create a tweak bar
    bar = TwNewBar("TweakBar");
    TwDefine(" GLOBAL help='This example shows how to integrate AntTweakBar with GLUT and OpenGL.' "); // Message added to the help bar.
    TwDefine(" TweakBar size='200 400' color='96 216 224' "); // change default tweak bar size and color

    // Add 'g_Zoom' to 'bar': this is a modifable (RW) variable of type TW_TYPE_FLOAT. Its key shortcuts are [z] and [Z].
    TwAddVarRW(bar, "Zoom", TW_TYPE_FLOAT, &g_Zoom, 
               " min=0.01 max=2.5 step=0.01 keyIncr=z keyDecr=Z help='Scale the object (1=original size).' ");

    // Add 'g_Rotation' to 'bar': this is a variable of type TW_TYPE_QUAT4F which defines the object's orientation
    TwAddVarRW(bar, "ObjRotation", TW_TYPE_QUAT4F, &g_Rotation, 
               " label='Object rotation' opened=true help='Change the object orientation.' ");

    // Add callback to toggle auto-rotate mode (callback functions are defined above).
    TwAddVarCB(bar, "AutoRotate", TW_TYPE_BOOL32, SetAutoRotateCB, GetAutoRotateCB, NULL, 
               " label='Auto-rotate' key=space help='Toggle auto-rotate mode.' ");

    // Add 'g_LightMultiplier' to 'bar': this is a variable of type TW_TYPE_FLOAT. Its key shortcuts are [+] and [-].
    TwAddVarRW(bar, "Multiplier", TW_TYPE_FLOAT, &g_LightMultiplier, 
               " label='Light booster' min=0.1 max=4 step=0.02 keyIncr='+' keyDecr='-' help='Increase/decrease the light power.' ");

    // Add 'g_LightDirection' to 'bar': this is a variable of type TW_TYPE_DIR3F which defines the light direction
    TwAddVarRW(bar, "LightDir", TW_TYPE_DIR3F, &g_LightDirection, 
               " label='Light direction' opened=true help='Change the light direction.' ");

    // Add 'g_MatAmbient' to 'bar': this is a variable of type TW_TYPE_COLOR3F (3 floats color, alpha is ignored)
    // and is inserted into a group named 'Material'.
    TwAddVarRW(bar, "Ambient", TW_TYPE_COLOR3F, &g_MatAmbient, " group='Material' ");

    // Add 'g_MatDiffuse' to 'bar': this is a variable of type TW_TYPE_COLOR3F (3 floats color, alpha is ignored)
    // and is inserted into group 'Material'.
    TwAddVarRW(bar, "Diffuse", TW_TYPE_COLOR3F, &g_MatDiffuse, " group='Material' ");

    // Add the enum variable 'g_CurrentShape' to 'bar'
    // (before adding an enum variable, its enum type must be declared to AntTweakBar as follow)
    {
        // ShapeEV associates Shape enum values with labels that will be displayed instead of enum values
        TwEnumVal shapeEV[NUM_SHAPES] = { {SHAPE_TEAPOT, "Teapot"}, {SHAPE_TORUS, "Torus"}, {SHAPE_CONE, "Cone"} };
        // Create a type for the enum shapeEV
        TwType shapeType = TwDefineEnum("ShapeType", shapeEV, NUM_SHAPES);
        // add 'g_CurrentShape' to 'bar': this is a variable of type ShapeType. Its key shortcuts are [<] and [>].
        TwAddVarRW(bar, "Shape", shapeType, &g_CurrentShape, " keyIncr='<' keyDecr='>' help='Change object shape.' ");
    }

    // Store time
    g_RotateTime = GetTimeMs();
    // Init rotation
    SetQuaternionFromAxisAngle(axis, angle, g_Rotation);
    SetQuaternionFromAxisAngle(axis, angle, g_RotateStart);

    // Call the GLUT main loop
    glutMainLoop();

    return 0;
}
示例#27
0
int main(int argc, char** argv)
	{
	// Initialize Glut
#ifdef __PPCGEKKO__
	printf("Press 1,2,+,-,a,HOME to drop boxes. Press b to shoot a box.\nArrows camera.\n");
#else
	printf("Press 1-6 to drop boxes. Press w to shoot a box.\nArrows and mouse move camera.\n");
	printf("Press p to pause the simulation.\n");
#endif

#if defined(_XBOX) || defined(__CELLOS_LV2__)
	glutRemapButtonExt(0, 'w', false); // A/X to shoot box
	glutRemapButtonExt(1, '1', false); // B/O, X/S, Y/T shifted/unshifted to drop boxes
	glutRemapButtonExt(2, '2', false);
	glutRemapButtonExt(3, '3', false);
	glutRemapButtonExt(1, '4', true);
	glutRemapButtonExt(2, '5', true);
	glutRemapButtonExt(3, '6', true);
#endif

#ifdef __PPCGEKKO__	
	glutRemapButtonExt('a','1');
	glutRemapButtonExt('b','w');
	glutRemapButtonExt('1','2');
	glutRemapButtonExt('2','3');
	glutRemapButtonExt('+','4');
	glutRemapButtonExt('-','5');
	glutRemapButtonExt(GLUT_KEY_HOME,'6');
	glutRemapButtonExt(GLUT_KEY_UP,101);
	glutRemapButtonExt(GLUT_KEY_DOWN,103);
	glutRemapButtonExt(GLUT_KEY_LEFT,100);
	glutRemapButtonExt(GLUT_KEY_RIGHT,102);
#endif

	glutInit(&argc, argv);
	glutInitWindowSize(512, 512);
	glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
	gMainHandle = glutCreateWindow("SampleMaterials");
	glutSetWindow(gMainHandle);
	glutDisplayFunc(RenderCallback);
	glutReshapeFunc(ReshapeCallback);
	glutIdleFunc(IdleCallback);
	glutKeyboardFunc(KeyboardCallback);
	glutSpecialFunc(ArrowKeyCallback);
	glutMouseFunc(MouseCallback);
	glutMotionFunc(MotionCallback);
	MotionCallback(0,0);
	
	atexit(ExitCallback);
	
	// Setup default render states
	glClearColor(0.3f, 0.4f, 0.5f, 1.0);
	glEnable(GL_DEPTH_TEST);
	glEnable(GL_COLOR_MATERIAL);
	glEnable(GL_CULL_FACE);
	
	// Setup lighting
	glEnable(GL_LIGHTING);
	float AmbientColor[]	= { 0.0f, 0.1f, 0.2f, 0.0f };		glLightfv(GL_LIGHT0, GL_AMBIENT, AmbientColor);
	float DiffuseColor[]	= { 1.0f, 1.0f, 1.0f, 0.0f };		glLightfv(GL_LIGHT0, GL_DIFFUSE, DiffuseColor);
	float SpecularColor[]	= { 0.0f, 0.0f, 0.0f, 0.0f };		glLightfv(GL_LIGHT0, GL_SPECULAR, SpecularColor);
	float Position[]		= { 100.0f, 100.0f, 400.0f, 1.0f };		glLightfv(GL_LIGHT0, GL_POSITION, Position);
	glEnable(GL_LIGHT0);

	// Initialize physics scene and start the application main loop if scene was created
	if (InitNx())
		glutMainLoop();

	return 0;
	}
示例#28
0
/**
  * POINT D'ENTREE PRINCIPAL
  **/
int main(int argc, char* argv[])
{
	LogConsole::createInstance();

	int screen_width = 1280;
	int screen_height = 720;

	glutInit(&argc, argv);
	glutInitContextVersion(3, 0);
	glutSetOption(
		GLUT_ACTION_ON_WINDOW_CLOSE,
		GLUT_ACTION_GLUTMAINLOOP_RETURNS
		);

	glutInitWindowSize(screen_width, screen_height);
	glutInitWindowPosition(0, 0);
	glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA | GLUT_MULTISAMPLE);

	glEnable(GL_MULTISAMPLE);

	Log::log(Log::ENGINE_INFO, (toString(argc) + " arguments en ligne de commande.").c_str());
	bool gameMode = true;
	for (int i = 0; i < argc; i++)
	{
		if (argv[i][0] == 'w')
		{
			Log::log(Log::ENGINE_INFO, "Arg w mode fenetre.\n");
			gameMode = false;
		}
	}

	if (gameMode)
	{
		int width = glutGet(GLUT_SCREEN_WIDTH);
		int height = glutGet(GLUT_SCREEN_HEIGHT);

		char gameModeStr[200];
		sprintf(gameModeStr, "%dx%d:[email protected]", width, height);
		glutGameModeString(gameModeStr);
		g_main_window_id = glutEnterGameMode();
	}
	else
	{
		g_main_window_id = glutCreateWindow("MyNecraft");
		glutReshapeWindow(screen_width, screen_height);
	}

	if (g_main_window_id < 1)
	{
		Log::log(Log::ENGINE_ERROR, "Erreur creation de la fenetre.");
		exit(EXIT_FAILURE);
	}

	GLenum glewInitResult = glewInit();

	if (glewInitResult != GLEW_OK)
	{
		Log::log(Log::ENGINE_ERROR, ("Erreur init glew " + std::string((char*)glewGetErrorString(glewInitResult))).c_str());
		_cprintf("ERROR : %s", glewGetErrorString(glewInitResult));
		exit(EXIT_FAILURE);
	}

	//Affichage des capacités du système
	Log::log(Log::ENGINE_INFO, ("OpenGL Version : " + std::string((char*)glGetString(GL_VERSION))).c_str());

	glutDisplayFunc(update);
	glutReshapeFunc(resizeFunction);
	glutKeyboardFunc(keyboardDownFunction);
	glutKeyboardUpFunc(keyboardUpFunction);
	glutSpecialFunc(specialDownFunction);
	glutSpecialUpFunc(specialUpFunction);
	glutMouseFunc(mouseFunction);
	glutMotionFunc(mouseMoveActiveFunction);
	glutPassiveMotionFunc(mouseMovePassiveFunction);
	glutIgnoreKeyRepeat(1);

	//Initialisation du renderer
	g_renderer = NYRenderer::getInstance();
	g_renderer->setRenderObjectFun(renderObjects);
	g_renderer->setRender2DFun(render2d);
	//g_renderer->setLightsFun(setLights);
	g_renderer->setLightsFun(setLightsBasedOnDayTime);
	//g_renderer->setBackgroundColor(NYColor(0, 181.f / 255.f, 221.f / 255.f, 1));
	g_program = g_renderer->createProgram("shaders/psbase.glsl", "shaders/vsbase.glsl");
	g_renderer->initialise(true);

	//On applique la config du renderer
	glViewport(0, 0, g_renderer->_ScreenWidth, g_renderer->_ScreenHeight);
	g_renderer->resize(g_renderer->_ScreenWidth, g_renderer->_ScreenHeight);

	//Ecran de jeu
	uint16 x = 10;
	uint16 y = 10;
	g_screen_jeu = new GUIScreen();

	g_screen_manager = new GUIScreenManager();

	//Bouton pour afficher les params
	BtnParams = new GUIBouton();
	BtnParams->Titre = std::string("Params");
	BtnParams->X = x;
	BtnParams->setOnClick(clickBtnParams);
	g_screen_jeu->addElement(BtnParams);

	y += BtnParams->Height + 1;

	LabelFps = new GUILabel();
	LabelFps->Text = "FPS";
	LabelFps->X = x;
	LabelFps->Y = y;
	LabelFps->Visible = true;
	g_screen_jeu->addElement(LabelFps);

	y += BtnParams->Height + 1;

	LabelCam = new GUILabel();
	LabelCam->Text = "Position";
	LabelCam->X = x;
	LabelCam->Y = y;
	LabelCam->Visible = true;
	g_screen_jeu->addElement(LabelCam);

	//Ecran de parametrage
	x = 10;
	y = 10;
	g_screen_params = new GUIScreen();

	GUIBouton * btnClose = new GUIBouton();
	btnClose->Titre = std::string("Close");
	btnClose->X = x;
	btnClose->setOnClick(clickBtnCloseParam);
	g_screen_params->addElement(btnClose);

	y += btnClose->Height + 1;
	y += 10;
	x += 10;

	GUILabel * label = new GUILabel();
	label->X = x;
	label->Y = y;
	label->Text = "Param :";
	g_screen_params->addElement(label);

	y += label->Height + 1;

	g_slider = new GUISlider();
	g_slider->setPos(x, y);
	g_slider->setMaxMin(1, 0);
	g_slider->Visible = true;
	g_screen_params->addElement(g_slider);

	y += g_slider->Height + 1;
	y += 10;

	//Ecran a rendre
	g_screen_manager->setActiveScreen(g_screen_jeu);

	//Init Camera
	g_renderer->_Camera->setPosition(NYVert3Df(-300, -300, 1300));
	g_renderer->_Camera->setLookAt(NYVert3Df(1300, 1300, 500));


	//Fin init moteur

	//Init application



	//Init Timer
	g_timer = new NYTimer();

	//On start
	g_timer->start();

	//Generation du monde
	g_world = new NYWorld();
	g_world->_FacteurGeneration = 1;
	g_world->init_world();

	avatar = new NYAvatar(g_renderer->_Camera, g_world, NYVert3Df(1, 1, 900));

	glutMainLoop();

	return 0;
}
示例#29
0
int main(int argc, char** argv) 
{
		g_filename=argv[1];


//	testTriangulation();
//downsampling();

//	float error=0.005;
//printf("value=%f\n",-error*log2(error)-(1-error)*log2(1-error)+error*log2(359));
//getchar();

readPatches_region();


	VECTOR3 minB, maxB; 

	osuflow = new OSUFlowEntropy(); 
	//printf("read file %s\n", argv[1]); 
//	g_filename=argv[1];
	osuflow->LoadData((const char*)argv[1], true);//, minB, maxB); //true: a steady flow field 

	osuflow->Boundary(minLen, maxLen); // get the boundary 
	minB[0] = minLen[0]; minB[1] = minLen[1];  minB[2] = minLen[2];
	maxB[0] = maxLen[0]; maxB[1] = maxLen[1];  maxB[2] = maxLen[2];
	osuflow->SetBoundary(minB, maxB);  // set the boundary. just to test
	// the subsetting feature of OSUFlow
	printf(" volume boundary X: [%f %f] Y: [%f %f] Z: [%f %f]\n", 
		minLen[0], maxLen[0], minLen[1], maxLen[1], 
		minLen[2], maxLen[2]); 

	center[0] = (minLen[0]+maxLen[0])/2.0; 
	center[1] = (minLen[1]+maxLen[1])/2.0; 
	center[2] = (minLen[2]+maxLen[2])/2.0; 
	printf("center is at %f %f %f \n", center[0], center[1], center[2]); 
	len[0] = maxLen[0]-minLen[0]; 
	len[1] = maxLen[1]-minLen[1]; 
	len[2] = maxLen[2]-minLen[2]; 

	int xdim,ydim,zdim;
	osuflow->GetFlowField()->getDimension(xdim,ydim,zdim);
	//	reseeding(xdim, ydim,"Time00_fake_3D.vec.data", "Time02_fake_3D.vec.data","seed1.data","seed2.data");

	glutInit(&argc, argv); 
	glutInitDisplayMode(GLUT_RGB|GLUT_DOUBLE|GLUT_DEPTH); 
	glutInitWindowSize(winWidth,winHeight); 

	glutCreateWindow("Display streamlines"); 
	glutPositionWindow(700,50);
	glutDisplayFunc(display); 
	//  glutIdleFunc(idle); 
	glutTimerFunc(10, timer, 0); 
	glutMouseFunc(mymouse); 
	glutMotionFunc(mymotion);
	glutKeyboardFunc(mykey); 
	//SetShaders();

	#if	ENTER_GLUT_LOOP	
	glutMainLoop();

	#else
	compute_streamlines();
	#endif
	return 0;
}
示例#30
0
int main(int argc, char** argv)
{
	testCount = 0;
	while (g_testEntries[testCount].createFcn != NULL)
	{
		++testCount;
	}

	testIndex = b2Clamp(testIndex, 0, testCount-1);
	testSelection = testIndex;

	entry = g_testEntries + testIndex;

	test = entry->createFcn();

	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
	glutInitWindowSize(width, height);
	char title[32];
	sprintf(title, "Box2D Version %d.%d.%d", b2_version.major, b2_version.minor, b2_version.revision);
	mainWindow = glutCreateWindow(title);
	//glutSetOption (GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS);

	glutDisplayFunc(SimulationLoop);

/*	int theConnection=0;
	theConnection=setup_rlglue_network();
	runEnvironmentEventLoop(theConnection);*/

	GLUI_Master.set_glutReshapeFunc(Resize);  
	GLUI_Master.set_glutKeyboardFunc(Keyboard);
	GLUI_Master.set_glutSpecialFunc(KeyboardSpecial);
	GLUI_Master.set_glutMouseFunc(Mouse);
#ifdef FREEGLUT
	glutMouseWheelFunc(MouseWheel);
#endif
	glutMotionFunc(MouseMotion);

	glui = GLUI_Master.create_glui_subwindow( mainWindow, 
		GLUI_SUBWINDOW_RIGHT );

	glui->add_statictext("Tests");
	GLUI_Listbox* testList =
		glui->add_listbox("", &testSelection);

	glui->add_separator();

	GLUI_Spinner* velocityIterationSpinner =
		glui->add_spinner("Vel Iters", GLUI_SPINNER_INT, &settings.velocityIterations);
	velocityIterationSpinner->set_int_limits(1, 500);

	GLUI_Spinner* positionIterationSpinner =
		glui->add_spinner("Pos Iters", GLUI_SPINNER_INT, &settings.positionIterations);
	positionIterationSpinner->set_int_limits(0, 100);

	GLUI_Spinner* hertzSpinner =
		glui->add_spinner("Hertz", GLUI_SPINNER_FLOAT, &settingsHz);

	hertzSpinner->set_float_limits(5.0f, 200.0f);

	glui->add_checkbox("Warm Starting", &settings.enableWarmStarting);
	glui->add_checkbox("Time of Impact", &settings.enableContinuous);

	//glui->add_separator();

	GLUI_Panel* drawPanel =	glui->add_panel("Draw");
	glui->add_checkbox_to_panel(drawPanel, "Shapes", &settings.drawShapes);
	glui->add_checkbox_to_panel(drawPanel, "Joints", &settings.drawJoints);
	glui->add_checkbox_to_panel(drawPanel, "AABBs", &settings.drawAABBs);
	glui->add_checkbox_to_panel(drawPanel, "Pairs", &settings.drawPairs);
	glui->add_checkbox_to_panel(drawPanel, "Contact Points", &settings.drawContactPoints);
	glui->add_checkbox_to_panel(drawPanel, "Contact Normals", &settings.drawContactNormals);
	glui->add_checkbox_to_panel(drawPanel, "Contact Forces", &settings.drawContactForces);
	glui->add_checkbox_to_panel(drawPanel, "Friction Forces", &settings.drawFrictionForces);
	glui->add_checkbox_to_panel(drawPanel, "Center of Masses", &settings.drawCOMs);
	glui->add_checkbox_to_panel(drawPanel, "Statistics", &settings.drawStats);

	int32 testCount = 0;
	TestEntry* e = g_testEntries;
	while (e->createFcn)
	{
		testList->add_item(testCount, e->name);
		++testCount;
		++e;
	}

	glui->add_button("Pause", 0, Pause);
	glui->add_button("Single Step", 0, SingleStep);
	glui->add_button("Restart", 0, Restart);

	glui->add_button("Quit", 0,(GLUI_Update_CB)exit);
	glui->set_main_gfx_window( mainWindow );

	// Use a timer to control the frame rate.
	glutTimerFunc(framePeriod, Timer, 0);

////////////////////////////////////////////////////////////////////////////////////////////
	/*const char *task_spec;
	printf("\nThis is a RL Test program(Start)\n");
	task_spec = RL_init();
	printf("\nTASK SPEC : %s\n",task_spec);
   	printf("Starting offline demo\n----------------------------\nWill alternate learning for 25 episodes, then freeze policy and evaluate for 10 episodes.\n\n");
	printf("After Episode\tMean Return\tStandard Deviation\n-------------------------------------------------------------------------\n");

	oa = RL_start();

	RL_agent_message("load_policy results.dat");
	RL_agent_message("freeze learning");*/

	const char* task_spec;
	task_spec = env_init();
	agent_init(task_spec);

////////////////////////////////////////////////////////////////////////////////////////////
/*
	agent_message("load_policy results.dat");
	agent_message("freeze learning");*/

	glutMainLoop();

	return 0;
}