Exemplo n.º 1
0
void keyboard(unsigned char key, int x, int y)
{
    switch(key) {
        case 'q': case 'Q': case 27:
            free_resources();
            exit(EXIT_SUCCESS);
        case ' ':
            active =! active;
            break;
        case '+':
            amplitude *= 1.5;
            setupTexture();
            break;
        case '-':
            amplitude /= 1.5;
            setupTexture();
            break;
        case 'z':
            camera_distance /= 1.1;
            break;
        case 'Z':
            camera_distance *= 1.1;
            break;
        case 'g':
            if(grid < N-10)
                grid += 10;
            setupTexture();
            break;
        case 'G':
            if(grid > 10)
                grid -= 10;
            setupTexture();
            break;
    }
}
Exemplo n.º 2
0
void special(int key, int x, int y)
{
    switch(key) {
        case GLUT_KEY_F1:
            interpolate = !interpolate;
            break;
        case GLUT_KEY_F2:
            clamp = !clamp;
            break;
        case GLUT_KEY_F3:
            rotate = !rotate;
            break;
        case GLUT_KEY_F4:
            polygonoffset = !polygonoffset;
            break;
        case GLUT_KEY_F5:
            mode = 0;
            setupTexture();
            break;
        case GLUT_KEY_F6:
            mode = 1;
            setupTexture();
            break;
        case GLUT_KEY_F7:
            mode = 2;
            setupTexture();
            break;
        case GLUT_KEY_F8:
            mode = 3;
			setupTexture();
             break;
        case GLUT_KEY_LEFT:
            texture_offset_x -= 0.03;
            break;
        case GLUT_KEY_RIGHT:
            texture_offset_x += 0.03;
            break;
        case GLUT_KEY_UP:
            texture_offset_y += 0.03;
            break;
        case GLUT_KEY_DOWN:
            texture_offset_y -= 0.03;
            break;
        case GLUT_KEY_PAGE_UP:
            texture_scale *= 1.5;
            break;
        case GLUT_KEY_PAGE_DOWN:
            texture_scale /= 1.5;
            break;
        case GLUT_KEY_HOME:
            camera_angle = PI/4;
            camera_distance = 3.0f;
            texture_angle = 0.0f;
            texture_offset_x = 0.0f;
            texture_offset_y = 0.0f;
            texture_scale = 1.0f;
            break;
    }
    glutPostRedisplay();
}
Exemplo n.º 3
0
int main(int argc, char **argv) 
{		
	if(argc < 2)
	{
		printf("Usage: myChip8.exe chip8application\n\n");
		return 1;
	}

	// Load game
	if(!LoadApp(argv[1]))		
		return 1;
		
    // Setup OpenGLabclixu123
	
    glutInit(&argc, argv);          
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA);

	glutInitWindowSize(display_width, display_height);
    glutInitWindowPosition(320, 320);
	glutCreateWindow("myChip8 by Laurence Muller");
	
	glutDisplayFunc(display);
	glutIdleFunc(display);
    glutReshapeFunc(reshape_window);        
	glutKeyboardFunc(keyboardDown);
	glutKeyboardUpFunc(keyboardUp); 

#ifdef DRAWWITHTEXTURE
	setupTexture();			
#endif	

	glutMainLoop(); 

	return 0;
}
Exemplo n.º 4
0
void main()
{
	dglWindowOpen("Light example", 900, 750, false);    // create a GL-enabled window of given pixel size

	setupLighting();
	setupTexture();

	glEnable(GL_DEPTH_TEST);
 
	// variables to control object rotation
	float	rotAngle = 0.0f;
	unsigned long long int prevTime = dglGetCurrentTime();

	while( !dglGetAsyncKeyState(DGLK_ESCAPE) )		// begin the main loop. Keep on running until user presses escape
	{
		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		gluPerspective(30, 900.0/750.0, 1.0, 100.0);
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		gluLookAt(0, 0, 10, 0, 0, 0, 0, 1, 0);

		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);		// clear screen black before drawing

		glRotatef(rotAngle, 0, 0.2, 0.2);
		glutSolidTeapot(1.5);
		
		dglSwapBuffers();	// frame is done and can be shown on the screen
		
		rotAngle += 0.02f * (dglGetCurrentTime() - prevTime);				// rotation speed 0.02 (degrees per millisecond)
		prevTime = dglGetCurrentTime();
	}

	dglWindowClose();
}
Exemplo n.º 5
0
int main(int argc, char** argv){
  setupVideoWriting();

  int width = image_width;
  int height = image_height;

  setupBoard(width, height, argc, argv);

  setupScreen(width, height);

  initShaders();

  loadTexture();
  setupTexture();

  setupBuffers();

  glutDisplayFunc(&drawScene);
  glutIdleFunc(&replay);

  glutMainLoop();

  cvReleaseVideoWriter(&writer);
  return 0;
}
void BillboardLayer::setup(int totBillboards, string textureName, ofVec3f spaceSize)
{
  this->totBillboards = totBillboards;
  this->spaceSize = spaceSize;
  setupBillboards();
  setupTexture(textureName);
}
Exemplo n.º 7
0
GLRenderer::GLRenderer(void)
{
	GLenum res = glewInit();
	if (res != GLEW_OK) {
		fprintf(stderr, "Error: '%s'\n", glewGetErrorString(res));
		return;
	}

	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);				// set the clear Display state to the black color; the windows will use this setting during the whole execution

	program = std::unique_ptr<GLProgram>(new GLProgram());
	program->run();
	program->transformObjIndex = glGetUniformLocation(program->getID(),"gObjectTransform");
	program->transformCamIndex = glGetUniformLocation(program->getID(),"gCamera");
	program->lightColorIndex = glGetUniformLocation(program->getID(), "light.lightColor");
	program->ambientIntensityIndex = glGetUniformLocation(program->getID(), "light.intensityAmbient");
	program->diffuseIntensityIndex = glGetUniformLocation(program->getID(), "light.intensityDiffuse");
	program->directionIndex = glGetUniformLocation(program->getID(), "light.direction");
	program->eyeIndex = glGetUniformLocation(program->getID(), "eyeWorldSpace");
	program->specularIntensityIndex = glGetUniformLocation(program->getID(), "specularIntensity");
	program->specularPowerIndex = glGetUniformLocation(program->getID(), "specularPower");

	_root = std::unique_ptr<Node>(new Node);

	/* Setup the scene */

	RawSceneLoader loader;
	Scene scene;
	loader.load(scene);

	setupMesh(scene.meshes[0],1);
	setupTexture(scene.textures[0],1);
	setupLight(scene.lights[0], 1);
	setupMaterial(scene.materials[0],1);
}
void initializeData(char *file, int argc, char **argv) {
    GLint bsize;
    unsigned int w, h;
    size_t file_length= strlen(file);

    if (!strcmp(&file[file_length-3], "pgm")) {
        if (cutLoadPGMub(file, &pixels, &w, &h) != CUTTrue) {
            printf("Failed to load image file: %s\n", file);
            exit(-1);
        }
        g_Bpp = 1;
    } else if (!strcmp(&file[file_length-3], "ppm")) {
        if (cutLoadPPM4ub(file, &pixels, &w, &h) != CUTTrue) {
            printf("Failed to load image file: %s\n", file);
            exit(-1);
        }
        g_Bpp = 4;
    } else {
        cutilDeviceReset();
        shrQAFinishExit(argc, (const char **)argv, QA_WAIVED);
    }
    imWidth = (int)w; imHeight = (int)h;
    setupTexture(imWidth, imHeight, pixels, g_Bpp);

    // copy function pointer tables to host side for later use
    setupFunctionTables();

    memset(pixels, 0x0, g_Bpp * sizeof(Pixel) * imWidth * imHeight);

    if (!g_bQAReadback) {
        // use OpenGL Path
        glGenBuffers(1, &pbo_buffer);
        glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo_buffer); 
        glBufferData(GL_PIXEL_UNPACK_BUFFER, 
                        g_Bpp * sizeof(Pixel) * imWidth * imHeight, 
                        pixels, GL_STREAM_DRAW);  

        glGetBufferParameteriv(GL_PIXEL_UNPACK_BUFFER, GL_BUFFER_SIZE, &bsize); 
        if ((GLuint)bsize != (g_Bpp * sizeof(Pixel) * imWidth * imHeight)) {
            printf("Buffer object (%d) has incorrect size (%d).\n", (unsigned)pbo_buffer, (unsigned)bsize);
            cutilDeviceReset();
            shrQAFinishExit(argc, (const char **)argv, QA_FAILED);
        }

        glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);

        // register this buffer object with CUDA
        cutilSafeCall(cudaGraphicsGLRegisterBuffer(&cuda_pbo_resource, pbo_buffer, cudaGraphicsMapFlagsWriteDiscard));	

        glGenTextures(1, &texid);
        glBindTexture(GL_TEXTURE_2D, texid);
        glTexImage2D(GL_TEXTURE_2D, 0, ((g_Bpp==1) ? GL_LUMINANCE : GL_BGRA), 
                    imWidth, imHeight,  0, GL_LUMINANCE, GL_UNSIGNED_BYTE, NULL);
        glBindTexture(GL_TEXTURE_2D, 0);

        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
        glPixelStorei(GL_PACK_ALIGNMENT, 1);
    }
}
Exemplo n.º 9
0
int displayInit(void){
    
    //Initialize SDL
    if ( SDL_Init( SDL_INIT_VIDEO ) < 0 ) { 
        printf( "SDL could not initialize! SDL_Error: %s\n", SDL_GetError() );
        return 1; 
    }
    
    /* Request opengl 3.2 context.
     * SDL doesn't have the ability to choose which profile at this time of writing,
     * but it should default to the core profile */
    //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);

    /* Turn on double buffering with a 24bit Z buffer.
     * You may need to change this to 16 or 32 for your system */
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);

    //Create window
    int width = SCREEN_WIDTH * modifier;
    int height = SCREEN_HEIGHT * modifier;
    window = SDL_CreateWindow( WINDOW_TITLE, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL ); 
    if ( window == NULL ) { 
        printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() );
        return 1;
    }
    
    /* Create our opengl context and attach it to our window */
    context = SDL_GL_CreateContext(window);
    if ( context == NULL ) { 
        printf( "Context could not be created! SDL_Error: %s\n", SDL_GetError() );
        return 1;
    }

    /* This makes our buffer swap syncronized with the monitor's vertical refresh */
    if (SDL_GL_SetSwapInterval(VSYNC) == 0)
        printf("[DEBUG] Vsync Disabled\n");
    else
        printf("[DEBUG] Error with Vsync.SDL_Error: %s\n", SDL_GetError() );  

    setupTexture(); // init Textures

    GLint dims[4] = {0};
    glGetIntegerv(GL_VIEWPORT, dims);
    glViewport(0, 0, dims[2], dims[3]);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0.0f, width, height, 0.0f, 0.0f, 1.0f);
    glMatrixMode(GL_MODELVIEW);
    
    /* FRAME RATE */
    memset(frametimes, 0, sizeof(frametimes));
    framecount = 0;
    framespersecond = 0;
    frametimelast = SDL_GetTicks();
    
    return 0;
}
void AbstractTextureRenderer::draw()
{
	if (!m_isLocked) {
		setupTexture();
	}

	executeDraw();
}
Exemplo n.º 11
0
void ObjObject::initialize()
{
	textureObject = setupTexture( textureName );

	buildShaderProgram();
	glUseProgram(shaderProgram);
	
	initObj();
}
Exemplo n.º 12
0
void VisusSphere::render()
{
    if (_texEnabled && _texName == 0)
	setupTexture();

    // Need to rebind our texture in case another texture was bound to 2D
    glBindTexture(GL_TEXTURE_2D, _texName);

    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
    glEnable(GL_NORMALIZE);
    glEnable(GL_TEXTURE_2D);

    glRotatef(-90, 1, 0, 0);

    double thetaScale = _texScale[1] / (_numtheta << 1);
    double phiScale = _texScale[0] / _numphi;

    double n[3], p[3];
    for (int j = 0; j < _numtheta; ++j) {
	int k = j + 1;
	double tj = (j << 1) * thetaScale;
	double tk = (k << 1) * thetaScale;
	
	glBegin(GL_QUAD_STRIP);
	for (int i = 0; i <= _numphi; ++i) {
	    double ti = i * phiScale;

	    n[0] = _costheta[k] * _cosphi[i];
	    n[1] = _sintheta[k];
	    n[2] = _costheta[k] * _sinphi[i];

	    p[0] = _origin[0] + _radius * n[0];
	    p[1] = _origin[1] + _radius * n[1];
	    p[2] = _origin[2] + _radius * n[2];
	    
	    glNormal3f(n[0], n[1], n[2]);
	    glTexCoord2f(ti, tk);
	    glVertex3f(p[0], p[1], p[2]);
	    
	    n[0] = _costheta[j] * _cosphi[i];
	    n[1] = _sintheta[j];
	    n[2] = _costheta[j] * _sinphi[i];

	    p[0] = _origin[0] + _radius * n[0];
	    p[1] = _origin[1] + _radius * n[1];
	    p[2] = _origin[2] + _radius * n[2];

	    glNormal3f(n[0], n[1], n[2]);
	    glTexCoord2f(ti, tj);
	    glVertex3f(p[0], p[1], p[2]);
	}
	glEnd();
    }
    glDisable(GL_NORMALIZE);
    glDisable(GL_TEXTURE_2D);
}
Exemplo n.º 13
0
void Box::initialize()
{
	textureObject = setupTexture( "earth.bmp" );

	buildShaderProgram();
	glUseProgram(shaderProgram);
	
	initTopBottomBack();
	initSides();
}
Exemplo n.º 14
0
void initializeData(char *file) {
    GLint bsize;
    unsigned int w, h;
    size_t file_length= strlen(file);

    if (!strcmp(&file[file_length-3], "pgm")) {
        if (cutLoadPGMub(file, &pixels, &w, &h) != CUTTrue) {
            printf("Failed to load image file: %s\n", file);
            exit(-1);
        }
        g_Bpp = 1;
    } else if (!strcmp(&file[file_length-3], "ppm")) {
        if (cutLoadPPM4ub(file, &pixels, &w, &h) != CUTTrue) {
            printf("Failed to load image file: %s\n", file);
            exit(-1);
        }
        g_Bpp = 4;
    } else {
        cudaThreadExit();
        exit(-1);
    }

    imWidth = (int)w; imHeight = (int)h;
    setupTexture(imWidth, imHeight, pixels, g_Bpp);

    memset(pixels, 0x0, g_Bpp * sizeof(Pixel) * imWidth * imHeight);

    if (!g_bQAReadback) {
        // use OpenGL Path
        glGenBuffers(1, &pbo_buffer);
        glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo_buffer); 
        glBufferData(GL_PIXEL_UNPACK_BUFFER, 
                        g_Bpp * sizeof(Pixel) * imWidth * imHeight, 
                        pixels, GL_STREAM_DRAW);  

        glGetBufferParameteriv(GL_PIXEL_UNPACK_BUFFER, GL_BUFFER_SIZE, &bsize); 
        if ((GLuint)bsize != (g_Bpp * sizeof(Pixel) * imWidth * imHeight)) {
            printf("Buffer object (%d) has incorrect size (%d).\n", (unsigned)pbo_buffer, (unsigned)bsize);
            cudaThreadExit();
            exit(-1);
        }

        glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
        cutilSafeCall(cudaGLRegisterBufferObject(pbo_buffer));

        glGenTextures(1, &texid);
        glBindTexture(GL_TEXTURE_2D, texid);
        glTexImage2D(GL_TEXTURE_2D, 0, ((g_Bpp==1) ? GL_LUMINANCE : GL_BGRA), 
                    imWidth, imHeight,  0, GL_LUMINANCE, GL_UNSIGNED_BYTE, NULL);
        glBindTexture(GL_TEXTURE_2D, 0);

        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
        glPixelStorei(GL_PACK_ALIGNMENT, 1);
    }
}
Exemplo n.º 15
0
// Construct visual object display list.
void Cylinder::initialize()
{
	textureObject = setupTexture( "test.bmp" );

	buildShaderProgram();
	
	initializeCylinderBottom();
	initializeCylinderBody();
	initializeCylinderTop();

	VisualObject::initialize();

} // end initialize
Exemplo n.º 16
0
Arquivo: sprite.c Projeto: wKLV/puun
SpriteSheet* loadSpriteSheet(String loc) {
    GLuint ImageId;
    u8* Image;
    int x, y, n;
    Image = stbi_load(loc, &x, &y, &n, 0);
    ImageId = setupTexture(Image, x, y);

    struct SpriteSheetData data = ZERO_STRUCT;
    data.ImageId = ImageId;
    assert(spritesheets_length<512);
    s32 id = spritesheets_length++;
    SpriteSheet sheet = ZERO_STRUCT;
    sheet.id = id;
    data.spritesheet = sheet;

    spritesheets[id] = data;
    return &spritesheets[id].spritesheet;
}
Exemplo n.º 17
0
JNIEXPORT void JNICALL Java_dugu9sword_esplayer_VideoTextureSurfaceRenderer_nativeSetupGraphics(
		JNIEnv* env, jobject obj, jint w, jint h) {
	width = w;
	height = h;

	/*
	 * 把java端的textures数组取过来
	 */
	jclass clazz = env->GetObjectClass(obj);
	jfieldID f_textures = env->GetFieldID(clazz,
			"textures", "[I");
	jintArray jia_textures = (jintArray) env->GetObjectField(
			obj, f_textures);
	textures = (unsigned int*)env->GetIntArrayElements(jia_textures, 0);


	setupTexture(env, obj);
	loadShaders(env, obj);
}
Exemplo n.º 18
0
void LoadingBar::copySpecialProperties(Widget *widget)
{
    LoadingBar* loadingBar = dynamic_cast<LoadingBar*>(widget);
    if (loadingBar)
    {
        _prevIgnoreSize = loadingBar->_prevIgnoreSize;
        setScale9Enabled(loadingBar->_scale9Enabled);

        // clone the inner sprite: https://github.com/cocos2d/cocos2d-x/issues/16930
        loadingBar->_barRenderer->copyTo(_barRenderer);
        setupTexture();

        setCapInsets(loadingBar->_capInsets);
        setPercent(loadingBar->_percent);
        setDirection(loadingBar->_direction);
        _textureFile = loadingBar->_textureFile;
        _totalLength = loadingBar->_totalLength;
        _barRendererTextureSize = loadingBar->_barRendererTextureSize;
    }
}
Exemplo n.º 19
0
void ImageView::setTextureRect(const Rect &rect)
{
    //This API should be refactor
    if (_scale9Enabled)
    {
    }
    else
    {
        auto sprite = _imageRenderer->getSprite();
        _imageRenderer->setScale9Enabled(false);
        if (sprite)
        {
            sprite->setTextureRect(rect);
        }
        else
        {
            CCLOG("Warning!! you should load texture before set the texture's rect!");
        }
        
        _imageRenderer->setContentSize(rect.size);
        setupTexture();
    }
}
Exemplo n.º 20
0
static void init (void) {
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

    glShadeModel(GL_SMOOTH);    
    glEnable(GL_DEPTH_TEST);

    /* Setup Textures */
    setupTexture();

    /* Setup Cube Display List */
    __cube_id = glGenLists(1);
    glNewList(__cube_id, GL_COMPILE);
        drawCube();
    glEndList();

    /* Setup Sphere Display List */
    __sphere_id = glGenLists(1);
    glNewList(__sphere_id, GL_COMPILE);
        drawSphere();
    glEndList();

    /* Setup Cube Right Bounding Box, Aprox. */
    gdHitSetBoxType(&__cube_right);
    gdVector3dInit(&(gdHitBox(&__cube_right)->min), 12.0f, 0.0f, 0.0f);
    gdVector3dInit(&(gdHitBox(&__cube_right)->max), 13.0f, 1.0f, 1.0f);

    /* Setup Cube Left Bounding Box, Aprox. */
    gdHitSetBoxType(&__cube_left);
    gdVector3dInit(&(gdHitBox(&__cube_left)->min), -7.0f, 0.0f, 0.0f);
    gdVector3dInit(&(gdHitBox(&__cube_left)->max), -6.0f, 1.0f, 1.0f);

    /* Setup Sphere Bounding Box, Aprox. */
    gdHitSetSphereType(&__sphere);
    gdHitSphere(&__sphere)->radius = 1.0f;
    gdVector3dInit(&(gdHitSphere(&__sphere)->center), 0.0f, 0.0f, 0.0f);    
}
Exemplo n.º 21
0
int main(int argc, char **argv)
{
    int devID;
    cudaDeviceProp deviceProps;
    printf("%s Starting...\n\n", sSDKname);
    printf("[%s] - [OpenGL/CUDA simulation] starting...\n", sSDKname);

    // First initialize OpenGL context, so we can properly set the GL for CUDA.
    // This is necessary in order to achieve optimal performance with OpenGL/CUDA interop.
    if (false == initGL(&argc, argv))
    {
        exit(EXIT_SUCCESS);
    }

    // use command-line specified CUDA device, otherwise use device with highest Gflops/s
    devID = findCudaGLDevice(argc, (const char **)argv);

    // get number of SMs on this GPU
    checkCudaErrors(cudaGetDeviceProperties(&deviceProps, devID));
    printf("CUDA device [%s] has %d Multi-Processors\n",
           deviceProps.name, deviceProps.multiProcessorCount);

    // automated build testing harness
    if (checkCmdLineFlag(argc, (const char **)argv, "file"))
    {
        getCmdLineArgumentString(argc, (const char **)argv, "file", &ref_file);
    }

    // Allocate and initialize host data
    GLint bsize;

    sdkCreateTimer(&timer);
    sdkResetTimer(&timer);

    hvfield = (cData *)malloc(sizeof(cData) * DS);
    memset(hvfield, 0, sizeof(cData) * DS);

    // Allocate and initialize device data
    cudaMallocPitch((void **)&dvfield, &tPitch, sizeof(cData)*DIM, DIM);

    cudaMemcpy(dvfield, hvfield, sizeof(cData) * DS,
               cudaMemcpyHostToDevice);
    // Temporary complex velocity field data
    cudaMalloc((void **)&vxfield, sizeof(cData) * PDS);
    cudaMalloc((void **)&vyfield, sizeof(cData) * PDS);

    setupTexture(DIM, DIM);
    bindTexture();

    // Create particle array
    particles = (cData *)malloc(sizeof(cData) * DS);
    memset(particles, 0, sizeof(cData) * DS);

    initParticles(particles, DIM, DIM);

    // Create CUFFT transform plan configuration
    cufftPlan2d(&planr2c, DIM, DIM, CUFFT_R2C);
    cufftPlan2d(&planc2r, DIM, DIM, CUFFT_C2R);
    // TODO: update kernels to use the new unpadded memory layout for perf
    // rather than the old FFTW-compatible layout
    cufftSetCompatibilityMode(planr2c, CUFFT_COMPATIBILITY_FFTW_PADDING);
    cufftSetCompatibilityMode(planc2r, CUFFT_COMPATIBILITY_FFTW_PADDING);

    glGenBuffersARB(1, &vbo);
    glBindBufferARB(GL_ARRAY_BUFFER_ARB, vbo);
    glBufferDataARB(GL_ARRAY_BUFFER_ARB, sizeof(cData) * DS,
                    particles, GL_DYNAMIC_DRAW_ARB);

    glGetBufferParameterivARB(GL_ARRAY_BUFFER_ARB, GL_BUFFER_SIZE_ARB, &bsize);

    if (bsize != (sizeof(cData) * DS))
        goto EXTERR;

    glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);

    checkCudaErrors(cudaGraphicsGLRegisterBuffer(&cuda_vbo_resource, vbo, cudaGraphicsMapFlagsNone));
    getLastCudaError("cudaGraphicsGLRegisterBuffer failed");

    if (ref_file)
    {
        autoTest(argv);
        cleanup();
        cudaDeviceReset();
        printf("[fluidsGL] - Test Results: %d Failures\n", g_TotalErrors);
        exit(g_TotalErrors == 0 ? EXIT_SUCCESS : EXIT_FAILURE);

    }
    else
    {
        atexit(cleanup);
        glutMainLoop();
    }

    cudaDeviceReset();

    if (!ref_file)
    {
        exit(EXIT_SUCCESS);
    }

    return 0;

EXTERR:
    printf("Failed to initialize GL extensions.\n");

    cudaDeviceReset();
    exit(EXIT_FAILURE);
}
Exemplo n.º 22
0
	bool CBR5Model::loadFromFile(std::string fileName)
	{
		/* ***************** 1. load the data ***************** */

		FILE *br5 = fopen(fileName.c_str(),"rb");

		if (!br5)
		{
			return false;
		}

		long fileSize = getFileSize(br5);

		byte *data = new byte[fileSize];
		byte *tmp = data;

		// read the full model data
		size_t read = fread(data,sizeof(byte),fileSize,br5);

		if (read!=fileSize)
		{
			return false;
		}

		// read the mark
		char mark[3];
		memcpy(mark,data,3);
		data+=3;

		if (mark[0]!='B' || mark[1]!='R' || mark[2]!='5')
		{
			// file is not a valid br5 model
			fclose(br5);
			return false;
		}

		// read texture name
		memcpy(textureName,data,256);
		data+=256;

		// read number of vertices
		vertexCount = *(unsigned int*)data;
		data+=4;

		textureCoordinates = new float[vertexCount*2];

		// read texture coordinates
		memcpy(textureCoordinates,data,sizeof(float)*vertexCount*2);
		data+=sizeof(float)*vertexCount*2;

		// read number of frames
		framesCount = *(unsigned int*)data;
		data+=4;

		if (framesCount==1)
		{
			// non animated version

			// read vertices
			vertexCoordinates = new float[vertexCount*3];
			memcpy(vertexCoordinates,data,sizeof(float)*vertexCount*3);
			data+=sizeof(float)*vertexCount*3;
		}
		else
		{
			// read vertices
			/*vertexCoordinates = new float[vertexCount*3];
			memcpy(vertexCoordinates,data,sizeof(float)*vertexCount*3);
			data+=sizeof(float)*vertexCount*3;*/

			// read other anims
			vertexCoordinatesAnim = new float*[framesCount];

			for (unsigned int i=0; i<framesCount; i++)
			{
				vertexCoordinatesAnim[i] = new float[vertexCount*3];
				memcpy(vertexCoordinatesAnim[i],data,sizeof(float)*vertexCount*3);
				data+=sizeof(float)*vertexCount*3;
			}

			vertexCoordinates = new float[vertexCount*3];

			memcpy(vertexCoordinates,vertexCoordinatesAnim[0],sizeof(float)*vertexCount*3);
		}

		fclose(br5);

		data = tmp;
		delete [] data;

		startFrame = 0;
		endFrame = framesCount-1;


		/* ***************** 3. setup the VBO ***************** */

		vbo = new CVBO(framesCount==1?CVBO::BT_STATIC_DRAW:CVBO::BT_STREAM_DRAW,false);
		vbo->setVertexData(vertexCount,3,sizeof(GLfloat),vertexCoordinates,CVBO::DT_FLOAT);
		vbo->setEnumMode(CVBO::EM_TRIANGLES);

		setupTexture();

		// calculate the bounding box
		boundingBox.reset();
		for (unsigned int v=0; v<vertexCount*3; v+=3)
		{
			boundingBox.update(vertexCoordinates+v);
		}
		boundingBox.calculateExtents();

		return true;
	}
Exemplo n.º 23
0
	void CBR5Model::setTextureName(std::string textureName)
	{
		strcpy(this->textureName,textureName.c_str());

		setupTexture();
	}
Exemplo n.º 24
0
// Construct visual object display list.
void Wall::initialize()
{
	//textureObject = setupTexture( this->textureFileName);
	textureObject = setupTexture( "stone_texture_012_stacked_slate.bmp");//this->textureFileName);

	buildShaderProgram( );

	// vector containers to hold  data
	vector<pntVertexData> v; // vertex positions
	vector<unsigned int> indices; // indices
	GLuint VBO, IBO; // Identifiers for buffer objects

	vec3 n = vec3( 0.0f, 0.0f, 1.0f);

	vec3 v0 = vec3( -width/2, 0.0f, 0.0f); 
	vec3 v1 = vec3( width/2, 0.0f, 0.0f); 
	vec3 v2 = vec3( width/2, height, 0.0f); 
	vec3 v3 = vec3( -width/2, height, 0.0f); 

	vec2 t0 = vec2(0.0f, 0.0f);
	vec2 t1 = vec2(2.0f, 0.0f);
	vec2 t2 = vec2(2.0f, 1.5f);
	vec2 t3 = vec2(0.0f, 1.5f);

	v.push_back( pntVertexData( v0, n, t0) ); // 0
	v.push_back( pntVertexData( v1, n, t1) ); // 1
	v.push_back( pntVertexData( v2, n, t2) ); // 2
	v.push_back( pntVertexData( v3, n, t3) ); // 3

	indices.push_back( 0 );
	indices.push_back( 1 );
	indices.push_back( 2 );
	indices.push_back( 0 );
	indices.push_back( 2 );
	indices.push_back( 3 );

	glGenVertexArrays (1, &vertexArrayObject);
	glBindVertexArray( vertexArrayObject );

	// Create the buffer to hold interleaved data and bind the data to them
	glGenBuffers(1, &VBO);
	glBindBuffer(GL_ARRAY_BUFFER, VBO); // Buffer for vertex data
	glBufferData(GL_ARRAY_BUFFER, v.size() * sizeof(pntVertexData), &v[0], GL_STATIC_DRAW); //Buffering vertex data

	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(pntVertexData), 0);
	glEnableVertexAttribArray(0);

	glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(pntVertexData), (const GLvoid*)sizeof(vec3) );
	glEnableVertexAttribArray(1);

	glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, sizeof(pntVertexData), (const GLvoid*)(2 * sizeof(vec3)) );
	glEnableVertexAttribArray(3);

	// Generate a buffer for the indices
	glGenBuffers(1, &IBO);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0] , GL_STATIC_DRAW);

	// store the number of indices for later use
	indiceCount = indices.size();
 
	v.clear();
	indices.clear();

	VisualObject::initialize();

} // end initialize
Exemplo n.º 25
0
int main(int argc,const char * argv[]){
    //初期化
    if(!glfwInit()){
        return EXIT_FAILURE;
    }

    if(!glfwOpenWindow(0, 0,
                       0, 0, 0,
                       0,
                       0, 0,
                       GLFW_WINDOW)){
   
        glfwTerminate();
        return EXIT_FAILURE;
    }
#if defined (_MSC_VER)
    if(glewInit() != GLEW_OK){
        glfwTerminate();
        return EXIT_FAILURE;
    }
#endif
    
    //OpenGLにtexture識別子を1つ作ってもらう
    GLuint texture_id;
//    GLuint texture_idArr[10];

    glGenTextures(1,&texture_id);
    
    //画像ファイルを読み込んでテクスチャ識別しに設定する
    if(!setupTexture(texture_id,"sample.raw",256,256)){
    //失敗した後始末
        glDeleteTextures(1, &texture_id);
        glfwTerminate();
        return EXIT_FAILURE;
    }
    
    while( glfwGetWindowParam(GLFW_OPENED))
    {
        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        
        static const GLfloat vtx[] = {
            -0.8f, -0.8f,
            0.8f,  -0.8f,
            0.8f,  0.8f,
            -0.8f, 0.8f
        };
        
        glVertexPointer(2, GL_FLOAT, 0, vtx);
        
        //頂点ごとのテクスチャ座標 UV
        static const GLfloat texture_uv[] = {
            -2.5f, 0.0f,
            2.5f, 0.0f,
            2.5f, 5.0f,
            -2.5f, 5.0f
        };
        glTexCoordPointer(2,GL_FLOAT, 0, texture_uv);
        
        //OpenGLに
        glEnable(GL_TEXTURE_2D);
//        glColor4f(0.2f,0.3f,1.0f,1.0f);

        glEnableClientState(GL_VERTEX_ARRAY);
        glEnableClientState(GL_TEXTURE_COORD_ARRAY);
        
        glDrawArrays(GL_QUADS, 0, 4);
        
        glDisableClientState(GL_VERTEX_ARRAY);
        
        glDisableClientState(GL_TEXTURE_COORD_ARRAY);
        glDisable(GL_TEXTURE_2D);
        
        glfwSwapBuffers();
    }
    
    //TODO:田中さんにテクスチャ識別子以上の数指定したら内部でどうなるか聞く
    //試しても落ちなかった。内部のメモリは?
    glDeleteTextures(1,&texture_id);
    glfwTerminate();
    
    return EXIT_SUCCESS;
    
//    glfwSwapInterval(1);
//    
//    while (glfwGetWindowParam(GLFW_OPENED)) {
//        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
//        glClear(GL_COLOR_BUFFER_BIT);
//        //点
//        //        static const GLfloat vtx[] = { 0.0f, 0.0f };
//        //線
//        //頂点座標群
//        static const GLfloat vtx[] = {
//            -0.5f, -0.5f,
//            0.5f, 0.5f
//        };
//        
//        glVertexPointer(2, GL_FLOAT, 0, vtx);
//        //太さ
////        glPointSize(4.0f);
//        glLineWidth(4.0f);
//        glColor4f(1.0f,1.0f,1.0f,1.0f);
//        glEnableClientState(GL_VERTEX_ARRAY);
//        //ここの引数の2とは?
//        glDrawArrays(GL_LINES, 0, 2);
//        glDisableClientState(GL_VERTEX_ARRAY);
//        glfwSwapBuffers();
//    }
//    
//    glfwTerminate();
//    
//    return EXIT_SUCCESS;
}
Exemplo n.º 26
0
int main(){
    
    if(!glfwInit()){
        return EXIT_FAILURE;
    }
    
    if(!glfwOpenWindow(0, 0, 0, 0, 0, 0, 0, 0, GLFW_WINDOW)){
        glfwTerminate();
        return EXIT_FAILURE;
    }
    
    //テクスチャ識別子を作る
    GLuint texture_id;
    glGenTextures(1, &texture_id);
    
    //画像を読み込む
    //失敗したら識別子を削除して終了する
    if(!setupTexture(texture_id, "sample.raw", 256, 256)){
        glDeleteTextures(1, &texture_id);
        glfwTerminate();
        return EXIT_FAILURE;
    }
    
    glfwSwapInterval(1);
    while(glfwGetWindowParam(GLFW_OPENED)){
        
        //描画バッファを塗りつぶす色成分を指定する
        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
        
        //描画バッファを塗りつぶす
        glClear(GL_COLOR_BUFFER_BIT);
        
        //描画する点の座標を配列で用意する
        static const GLfloat vtx[] = {
            -0.5f, -0.5f,
            0.5f, -0.5f,
            0.5f,  0.5f,
            -0.5f,  0.5f
        };
        
        //頂点ごとのUV座標を指定する
        static const GLfloat texture_uv[] = {
            0.0f, 1.0f,
            1.0f, 1.0f,
            1.0f, 0.0f,
            0.0f, 0.0f
        };
        
        static const GLfloat texture_uv1[] = {
            -2.5f, 0.0f,
            2.5f, 0.0f,
            2.5f, 5.0f,
            -2.5f, 5.0f
        };
        
        //描画に使う頂点配列を指定する
        glVertexPointer(2, GL_FLOAT, 0, vtx);
        glTexCoordPointer(2, GL_FLOAT, 0, texture_uv);
        
        //ブレンドを有効にする
        glEnable(GL_BLEND);
        //ブレンドの方法を指定する
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        
        glEnable(GL_TEXTURE_2D);
        
        //頂点配列で描画するモードに切り替える
        glEnableClientState(GL_VERTEX_ARRAY);
        
        //描写時にテクスチャ座標配列も使うと指示する
        glEnableClientState(GL_TEXTURE_COORD_ARRAY);
        
        glDrawArrays(GL_QUADS, 0, 4);
        
        //描画モードを元に戻す
        glDisableClientState(GL_VERTEX_ARRAY);
        glDisableClientState(GL_TEXTURE_COORD_ARRAY);
        glDisable(GL_TEXTURE_2D);
        glDisable(GL_BLEND);
        
        
        glfwSwapBuffers();
    }
    
    //テクスチャ識別子を削除する
    glDeleteTextures(1, &texture_id);
    
    glfwTerminate();
    return EXIT_SUCCESS;
}
Exemplo n.º 27
0
SimText3D::SimText3D(int dim_num1,int w,int h,int d,int pixel_size,void* data,int n_ID_to_use,bool n_linear,int nt_type):linear(n_linear),t_type(nt_type),dim_num(dim_num1)
{

	ID_to_use = 1;//n_ID_to_use;//GetFreeID();
	glActiveTexture(GL_TEXTURE0+ID_to_use);
	
	if(dim_num==1)texture_target=GL_TEXTURE_1D;
	if(dim_num==2)texture_target=GL_TEXTURE_2D;
	if(dim_num==3)texture_target=GL_TEXTURE_3D;

	glEnable(texture_target);
	arr=data;
	if(pixel_size==1)
	{
		
		if(t_type==GL_FLOAT)
		{
			internal_format=GL_ALPHA16F_ARB;
			texture_format=GL_ALPHA;
			//internal_format=GL_LUMINANCE16F_ARB;
			//texture_format=GL_LUMINANCE;//GL_ALPHA;
		}else
		if(t_type==GL_UNSIGNED_BYTE)
		{
			
			//internal_format=GL_ALPHA8;
			//texture_format=GL_ALPHA;
			internal_format=GL_LUMINANCE8;
			texture_format=GL_LUMINANCE;
			
		}else
		{
			texture_format=GL_LUMINANCE;

//texture_format=GL_ALPHA_INTEGER_EXT;
//internal_format=GL_ALPHA16I_EXT;

//texture_format=GL_LUMINANCE_INTEGER_EXT;
//internal_format=GL_LUMINANCE16I_EXT;
			internal_format=GL_LUMINANCE16;

			//internal_format=GL_ALPHA16F_ARB;
			//internal_format=GL_ALPHA16;
			//texture_format=GL_ALPHA;
		}
		
	}else
if(pixel_size==2)
	{
		
		if(t_type==GL_FLOAT)
		{
			//internal_format=GL_RGB16F_ARB;
			//texture_format=GL_RGB;
		}else
		if(t_type==GL_UNSIGNED_BYTE)
		{
			//internal_format=GL_RGB8;
			//texture_format=GL_RGB;
		}else
		{
			internal_format=GL_LUMINANCE16_ALPHA16;
			texture_format=GL_LUMINANCE_ALPHA;
		}
	}else
	if(pixel_size==3)
	{
		
		if(t_type==GL_FLOAT)
		{
			internal_format=GL_RGB16F_ARB;
			texture_format=GL_RGB;
		}else
		if(t_type==GL_UNSIGNED_BYTE)
		{
			internal_format=GL_RGB8;
			texture_format=GL_RGB;
		}else
		{
			internal_format=GL_RGB16;
			texture_format=GL_RGB;
		}
	}
	else
	{
		//if(pixel_size!=4)std::cout << "WARNING: Unable to create (" << pixel_size << ")-pixeled texture.";
		if(t_type==GL_FLOAT)
		{
			internal_format=GL_RGBA32F_ARB;
			texture_format=GL_RGBA;
		}else
		{
			internal_format=GL_RGBA8;
			texture_format=GL_RGBA;
		}
	}

	width=w;
	height=h;
	depth=d;

    glGenTextures(1, &texture);

    setupTexture(texture);


    transferToTexture(texture);

	
	glDisable(texture_target);
	glActiveTexture(GL_TEXTURE0);
};
Exemplo n.º 28
0
int main(int argc, char **argv)
{
    int devID;
    cudaDeviceProp deviceProps;
    printf("%s Starting...\n\n", sSDKname);
    printf("[%s] - [OpenGL/CUDA simulation] starting...\n", sSDKname);

    // First initialize OpenGL context, so we can properly set the GL for CUDA.
    // This is necessary in order to achieve optimal performance with OpenGL/CUDA interop.
    if (false == initGL(&argc, argv))
    {
        exit(EXIT_SUCCESS);
    }

    // use command-line specified CUDA device, otherwise use device with highest Gflops/s
#ifndef OPTIMUS
    devID = findCudaGLDevice(argc, (const char **)argv);
#else
    devID = gpuGetMaxGflopsDeviceId();
#endif

    // get number of SMs on this GPU
    checkCudaErrors(cudaGetDeviceProperties(&deviceProps, devID));
    printf("CUDA device [%s] has %d Multi-Processors\n",
           deviceProps.name, deviceProps.multiProcessorCount);

    // automated build testing harness
    if (checkCmdLineFlag(argc, (const char **)argv, "file"))
    {
        getCmdLineArgumentString(argc, (const char **)argv, "file", &ref_file);
    }

    // Allocate and initialize host data
    GLint bsize;

    sdkCreateTimer(&timer);
    sdkResetTimer(&timer);

    hvfield = (cData *)malloc(sizeof(cData) * DS);
    memset(hvfield, 0, sizeof(cData) * DS);

    // Allocate and initialize device data
    cudaMallocPitch((void **)&dvfield, &tPitch, sizeof(cData)*DIM, DIM);

    cudaMemcpy(dvfield, hvfield, sizeof(cData) * DS,
               cudaMemcpyHostToDevice);
    // Temporary complex velocity field data
    cudaMalloc((void **)&vxfield, sizeof(cData) * PDS);
    cudaMalloc((void **)&vyfield, sizeof(cData) * PDS);

    setupTexture(DIM, DIM);
    bindTexture();

    // Create particle array in host memory
    particles = (cData *)malloc(sizeof(cData) * DS);
    memset(particles, 0, sizeof(cData) * DS);

#ifdef BROADCAST
	int step = 1;

	// Broadcasted visualization stepping.
	if (argc > 3)
		step = atoi(argv[3]);

	// Create additional space to store particle packets
	// for broadcasting.
	wstep = step; hstep = step;
	int npackets = sizeof(float) * (DIM / wstep) * (DIM / hstep) / UdpBroadcastServer::PacketSize;
	if (sizeof(float) * (DIM / wstep) * (DIM / hstep) % UdpBroadcastServer::PacketSize)
		npackets++;
	packets = (char*)malloc(npackets *
		(UdpBroadcastServer::PacketSize + sizeof(unsigned int)));
#endif

    initParticles(particles, DIM, DIM);

#if defined(OPTIMUS) || defined(BROADCAST)
    // Create particle array in device memory
    cudaMalloc((void **)&particles_gpu, sizeof(cData) * DS);
    cudaMemcpy(particles_gpu, particles, sizeof(cData) * DS, cudaMemcpyHostToDevice);
#endif

    // Create CUFFT transform plan configuration
    cufftPlan2d(&planr2c, DIM, DIM, CUFFT_R2C);
    cufftPlan2d(&planc2r, DIM, DIM, CUFFT_C2R);
    // TODO: update kernels to use the new unpadded memory layout for perf
    // rather than the old FFTW-compatible layout
    cufftSetCompatibilityMode(planr2c, CUFFT_COMPATIBILITY_FFTW_PADDING);
    cufftSetCompatibilityMode(planc2r, CUFFT_COMPATIBILITY_FFTW_PADDING);

    glGenBuffersARB(1, &vbo);
    glBindBufferARB(GL_ARRAY_BUFFER_ARB, vbo);
    glBufferDataARB(GL_ARRAY_BUFFER_ARB, sizeof(cData) * DS,
                    particles, GL_DYNAMIC_DRAW_ARB);

    glGetBufferParameterivARB(GL_ARRAY_BUFFER_ARB, GL_BUFFER_SIZE_ARB, &bsize);

    if (bsize != (sizeof(cData) * DS))
        goto EXTERR;

    glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);

#ifndef OPTIMUS
    checkCudaErrors(cudaGraphicsGLRegisterBuffer(&cuda_vbo_resource, vbo, cudaGraphicsMapFlagsNone));
    getLastCudaError("cudaGraphicsGLRegisterBuffer failed");
#endif

    if (ref_file)
    {
        autoTest(argv);
        cleanup();

        // 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();
        printf("[fluidsGL] - Test Results: %d Failures\n", g_TotalErrors);
        exit(g_TotalErrors == 0 ? EXIT_SUCCESS : EXIT_FAILURE);

    }
    else
    {
#ifdef BROADCAST
		const char *sv_addr = "127.0.0:9097";
		const char *bc_addr = "127.255.255.2:9097";

		// Server address
		if (argc > 2)
			sv_addr = argv[2];

		// Broadcast address
		if (argc > 1)
			bc_addr = argv[1];

		server.reset(new UdpBroadcastServer(sv_addr, bc_addr));

		// Listen to clients' feedbacks in a separate thread.
		{
			pthread_t tid;
			pthread_create(&tid, NULL, &feedback_listener, &step);
		}

		// Broadcast the particles state in a separate thread.
		{
			pthread_t tid;
			pthread_create(&tid, NULL, &broadcaster, &step);
		}
#endif
#if defined (__APPLE__) || defined(MACOSX)
        atexit(cleanup);
#else
        glutCloseFunc(cleanup);
#endif
        glutMainLoop();
    }

    // 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();

    if (!ref_file)
    {
        exit(EXIT_SUCCESS);
    }

    return 0;

EXTERR:
    printf("Failed to initialize GL extensions.\n");

    // 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(EXIT_FAILURE);
}
void initializeData(char *file)
{
    GLint bsize;
    unsigned int w, h;
    size_t file_length= strlen(file);

    if (!strcmp(&file[file_length-3], "pgm"))
    {
        if (sdkLoadPGM<unsigned char>(file, &pixels, &w, &h) != true)
        {
            printf("Failed to load PGM image file: %s\n", file);
            exit(EXIT_FAILURE);
        }

        g_Bpp = 1;
    }
    else if (!strcmp(&file[file_length-3], "ppm"))
    {
        if (sdkLoadPPM4(file, &pixels, &w, &h) != true)
        {
            printf("Failed to load PPM image file: %s\n", file);
            exit(EXIT_FAILURE);
        }

        g_Bpp = 4;
    }
    else
    {
        // 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(EXIT_FAILURE);
    }

    imWidth = (int)w;
    imHeight = (int)h;
    setupTexture(imWidth, imHeight, pixels, g_Bpp);

    memset(pixels, 0x0, g_Bpp * sizeof(Pixel) * imWidth * imHeight);

    if (!g_bQAReadback)
    {
        // use OpenGL Path
        glGenBuffers(1, &pbo_buffer);
        glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo_buffer);
        glBufferData(GL_PIXEL_UNPACK_BUFFER,
                     g_Bpp * sizeof(Pixel) * imWidth * imHeight,
                     pixels, GL_STREAM_DRAW);

        glGetBufferParameteriv(GL_PIXEL_UNPACK_BUFFER, GL_BUFFER_SIZE, &bsize);

        if ((GLuint)bsize != (g_Bpp * sizeof(Pixel) * imWidth * imHeight))
        {
            printf("Buffer object (%d) has incorrect size (%d).\n", (unsigned)pbo_buffer, (unsigned)bsize);

            // 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(EXIT_FAILURE);
        }

        glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);

        // register this buffer object with CUDA
        checkCudaErrors(cudaGraphicsGLRegisterBuffer(&cuda_pbo_resource, pbo_buffer, cudaGraphicsMapFlagsWriteDiscard));

        glGenTextures(1, &texid);
        glBindTexture(GL_TEXTURE_2D, texid);
        glTexImage2D(GL_TEXTURE_2D, 0, ((g_Bpp==1) ? GL_LUMINANCE : GL_BGRA),
                     imWidth, imHeight,  0, GL_LUMINANCE, GL_UNSIGNED_BYTE, NULL);
        glBindTexture(GL_TEXTURE_2D, 0);

        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
        glPixelStorei(GL_PACK_ALIGNMENT, 1);
    }
}
Exemplo n.º 30
0
void Image::createTexture(const void *input, unsigned int size)
{
	const char *filename = m_src.c_str();

	do{
		const void *raws = input;
		
		png_byte header[8];
        memcpy(header, raws, 8);

		// 读取图片头,判断是否PNG文件
		if( png_sig_cmp(header, 0, 8) )
		{
			LOG("Not a png file : %s", filename);
			break;
		}

		// 创建PNG读取结构
		png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
		if( !png_ptr )
		{
			LOG("Unable to create png struct : %s", filename);
			break;
		}

		// 创建PNG信息结构
		png_infop info_ptr = png_create_info_struct(png_ptr);
		if( !info_ptr )
		{
			png_destroy_read_struct(&png_ptr, (png_infopp) NULL, (png_infopp) NULL);
			LOG("Unable to create png info : %s", filename);
			break;
		}

		if( setjmp(png_jmpbuf(png_ptr)) )
		{
			LOG("Error during setjmp : %s", filename);
			png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp) NULL);
			break;
		}
		
		// 设置数据读取函数
		void *inputCopy = (void *)input;
        png_set_read_fn(png_ptr, &inputCopy, png_raw_read);

		// 设置PNG数据宽度处理 RGB/RGBA 24/32bit
		//png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_EXPAND | PNG_TRANSFORM_PACKING
		//								| PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_GRAY_TO_RGB, 0);
		png_read_info(png_ptr, info_ptr);

		// 读取图片信息
		int bit_depth, color_type;
		png_uint_32 twidth, theight;

		png_get_IHDR(png_ptr, info_ptr, &twidth, &theight, &bit_depth, &color_type, NULL, NULL, NULL);
		hasAlpha = ( color_type & PNG_COLOR_MASK_ALPHA ) ? true:false;

		LOG("PNG width=%u height=%u bit_depth=%d alpha=%d", twidth, theight, bit_depth, hasAlpha);
		

		// Update the png info struct.
		//png_read_update_info(png_ptr, info_ptr);

		int rowbytes = png_get_rowbytes(png_ptr, info_ptr);
		LOG("PNG rowbytes:%d", rowbytes);
		
		int bytes_per_component = hasAlpha ? 4:3;

		width = twidth;
		height = theight;
		POTWidth = computePOT(width);
		POTHeight = computePOT(height);

		png_byte *image_data = new png_byte[POTWidth * POTHeight * bytes_per_component];
		if( !image_data )
		{
			png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp) NULL);
			LOG("Unable to allocate image_data while loading %s ", filename);
			break;
		}

		// 创建并设置行指针
		png_bytep *row_pointers = new png_bytep[theight];
		if( !row_pointers )
		{
			png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp) NULL);
			delete[] image_data;
			LOG("Unable to allocate row_pointer while loading %s ", filename);
			break;
		}

		for( int i = 0; i < theight; i++ )
		{
			row_pointers[i] = image_data + i * POTWidth * bytes_per_component;
		}

		png_read_image(png_ptr, row_pointers);

		png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp) NULL);
		delete[] row_pointers;

		// 如果有alpha值,开始预乘
		if( hasAlpha )
		{
			for( int i=0; i<theight; i++ )
			{
				for( int j=0; j<twidth; j++ )
				{
					unsigned char *pixel = (unsigned char *)(image_data + (i * POTWidth + j) * bytes_per_component);
					*((unsigned int *)pixel) = CC_RGB_PREMULTIPLY_APLHA( pixel[0], pixel[1], pixel[2], pixel[3] );
				}
			}
		}

        setupTexture(image_data);
		delete[] image_data;

        JSCContext::getInstance()->callJSFunction(onload);
        TRACE("load Texture finished:%s", m_src.c_str());
        TRACE("texture %d", m_texture);

	}while(false);
}