Exemple #1
0
int main(int argc,char** argv)
{
	SDL_Init(SDL_INIT_EVERYTHING);	//init the SDL
	SDL_Surface* screen=SDL_SetVideoMode(BLOCK_SIZE*WIDTH+BLOCK_SIZE*10,BLOCK_SIZE*HEIGHT,32,SDL_SWSURFACE);	//and our screen
	TTF_Init();	//the TTF as well, cus we want to write out stuff
	TTF_Font* font=TTF_OpenFont("air.ttf",12);
	Uint32 start;	//the start time, to limit FPS
	bool running=true;	//is the program still running?
	SDL_Event event;	//What event has happened?
	srand(time(0));	//seed the random number generator
	int db=0;	//how many blocks do we have (init 0)?
	int elements[8][4][4];	//we store all of the blocks in this 3D array
	int table[HEIGHT][WIDTH];	//This is our whole game-table, all of the blocks, which already put down is stored here
	int currentblock[4][4];	//our current falling block
	fillelement(elements,db);	//load the blocks
	SDL_Surface* blocks=SDL_LoadBMP("blocks.bmp");	//load the image, which stores, the part of the images
	SDL_SetColorKey(blocks,SDL_SRCCOLORKEY,SDL_MapRGB(screen->format,255,0,255));	//The purple color should be invisible
	int blockx;	//the init position of the falling block
	int blocky;
	bool h;	//if it's the 1. or 2. block, we need 4x4, else 3x3
	Uint32 lastmove=SDL_GetTicks();	//how often should the block come down one
	Uint32 lastkey=SDL_GetTicks();	//how often should react the block, when the key is pressed (without release)
	bool keys[2]={0,0};	//if left arrow pressed, than keys[0]=1 if right arrow is pressed keys[1]=1
	int points;
	int normalspeed;	//how quick the tetris blocks fall (in this case once every 0.5 seconds)
	int speed=500;	//the speed, the game currently running (the speed increase, when you press the down arrow)
	const int FPS=30;	//how many FPS the game will run (this effect minimally, how quick the blocks fall)
	int nextblock;	//what is the next block?
	int deletedlines;	//how much lines we already deleted
	int movingspeed=400;	//if we hold down the left/right arrow, how often (150ms) we want to move the block
	int quickmovingspeed=30;
	bool mousepointing=false;	//do we pointing to the toplist text?
	int tmpx,tmpy;	//the location of the mouse cursor
	//we initialize the game (set every parameter to default)
	initGame(&blockx,&blocky,&h,elements,table,currentblock,&normalspeed,&points,&deletedlines,&nextblock,&speed,db);
	int moved=0;
	while(running)	//while the game running
	{
		start=SDL_GetTicks();	//get the current time (for FPS limitation)
		while(SDL_PollEvent(&event))
		{
			switch(event.type)
			{
				case SDL_KEYDOWN:
					switch(event.key.keysym.sym)
					{
						case SDLK_ESCAPE:	//if escape is pressed, escape
							running=false;
							break;
						case SDLK_UP:	//if up arrow is pressed
							rotateleft(currentblock,h);	//rotate the block
							if(checkCollision(currentblock,blockx,blocky,table))	//and check if there is a collision
								for(int i=0;i<3;i++)
									rotateleft(currentblock,h);	//if there was a collision, rotate back (rotate 4 times, is like if you haven't done anything)
									
							break;
						case SDLK_LEFT:
							keys[0]=1;
							break;
						case SDLK_RIGHT:
							keys[1]=1;
							break;
						case SDLK_DOWN:
							speed=10;	//if down key is pressed, speed up a little bit
							break;
					}
					break;
				case SDL_KEYUP:
					switch(event.key.keysym.sym)
					{
						case SDLK_DOWN:
							speed=normalspeed;	//if you released the down arrow, set back the speed
							break;
						case SDLK_LEFT:
							keys[0]=0;
							moved=0;
							break;
						case SDLK_RIGHT:
							keys[1]=0;
							moved=0;
							break;
					}
					break;
				case SDL_QUIT:
					running=false;
					break;
				case SDL_MOUSEMOTION:
					//if we moved the mouse
					tmpx=event.motion.x;	//get the coordinates
					tmpy=event.motion.y;
					//if we are pointing to the square, which contain the toplist text
					if(tmpx>BLOCK_SIZE*WIDTH+2 && tmpx<BLOCK_SIZE*WIDTH+80 && tmpy>80+BLOCK_SIZE*5 && tmpy<80+BLOCK_SIZE*5+20)
						mousepointing=true;	//make this boolean true
					else
						mousepointing=false;	//else false
					break;
				case SDL_MOUSEBUTTONDOWN:
				//if we hit the mousebutton
					tmpx=event.button.x;
					tmpy=event.button.y;
					//on the toplist text
					if(tmpx>BLOCK_SIZE*WIDTH && tmpx<BLOCK_SIZE*WIDTH+80 && tmpy>80+BLOCK_SIZE*5 && tmpy<80+BLOCK_SIZE*5+20)
						displayToplist(font);	//display it
					break;
			}
		}
		//LOGIC
		
		//if the collision happens, and the block is at the top of the screen, than game is over
		if(checkCollision(currentblock,blockx,blocky,table) && blocky==0)
		{
			if(addToplist(font,points))	//try to add out points to the toplist, if addtoplist returns 1, restart the game
				initGame(&blockx,&blocky,&h,elements,table,currentblock,&normalspeed,&points,&deletedlines,&nextblock,&speed,db);
			else
				running=false;	//else we exit
		}

		//if we exceeded the time, how often should it go down, than move it down, and set back the time
		if(SDL_GetTicks()-lastmove>speed)
		{
			blocky++;
			lastmove=SDL_GetTicks();
		}
		//if (left) key was pressed, and last time, when we moved the block is more than 200ms, than move it again
		if((keys[0] && moved>=2 && SDL_GetTicks()-lastkey>quickmovingspeed) || (keys[0] && moved==0) || (keys[0] && moved==1 && SDL_GetTicks()-lastkey>movingspeed))
		{
			blockx--;	//move
			moved++;
			lastkey=SDL_GetTicks();	//set back the time
			if(checkCollision(currentblock,blockx,blocky,table)==1)//if there is a collision
				blockx++;			//move back
		}else if((keys[1] && moved>=2 && SDL_GetTicks()-lastkey>quickmovingspeed) || (keys[1] && moved==0) || (keys[1] && moved==1 && SDL_GetTicks()-lastkey>movingspeed))	//same with right arrow
		{
			blockx++;
			moved++;
			lastkey=SDL_GetTicks();
			if(checkCollision(currentblock,blockx,blocky,table)==1)
				blockx--;		
		}
		
		
		//RENDER
		SDL_FillRect(screen,&screen->clip_rect,SDL_MapRGB(screen->format,0,0,0));	//clear the screen
		
		for(int i=0;i<24;i++)	//render out the table
			for(int j=0;j<12;j++)
			{
				if(!table[i][j])	//if a value=0, than don't do anything, else draw the corresponding block (1 is the first block on the images, 2 is the 2...)
					continue;
				else
					blitSurface(blocks,(table[i][j]-1)*BLOCK_SIZE,0,BLOCK_SIZE,BLOCK_SIZE,screen,j*BLOCK_SIZE,i*BLOCK_SIZE,BLOCK_SIZE,BLOCK_SIZE);
			}
		//render the falling block
		for(int i=0;i<4;i++)
			for(int j=0;j<4;j++)
			{
				if(currentblock[i][j])	//if not "empty", draw the corresponding block
					blitSurface(blocks,(currentblock[i][j]-1)*BLOCK_SIZE,0,BLOCK_SIZE,BLOCK_SIZE,screen,blockx*BLOCK_SIZE+j*BLOCK_SIZE,blocky*BLOCK_SIZE+i*BLOCK_SIZE,BLOCK_SIZE,BLOCK_SIZE);
			}
		//here I check the collision, first I move the object down
		blocky++;
		if(checkCollision(currentblock,blockx,blocky,table))//and if there is a collision
		{
			blocky--;	//move back
			for(int i=0;i<4;i++)
				for(int j=0;j<4;j++)
				{
					if(currentblock[i][j]!=0)
						table[blocky+i][blockx+j]=currentblock[i][j];	//and draw the block to the table matrix (except the 0), so we handle it as fallen block, it's not falling anymore
				}
			blocky=0;	//and generate a new block the same way, as we did in the beginning of the main
			blockx=4;
			setCurrentblock(elements,currentblock,nextblock);
			h=(nextblock>2);
			nextblock=rand()%(db+1);
		}else
			blocky--;	//if there was no collision, move the object back (else it will go every 2nd line)
		
		//this while loop will go as long, as we have full lines
		while(1)
		{
			int k=checkful(table);
			if(k==-1)
				break;
			deletedlines++;
			//if we have full lines
			for(int i=k;i>0;i--)
				for(int j=0;j<WIDTH;j++)
					table[i][j]=table[i-1][j];	//delete them, by move everything above it a line down
			for(int i=0;i<HEIGHT;i++)
				table[0][i]=0;	//and 0 out the most top line (usually this has no effect, except, if there is a block-part in the top row)
			points+=(550-normalspeed)/10;
			if((points%50)==0 && normalspeed>0)	//if the points are dividable by 50 (50,100,150...), speed up the game
			{
				if(normalspeed>50)
					normalspeed-=50;
				else if(normalspeed>0)
					normalspeed-=10;
			}
		}

		//render the menu
		SDL_Rect rec={BLOCK_SIZE*WIDTH,0,screen->clip_rect.w,screen->clip_rect.h};	//the background of the tetris is black (if you want
		SDL_FillRect(screen,&rec,SDL_MapRGB(screen->format,50,50,50));							//you can change it to an image)

		rec.x=BLOCK_SIZE*WIDTH+10;	//this is the part next to the tetris (the menu)
		rec.w=4*BLOCK_SIZE;
		rec.y=20;
		rec.h=4*BLOCK_SIZE;
		SDL_FillRect(screen,&rec,SDL_MapRGB(screen->format,100,100,100));	//fill it with gray
		for(int i=0;i<4;i++)
			for(int j=0;j<4;j++)
			{
				if(elements[nextblock][i][j])	//if not "empty", draw the corresponding block
				{
					blitSurface(blocks,(elements[nextblock][i][j]-1)*BLOCK_SIZE,0,BLOCK_SIZE,BLOCK_SIZE,screen,(BLOCK_SIZE*WIDTH)+j*BLOCK_SIZE+20,20+i*BLOCK_SIZE,BLOCK_SIZE,BLOCK_SIZE);
				}
			}
		//draw all of the menutext (huhh, it's good, that I have this function, else it would be a 4,5 times that amount of line)
		writeText(font,BLOCK_SIZE*WIDTH,0,"NEXT BLOCK",255,255,255);
		writeText(font,BLOCK_SIZE*WIDTH,20+BLOCK_SIZE*5,"POINTS: ",255,255,255);
		writeText(font,BLOCK_SIZE*WIDTH+150,20+BLOCK_SIZE*5,points,255,255,255);
		writeText(font,BLOCK_SIZE*WIDTH,40+BLOCK_SIZE*5,"CURRENT SPEED:",255,255,255);
		writeText(font,BLOCK_SIZE*WIDTH+150,40+BLOCK_SIZE*5,normalspeed,255,255,255);
		writeText(font,BLOCK_SIZE*WIDTH,60+BLOCK_SIZE*5,"DELETED LINES: ",255,255,255);
		writeText(font,BLOCK_SIZE*WIDTH+150,60+BLOCK_SIZE*5,deletedlines,255,255,255);
		rec.x=BLOCK_SIZE*WIDTH+2;	//the toplist square
		rec.y=80+BLOCK_SIZE*5;
		rec.w=80;
		rec.h=20;
		if(!mousepointing)	//if we are not pointing to the toplist square, fill it with
		{
			SDL_FillRect(screen,&rec,SDL_MapRGB(screen->format,0,0,0));	//black
		}else
		{
			SDL_FillRect(screen,&rec,SDL_MapRGB(screen->format,255,0,0));	//else red
		}
			writeText(font,BLOCK_SIZE*WIDTH+5,80+BLOCK_SIZE*5,"TOPLIST",255,255,255);	//and write the toplist text

			
		SDL_Flip(screen);	//show evrything o the real screen
		if(1000.0/FPS>SDL_GetTicks()-start)	
			SDL_Delay(1000.0/FPS-(SDL_GetTicks()-start));	//regulate the FPS
	}
	SDL_FreeSurface(blocks);	//delete and close everything
	TTF_CloseFont(font);
	TTF_Quit();
	SDL_Quit();
	return 0;
}
Exemple #2
0
int main(int argc, char *argv[])
{
    SDL_Surface *screen;

    // Slightly different SDL initialization
    if ( SDL_Init(SDL_INIT_VIDEO) != 0 ) {
        printf("Unable to initialize SDL: %s\n", SDL_GetError());
        return 1;
    }

    SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); // *new*

    screen = SDL_SetVideoMode( 640, 480, 16, SDL_OPENGL ); // *changed*
    if ( !screen ) {
        printf("Unable to set video mode: %s\n", SDL_GetError());
        return 1;
    }

    // Set the OpenGL state after creating the context with SDL_SetVideoMode

    glClearColor( 0, 0, 0, 0 );

#ifndef __EMSCRIPTEN__
    glEnable( GL_TEXTURE_2D ); // Need this to display a texture XXX unnecessary in OpenGL ES 2.0/WebGL
#endif

    glViewport( 0, 0, 640, 480 );

    glMatrixMode( GL_PROJECTION );
    GLfloat matrixData[] = { 2.0/640,        0,  0,  0,
                                   0, -2.0/480,  0,  0,
                                   0,        0, -1,  0,
                                  -1,        1,  0,  1 };
    glLoadMatrixf(matrixData); // test loadmatrix

    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();

    // Load the OpenGL texture

    GLuint texture; // Texture object handle
    SDL_Surface *surface; // Gives us the information to make the texture

    if ( (surface = IMG_Load("screenshot.png")) ) {

        // Check that the image's width is a power of 2
        if ( (surface->w & (surface->w - 1)) != 0 ) {
            printf("warning: image.bmp's width is not a power of 2\n");
        }

        // Also check if the height is a power of 2
        if ( (surface->h & (surface->h - 1)) != 0 ) {
            printf("warning: image.bmp's height is not a power of 2\n");
        }

        // Have OpenGL generate a texture object handle for us
        glGenTextures( 1, &texture );

        // Bind the texture object
        glBindTexture( GL_TEXTURE_2D, texture );

        // Set the texture's stretching properties
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

        //SDL_LockSurface(surface);

        // Add some greyness
        memset(surface->pixels, 0x66, surface->w*surface->h);

        // Edit the texture object's image data using the information SDL_Surface gives us
        glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, surface->w, surface->h, 0,
                      GL_RGBA, GL_UNSIGNED_BYTE, surface->pixels );

        //SDL_UnlockSurface(surface);
    }
    else {
        printf("SDL could not load image.bmp: %s\n", SDL_GetError());
        SDL_Quit();
        return 1;
    }

    // Free the SDL_Surface only if it was successfully created
    if ( surface ) {
        SDL_FreeSurface( surface );
    }

    // Clear the screen before drawing
    glClear( GL_COLOR_BUFFER_BIT );

    shaders();

    // Bind the texture to which subsequent calls refer to
    glBindTexture( GL_TEXTURE_2D, texture );

    // Use clientside vertex pointers to render two items
    GLfloat vertexData[] = { 0, 0, 10, 10, // texture2, position2
                             1, 0, 300, 10,
                             1, 1, 300, 128,
                             0, 1, 10, 128,
                             0, 0.5, 410, 10,
                             1, 0.5, 600, 10,
                             1, 1, 630, 200,
                             0.5, 1, 310, 250,
                             0, 0, 100, 300,
                             1, 0, 300, 300,
                             1, 1, 300, 400,
                             0, 1, 100, 400 };

    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    glTexCoordPointer(2, GL_FLOAT, 4*4, &vertexData[0]);
    glEnableClientState(GL_VERTEX_ARRAY);
    glVertexPointer(2, GL_FLOAT, 4*4, &vertexData[2]);

    glDrawArrays(GL_QUADS, 0, 12);

    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    glDisableClientState(GL_VERTEX_ARRAY);

    SDL_GL_SwapBuffers();

#ifndef __EMSCRIPTEN__
    // Wait for 3 seconds to give us a chance to see the image
    SDL_Delay(3000);
#endif

    // Now we can delete the OpenGL texture and close down SDL
    glDeleteTextures( 1, &texture );

    SDL_Quit();

    return 0;
}
bool Game::OnInit()
{
	if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
	{
		printf("SDL_Init > SDL_INIT_EVERYTHING failed.\n");
		return false;
	}

	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

	if ((gameScreen = SDL_SetVideoMode(SCREEN_W, SCREEN_H, 32, SDL_OPENGL)) == NULL)
	{
		printf("Setting gameScreen failed.\n");
		return false;
	}

	// enable texture 2d
	glEnable(GL_TEXTURE_2D);

	// set clear color to black
	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

	// set our viewport
	glViewport(0, 0, SCREEN_W, SCREEN_H);

	// enable alpha
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	// clear screen
	glClear(GL_COLOR_BUFFER_BIT);

	// set the matrix for projection
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();

	// set the ortho to the screen
	glOrtho(0.0f, SCREEN_W, SCREEN_H, 0.0f, -1.0f, 1.0f);

	// switch to model view
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	// load lua
	if ((LuaController::Controller.OnInit()) == false)
	{
		printf("Lua initialization failed.\n");
		return false;
	}

	// load player
	if (player.OnLoad("../resources/sprites/player.png", 3, true) == false)
	{
		printf("Loading player failed.\n");
		return false;
	}
	Entity::EntityStack.push_back(&player);

	// Load map
	/*
	if (map.OnLoad("../resources/maps/autotest.map") == false)
	{
		printf("Loading map failed.\n");
		return false;
	}
	*/
	map.OnCreate(30, 25);
	Map::MapStack.push_back(&map);

	player.setPosition(map.getStartX(), map.getStartY());

	if (debugWindow.OnLoad("../resources/sprites/window.png") == false)
	{
		printf("Loading window failed.\n");
		return false;
	}

	debugWindow.setSize(160, 32);
	debugWindow.setPosition(8, 8);
	Window::WindowStack.push_back(&debugWindow);

	Camera::CameraControl.targetMode = TARGET_MODE_CENTER;
	Camera::CameraControl.SetBounds((SDL_Rect){0, 0, map.getTilesX() * TILE_SIZE, map.getTilesY() * TILE_SIZE});

	SDL_WM_SetCaption("Blade Brothers Engine", "../resources/icons/icon.png");

	return true;
}
Exemple #4
0
int main(int argc, char *argv[]) {
  SDL_Event       event;
  VideoState      *is;
  is = av_mallocz(sizeof(VideoState));
  if(argc < 2) {
    fprintf(stderr, "Usage: test <file>\n");
    exit(1);
  }
  // Register all formats and codecs
  av_register_all();

  if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) {
    fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError());
    exit(1);
  }

  // Make a screen to put our video
#ifndef __DARWIN__
  screen = SDL_SetVideoMode(640, 480, 0, 0);
#else
  screen = SDL_SetVideoMode(640, 480, 24, 0);
#endif
  if(!screen) {
    fprintf(stderr, "SDL: could not set video mode - exiting\n");
    exit(1);
  }

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


  // 初始化为视频缓冲准备的锁(pictq)
  // 因为一旦事件驱动调用视频函数, 视频函数会从 pictq 抽出预解码帧。
  // 同时, 视频解码器会把信息放进去, 我们不知道那个动作会先发生。
  is->pictq_mutex = SDL_CreateMutex();
  is->pictq_cond = SDL_CreateCond();

  // schedule_refresh 是一个将要定义的函数。它的动作是告诉系统在某个特定的毫秒数后弹出 FF_REFRESH_EVENT 事件。
  schedule_refresh(is, 40);

  is->av_sync_type = DEFAULT_AV_SYNC_TYPE;
  // 生成一个新线程能完全访问原始进程中的内存,启动我们给的线程,在这种情况下, 调用 decode_thread()并与 VideoState 结构体连接。
  is->parse_tid = SDL_CreateThread(decode_thread, is);
  if(!is->parse_tid) {
    av_free(is);
    return -1;
  }

//  事件循环
  for(;;) {

    SDL_WaitEvent(&event);
    switch(event.type) {
    case FF_QUIT_EVENT:
    case SDL_QUIT:
      is->quit = 1;
      /*
       * If the video has finished playing, then both the picture and
       * audio queues are waiting for more data.  Make them stop
       * waiting and terminate normally.
       */
      SDL_CondSignal(is->audioq.cond);
      SDL_CondSignal(is->videoq.cond);
      SDL_Quit();
      exit(0);
      break;
    case FF_ALLOC_EVENT:
      alloc_picture(event.user.data1);
      break;
    case FF_REFRESH_EVENT:
      video_refresh_timer(event.user.data1);
      break;
    default:
      break;
    }
  }
  return 0;
}
Exemple #5
0
/* w, h is layer resolution */
int plat_sdl_change_video_mode(int w, int h, int force)
{
  static int prev_w, prev_h;

  if (w == 0)
    w = prev_w;
  else
    prev_w = w;
  if (h == 0)
    h = prev_h;
  else
    prev_h = h;

  // skip GL recreation if window doesn't change - avoids flicker
  if (plat_target.vout_method == vout_mode_gl && plat_sdl_gl_active
      && plat_target.vout_fullscreen == old_fullscreen && !force)
  {
    return 0;
  }

  if (plat_sdl_overlay != NULL) {
    SDL_FreeYUVOverlay(plat_sdl_overlay);
    plat_sdl_overlay = NULL;
  }
  if (plat_sdl_gl_active) {
    gl_finish();
    plat_sdl_gl_active = 0;
  }

  if (plat_target.vout_method != 0) {
    Uint32 flags = SDL_RESIZABLE | SDL_SWSURFACE;
    int win_w = window_w;
    int win_h = window_h;

    if (plat_target.vout_fullscreen) {
      flags |= SDL_FULLSCREEN;
      win_w = fs_w;
      win_h = fs_h;
    }

    // XXX: workaround some occasional mysterious deadlock in SDL_SetVideoMode
    SDL_PumpEvents();

    plat_sdl_screen = SDL_SetVideoMode(win_w, win_h, 0, flags);
    if (plat_sdl_screen == NULL) {
      fprintf(stderr, "SDL_SetVideoMode failed: %s\n", SDL_GetError());
      plat_target.vout_method = 0;
    }
  }

  if (plat_target.vout_method == vout_mode_overlay) {
    plat_sdl_overlay = SDL_CreateYUVOverlay(w, h, SDL_UYVY_OVERLAY, plat_sdl_screen);
    if (plat_sdl_overlay != NULL) {
      if ((long)plat_sdl_overlay->pixels[0] & 3)
        fprintf(stderr, "warning: overlay pointer is unaligned\n");

      plat_sdl_overlay_clear();
    }
    else {
      fprintf(stderr, "warning: could not create overlay.\n");
      plat_target.vout_method = 0;
    }
  }
  else if (plat_target.vout_method == vout_mode_gl) {
    plat_sdl_gl_active = (gl_init(display, window, &gl_quirks) == 0);
    if (!plat_sdl_gl_active) {
      fprintf(stderr, "warning: could not init GL.\n");
      plat_target.vout_method = 0;
    }
  }

  if (plat_target.vout_method == 0) {
    SDL_PumpEvents();

    plat_sdl_screen = SDL_SetVideoMode(w, h, 16, SDL_SWSURFACE);
    if (plat_sdl_screen == NULL) {
      fprintf(stderr, "SDL_SetVideoMode failed: %s\n", SDL_GetError());
      return -1;
    }
  }

  old_fullscreen = plat_target.vout_fullscreen;
  if (plat_sdl_resize_cb != NULL)
    plat_sdl_resize_cb(plat_sdl_screen->w, plat_sdl_screen->h);

  return 0;
}
Exemple #6
0
int g_Open( char *file ) {
	char c; int i; float f;
	float screenfactor;
	unsigned long x, y;
	FILE *fp;
	char name[32];
	char valid_data[10];
	Mix_Chunk *psize;

	gameloop = 1;
	hx=xres>>1; hy=yres>>1; hz = hx;
	
	screenfactor = ((float)(xres))/320.0;
	//SDL_Rect src, dest;
	//src.x=0; dest.x=0;
	//src.y=0; dest.y=0;
	//src.w=1280*screenfactor; dest.w=0;
	//src.h=468*screenfactor; dest.h=0;
	
	// allocate memory for tables
	zbuffer = (float *) malloc(sizeof(f)*yres*xres);
	floorbuffer = (int *) malloc(sizeof(i)*yres*xres*2);
	floorbuffer_s = (int *) malloc(sizeof(i)*yres*xres*2);
	rowbuffer = (char *) malloc(sizeof(c)*yres);

	// build some tables
	map.loaded = 0;
	for( x=0; x<xres; x++ ) {
		for( y=0; y<yres; y++ ) {
			floorbuffer_s[y+x*yres]=16383;
			floorbuffer_s[y+x*yres+vidsize]=-1;
		}
	}

	// load general bitmaps
	font8_bmp = SDL_LoadBMP("images/8font.bmp");
	SDL_SetColorKey( font8_bmp, SDL_SRCCOLORKEY, SDL_MapRGB( font8_bmp->format, 255, 0, 255 ) );
	font16_bmp = SDL_LoadBMP("images/16font.bmp");
	SDL_SetColorKey( font16_bmp, SDL_SRCCOLORKEY, SDL_MapRGB( font16_bmp->format, 255, 0, 255 ) );
	r_LoadBmp("images/console.bmp", &console_bmp);
	
	// load textures
	sky2_bmp = SDL_LoadBMP("images/sky.bmp");
	sky_bmp = r_ScaleSurface(sky2_bmp, 1280*screenfactor,468*screenfactor);
	//sky_bmp = SDL_CreateRGBSurface(SDL_HWSURFACE,1280*screenfactor,468*screenfactor,32,0,0,0,0);
	//SDL_BlitSurface( SPG_Scale( sky2_bmp, screenfactor, screenfactor ), &src, sky_bmp, &dest );
	//SDL_BlitSurface( sky2_bmp, &src, sky_bmp, &dest );
	//SDL_BlitSurface( sky2_bmp, &src, sky_bmp, &dest );
	fp = fopen("images/textures.txt","r");
	for( texture_num=0; !feof(fp); texture_num++ ) {
		while( fgetc(fp) != '\n' ) if( feof(fp) ) break;
	}
	fclose(fp);
	walltex_bmp = (bitmap_t *) malloc(sizeof(bitmap_t)*texture_num);
	fp = fopen("images/textures.txt","r");
	for( x=0; !feof(fp); x++ ) {
		fscanf(fp,"%s",name); while( fgetc(fp) != '\n' ) if( feof(fp) ) break;
		r_LoadBmp(name, &walltex_bmp[x]);
	}
	fclose(fp);
	
	// load sprites
	fp = fopen("images/sprites.txt","r");
	for( sprite_num=0; !feof(fp); sprite_num++ ) {
		while( fgetc(fp) != '\n' ) if( feof(fp) ) break;
	}
	fclose(fp);
	sprite_bmp = (bitmap_t *) malloc(sizeof(bitmap_t)*sprite_num);
	fp = fopen("images/sprites.txt","r");
	for( x=0; !feof(fp); x++ ) {
		fscanf(fp,"%s",name); while( fgetc(fp) != '\n' ) if( feof(fp) ) break;
		r_LoadBmp(name, &sprite_bmp[x]);
	}
	fclose(fp);
	
	// load weapon bitmaps
	r_LoadBmp( "images/pistol1.bmp", &pistol_bmp[0] );
	r_LoadBmp( "images/pistol2.bmp", &pistol_bmp[1] );
	r_LoadBmp( "images/pistol3.bmp", &pistol_bmp[2] );
	r_LoadBmp( "images/pistol4.bmp", &pistol_bmp[3] );
	r_LoadBmp( "images/pistol5.bmp", &pistol_bmp[4] );
	r_LoadBmp( "images/shotgun1.bmp", &shotgun_bmp[0] );
	r_LoadBmp( "images/shotgun3.bmp", &shotgun_bmp[1] );
	shotgun_bmp[2] = shotgun_bmp[0];
	shotgun_bmp[3] = shotgun_bmp[0];
	shotgun_bmp[4] = shotgun_bmp[0];
	shotgun_bmp[5] = shotgun_bmp[0];
	r_LoadBmp( "images/shotgun4.bmp", &shotgun_bmp[6] );
	shotgun_bmp[7] = shotgun_bmp[6];
	r_LoadBmp( "images/shotgun5.bmp", &shotgun_bmp[8] );
	shotgun_bmp[9] = shotgun_bmp[6];
	shotgun_bmp[10] = shotgun_bmp[6];
	r_LoadBmp( "images/shotgun2.bmp", &shotgun_bmp[11] ); // swapped with shotgun[1] when needed

	// precompute some things
	sprsize = 2.45*((double)yres/240);
	texsize = 2.5*((double)yres/240);

	// load a map
	if( strstr(file,".bsm") == NULL )
		strcat(file,".bsm");
	fp = fopen(file, "rb");
	if( fp == NULL ) {
		printf( "ERROR: Could not load map file: %s\n\n", file );
		g_Close();
		exit(15);
	}
	
	// validate the file
	fread(valid_data, sizeof(char), strlen("BSDLMAP"), fp);
	if( strncmp(valid_data,"BSDLMAP",7) || fgetc(fp) != MAPVERSION ) {
		printf( "ERROR: Not a valid map file: %s\n\n", file );
		fclose(fp);
		g_Close();
		exit(46);
	}
	else
		map.loaded = 1; // lets the engine know that there's junk to be freed
	
	// header
	fread(map.name, sizeof(char), 32, fp);   // map name
	fread(map.author, sizeof(char), 32, fp); // map author
	fread(&map.width, sizeof(int), 1, fp);    // map width
	fread(&map.height, sizeof(int), 1, fp);   // map height
	
	// allocate data
	map.floors = (int *) malloc(sizeof(int)*map.width*map.height);
	map.floors_tex = (int *) malloc(sizeof(int)*map.width*map.height);
	map.floors_tex2 = (int *) malloc(sizeof(int)*map.width*map.height);
	map.ceilings = (int *) malloc(sizeof(int)*map.width*map.height);
	map.ceilings_tex = (int *) malloc(sizeof(int)*map.width*map.height);
	map.ceilings_tex2 = (int *) malloc(sizeof(int)*map.width*map.height);
	
	// map data
	fread(map.floors, sizeof(int), map.width*map.height, fp);        // floor height
	fread(map.floors_tex, sizeof(int), map.width*map.height, fp);    // lower wall texture
	fread(map.floors_tex2, sizeof(int), map.width*map.height, fp);   // floor texture
	fread(map.ceilings, sizeof(int), map.width*map.height, fp);      // ceiling height
	fread(map.ceilings_tex, sizeof(int), map.width*map.height, fp);  // upper wall texture
	fread(map.ceilings_tex2, sizeof(int), map.width*map.height, fp); // ceiling texture
	
	// close the file
	fclose(fp);
	
	// spawn the player
	if( !server ) {
		e_CreateEntity();
		player = lastentity;
		player->behavior = &e_ActPlayer;
		
		player->sizex = .5;
		player->sizey = .5;
		player->sizez = 52;
		
		player->x=2.5;
		player->y=2.5;
		player->z=0;
		player->ang=0;
	}
	vang=0;
	bob1 = 0; bob2 = 0; bob3 = 1;
	weap_mag[2]=2;
	
	// set camera
	camx=8;
	camy=2.5;
	camz=0;
	camang=0;

	// initiate SDL
	if( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER ) == -1 ) {
		printf("ERROR: Could not initialize SDL. Aborting...\n\n");
		g_Close();
		exit(4);
	}
	//SDL_WM_GrabInput(SDL_GRAB_ON);
	
	// open audio
	if(Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers)) {
		printf("Unable to open audio!\n");
		exit(1);
	}

	// create a screen surface
	screen = SDL_CreateRGBSurface(SDL_HWSURFACE,xres,yres,32,0,0,0,0);
	if( !windowed )
		screen2 = SDL_SetVideoMode( xres, yres, 32, SDL_HWSURFACE | SDL_FULLSCREEN );
	else
		screen2 = SDL_SetVideoMode( xres, yres, 32, SDL_HWSURFACE );
	if( screen == NULL || screen2 == NULL ) {
		printf("ERROR: Could not create video surface. Aborting...\n\n");
		g_Close();
		exit(5);
	}
	SDL_WM_SetCaption( "Bubbenstein/SDL\n\n", 0 );
	SDL_ShowCursor(SDL_DISABLE);
	
	// reset the clock
	ot=SDL_GetTicks();
	i_GetFrameRate();
	
	// load sound effects
	fp = fopen("sound/sounds.txt","r");
	for( sound_num=0; !feof(fp); sound_num++ ) {
		while( fgetc(fp) != '\n' ) if( feof(fp) ) break;
	}
	fclose(fp);
	sounds = (Mix_Chunk **) malloc(sizeof(psize)*sound_num);
	fp = fopen("sound/sounds.txt","r");
	for( x=0; !feof(fp); x++ ) {
		fscanf(fp,"%s",name); while( fgetc(fp) != '\n' ) if( feof(fp) ) break;
		sounds[x] = Mix_LoadWAV(name);
	}
	fclose(fp);
	
	// load music
	music = Mix_LoadMUS("music/dead.ogg");
	Mix_VolumeMusic(64);
	//Mix_PlayMusic(music, -1);
	musicplaying=0;
	
	// multiplayer
	if (SDLNet_Init() < 0) {
		g_Close();
		printf("ERROR: SDLNet_Init: %s\n", SDLNet_GetError());
		exit(EXIT_FAILURE);
	}

	// starting a server
	if( server ) {
		// listen on the host's port
		if( !(sd = SDLNet_UDP_Open(PORT)) ) {
			g_Close();
			printf("ERROR: SDLNet_UDP_Open: %s\n", SDLNet_GetError());
			exit(EXIT_FAILURE);
		}
		
		// Allocate memory for the packet
		if( !(packet = SDLNet_AllocPacket(512)) ) {
			printf("ERROR: SDLNet_AllocPacket: %s\n", SDLNet_GetError());
			exit(EXIT_FAILURE);
		}
	}
	
	// joining a server
	else if( address != NULL ) {
		if( !(sd = SDLNet_UDP_Open(0)) ) {
			g_Close();
			printf("ERROR: SDLNet_UDP_Open: %s\n", SDLNet_GetError());
			exit(EXIT_FAILURE);
		}
		
		if( SDLNet_ResolveHost(&ip, address, PORT) < 0 ) {
			printf("ERROR: SDLNet_ResolveHost: %s\n", SDLNet_GetError());
			exit(EXIT_FAILURE);
		}
		
		// Allocate memory for the packet
		if( !(packet = SDLNet_AllocPacket(512)) ) {
			printf("ERROR: SDLNet_AllocPacket: %s\n", SDLNet_GetError());
			exit(EXIT_FAILURE);
		}
	}
	
	// report a success!
	if( address == NULL )
		i_Message( "Map loaded: %s", file );
	else
		i_Message( "Map loaded: %s\nConnected to %s", file, address );
	return(0);
}
	void SDLWindow::create(const String& name, unsigned int width, unsigned int height,
	            bool fullScreen, const NameValuePairList *miscParams)
    {
		int colourDepth = 32;
		String title = name;
		if(miscParams)
		{
			// Parse miscellenous parameters
			NameValuePairList::const_iterator opt;
			// Bit depth
			opt = miscParams->find("colourDepth");
			if(opt != miscParams->end()) //check for FSAA parameter, if not ignore it...
				colourDepth = StringConverter::parseUnsignedInt(opt->second);
			// Full screen antialiasing
			opt = miscParams->find("FSAA");
			if(opt != miscParams->end()) //check for FSAA parameter, if not ignore it...
			{
				size_t fsaa_x_samples = StringConverter::parseUnsignedInt(opt->second);
				if(fsaa_x_samples>1) {
					// If FSAA is enabled in the parameters, enable the MULTISAMPLEBUFFERS
					// and set the number of samples before the render window is created.
					SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS,1);
					SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES,fsaa_x_samples);
				}
			}
			// Window title
			opt = miscParams->find("title");
			if(opt != miscParams->end()) //check for FSAA parameter, if not ignore it...
				title = opt->second;
		}   
	
        LogManager::getSingleton().logMessage("SDLWindow::create", LML_TRIVIAL);
        SDL_Surface* screen;
        int flags = SDL_OPENGL | SDL_HWPALETTE | SDL_RESIZABLE;
		
        SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
        // request good stencil size if 32-bit colour
        if (colourDepth == 32)
        {
            SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, 8);
        }
		
        if (fullScreen)
            flags |= SDL_FULLSCREEN;

        LogManager::getSingleton().logMessage("Create window", LML_TRIVIAL);
        screen = SDL_SetVideoMode(width, height, colourDepth, flags);
        if (!screen)
        {
            LogManager::getSingleton().logMessage(LML_CRITICAL, 
                String("Could not make screen: ") + SDL_GetError());
            exit(1);
        }
        LogManager::getSingleton().logMessage("screen is valid", LML_TRIVIAL);
        mScreen = screen;

        mName = name;

        mWidth = width;
        mHeight = height;

        mActive = true;

        if (!fullScreen)
            SDL_WM_SetCaption(title.c_str(), 0);

        glXGetVideoSyncSGI = (int (*)(unsigned int *))SDL_GL_GetProcAddress("glXGetVideoSyncSGI");
        glXWaitVideoSyncSGI = (int (*)(int, int, unsigned int *))SDL_GL_GetProcAddress("glXWaitVideoSyncSGI");
    }
Exemple #8
0
/**
 * Display a video frame
 *
 * @param st    Video display state
 * @param title Window title
 * @param frame Video frame
 *
 * @return 0 if success, otherwise errorcode
 *
 * @note: On Darwin, this must be called from the main thread
 */
static int display(struct vidisp_st *st, const char *title,
		   const struct vidframe *frame)
{
	SDL_Rect rect;

	if (!st || !sdl.open)
		return EINVAL;

	if (!vidsz_cmp(&sdl.size, &frame->size)) {
		if (sdl.size.w && sdl.size.h) {
			info("sdl: reset size %u x %u  --->  %u x %u\n",
			     sdl.size.w, sdl.size.h,
			     frame->size.w, frame->size.h);
		}
		sdl_reset();
	}

	if (!sdl.screen) {
		int flags = SDL_HWSURFACE | SDL_ASYNCBLIT | SDL_HWACCEL;
		char capt[256];

		if (sdl.fullscreen)
			flags |= SDL_FULLSCREEN;
		else if (sdl.resizeh)
			flags |= SDL_RESIZABLE;

		if (title) {
			re_snprintf(capt, sizeof(capt), "%s - %u x %u",
				    title, frame->size.w, frame->size.h);
		}
		else {
			re_snprintf(capt, sizeof(capt), "%u x %u",
				    frame->size.w, frame->size.h);
		}

		SDL_WM_SetCaption(capt, capt);

		sdl.screen = SDL_SetVideoMode(frame->size.w, frame->size.h,
					      0, flags);
		if (!sdl.screen) {
			warning("sdl: unable to get video screen: %s\n",
				SDL_GetError());
			return ENODEV;
		}

		sdl.size = frame->size;
	}

	if (!sdl.bmp) {
		sdl.bmp = SDL_CreateYUVOverlay(frame->size.w, frame->size.h,
					       SDL_YV12_OVERLAY, sdl.screen);
		if (!sdl.bmp) {
			warning("sdl: unable to create overlay: %s\n",
				SDL_GetError());
			return ENODEV;
		}
	}

	SDL_LockYUVOverlay(sdl.bmp);
	picture_copy(sdl.bmp->pixels, sdl.bmp->pitches, frame);
	SDL_UnlockYUVOverlay(sdl.bmp);

	rect.x = 0;
	rect.y = 0;
	rect.w = sdl.size.w;
	rect.h = sdl.size.h;

	SDL_DisplayYUVOverlay(sdl.bmp, &rect);

	return 0;
}
Exemple #9
0
int main()
{
#ifdef __MIPSEL__
    create_app_dir(BASE_PATH);
#endif

    if (SDL_Init(SDL_INIT_VIDEO) < 0)
    {
        log(FATAL, "Cannot init SDL.");
    }

    if (!(screen = SDL_SetVideoMode(WIDTH, HEIGHT, DEPTH, SDL_HWSURFACE | SDL_DOUBLEBUF)))
    {
        SDL_Quit();
        log(FATAL, "Cannot SetVideoMode.");
    }

    SDL_ShowCursor(SDL_DISABLE);

    if (TTF_Init() < 0)
    {
        SDL_Quit();
        log(FATAL, "Unable to start the TTF.");
    }

    int img_flags = IMG_INIT_PNG;

    if(!(IMG_Init(img_flags) & img_flags))
    {
        TTF_Quit();
        SDL_Quit();
        log(FATAL, "SDL_image could not initialize. %s.", IMG_GetError());
    }

    pconfig = new Config();
    pconfig->load();

    pmixer = new Mixer();
    current_volume = pmixer->get_speaker_volume();
    pmixer->set_speaker_volume(current_volume);

    load_resources();
    draw_buttons();
    draw_timer(0, 0, 0);
    draw_volume();
    draw_vu(1, -1);
    draw_vu(1, 1);

    pmic = new Mic();
    pmic->set_on_terminate_event(on_terminate_exec);
    pmic->set_on_vu_change_event(on_vu_changed);

    main_loop();

    delete pmic;
    delete pmixer;
    delete pconfig;

    TTF_CloseFont(font_10);
    TTF_CloseFont(font_28);

    IMG_Quit();
    TTF_Quit();
    SDL_Quit();

    return 0;
}
Exemple #10
0
static void SetVideoMode(screen_mode_t *mode, int w, int h)
{
    byte *doompal;
    int flags = 0;

    doompal = W_CacheLumpName(DEH_String("PLAYPAL"), PU_CACHE);

    // If we are already running and in a true color mode, we need
    // to free the screenbuffer surface before setting the new mode.

    if (screenbuffer != NULL && screen != screenbuffer)
    {
        SDL_FreeSurface(screenbuffer);
    }

    // Generate lookup tables before setting the video mode.

    if (mode != NULL && mode->InitMode != NULL)
    {
        mode->InitMode(doompal);
    }

    // Set the video mode.

    flags |= SDL_SWSURFACE | SDL_DOUBLEBUF;

    if (screen_bpp == 8)
    {
        flags |= SDL_HWPALETTE;
    }

    if (fullscreen)
    {
        flags |= SDL_FULLSCREEN;
    }
    else
    {
        // In windowed mode, the window can be resized while the game is
        // running.  This feature is disabled on OS X, as it adds an ugly
        // scroll handle to the corner of the screen.

#ifndef __MACOSX__
        flags |= SDL_RESIZABLE;
#endif
    }

    screen = SDL_SetVideoMode(w, h, screen_bpp, flags);

    if (screen == NULL)
    {
        I_Error("Error setting video mode %ix%ix%ibpp: %s\n",
                w, h, screen_bpp, SDL_GetError());
    }

    // Blank out the full screen area in case there is any junk in
    // the borders that won't otherwise be overwritten.

    SDL_FillRect(screen, NULL, 0);

    // If mode was not set, it must be set now that we know the
    // screen size.

    if (mode == NULL)
    {
        mode = I_FindScreenMode(screen->w, screen->h);

        if (mode == NULL)
        {
            I_Error("I_InitGraphics: Unable to find a screen mode small "
                    "enough for %ix%i", screen->w, screen->h);
        }

        // Generate lookup tables before setting the video mode.

        if (mode->InitMode != NULL)
        {
            mode->InitMode(doompal);
        }
    }

    // Create the screenbuffer surface; if we have a real 8-bit palettized
    // screen, then we can use the screen as the screenbuffer.

    if (screen->format->BitsPerPixel == 8)
    {
        screenbuffer = screen;
    }
    else
    {
        screenbuffer = SDL_CreateRGBSurface(SDL_SWSURFACE,
                                            mode->width, mode->height, 8,
                                            0, 0, 0, 0);

        SDL_FillRect(screenbuffer, NULL, 0);
    }

    // Save screen mode.

    screen_mode = mode;
}
Exemple #11
0
/*
** GLimp_InitGraphics
**
** This initializes the software refresh's implementation specific
** graphics subsystem.  In the case of Windows it creates DIB or
** DDRAW surfaces.
**
** The necessary width and height parameters are grabbed from
** vid.width and vid.height.
*/
static qboolean GLimp_InitGraphics( qboolean fullscreen )
{
	int flags;
	
	/* Just toggle fullscreen if that's all that has been changed */
	if (surface && (surface->w == vid.width) && (surface->h == vid.height)) {
		int isfullscreen = (surface->flags & SDL_FULLSCREEN) ? 1 : 0;
		if (fullscreen != isfullscreen)
			SDL_WM_ToggleFullScreen(surface);

		isfullscreen = (surface->flags & SDL_FULLSCREEN) ? 1 : 0;
		if (fullscreen == isfullscreen)
			return true;
	}
	
	srandom(getpid());

	// free resources in use
	if (surface)
		SDL_FreeSurface(surface);

	// let the sound and input subsystems know about the new window
	ri.Vid_NewWindow (vid.width, vid.height);

	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

	if (1) {
		SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
		SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
		SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
		SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
		SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
		SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
        }
        else {
		SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
		SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
		SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
		SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
        }
	
	flags = SDL_OPENGL;
	if (fullscreen)
		flags |= SDL_FULLSCREEN;
	
	SetSDLIcon(); /* currently uses q2icon.xbm data */
	
	if ((surface = SDL_SetVideoMode(vid.width, vid.height, 0, flags)) == NULL) {
		Sys_Error("(SDLGL) SDL SetVideoMode failed: %s\n", SDL_GetError());
		return false;
	}

	// stencilbuffer shadows
 	{
		int stencil_bits;
	  
		have_stencil = false;
	  
		if (!SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, &stencil_bits)) {
			ri.Con_Printf(PRINT_ALL, "I got %d bits of stencil\n", 
			              stencil_bits);
		
			if (stencil_bits >= 1) {
				have_stencil = true;
	    		}
	  	}
	}

	SDL_WM_SetCaption(WINDOW_CLASS_NAME, WINDOW_CLASS_NAME);

	SDL_ShowCursor(0);

	X11_active = true;
		
	SetSDLGamma();
	
	SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);

	return true;
}
Exemple #12
0
static rt_err_t  sdlfb_control(rt_device_t dev, rt_uint8_t cmd, void *args)
{
	struct sdlfb_device *device;

	device = (struct sdlfb_device*)dev;
	RT_ASSERT(device != RT_NULL);
	RT_ASSERT(device->screen != RT_NULL);

	switch (cmd)
	{
	case RTGRAPHIC_CTRL_GET_INFO:
		{
		struct rt_device_graphic_info *info;

		info = (struct rt_device_graphic_info*) args;
		info->bits_per_pixel = 16;
		info->pixel_format = RTGRAPHIC_PIXEL_FORMAT_RGB565P;
		info->framebuffer = device->screen->pixels;
		info->width = device->screen->w;
		info->height = device->screen->h;
		}
		break;
	case RTGRAPHIC_CTRL_RECT_UPDATE:
		{
		struct rt_device_rect_info *rect;
		rect = (struct rt_device_rect_info*)args;

		/* SDL_UpdateRect(_device.screen, rect->x, rect->y, rect->x + rect->w, rect->y + rect->h); */
		SDL_UpdateRect(_device.screen, 0, 0, device->width, device->height);
		}
		break;
	case RTGRAPHIC_CTRL_SET_MODE:
		{		
		struct rt_device_rect_info* rect;

		rect = (struct rt_device_rect_info*)args;
		if ((_device.width == rect->width) && (_device.height == rect->height)) return -RT_ERROR;
		
		_device.width = rect->width;
		_device.height = rect->height;
		
		if (_device.screen != RT_NULL)
		{
			SDL_FreeSurface(_device.screen);
		
			/* re-create screen surface */
			_device.screen = SDL_SetVideoMode(_device.width, _device.height, 16, SDL_SWSURFACE | SDL_DOUBLEBUF);
			if ( _device.screen == NULL )
			{
				fprintf(stderr, "Couldn't set video mode: %s\n", SDL_GetError());
				exit(1);
			}

			SDL_WM_SetCaption ("RT-Thread/GUI Simulator", NULL);
		}
		}
		break;
	}

	return RT_EOK;
}
Exemple #13
0
void sdl_free( void ) {
	if( config_get()->iface.full_screen )
		SDL_SetVideoMode( saved_video.current_w, saved_video.current_h, saved_video.vfmt->BitsPerPixel, SDL_FULLSCREEN );
	SDL_Quit();
}
Exemple #14
0
int main(int argc, char *argv[])
{	//inicializando SDL
        if(SDL_Init(SDL_INIT_VIDEO)<0)
        {       printf("Error al establecer modo video\n");exit(1);}
        SDL_WM_SetCaption("Prueba_botones",NULL);
        screen=SDL_SetVideoMode(ancho,alto,24,SDL_SWSURFACE);
        if(screen==NULL)
        {       printf("No se establecio el modo de video\n");
                exit(1);
        }
	//font
	TTF_Init();
	font_num=TTF_OpenFont("fonts/quid.ttf",60);
	if(font_num==NULL)
		printf("Error al cargar font\n");
	font_menu=TTF_OpenFont("fonts/font_menu.ttf",80);
	if(font_menu==NULL)
		printf("Error al cargar font_menu\n");
	font=TTF_OpenFont("fonts/FUAA.ttf",34);
	if(font==NULL)
		printf("Error en font\n");
	font_op=TTF_OpenFont("fonts/FUAA.ttf",20);
	arbol_ttf=TTF_OpenFont("fonts/arbol.ttf",25);
	if(arbol_ttf==NULL)
		printf("Error al cargar arbol\n");
	recorrido_ttf=TTF_OpenFont("fonts/arbol.ttf",17);
	fcolor.r=0; fcolor.g=0; fcolor.b=0;
	
	//principal
	A=NULL;
	int opcion=-1,n,dato;
	SDL_Rect pos;
	cargando_interface();
	menu_principal();
	draw_interface_principal();
	SDL_Event evento;
	while(opcion!=0)
	{	SDL_WaitEvent(&evento);
		if(evento.type==SDL_MOUSEMOTION)
		{	if(posicion_cursor(20,85,12,35,evento.motion.x,evento.motion.y))
			{	pos.x=20; pos.y=12;
				SDL_BlitSurface(boton_insertar[1],NULL,screen,&pos);
			}
			else if(posicion_cursor(145,210,12,35,evento.motion.x,evento.motion.y))
                        {       pos.x=145; pos.y=12;
                                SDL_BlitSurface(boton_eliminar[1],NULL,screen,&pos);
                        }
			else if(posicion_cursor(270,335,12,35,evento.motion.x,evento.motion.y))
                        {       pos.x=270; pos.y=12;
                                SDL_BlitSurface(boton_recorridos[1],NULL,screen,&pos);
                        }
			else if(posicion_cursor(820,885,12,35,evento.motion.x,evento.motion.y))
                        {       pos.x=820; pos.y=12;
                                SDL_BlitSurface(boton_salir[1],NULL,screen,&pos);
                        }
			else
				draw_menu_botones();
			SDL_Flip(screen);		
		}
		else if(evento.type==SDL_MOUSEBUTTONDOWN)
		{	if(posicion_cursor(820,885,12,35,evento.button.x,evento.button.y))
                        {
				menu_principal();
			}
			else if(posicion_cursor(20,85,12,35,evento.button.x,evento.button.y))
			{	dato=mini_ventana("Insertar dato: ",1);
				if(bandera!=0 && nivel_superado(A,0,dato))
					ventana_alerta("La rama supero el maximo");
				else
				{	if(bandera!=0)
						insertar_arbol(&A,dato);
					calcular_posiciones(A,70,450,450,0);
				}
				print_arbol(A,0);
				SDL_Flip(screen);
			}
			else if(posicion_cursor(145,210,12,35,evento.button.x,evento.button.y))
			{	dato=mini_ventana("Eliminar dato: ",2);
				eliminar(&A,dato);
				draw_interface_principal();
				calcular_posiciones(A,70,450,450,0);
				print_arbol(A,0);
				SDL_Flip(screen);
				
			}
			else if(posicion_cursor(270,335,12,35,evento.button.x,evento.button.y))
			{	ventana_recorridos();
			}
	
		}
		else if(evento.type==SDL_KEYDOWN)
                {       switch(evento.key.keysym.sym)
                        {       case SDLK_1:
				{ 	dato=mini_ventana("Insertar dato: ",1);
                               		if(bandera!=0 && nivel_superado(A,0,dato))
                                		ventana_alerta("La rama supero el maximo");	
					else
	                                {       if(bandera!=0)
        	                                        insertar_arbol(&A,dato);
                	                        calcular_posiciones(A,70,450,450,0);
                        	        }
                                	print_arbol(A,0);
                               		SDL_Flip(screen);
					break;
				}
				case SDLK_2:
				{	dato=mini_ventana("Eliminar dato: ",2);
  	         	                eliminar(&A,dato);
        	                        draw_interface_principal();
                	                calcular_posiciones(A,70,450,450,0);
                        	        print_arbol(A,0);
                                        SDL_Flip(screen);
       		                        break;
				}
				case SDLK_4:
				{	menu_principal();
					break;
				}
				case SDLK_3:
				{	ventana_recorridos();
					break;
				}
				
			}
		}
	}
	SDL_Quit();
	return 0;

}
//-----------------------------------------------------------------------------
// Initialize
//-----------------------------------------------------------------------------
bool GraphicsPlugin::initialize(GFX_INFO* graphicsInfo)
{
    //Initialize video output
    if (CoreVideo_Init() != M64ERR_SUCCESS)
    {
        Logger::getSingleton().printMsg("Could not initialize video.", M64MSG_ERROR);
        return false;
    }

    //Save pointer to graphics info
    m_graphicsInfo = graphicsInfo;

    m_numDListProcessed = 0;

    //Detect what rom it is
    m_romDetector = &ROMDetector::getSingleton();        
    m_romDetector->initialize( m_graphicsInfo->HEADER );
#ifdef HAVE_GLES
	SDL_SetVideoMode(m_config->fullscreenWidth, m_config->fullscreenHeight, m_config->fullscreenBitDepth, SDL_FULLSCREEN);
    SDL_ShowCursor(SDL_DISABLE);
	EGL_Open(m_config->fullscreenWidth, m_config->fullscreenHeight);
#else
    if (m_config->multiSampling > 0)
    {
        CoreVideo_GL_SetAttribute(M64P_GL_MULTISAMPLEBUFFERS, 1);
        if (m_config->multiSampling <= 2)
            CoreVideo_GL_SetAttribute(M64P_GL_MULTISAMPLESAMPLES, 2);
        else if (m_config->multiSampling <= 4)
            CoreVideo_GL_SetAttribute(M64P_GL_MULTISAMPLESAMPLES, 4);
        else if (m_config->multiSampling <= 8)
            CoreVideo_GL_SetAttribute(M64P_GL_MULTISAMPLESAMPLES, 8);
        else
            CoreVideo_GL_SetAttribute(M64P_GL_MULTISAMPLESAMPLES, 16);
    }

    if (CoreVideo_GL_SetAttribute(M64P_GL_DOUBLEBUFFER, 1) != M64ERR_SUCCESS ||
        CoreVideo_GL_SetAttribute(M64P_GL_BUFFER_SIZE, 32) != M64ERR_SUCCESS ||
        CoreVideo_GL_SetAttribute(M64P_GL_DEPTH_SIZE, 24)  != M64ERR_SUCCESS)
    {
        Logger::getSingleton().printMsg("Could not set video attributes.", M64MSG_ERROR);
        return false;
    }

    if (CoreVideo_SetVideoMode(m_config->fullscreenWidth, m_config->fullscreenHeight, m_config->fullscreenBitDepth, 
        m_config->startFullscreen ? M64VIDEO_FULLSCREEN : M64VIDEO_WINDOWED, (m64p_video_flags) 0) != M64ERR_SUCCESS)
    {
        Logger::getSingleton().printMsg("Could not set video mode.", M64MSG_ERROR);
        return false;
    }

    CoreVideo_SetCaption("Arachnoid");
#endif
    //Initialize Video Interface
    m_vi = new VI();
    m_vi->calcSize(m_graphicsInfo);

    //Initialize Memory
    m_memory = new Memory();
    if ( !m_memory->initialize(m_graphicsInfo->RDRAM, m_graphicsInfo->DMEM) ) 
    {
        return false;
    }
    
    m_displayListParser = new DisplayListParser();
    m_displayListParser->initialize(&m_rsp, &m_rdp, &m_gbi, m_memory);

    //Init OpenGL
    if ( !m_openGLMgr.initialize(m_config->startFullscreen, m_config->fullscreenWidth, m_config->fullscreenHeight, m_config->fullscreenBitDepth, m_config->fullscreenRefreshRate, true, false) ) 
    {
        Logger::getSingleton().printMsg("Unable to initialize OpenGL", M64MSG_ERROR);
        return false;
    }

    
    m_openGLMgr.calcViewScale(m_vi->getWidth(), m_vi->getHeight());

    //Initialize Fog Manager
    m_fogManager = new FogManager();
    m_fogManager->initialize();



    //Initialize Texture Cache
    //! @todo Not "hardcode" TextureBitDepth.
    m_textureCache.initialize(&m_rsp, &m_rdp, m_memory, 16);
    m_textureCache.setMipmap( m_config->mipmapping );

    //Initialize OpenGL Renderer
    if ( !OpenGLRenderer::getSingleton().initialize(&m_rsp, &m_rdp, &m_textureCache, m_vi, m_fogManager) ) 
    {
        Logger::getSingleton().printMsg("Unable to initialize OpenGL Renderer", M64MSG_ERROR);
        return false;
    }

    //Initialize Processors
    m_rdp.initialize(m_graphicsInfo, &m_rsp, m_memory, &m_gbi, &m_textureCache, m_vi, m_displayListParser, m_fogManager);
    m_rsp.initialize(m_graphicsInfo, &m_rdp, m_memory, m_vi, m_displayListParser, m_fogManager);
    m_gbi.initialize(&m_rsp, &m_rdp, m_memory, m_displayListParser);    
        

    //Set Background color
    m_openGLMgr.setClearColor(0.0f, 0.0f, 0.0f);
    m_openGLMgr.setLighting(false);
    glDisable(GL_LIGHTING);
    m_openGLMgr.setCullMode(false, true);
    m_openGLMgr.setWireFrame(m_config->wireframe);   

    //Initialize framebuffer
    //framebuffer01.initialize(width, height);
   // framebuffer02.initialize(width, height);

    m_initialized = true;
    return true;
}
Exemple #16
0
int main(int argc, char *argv[])
{
	SDL_Surface *screen;
	SDL_Surface *icon;
	Uint8 *icon_mask;
	int i, parsed;
	Uint8 *buffer;
	SDL_Color palette[256];
	Uint32 init_flags;
	Uint8  video_bpp;
	Uint32 video_flags;
	SDL_Thread *mouse_thread;
	SDL_Thread *keybd_thread;

	/* Set the options, based on command line arguments */
	init_flags = SDL_INIT_VIDEO;
	video_bpp = 8;
	video_flags = SDL_SWSURFACE;
	parsed = 1;
	while ( parsed ) {
		/* If the threaded option is enabled, and the SDL library hasn't
		   been compiled with threaded events enabled, then the mouse and
		   keyboard won't respond.
		 */
		if ( (argc >= 2) && (strcmp(argv[1], "-threaded") == 0) ) {
			init_flags |= SDL_INIT_EVENTTHREAD;
			argc -= 1;
			argv += 1;
			printf("Running with threaded events\n");
		} else
		if ( (argc >= 2) && (strcmp(argv[1], "-fullscreen") == 0) ) {
			video_flags |= SDL_FULLSCREEN;
			argc -= 1;
			argv += 1;
		} else
		if ( (argc >= 3) && (strcmp(argv[1], "-bpp") == 0) ) {
			video_bpp = atoi(argv[2]);
			argc -= 2;
			argv += 2;
		} else {
			parsed = 0;
		}
	}

	/* Initialize SDL with the requested flags */
	if ( SDL_Init(init_flags) < 0 ) {
		fprintf(stderr,
			"Couldn't initialize SDL: %s\n", SDL_GetError());
		return(1);
	}

	/* Set the icon -- this must be done before the first mode set */
	icon = LoadIconSurface("app/native/icon.bmp", &icon_mask);
	if ( icon != NULL ) {
		SDL_WM_SetIcon(icon, icon_mask);
	}
	if ( icon_mask != NULL )
		free(icon_mask);

	/* Initialize the display */
	screen = SDL_SetVideoMode(640, 480, video_bpp, video_flags);
	if (  screen == NULL ) {
		fprintf(stderr, "Couldn't set 640x480x%d video mode: %s\n",
						video_bpp, SDL_GetError());
		quit(1);
	}
	printf("Running in %s mode\n", screen->flags & SDL_FULLSCREEN ?
						"fullscreen" : "windowed");

	/* Enable printable characters */
	SDL_EnableUNICODE(1);

	/* Set an event filter that discards everything but QUIT */
	SDL_SetEventFilter(FilterEvents);

	/* Create the event handling threads */
	mouse_thread = SDL_CreateThread(HandleMouse, NULL);
	keybd_thread = SDL_CreateThread(HandleKeyboard, NULL);

	/* Set the surface pixels and refresh! */
	for ( i=0; i<256; ++i ) {
		palette[i].r = 255-i;
		palette[i].g = 255-i;
		palette[i].b = 255-i;
	}
	SDL_SetColors(screen, palette, 0, 256);
	if ( SDL_LockSurface(screen) < 0 ) {
		fprintf(stderr, "Couldn't lock display surface: %s\n",
							SDL_GetError());
		quit(2);
	}
	buffer = (Uint8 *)screen->pixels;
	for ( i=0; i<screen->h; ++i ) {
		memset(buffer,(i*255)/screen->h,
				screen->w*screen->format->BytesPerPixel);
		buffer += screen->pitch;
	}
	SDL_UnlockSurface(screen);
	SDL_UpdateRect(screen, 0, 0, 0, 0);

	/* Loop, waiting for QUIT */
	while ( ! done ) {
		if ( ! (init_flags & SDL_INIT_EVENTTHREAD) ) {
			SDL_PumpEvents(); /* Needed when event thread is off */
		}
		if ( SDL_PeepEvents(NULL, 0, SDL_PEEKEVENT, SDL_QUITMASK) ) {
			done = 1;
		}
		/* Give up some CPU so the events can accumulate */
		SDL_Delay(20);
	}
	SDL_WaitThread(mouse_thread, NULL);
	SDL_WaitThread(keybd_thread, NULL);
	SDL_Quit();
	return(0);
}
Exemple #17
0
/** Sets the height and width of the window.
	@param iWidth The width of the window
	@param iHeight The height of the window
**/
void CEngine::SetSize(const int& iWidth, const int& iHeight)
{
	m_iWidth  = iWidth;
	m_iHeight = iHeight;
	m_pScreen = SDL_SetVideoMode( iWidth, iHeight, 0, SDL_SWSURFACE );
}
int main(int argc, char *argv[]) {
    AVFormatContext *pFormatCtx = NULL;
    int             i, videoStream;
    AVCodecContext  *pCodecCtx = NULL;
    AVCodecParameters       *pCodecParam = NULL;
    AVCodec         *pCodec = NULL;
    AVFrame         *pFrame = NULL;
    AVPacket        packet;
    int             send_packet, receive_frame;
    //float           aspect_ratio;
    AVFrame        *pict;
    /*
    std::unique_ptr<AVFrame, std::function<void(AVFrame*)>> frame_converted{
        av_frame_alloc(),
        [](AVFrame* f){ av_free(f->data[0]); } };
    if (av_frame_copy_props(frame_converted.get(),
        frame_decoded.get()) < 0) {
        throw std::runtime_error("Copying frame properties");
    }
    if (av_image_alloc(
        frame_converted->data, frame_converted->linesize,
        video_decoder_->width(), video_decoder_->height(),
        video_decoder_->pixel_format(), 1) < 0) {
        throw std::runtime_error("Allocating picture");
    }
    */
    AVDictionary    *optionsDict = NULL;
    struct SwsContext *sws_ctx = NULL;

    SDL_Texture*    pTexture = nullptr;
    SDL_Window*     pWindows = nullptr;
    SDL_Renderer*   pRenderer = nullptr;

    SDL_Event       event;

    if (argc < 2) {
        fprintf(stderr, "Usage: test <file>\n");
        exit(1);
    }
    // Register all formats and codecs
    av_register_all();

    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) {
        fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError());
        exit(1);
    }

    // Open video file
    if (avformat_open_input(&pFormatCtx, argv[1], NULL, NULL) != 0)
        return -1; // Couldn't open file

    // Retrieve stream information
    if (avformat_find_stream_info(pFormatCtx, NULL)<0)
        return -1; // Couldn't find stream information

    // Dump information about file onto standard error
    av_dump_format(pFormatCtx, 0, argv[1], 0);

    // Find the first video stream
    videoStream = -1;
    for (i = 0; i<pFormatCtx->nb_streams; i++)
        if (pFormatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
            videoStream = i;
            break;
        }
    if (videoStream == -1)
        return -1; // Didn't find a video stream

    // Get a pointer to the codec context for the video stream
    //AVCodecContext *codec is deprecated,so use the codecpar struct (AVCodecParameters) instead.
    pCodecParam = pFormatCtx->streams[videoStream]->codecpar;
    //but function avcodec_open2() need pCodecCtx,so copy  (AVCodecParameters) pCodecParam to (AVCodecContext) pCodecCtx
    pCodec = avcodec_find_decoder(pCodecParam->codec_id);
    // Find the decoder for the video stream
    if (pCodec == NULL) {
        fprintf(stderr, "Unsupported codec!\n");
        return -1; // Codec not found
    }
    pCodecCtx = avcodec_alloc_context3(pCodec);
    avcodec_parameters_to_context(pCodecCtx, pCodecParam);

    // Open codec
    if (avcodec_open2(pCodecCtx, pCodec, &optionsDict)<0)
        return -1; // Could not open codec

    // Allocate video frame
    pFrame = av_frame_alloc();

    // Make a screen to put our video
#ifndef __DARWIN__
    pWindows = SDL_CreateWindow(argv[1],SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,pCodecParam->width, pCodecParam->height,SDL_WINDOW_BORDERLESS|SDL_WINDOW_RESIZABLE);
#else
    screen = SDL_SetVideoMode(pCodecParam->width, pCodecParam->height, 24, 0);
#endif
    if (!pWindows) {
        fprintf(stderr, "SDL: could not set video mode - exiting\n");
        exit(1);
    }
    
    // Allocate a place to put our YUV image on that screen
    pRenderer = SDL_CreateRenderer(pWindows, -1, 0);
    if (!pRenderer) {
        fprintf(stderr, "SDL: could not create renderer - exiting\n");
        exit(1);
    }
    pTexture = SDL_CreateTexture(pRenderer, SDL_PIXELFORMAT_YV12, SDL_TEXTUREACCESS_STREAMING, pCodecParam->width, pCodecParam->height);
    sws_ctx =
        sws_getContext
        (
        pCodecParam->width,
        pCodecParam->height,
        (AVPixelFormat)pCodecParam->format,
        pCodecParam->width,
        pCodecParam->height,
        AV_PIX_FMT_YUV420P,
        SWS_BILINEAR,
        NULL,
        NULL,
        NULL
        );
    pict = av_frame_alloc();
    if (pict == nullptr){
        exit(1);
    }
    if (av_image_alloc(pict->data, pict->linesize,
        pCodecParam->width, pCodecParam->height,
        (AVPixelFormat)pCodecParam->format, 1) < 0){
        exit(1);
    }


    // Read frames and save first five frames to disk
    i = 0;
    while (av_read_frame(pFormatCtx, &packet) >= 0) {
        // Is this a packet from the video stream?
        if (packet.stream_index == videoStream) {
            // Decode video frame
            //avcodec_decode_video2 is deprecated Use avcodec_send_packet() and avcodec_receive_frame().
            send_packet = avcodec_send_packet(pCodecCtx, &packet);
            receive_frame = avcodec_receive_frame(pCodecCtx, pFrame);

            // Did we get a video frame?
            if (send_packet == SEND_PACKET_SUCCESS && receive_frame == RECEIVE_FRAME_SUCCESS) {
                //SDL_LockYUVOverlay(bmp);
                //SDL_LockTexture(pTexture,NULL,);
                // Convert the image into YUV format that SDL uses
                if (av_frame_copy_props(pFrame,
                    pict) < 0) {
                    exit(1);
                }

                sws_scale
                    (
                    sws_ctx,
                    pFrame->data,
                    pFrame->linesize,
                    0,
                    pCodecParam->height,
                    pict->data,
                    pict->linesize
                    );
                
                //SDL_UnlockYUVOverlay(bmp);
                SDL_UpdateYUVTexture(pTexture, NULL, pict->data[0], pict->linesize[0], pict->data[1], pict->linesize[1], pict->data[2], pict->linesize[2]);
                SDL_RenderCopy(pRenderer, pTexture, NULL, NULL);
                SDL_RenderPresent(pRenderer);

            }
        }

        // Free the packet that was allocated by av_read_frame
        av_packet_unref(&packet);
        SDL_PollEvent(&event);
        switch (event.type) {
        case SDL_QUIT:
            SDL_DestroyRenderer(pRenderer);
            SDL_DestroyTexture(pTexture);
            SDL_DestroyWindow(pWindows);
            SDL_Quit();
            exit(0);
            break;
        default:
            break;
        }

    }

    // Free the YUV frame
    av_frame_free(&pFrame);
    //free pict
    av_freep(&pict->data[0]);
    av_frame_free(&pict);

    // Close the codec
    avcodec_close(pCodecCtx);

    // Close the video file
    avformat_close_input(&pFormatCtx);

    return 0;
}
int
main(int argc, char *argv[])
{
    const SDL_VideoInfo *info;
    SDL_Surface *screen;
    int w, h;
    Uint8 video_bpp;
    Uint32 videoflags;
    int i, done;
    SDL_Event event;
    SDL_Surface *light;
    int mouse_pressed;
    Uint32 ticks, lastticks;


    /* Initialize SDL */
    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError());
        return (1);
    }

    /* Alpha blending doesn't work well at 8-bit color */
#ifdef _WIN32_WCE
    /* Pocket PC */
    w = 240;
    h = 320;
#else
    w = 640;
    h = 480;
#endif
    info = SDL_GetVideoInfo();
    if (info->vfmt->BitsPerPixel > 8) {
        video_bpp = info->vfmt->BitsPerPixel;
    } else {
        video_bpp = 16;
        fprintf(stderr, "forced 16 bpp mode\n");
    }
    videoflags = SDL_SWSURFACE;
    for (i = 1; argv[i]; ++i) {
        if (strcmp(argv[i], "-bpp") == 0) {
            video_bpp = atoi(argv[++i]);
            if (video_bpp <= 8) {
                video_bpp = 16;
                fprintf(stderr, "forced 16 bpp mode\n");
            }
        } else if (strcmp(argv[i], "-hw") == 0) {
            videoflags |= SDL_HWSURFACE;
        } else if (strcmp(argv[i], "-warp") == 0) {
            videoflags |= SDL_HWPALETTE;
        } else if (strcmp(argv[i], "-width") == 0 && argv[i + 1]) {
            w = atoi(argv[++i]);
        } else if (strcmp(argv[i], "-height") == 0 && argv[i + 1]) {
            h = atoi(argv[++i]);
        } else if (strcmp(argv[i], "-resize") == 0) {
            videoflags |= SDL_RESIZABLE;
        } else if (strcmp(argv[i], "-noframe") == 0) {
            videoflags |= SDL_NOFRAME;
        } else if (strcmp(argv[i], "-fullscreen") == 0) {
            videoflags |= SDL_FULLSCREEN;
        } else {
            fprintf(stderr,
                    "Usage: %s [-width N] [-height N] [-bpp N] [-warp] [-hw] [-fullscreen]\n",
                    argv[0]);
            quit(1);
        }
    }

    /* Set video mode */
    if ((screen = SDL_SetVideoMode(w, h, video_bpp, videoflags)) == NULL) {
        fprintf(stderr, "Couldn't set %dx%dx%d video mode: %s\n",
                w, h, video_bpp, SDL_GetError());
        quit(2);
    }
    FillBackground(screen);

    /* Create the light */
    light = CreateLight(82);
    if (light == NULL) {
        quit(1);
    }

    /* Load the sprite */
    if (LoadSprite(screen, "icon.bmp") < 0) {
        SDL_FreeSurface(light);
        quit(1);
    }

    /* Print out information about our surfaces */
    printf("Screen is at %d bits per pixel\n", screen->format->BitsPerPixel);
    if ((screen->flags & SDL_HWSURFACE) == SDL_HWSURFACE) {
        printf("Screen is in video memory\n");
    } else {
        printf("Screen is in system memory\n");
    }
    if ((screen->flags & SDL_DOUBLEBUF) == SDL_DOUBLEBUF) {
        printf("Screen has double-buffering enabled\n");
    }
    if ((sprite->flags & SDL_HWSURFACE) == SDL_HWSURFACE) {
        printf("Sprite is in video memory\n");
    } else {
        printf("Sprite is in system memory\n");
    }

    /* Run a sample blit to trigger blit acceleration */
    MoveSprite(screen, NULL);
    if ((sprite->flags & SDL_HWACCEL) == SDL_HWACCEL) {
        printf("Sprite blit uses hardware alpha acceleration\n");
    } else {
        printf("Sprite blit dosn't uses hardware alpha acceleration\n");
    }

    /* Set a clipping rectangle to clip the outside edge of the screen */
    {
        SDL_Rect clip;
        clip.x = 32;
        clip.y = 32;
        clip.w = screen->w - (2 * 32);
        clip.h = screen->h - (2 * 32);
        SDL_SetClipRect(screen, &clip);
    }

    /* Wait for a keystroke */
    lastticks = SDL_GetTicks();
    done = 0;
    mouse_pressed = 0;
    while (!done) {
        /* Update the frame -- move the sprite */
        if (mouse_pressed) {
            MoveSprite(screen, light);
            mouse_pressed = 0;
        } else {
            MoveSprite(screen, NULL);
        }

        /* Slow down the loop to 30 frames/second */
        ticks = SDL_GetTicks();
        if ((ticks - lastticks) < FRAME_TICKS) {
#ifdef CHECK_SLEEP_GRANULARITY
            fprintf(stderr, "Sleeping %d ticks\n",
                    FRAME_TICKS - (ticks - lastticks));
#endif
            SDL_Delay(FRAME_TICKS - (ticks - lastticks));
#ifdef CHECK_SLEEP_GRANULARITY
            fprintf(stderr, "Slept %d ticks\n", (SDL_GetTicks() - ticks));
#endif
        }
        lastticks = ticks;

        /* Check for events */
        while (SDL_PollEvent(&event)) {
            switch (event.type) {
            case SDL_VIDEORESIZE:
                screen =
                    SDL_SetVideoMode(event.resize.w, event.resize.h,
                                     video_bpp, videoflags);
                if (screen) {
                    FillBackground(screen);
                }
                break;
                /* Attract sprite while mouse is held down */
            case SDL_MOUSEMOTION:
                if (event.motion.state != 0) {
                    AttractSprite(event.motion.x, event.motion.y);
                    mouse_pressed = 1;
                }
                break;
            case SDL_MOUSEBUTTONDOWN:
                if (event.button.button == 1) {
                    AttractSprite(event.button.x, event.button.y);
                    mouse_pressed = 1;
                } else {
                    SDL_Rect area;

                    area.x = event.button.x - 16;
                    area.y = event.button.y - 16;
                    area.w = 32;
                    area.h = 32;
                    SDL_FillRect(screen, &area,
                                 SDL_MapRGB(screen->format, 0, 0, 0));
                    SDL_UpdateRects(screen, 1, &area);
                }
                break;
            case SDL_KEYDOWN:
                if (event.key.keysym.sym == SDLK_ESCAPE) {
                    done = 1;
                }
                if (event.key.keysym.sym == SDLK_RETURN) {
                    SDL_WM_ToggleFullScreen(screen);
                }
                break;
            case SDL_QUIT:
                done = 1;
                break;
            default:
                break;
            }
        }
    }
    SDL_FreeSurface(light);
    SDL_FreeSurface(sprite);
    SDL_FreeSurface(backing);

    /* Print out some timing information */
    if (flashes > 0) {
        printf("%d alpha blits, ~%4.4f ms per blit\n",
               flashes, (float) flashtime / flashes);
    }

    SDL_Quit();
    return (0);
}
Exemple #20
0
// Entry point
int main(int argc, char *argv[])
{
  // Initialize SDL's subsystems - in this case, only video.
  if ( SDL_Init(SDL_INIT_VIDEO) < 0 ) 
  {
    fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError());
    exit(1);
  }
  
  // printf(" size %d ", sizeof(coordlist)/sizeof(Coord));
  // Register SDL_Quit to be called at exit; makes sure things are
  // cleaned up when we quit.
  atexit(SDL_Quit);
    
  // Attempt to create a 640x480 window with 32bit pixels.
  screen = SDL_SetVideoMode(800, 600, 32, SDL_SWSURFACE);
  
  // If we fail, return error.
  if ( screen == NULL ) 
  {
    fprintf(stderr, "Unable to set 640x480 video: %s\n", SDL_GetError());
    exit(1);
  }

  List *list = new List();
  Coord* crd1 = new Coord(12,123);
  Coord* crd2 = new Coord(300,100);
  list->append(*crd1);
  list->append(*crd2);
  list->add_after_last_point(-10,20);
  // list->get(0).x=10; this is bad I guess... -fpermissive?
  printf("0--> %d %d\n",list->get(0).x,list->get(0).y);
  printf("1--> %d %d\n",list->get(1).x,list->get(1).y);
  printf("2--> %d %d\n",list->get(2).x,list->get(2).y);


  // Main loop: loop forever.
  while (1)
  {
    // Render stuff
    render();


    // Poll for events, and handle the ones we care about.
    SDL_Event event;
    while (SDL_PollEvent(&event)) 
    {
      switch (event.type) 
      {
      case SDL_KEYDOWN:
        break;
      case SDL_KEYUP:
        // If escape is pressed, return (and thus, quit)
        if (event.key.keysym.sym == SDLK_ESCAPE)
          return 0;
        break;
      case SDL_QUIT:
        return(0);
      }
    }
  }
  return 0;
}
//@param flags Video flags for SDL video subsystem
//@return 0 on success.
static int setupVideo(int *flags, SDL_Surface *surface)
{
    int videoFlags = 0;
    /* initialize SDL */
    if ( SDL_Init( SDL_INIT_VIDEO ) < 0 )
    {
	    fprintf( stderr, "Video initialization failed: %s\n",
                SDL_GetError( ) );
	    return 1;
	}
    /* this holds some info about our display */
    const SDL_VideoInfo *videoInfo;
    /* Fetch the video info */
    videoInfo = SDL_GetVideoInfo( );
    
    if ( !videoInfo )
	{
	    fprintf( stderr, "Video query failed: %s\n",
                SDL_GetError( ) );
	    return 1;
	}

    /* the flags to pass to SDL_SetVideoMode */
    videoFlags  = SDL_OPENGL;          /* Enable OpenGL in SDL */
    videoFlags |= SDL_GL_DOUBLEBUFFER; /* Enable double buffering */
    videoFlags |= SDL_HWPALETTE;       /* Store the palette in hardware */
    videoFlags |= SDL_RESIZABLE;       /* Enable window resizing */
    //videoFlags |= SDL_FULLSCREEN;
    
    /* This checks to see if surfaces can be stored in memory */
    if ( videoInfo->hw_available )
        videoFlags |= SDL_HWSURFACE;
    else
        videoFlags |= SDL_SWSURFACE;
    
    /* This checks if hardware blits can be done */
    if ( videoInfo->blit_hw )
        videoFlags |= SDL_HWACCEL;
    
    /* Sets up OpenGL double buffering */
    SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
    SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, TRUE);

    *flags = videoFlags;

    /* get a SDL surface */
    surface = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP,
		videoFlags );

    /* Verify there is a surface */
    if ( !surface )
	{
	    fprintf( stderr,  "Video mode set failed: %s\n", SDL_GetError( ) );
	    return 1;
	}

    /* initialize OpenGL */
    initGL( );
    
    /* resize the initial window */
    resizeWindow( SCREEN_WIDTH, SCREEN_HEIGHT );
    SDL_WM_GrabInput( SDL_GRAB_ON );
    SDL_ShowCursor(0);
    
    return 0;
}
Exemple #22
0
int main(int argc, char **argv)
{
    char inp[60];
    int i, j, seed;

    seed = time((time_t *)0);
    srand(seed);

    /* Initialize SDL */

    if (SDL_Init(SDL_INIT_VIDEO) < 0)
        exit(1);

    atexit(SDL_Quit);

    pdc_screen = SDL_SetVideoMode(640, 480, 0, SDL_SWSURFACE|SDL_ANYFORMAT);

    /* Initialize PDCurses */

    pdc_yoffset = 416;  /* 480 - 4 * 16 */

    initscr();
    start_color();
    scrollok(stdscr, TRUE);

    PDC_set_title("PDCurses for SDL");

    /* Do some SDL stuff */

    for (i = 640, j = 416; j; i -= 2, j -= 2)
    {
        SDL_Rect dest;

        dest.x = (640 - i) / 2;
        dest.y = (416 - j) / 2;
        dest.w = i;
        dest.h = j;

        SDL_FillRect(pdc_screen, &dest, 
                     SDL_MapRGB(pdc_screen->format, rand() % 256,
                                rand() % 256, rand() % 256));
    }

    SDL_UpdateRect(pdc_screen, 0, 0, 640, 416);

    /* Do some curses stuff */

    init_pair(1, COLOR_WHITE + 8, COLOR_BLUE);
    bkgd(COLOR_PAIR(1));

    addstr("This is a demo of ");
    attron(A_UNDERLINE);
    addstr("PDCurses for SDL");
    attroff(A_UNDERLINE);
    addstr(".\nYour comments here: ");
    getnstr(inp, 59);
    addstr("Press any key to exit.");

    getch();
    endwin();

    return 0;
}
Exemple #23
0
int plat_sdl_init(void)
{
  static const char *vout_list[] = { NULL, NULL, NULL, NULL };
  const SDL_VideoInfo *info;
  SDL_SysWMinfo wminfo;
  int overlay_works = 0;
  int gl_works = 0;
  int i, ret, h;

  ret = SDL_Init(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE);
  if (ret != 0) {
    fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());
    return -1;
  }

  info = SDL_GetVideoInfo();
  if (info != NULL) {
    fs_w = info->current_w;
    fs_h = info->current_h;
    printf("plat_sdl: using %dx%d as fullscreen resolution\n", fs_w, fs_h);
  }

  g_menuscreen_w = 640;
  if (fs_w != 0 && g_menuscreen_w > fs_w)
    g_menuscreen_w = fs_w;
  g_menuscreen_h = 480;
  if (fs_h != 0) {
    h = fs_h;
    if (info && info->wm_available && h > WM_DECORATION_H)
      h -= WM_DECORATION_H;
    if (g_menuscreen_h > h)
      g_menuscreen_h = h;
  }

  ret = plat_sdl_change_video_mode(g_menuscreen_w, g_menuscreen_h, 1);
  if (ret != 0) {
    plat_sdl_screen = SDL_SetVideoMode(0, 0, 16, SDL_SWSURFACE);
    if (plat_sdl_screen == NULL) {
      fprintf(stderr, "SDL_SetVideoMode failed: %s\n", SDL_GetError());
      goto fail;
    }

    if (plat_sdl_screen->w < 320 || plat_sdl_screen->h < 240) {
      fprintf(stderr, "resolution %dx%d is too small, sorry.\n",
              plat_sdl_screen->w, plat_sdl_screen->h);
      goto fail;
    }
  }
  g_menuscreen_w = window_w = plat_sdl_screen->w;
  g_menuscreen_h = window_h = plat_sdl_screen->h;

  plat_sdl_overlay = SDL_CreateYUVOverlay(plat_sdl_screen->w, plat_sdl_screen->h,
    SDL_UYVY_OVERLAY, plat_sdl_screen);
  if (plat_sdl_overlay != NULL) {
    printf("plat_sdl: overlay: fmt %x, planes: %d, pitch: %d, hw: %d\n",
      plat_sdl_overlay->format, plat_sdl_overlay->planes, *plat_sdl_overlay->pitches,
      plat_sdl_overlay->hw_overlay);

    if (plat_sdl_overlay->hw_overlay)
      overlay_works = 1;
    else
      fprintf(stderr, "warning: video overlay is not hardware accelerated, "
                      "not going to use it.\n");
    SDL_FreeYUVOverlay(plat_sdl_overlay);
    plat_sdl_overlay = NULL;
  }
  else
    fprintf(stderr, "overlay is not available.\n");

  // get x11 display/window for GL
  SDL_VideoDriverName(vid_drv_name, sizeof(vid_drv_name));
#ifdef SDL_VIDEO_DRIVER_X11
  if (strcmp(vid_drv_name, "x11") == 0) {
    SDL_VERSION(&wminfo.version);
    ret = SDL_GetWMInfo(&wminfo);
    if (ret > 0) {
      display = wminfo.info.x11.display;
      window = (void *)wminfo.info.x11.window;
    }
  }
#endif

  ret = gl_init(display, window, &gl_quirks);
  if (ret == 0) {
    gl_works = 1;
    gl_finish();
  }

  i = 0;
  vout_list[i++] = "SDL Window";
  if (overlay_works) {
    plat_target.vout_method = vout_mode_overlay = i;
    vout_list[i++] = "Video Overlay";
  }
  if (gl_works) {
    plat_target.vout_method = vout_mode_gl = i;
    vout_list[i++] = "OpenGL";
  }
  plat_target.vout_methods = vout_list;

  return 0;

fail:
  SDL_Quit();
  return -1;
}
int main(int argc, char *argv[]) {
    AVFormatContext *pFormatCtx = NULL;
    int             i, videoStream;
    AVCodecContext  *pCodecCtx;
    AVCodec         *pCodec;
    AVFrame         *pFrame;
    AVPacket        packet;
    int             frameFinished;
    float           aspect_ratio;
    struct SwsContext *img_convert_ctx;

    SDL_Overlay     *bmp;
    SDL_Surface     *screen;
    SDL_Rect        rect;
    SDL_Event       event;

    if(argc < 2) {
        fprintf(stderr, "Usage: test <file>\n");
        exit(1);
    }
    // Register all formats and codecs
    av_register_all();

    if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) {
        fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError());
        exit(1);
    }

    // Open video file
    if(avformat_open_input(&pFormatCtx, argv[1], NULL, NULL)!=0)
        return -1; // Couldn't open file

    // Retrieve stream information
    if(avformat_find_stream_info(pFormatCtx, NULL)<0)
        return -1; // Couldn't find stream information

    // Find the first video stream
    videoStream=-1;
    for(i=0; i<pFormatCtx->nb_streams; i++)
        if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
            videoStream=i;
            break;
        }
    if(videoStream==-1)
        return -1; // Didn't find a video stream

    // Get a pointer to the codec context for the video stream
    pCodecCtx=pFormatCtx->streams[videoStream]->codec;

    // Find the decoder for the video stream
    pCodec=avcodec_find_decoder(pCodecCtx->codec_id);
    if(pCodec==NULL) {
        fprintf(stderr, "Unsupported codec!\n");
        return -1; // Codec not found
    }

    // Open codec
    if(avcodec_open2(pCodecCtx, pCodec, NULL)<0)
        return -1; // Could not open codec

    // Allocate video frame
    pFrame=av_frame_alloc();

    // Make a screen to put our video
    screen = SDL_SetVideoMode(pCodecCtx->width, pCodecCtx->height, 0, 0);

    if(!screen) {
        fprintf(stderr, "SDL: could not set video mode - exiting\n");
        exit(1);
    }

    // Allocate a place to put our YUV image on that screen
    bmp = SDL_CreateYUVOverlay(pCodecCtx->width,
            pCodecCtx->height,
            SDL_YV12_OVERLAY,
            screen);


    // Read frames and save first five frames to disk
    i=0;
    while(av_read_frame(pFormatCtx, &packet)>=0) {
        // Is this a packet from the video stream?
        if(packet.stream_index==videoStream) {
            // Decode video frame
            avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished,
                    &packet);

            // Did we get a video frame?
            if(frameFinished) {
                SDL_LockYUVOverlay(bmp);

                AVPicture pict;
                pict.data[0] = bmp->pixels[0];
                pict.data[1] = bmp->pixels[2];
                pict.data[2] = bmp->pixels[1];

                pict.linesize[0] = bmp->pitches[0];
                pict.linesize[1] = bmp->pitches[2];
                pict.linesize[2] = bmp->pitches[1];

                // Convert the image into YUV format that SDL uses
                img_convert_ctx = sws_getContext(pCodecCtx->width,
                        pCodecCtx->height,
                        pCodecCtx->pix_fmt,
                        pCodecCtx->width,
                        pCodecCtx->height,
                        PIX_FMT_YUV420P,
                        SWS_BICUBIC,NULL,
                        NULL,NULL);
                sws_scale(img_convert_ctx, pFrame->data,
                        pFrame->linesize,
                        0,
                        pFrame->height,
                        pict.data,
                        pict.linesize);

                SDL_UnlockYUVOverlay(bmp);

                rect.x = 0;
                rect.y = 0;
                rect.w = pCodecCtx->width;
                rect.h = pCodecCtx->height;
                SDL_DisplayYUVOverlay(bmp, &rect);

            }
        }

        // Free the packet that was allocated by av_read_frame
        av_free_packet(&packet);
        SDL_PollEvent(&event);
        switch(event.type) {
            case SDL_QUIT:
                SDL_Quit();
                exit(0);
                break;
            default:
                break;
        }

    }

    // Free the YUV frame
    av_free(pFrame);

    // Close the codec
    avcodec_close(pCodecCtx);

    // Close the video file
    avformat_close_input(&pFormatCtx);

    return 0;
}
Exemple #25
0
int SDL_main (int argc,char* argv[]) {
#elif __APPLE__
int SDL_main (int argc,char* argv[]) {
#else
#ifdef main
#undef main
#endif
int main(int argc,char* argv[]) {
#endif

printf("[INFO] Entering main\n");

uint32_t flags=SDL_INIT_VIDEO;
#ifndef WIN32
flags|=SDL_INIT_EVENTTHREAD;
#endif
#ifdef __MACH__
flags = SDL_INIT_EVERYTHING;
#endif
if (SDL_Init(flags)==-1) {
printf("SDL_Init: %s\n", SDL_GetError ());
return -1;
}
screen=SDL_SetVideoMode(SCREEN_WIDTH,SCREEN_HEIGHT, 32, SDL_SWSURFACE);
if(screen == NULL) {
printf("SDL_SetVideoMode failed!\n");
return -2;
}
SDL_WM_SetCaption ("Pebble Local Simulator - 24H Style",0);
pebbleScreen = createScreen;

if(TTF_Init()==-1) {
    printf("TTF_Init: %s\n", TTF_GetError());
    return -3;
}

if (IMG_Init (IMG_INIT_PNG)==-1) {
    printf("IMG_Init: %s\n", IMG_GetError());
    return -4;
}

if (!loadSimulatorImages())
    return -5;
bodyImg=getSimulatorImage(SIM_IMG_BODY);
shadowImg=getSimulatorImage(SIM_IMG_SCREEN_SHADOW);
vibeImg=getSimulatorImage(SIM_IMG_VIBE);
lightImg=getSimulatorImage(SIM_IMG_BACKLIGHT);
logFile=fopen (LOG_FILE,"a");

if (!initRender(pebbleScreen))
    return -9;
initHardwareOutput ();
initButtons();
pbl_main();
unloadSystemFonts ();
quitRender();

if (logFile!=0)
    fclose(logFile);

freeSimulatorImages();
IMG_Quit ();
TTF_Quit ();
SDL_Quit ();
return 0;
}
Exemple #26
0
int main(int /*argc*/, char** /*argv*/)
{
	// Init SDL
	if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
	{
		printf("Could not initialise SDL\n");
		return -1;
	}
	
	// Center window
	char env[] = "SDL_VIDEO_CENTERED=1";
	putenv(env);

	// Init OpenGL
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
	SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
//#ifndef WIN32
	SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
	SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
//#endif

	const SDL_VideoInfo* vi = SDL_GetVideoInfo();

	bool presentationMode = false;

	int width, height;
	SDL_Surface* screen = 0;
	
	if (presentationMode)
	{
		width = vi->current_w;
		height = vi->current_h;
		screen = SDL_SetVideoMode(width, height, 0, SDL_OPENGL|SDL_FULLSCREEN);
	}
	else
	{	
		width = rcMin(vi->current_w, (int)(vi->current_h * 16.0 / 9.0));
		width = width - 80;
		height = vi->current_h - 80;
		screen = SDL_SetVideoMode(width, height, 0, SDL_OPENGL);
	}
	
	if (!screen)
	{
		printf("Could not initialise SDL opengl\n");
		return -1;
	}

	glEnable(GL_MULTISAMPLE);

	SDL_WM_SetCaption("Recast Demo", 0);
	
	if (!imguiRenderGLInit("DroidSans.ttf"))
	{
		printf("Could not init GUI renderer.\n");
		SDL_Quit();
		return -1;
	}
	
	float t = 0.0f;
	float timeAcc = 0.0f;
	Uint32 lastTime = SDL_GetTicks();
	int mx = 0, my = 0;
	float rx = 45;
	float ry = -45;
	float moveW = 0, moveS = 0, moveA = 0, moveD = 0;
	float camx = 0, camy = 0, camz = 0, camr = 1000;
	float origrx = 0, origry = 0;
	int origx = 0, origy = 0;
	float scrollZoom = 0;
	bool rotate = false;
	bool movedDuringRotate = false;
	float rays[3], raye[3]; 
	bool mouseOverMenu = false;
	bool showMenu = !presentationMode;
	bool showLog = false;
	bool showTools = true;
	bool showLevels = false;
	bool showSample = false;
	bool showTestCases = false;

	int propScroll = 0;
	int logScroll = 0;
	int toolsScroll = 0;
	
	char sampleName[64] = "Choose Sample..."; 
	
	FileList files;
	char meshName[128] = "Choose Mesh...";
	
	float mpos[3] = {0,0,0};
	bool mposSet = false;
	
	SlideShow slideShow;
	slideShow.init("slides/");
	
	InputGeom* geom = 0;
	Sample* sample = 0;
	TestCase* test = 0;
    bool trinityCoreSettings = false;

	BuildContext ctx;
	
	glEnable(GL_CULL_FACE);
	
	float fogCol[4] = { 0.32f, 0.31f, 0.30f, 1.0f };
	glEnable(GL_FOG);
	glFogi(GL_FOG_MODE, GL_LINEAR);
	glFogf(GL_FOG_START, camr*0.1f);
	glFogf(GL_FOG_END, camr*1.25f);
	glFogfv(GL_FOG_COLOR, fogCol);
	
	glDepthFunc(GL_LEQUAL);
	
	bool done = false;
	while(!done)
	{
		// Handle input events.
		int mscroll = 0;
		bool processHitTest = false;
		bool processHitTestShift = false;
		SDL_Event event;

        if (sample)
            trinityCoreSettings = sample->getTrinityCoreValues();
		
		while (SDL_PollEvent(&event))
		{
			switch (event.type)
			{
				case SDL_KEYDOWN:
					// Handle any key presses here.
					if (event.key.keysym.sym == SDLK_ESCAPE)
					{
						done = true;
					}
					else if (event.key.keysym.sym == SDLK_t)
					{
						showLevels = false;
						showSample = false;
						showTestCases = true;
						scanDirectory("Tests", ".txt", files);
					}
					else if (event.key.keysym.sym == SDLK_TAB)
					{
						showMenu = !showMenu;
					}
					else if (event.key.keysym.sym == SDLK_SPACE)
					{
						if (sample)
							sample->handleToggle();
					}
					else if (event.key.keysym.sym == SDLK_1)
					{
						if (sample)
							sample->handleStep();
					}
					else if (event.key.keysym.sym == SDLK_9)
					{
						if (geom)
							geom->save("geomset.txt");
					}
					else if (event.key.keysym.sym == SDLK_0)
					{
						delete geom;
						geom = new InputGeom;
                        if (!geom || !geom->load(&ctx, "geomset.txt", trinityCoreSettings))
						{
							delete geom;
							geom = 0;
							
							showLog = true;
							logScroll = 0;
							ctx.dumpLog("Geom load log %s:", meshName);
						}
						if (sample && geom)
						{
							sample->handleMeshChanged(geom);
						}
							
						if (geom || sample)
						{
							const float* bmin = 0;
							const float* bmax = 0;
							if (sample)
							{
								bmin = sample->getBoundsMin();
								bmax = sample->getBoundsMax();
							}
							else if (geom)
							{
								bmin = geom->getMeshBoundsMin();
								bmax = geom->getMeshBoundsMax();
							}
							// Reset camera and fog to match the mesh bounds.
							if (bmin && bmax)
							{
								camr = sqrtf(rcSqr(bmax[0]-bmin[0]) +
											 rcSqr(bmax[1]-bmin[1]) +
											 rcSqr(bmax[2]-bmin[2])) / 2;
								camx = (bmax[0] + bmin[0]) / 2 + camr;
								camy = (bmax[1] + bmin[1]) / 2 + camr;
								camz = (bmax[2] + bmin[2]) / 2 + camr;
								camr *= 3;
							}
							rx = 45;
							ry = -45;
							glFogf(GL_FOG_START, camr*0.2f);
							glFogf(GL_FOG_END, camr*1.25f);
						}
					}
					else if (event.key.keysym.sym == SDLK_RIGHT)
					{
						slideShow.nextSlide();
					}
					else if (event.key.keysym.sym == SDLK_LEFT)
					{
						slideShow.prevSlide();
					}
					break;
					
				case SDL_MOUSEBUTTONDOWN:
					if (event.button.button == SDL_BUTTON_RIGHT)
					{
						if (!mouseOverMenu)
						{
							// Rotate view
							rotate = true;
							movedDuringRotate = false;
							origx = mx;
							origy = my;
							origrx = rx;
							origry = ry;
						}
					}	
					else if (event.button.button == SDL_BUTTON_WHEELUP)
					{
						if (mouseOverMenu)
							mscroll--;
						else
							scrollZoom -= 10.0f;
					}
					else if (event.button.button == SDL_BUTTON_WHEELDOWN)
					{
						if (mouseOverMenu)
							mscroll++;
						else
							scrollZoom += 10.0f;
					}
					break;
					
				case SDL_MOUSEBUTTONUP:
					// Handle mouse clicks here.
					if (event.button.button == SDL_BUTTON_RIGHT)
					{
						rotate = false;
						if (!mouseOverMenu)
						{
							if (!movedDuringRotate)
							{
								processHitTest = true;
								processHitTestShift = true;
							}
						}
					}
					else if (event.button.button == SDL_BUTTON_LEFT)
					{
						if (!mouseOverMenu)
						{
							processHitTest = true;
							processHitTestShift = (SDL_GetModState() & KMOD_SHIFT) ? true : false;
						}
					}
					
					break;
					
				case SDL_MOUSEMOTION:
					mx = event.motion.x;
					my = height-1 - event.motion.y;
					if (rotate)
					{
						int dx = mx - origx;
						int dy = my - origy;
						rx = origrx - dy*0.25f;
						ry = origry + dx*0.25f;
						if (dx*dx+dy*dy > 3*3)
							movedDuringRotate = true;
					}
					break;
					
				case SDL_QUIT:
					done = true;
					break;
					
				default:
					break;
			}
		}

		unsigned char mbut = 0;
		if (SDL_GetMouseState(0,0) & SDL_BUTTON_LMASK)
			mbut |= IMGUI_MBUT_LEFT;
		if (SDL_GetMouseState(0,0) & SDL_BUTTON_RMASK)
			mbut |= IMGUI_MBUT_RIGHT;
		
		Uint32	time = SDL_GetTicks();
		float	dt = (time - lastTime) / 1000.0f;
		lastTime = time;
		
		t += dt;


		// Hit test mesh.
		if (processHitTest && geom && sample)
		{
			float hitt;
			bool hit = geom->raycastMesh(rays, raye, hitt);
			
			if (hit)
			{
				if (SDL_GetModState() & KMOD_CTRL)
				{
					// Marker
					mposSet = true;
					mpos[0] = rays[0] + (raye[0] - rays[0])*hitt;
					mpos[1] = rays[1] + (raye[1] - rays[1])*hitt;
					mpos[2] = rays[2] + (raye[2] - rays[2])*hitt;
				}
				else
				{
					float pos[3];
					pos[0] = rays[0] + (raye[0] - rays[0])*hitt;
					pos[1] = rays[1] + (raye[1] - rays[1])*hitt;
					pos[2] = rays[2] + (raye[2] - rays[2])*hitt;
					sample->handleClick(rays, pos, processHitTestShift);
				}
			}
			else
			{
				if (SDL_GetModState() & KMOD_CTRL)
				{
					// Marker
					mposSet = false;
				}
			}
		}
		
		// Update sample simulation.
		const float SIM_RATE = 20;
		const float DELTA_TIME = 1.0f/SIM_RATE;
		timeAcc = rcClamp(timeAcc+dt, -1.0f, 1.0f);
		int simIter = 0;
		while (timeAcc > DELTA_TIME)
		{
			timeAcc -= DELTA_TIME;
			if (simIter < 5)
			{
				if (sample)
					sample->handleUpdate(DELTA_TIME);
			}
			simIter++;
		}

		// Clamp the framerate so that we do not hog all the CPU.
		const float MIN_FRAME_TIME = 1.0f/40.0f;
		if (dt < MIN_FRAME_TIME)
		{
			int ms = (int)((MIN_FRAME_TIME - dt)*1000.0f);
			if (ms > 10) ms = 10;
			if (ms >= 0)
				SDL_Delay(ms);
		}
		
		
		// Update and render
		glViewport(0, 0, width, height);
		glClearColor(0.3f, 0.3f, 0.32f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		glDisable(GL_TEXTURE_2D);
		
		// Render 3d
		glEnable(GL_DEPTH_TEST);
		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		gluPerspective(50.0f, (float)width/(float)height, 1.0f, camr);
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		glRotatef(rx,1,0,0);
		glRotatef(ry,0,1,0);
		glTranslatef(-camx, -camy, -camz);
		
		// Get hit ray position and direction.
		GLdouble proj[16];
		GLdouble model[16];
		GLint view[4];
		glGetDoublev(GL_PROJECTION_MATRIX, proj);
		glGetDoublev(GL_MODELVIEW_MATRIX, model);
		glGetIntegerv(GL_VIEWPORT, view);
		GLdouble x, y, z;
		gluUnProject(mx, my, 0.0f, model, proj, view, &x, &y, &z);
		rays[0] = (float)x; rays[1] = (float)y; rays[2] = (float)z;
		gluUnProject(mx, my, 1.0f, model, proj, view, &x, &y, &z);
		raye[0] = (float)x; raye[1] = (float)y; raye[2] = (float)z;
		
		// Handle keyboard movement.
		Uint8* keystate = SDL_GetKeyState(NULL);
		moveW = rcClamp(moveW + dt * 4 * (keystate[SDLK_w] ? 1 : -1), 0.0f, 1.0f);
		moveS = rcClamp(moveS + dt * 4 * (keystate[SDLK_s] ? 1 : -1), 0.0f, 1.0f);
		moveA = rcClamp(moveA + dt * 4 * (keystate[SDLK_a] ? 1 : -1), 0.0f, 1.0f);
		moveD = rcClamp(moveD + dt * 4 * (keystate[SDLK_d] ? 1 : -1), 0.0f, 1.0f);
		
		float keybSpeed = 22.0f;
		if (SDL_GetModState() & KMOD_SHIFT)
			keybSpeed *= 20.0f;
		
		float movex = (moveD - moveA) * keybSpeed * dt;
		float movey = (moveS - moveW) * keybSpeed * dt;
		
		movey += scrollZoom * 2.0f;
		scrollZoom = 0;
		
		camx += movex * (float)model[0];
		camy += movex * (float)model[4];
		camz += movex * (float)model[8];
		
		camx += movey * (float)model[2];
		camy += movey * (float)model[6];
		camz += movey * (float)model[10];

		glEnable(GL_FOG);

		if (sample)
			sample->handleRender();
		if (test)
			test->handleRender();
		
		glDisable(GL_FOG);
		
		// Render GUI
		glDisable(GL_DEPTH_TEST);
		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		gluOrtho2D(0, width, 0, height);
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		
		mouseOverMenu = false;
		
		imguiBeginFrame(mx,my,mbut,mscroll);
		
		if (sample)
		{
			sample->handleRenderOverlay((double*)proj, (double*)model, (int*)view);
		}
		if (test)
		{
			if (test->handleRenderOverlay((double*)proj, (double*)model, (int*)view))
				mouseOverMenu = true;
		}

		// Help text.
		if (showMenu)
		{
			const char msg[] = "W/S/A/D: Move  RMB: Rotate";
			imguiDrawText(280, height-20, IMGUI_ALIGN_LEFT, msg, imguiRGBA(255,255,255,128));
		}
		
		if (showMenu)
		{
			if (imguiBeginScrollArea("Properties", width-250-10, 10, 250, height-20, &propScroll))
				mouseOverMenu = true;

			if (imguiCheck("Show Log", showLog))
				showLog = !showLog;
			if (imguiCheck("Show Tools", showTools))
				showTools = !showTools;

			imguiSeparator();
			imguiLabel("Sample");
			if (imguiButton(sampleName))
			{
				if (showSample)
				{
					showSample = false;
				}
				else
				{
					showSample = true;
					showLevels = false;
					showTestCases = false;
				}
			}
			
			imguiSeparator();
			imguiLabel("Input Mesh");
			if (imguiButton(meshName))
			{
				if (showLevels)
				{
					showLevels = false;
				}
				else
				{
					showSample = false;
					showTestCases = false;
					showLevels = true;
					scanDirectory("Meshes", ".obj", files);
				}
			}
			if (geom)
			{
				char text[64];
				snprintf(text, 64, "Verts: %.1fk  Tris: %.1fk",
						 geom->getMesh()->getVertCount()/1000.0f,
						 geom->getMesh()->getTriCount()/1000.0f);
				imguiValue(text);
			}
			imguiSeparator();

			if (geom && sample)
			{
				imguiSeparatorLine();
				
				sample->handleSettings();

				if (imguiButton("Build"))
				{
					ctx.resetLog();
					if (!sample->handleBuild())
					{
						showLog = true;
						logScroll = 0;
					}
					ctx.dumpLog("Build log %s:", meshName);
					
					// Clear test.
					delete test;
					test = 0;
				}

                if (imguiButton("Load mmtile"))
                {
                    ctx.resetLog();
                    if (!sample->handleLoad())
                    {
                        showLog = true;
                        logScroll = 0;
                    }
                    ctx.dumpLog("Load log %s:", meshName);

                    // Clear test.
                    delete test;
                    test = 0;
                }

                if (imguiButton("Load sub mmtile"))
                {
                    ctx.resetLog();
                    if (!sample->handleLoadSubTiles())
                    {
                        showLog = true;
                        logScroll = 0;
                    }
                    ctx.dumpLog("Load log %s:", meshName);

                    // Clear test.
                    delete test;
                    test = 0;
                }

				imguiSeparator();
			}
			
			if (sample)
			{
				imguiSeparatorLine();
				sample->handleDebugMode();
			}

			imguiEndScrollArea();
		}
		
		// Sample selection dialog.
		if (showSample)
		{
			static int levelScroll = 0;
			if (imguiBeginScrollArea("Choose Sample", width-10-250-10-200, height-10-250, 200, 250, &levelScroll))
				mouseOverMenu = true;

			Sample* newSample = 0;
			for (int i = 0; i < g_nsamples; ++i)
			{
				if (imguiItem(g_samples[i].name))
				{
					newSample = g_samples[i].create();
					if (newSample)
						strcpy(sampleName, g_samples[i].name);
				}
			}
			if (newSample)
			{
				delete sample;
				sample = newSample;
				sample->setContext(&ctx);
				if (geom && sample)
				{
					sample->handleMeshChanged(geom);
				}
				showSample = false;
			}

			if (geom || sample)
			{
				const float* bmin = 0;
				const float* bmax = 0;
				if (sample)
				{
					bmin = sample->getBoundsMin();
					bmax = sample->getBoundsMax();
				}
				else if (geom)
				{
					bmin = geom->getMeshBoundsMin();
					bmax = geom->getMeshBoundsMax();
				}
				// Reset camera and fog to match the mesh bounds.
				if (bmin && bmax)
				{
					camr = sqrtf(rcSqr(bmax[0]-bmin[0]) +
								 rcSqr(bmax[1]-bmin[1]) +
								 rcSqr(bmax[2]-bmin[2])) / 2;
					camx = (bmax[0] + bmin[0]) / 2 + camr;
					camy = (bmax[1] + bmin[1]) / 2 + camr;
					camz = (bmax[2] + bmin[2]) / 2 + camr;
					camr *= 3;
				}
				rx = 45;
				ry = -45;
				glFogf(GL_FOG_START, camr*0.1f);
				glFogf(GL_FOG_END, camr*1.25f);
			}
			
			imguiEndScrollArea();
		}
		


		// Level selection dialog.
		if (showLevels)
		{
			static int levelScroll = 0;
			if (imguiBeginScrollArea("Choose Level", width-10-250-10-200, height-10-450, 200, 450, &levelScroll))
				mouseOverMenu = true;
			
			int levelToLoad = -1;
			for (int i = 0; i < files.size; ++i)
			{
				if (imguiItem(files.files[i]))
					levelToLoad = i;
			}
			
			if (levelToLoad != -1)
			{
				strncpy(meshName, files.files[levelToLoad], sizeof(meshName));
				meshName[sizeof(meshName)-1] = '\0';
				showLevels = false;
				
				delete geom;
				geom = 0;
				
				char path[256];
				strcpy(path, "Meshes/");
				strcat(path, meshName);
				
				geom = new InputGeom;
                if (!geom || !geom->loadMesh(&ctx, path, trinityCoreSettings))
				{
					delete geom;
					geom = 0;
					
					showLog = true;
					logScroll = 0;
					ctx.dumpLog("Geom load log %s:", meshName);
				}
				if (sample && geom)
				{
					sample->handleMeshChanged(geom);
				}

				if (geom || sample)
				{
					const float* bmin = 0;
					const float* bmax = 0;
					if (sample)
					{
						bmin = sample->getBoundsMin();
						bmax = sample->getBoundsMax();
					}
					else if (geom)
					{
						bmin = geom->getMeshBoundsMin();
						bmax = geom->getMeshBoundsMax();
					}
					// Reset camera and fog to match the mesh bounds.
					if (bmin && bmax)
					{
						camr = sqrtf(rcSqr(bmax[0]-bmin[0]) +
									 rcSqr(bmax[1]-bmin[1]) +
									 rcSqr(bmax[2]-bmin[2])) / 2;
						camx = (bmax[0] + bmin[0]) / 2 + camr;
						camy = (bmax[1] + bmin[1]) / 2 + camr;
						camz = (bmax[2] + bmin[2]) / 2 + camr;
						camr *= 3;
					}
					rx = 45;
					ry = -45;
					glFogf(GL_FOG_START, camr*0.1f);
					glFogf(GL_FOG_END, camr*1.25f);
				}
			}
			
			imguiEndScrollArea();
			
		}
		
		// Test cases
		if (showTestCases)
		{
			static int testScroll = 0;
			if (imguiBeginScrollArea("Choose Test To Run", width-10-250-10-200, height-10-450, 200, 450, &testScroll))
				mouseOverMenu = true;

			int testToLoad = -1;
			for (int i = 0; i < files.size; ++i)
			{
				if (imguiItem(files.files[i]))
					testToLoad = i;
			}
			
			if (testToLoad != -1)
			{
				char path[256];
				strcpy(path, "Tests/");
				strcat(path, files.files[testToLoad]);
				test = new TestCase;
				if (test)
				{
					// Load the test.
					if (!test->load(path))
					{
						delete test;
						test = 0;
					}

					// Create sample
					Sample* newSample = 0;
					for (int i = 0; i < g_nsamples; ++i)
					{
						if (strcmp(g_samples[i].name, test->getSampleName()) == 0)
						{
							newSample = g_samples[i].create();
							if (newSample) strcpy(sampleName, g_samples[i].name);
						}
					}
					if (newSample)
					{
						delete sample;
						sample = newSample;
						sample->setContext(&ctx);
						showSample = false;
					}

					// Load geom.
					strcpy(meshName, test->getGeomFileName());
					meshName[sizeof(meshName)-1] = '\0';
					
					delete geom;
					geom = 0;
					
					strcpy(path, "Meshes/");
					strcat(path, meshName);
					
					geom = new InputGeom;
                    if (!geom || !geom->loadMesh(&ctx, path, trinityCoreSettings))
					{
						delete geom;
						geom = 0;
						showLog = true;
						logScroll = 0;
						ctx.dumpLog("Geom load log %s:", meshName);
					}
					if (sample && geom)
					{
						sample->handleMeshChanged(geom);
					}

					// This will ensure that tile & poly bits are updated in tiled sample.
					if (sample)
						sample->handleSettings();

					ctx.resetLog();
					if (sample && !sample->handleBuild())
					{
						ctx.dumpLog("Build log %s:", meshName);
					}
					
					if (geom || sample)
					{
						const float* bmin = 0;
						const float* bmax = 0;
						if (sample)
						{
							bmin = sample->getBoundsMin();
							bmax = sample->getBoundsMax();
						}
						else if (geom)
						{
							bmin = geom->getMeshBoundsMin();
							bmax = geom->getMeshBoundsMax();
						}
						// Reset camera and fog to match the mesh bounds.
						if (bmin && bmax)
						{
							camr = sqrtf(rcSqr(bmax[0]-bmin[0]) +
										 rcSqr(bmax[1]-bmin[1]) +
										 rcSqr(bmax[2]-bmin[2])) / 2;
							camx = (bmax[0] + bmin[0]) / 2 + camr;
							camy = (bmax[1] + bmin[1]) / 2 + camr;
							camz = (bmax[2] + bmin[2]) / 2 + camr;
							camr *= 3;
						}
						rx = 45;
						ry = -45;
						glFogf(GL_FOG_START, camr*0.2f);
						glFogf(GL_FOG_END, camr*1.25f);
					}
					
					// Do the tests.
					if (sample)
						test->doTests(sample->getNavMesh(), sample->getNavMeshQuery());
				}
			}				
				
			imguiEndScrollArea();
		}

		
		// Log
		if (showLog && showMenu)
		{
			if (imguiBeginScrollArea("Log", 250+20, 10, width - 300 - 250, 200, &logScroll))
				mouseOverMenu = true;
			for (int i = 0; i < ctx.getLogCount(); ++i)
				imguiLabel(ctx.getLogText(i));
			imguiEndScrollArea();
		}
		
		// Tools
		if (!showTestCases && showTools && showMenu) // && geom && sample)
		{
			if (imguiBeginScrollArea("Tools", 10, 10, 250, height-20, &toolsScroll))
				mouseOverMenu = true;

			if (sample)
				sample->handleTools();
			
			imguiEndScrollArea();
		}
		
		slideShow.updateAndDraw(dt, (float)width, (float)height);
		
		// Marker
		if (mposSet && gluProject((GLdouble)mpos[0], (GLdouble)mpos[1], (GLdouble)mpos[2],
								  model, proj, view, &x, &y, &z))
		{
			// Draw marker circle
			glLineWidth(5.0f);
			glColor4ub(240,220,0,196);
			glBegin(GL_LINE_LOOP);
			const float r = 25.0f;
			for (int i = 0; i < 20; ++i)
			{
				const float a = (float)i / 20.0f * RC_PI*2;
				const float fx = (float)x + cosf(a)*r;
				const float fy = (float)y + sinf(a)*r;
				glVertex2f(fx,fy);
			}
			glEnd();
			glLineWidth(1.0f);
		}
		
		imguiEndFrame();
		imguiRenderGLDraw();		
		
		glEnable(GL_DEPTH_TEST);
		SDL_GL_SwapBuffers();
	}
	
	imguiRenderGLDestroy();
	
	SDL_Quit();
	
	delete sample;
	delete geom;
	
	return 0;
}
Exemple #27
0
void GFXEngine::toggleFullscreen()
{				
	SDL_Surface *screen = SDL_GetVideoSurface();
	SDL_SetVideoMode(screen->w, screen->h, screen->format->BitsPerPixel, screen->flags^ SDL_FULLSCREEN);	
}
int main(int argc, char *argv[])
{
	Uint32 flags;
	SDL_Surface *screen, *image;
	int i, depth, done;
	SDL_Event event;
#if 0
	SDL_RWops* rw_ops;
#endif

	/* Check command line usage */
	if ( ! argv[1] ) {
		fprintf(stderr, "Usage: %s <image_file>\n", argv[0]);
		return(1);
	}

	/* Initialize the SDL library */
	if ( SDL_Init(SDL_INIT_VIDEO) < 0 ) {
		fprintf(stderr, "Couldn't initialize SDL: %s\n",SDL_GetError());
		return(255);
	}

	flags = SDL_SWSURFACE;
	for ( i=1; argv[i]; ++i ) {
		if ( strcmp(argv[i], "-fullscreen") == 0 ) {
			SDL_ShowCursor(0);
			flags |= SDL_FULLSCREEN;
			continue;
		}
#if 0
		rw_ops = SDL_RWFromFile(argv[1], "r");
		
		fprintf(stderr, "BMP:\t%d\n", IMG_isBMP(rw_ops));
		fprintf(stderr, "GIF:\t%d\n", IMG_isGIF(rw_ops));
		fprintf(stderr, "JPG:\t%d\n", IMG_isJPG(rw_ops));
		fprintf(stderr, "PNG:\t%d\n", IMG_isPNG(rw_ops));
		fprintf(stderr, "TIF:\t%d\n", IMG_isTIF(rw_ops));
		/* fprintf(stderr, "TGA:\t%d\n", IMG_isTGA(rw_ops)); */
		fprintf(stderr, "PCX:\t%d\n", IMG_isPCX(rw_ops));
#endif

		/* Open the image file */
#ifdef XPM_INCLUDED
		image = IMG_ReadXPMFromArray(picture_xpm);
#else
		image = IMG_Load(argv[i]);
#endif
		if ( image == NULL ) {
			fprintf(stderr, "Couldn't load %s: %s\n",
			        argv[i], SDL_GetError());
			continue;
		}
		SDL_WM_SetCaption(argv[i], "showimage");

		/* Create a display for the image */
		depth = SDL_VideoModeOK(image->w, image->h, 32, flags);
		/* Use the deepest native mode, except that we emulate 32bpp
		   for viewing non-indexed images on 8bpp screens */
		if ( depth == 0 ) {
			if ( image->format->BytesPerPixel > 1 ) {
				depth = 32;
			} else {
				depth = 8;
			}
		} else
		if ( (image->format->BytesPerPixel > 1) && (depth == 8) ) {
	    		depth = 32;
		}
		if(depth == 8)
			flags |= SDL_HWPALETTE;
		screen = SDL_SetVideoMode(image->w, image->h, depth, flags);
		if ( screen == NULL ) {
			fprintf(stderr,"Couldn't set %dx%dx%d video mode: %s\n",
				image->w, image->h, depth, SDL_GetError());
			continue;
		}

		/* Set the palette, if one exists */
		if ( image->format->palette ) {
			SDL_SetColors(screen, image->format->palette->colors,
			              0, image->format->palette->ncolors);
		}

		/* Draw a background pattern if the surface has transparency */
		if(image->flags & (SDL_SRCALPHA | SDL_SRCCOLORKEY))
	    		draw_background(screen);

		/* Display the image */
		SDL_BlitSurface(image, NULL, screen, NULL);
		SDL_UpdateRect(screen, 0, 0, 0, 0);

		done = 0;
		while ( ! done ) {
			if ( SDL_PollEvent(&event) ) {
				switch (event.type) {
				    case SDL_KEYUP:
					switch (event.key.keysym.sym) {
					    case SDLK_LEFT:
						if ( i > 1 ) {
							i -= 2;
							done = 1;
						}
						break;
					    case SDLK_RIGHT:
						if ( argv[i+1] ) {
							done = 1;
						}
						break;
					    case SDLK_ESCAPE:
					    case SDLK_q:
						argv[i+1] = NULL;
						/* Drop through to done */
					    case SDLK_SPACE:
					    case SDLK_TAB:
						done = 1;
						break;
					    default:
						break;
					}
					break;
				    case SDL_MOUSEBUTTONDOWN:
					done = 1;
					break;
                                    case SDL_QUIT:
					argv[i+1] = NULL;
					done = 1;
					break;
				    default:
					break;
				}
			} else {
				SDL_Delay(10);
			}
		}
		SDL_FreeSurface(image);
	}

	/* We're done! */
	SDL_Quit();
	return(0);
}
Exemple #29
0
int PDC_scr_open(int argc, char **argv)
{
    int i;

    PDC_LOG(("PDC_scr_open() - called\n"));

    SP = calloc(1, sizeof(SCREEN));

    if (!SP)
        return ERR;

    pdc_own_screen = !pdc_screen;

    if (pdc_own_screen)
    {
        if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) < 0)
        {
            fprintf(stderr, "Could not start SDL: %s\n", SDL_GetError());
            return ERR;
        }

        atexit(SDL_Quit);
    }

    if (!pdc_font)
    {
        const char *fname = getenv("PDC_FONT");
        pdc_font = SDL_LoadBMP(fname ? fname : "pdcfont.bmp");
    }

    if (!pdc_font)
        pdc_font = SDL_LoadBMP_RW(SDL_RWFromMem(deffont, sizeof(deffont)), 0);

    if (!pdc_font)
    {
        fprintf(stderr, "Could not load font\n");
        return ERR;
    }

    SP->mono = !pdc_font->format->palette;

    if (!SP->mono && !pdc_back)
    {
        const char *bname = getenv("PDC_BACKGROUND");
        pdc_back = SDL_LoadBMP(bname ? bname : "pdcback.bmp");
    }

    if (!SP->mono && (pdc_back || !pdc_own_screen))
    {
        SP->orig_attr = TRUE;
        SP->orig_fore = COLOR_WHITE;
        SP->orig_back = -1;
    }
    else
        SP->orig_attr = FALSE;

    pdc_fheight = pdc_font->h / 8;
    pdc_fwidth = pdc_font->w / 32;

    if (!SP->mono)
        pdc_flastc = pdc_font->format->palette->ncolors - 1;

    if (pdc_own_screen && !pdc_icon)
    {
        const char *iname = getenv("PDC_ICON");
        pdc_icon = SDL_LoadBMP(iname ? iname : "pdcicon.bmp");

        if (!pdc_icon)
            pdc_icon = SDL_LoadBMP_RW(SDL_RWFromMem(deficon,
                                                    sizeof(deficon)), 0);

        if (pdc_icon)
            SDL_WM_SetIcon(pdc_icon, NULL);
    }

    if (pdc_own_screen)
    {
        const char *env = getenv("PDC_LINES");
        pdc_sheight = (env ? atoi(env) : 25) * pdc_fheight;

        env = getenv("PDC_COLS");
        pdc_swidth = (env ? atoi(env) : 80) * pdc_fwidth;

        pdc_screen = SDL_SetVideoMode(pdc_swidth, pdc_sheight, 0,
            SDL_SWSURFACE|SDL_ANYFORMAT|SDL_RESIZABLE);
    }
    else
    {
        if (!pdc_sheight)
            pdc_sheight = pdc_screen->h - pdc_yoffset;

        if (!pdc_swidth)
            pdc_swidth = pdc_screen->w - pdc_xoffset;
    }

    if (!pdc_screen)
    {
        fprintf(stderr, "Couldn't create a surface: %s\n", SDL_GetError());
        return ERR;
    }

    if (SP->orig_attr)
        PDC_retile();

    for (i = 0; i < 8; i++)
    {
        pdc_color[i].r = (i & COLOR_RED) ? 0xc0 : 0;
        pdc_color[i].g = (i & COLOR_GREEN) ? 0xc0 : 0;
        pdc_color[i].b = (i & COLOR_BLUE) ? 0xc0 : 0;

        pdc_color[i + 8].r = (i & COLOR_RED) ? 0xff : 0x40;
        pdc_color[i + 8].g = (i & COLOR_GREEN) ? 0xff : 0x40;
        pdc_color[i + 8].b = (i & COLOR_BLUE) ? 0xff : 0x40;
    }

    for (i = 0; i < 16; i++)
        pdc_mapped[i] = SDL_MapRGB(pdc_screen->format, pdc_color[i].r,
                                   pdc_color[i].g, pdc_color[i].b);

    SDL_EnableUNICODE(1);

    PDC_mouse_set();

    if (pdc_own_screen)
        PDC_set_title(argc ? argv[0] : "PDCurses");

    SP->lines = PDC_get_rows();
    SP->cols = PDC_get_columns();

    SP->mouse_wait = PDC_CLICK_PERIOD;
    SP->audible = FALSE;

    PDC_reset_prog_mode();

    return OK;
}
Exemple #30
0
int	main(int argc, char *argv[])
{
	const char*	chunkfile = "crater/crater.chu";
	const char*	texturefile = "crater/crater.jpg";

	// Process command-line args.
	int	file_arg_index = 0;
	for (int i = 1; i < argc; i++) {
		switch (argv[i][0]) {
		case '-': {
			switch (argv[i][1]) {
			case 0:
			default:
				printf("error: unknown switch '%s'\n\n", argv[i]);
				print_usage();
				exit(1);
				break;

			case 'w':	// window width.
				i++;
				if (i >= argc) {
					printf("error: -w switch must be followed by a window width (in pixels)\n\n");
					print_usage();
					exit(1);
				}
				window_width = atoi(argv[i]);
				// bounds checking here?
				break;

			case 'h':	// window height.
				i++;
				if (i >= argc) {
					printf("error: -h switch must be followed by a window height (in pixels)\n\n");
					print_usage();
					exit(1);
				}
				window_height = atoi(argv[i]);
				// bounds checking here?
				break;

			case 'b':	// bits per pixel
				i++;
				if (i >= argc) {
					printf("error: -b switch must be followed by the desired window bits per pixel\n\n");
					print_usage();
					exit(1);
				}
				bits_per_pixel = atoi(argv[i]);
				break;

			case 'f':	// fullscreen flag.
				fullscreen = true;
				break;
			}
			break;
		}

		default: {	// file args.
			if (file_arg_index == 0) {
				chunkfile = argv[i];
				file_arg_index++;

			} else if (file_arg_index == 1) {
				texturefile = argv[i];
				file_arg_index++;

			} else {
				printf("error: too many args, starting with '%s'.\n\n", argv[i]);
				print_usage();
				exit(1);
			}
			break;
		}
		}
	}

	// Print out program info.
	print_usage();

	// Initialize the SDL subsystems we're using.
	if (SDL_Init(SDL_INIT_VIDEO /* | SDL_INIT_JOYSTICK | SDL_INIT_CDROM | SDL_INIT_AUDIO*/))
	{
		fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError());
		exit(1);
	}
	atexit(SDL_Quit);

	// Get current display info.
	const SDL_VideoInfo* info = NULL;
	info = SDL_GetVideoInfo();
	if (!info) {
		fprintf(stderr, "SDL_GetVideoInfo() failed.");
		exit(1);
	}

	if (bits_per_pixel == 0) {
		// Take the default desktop depth.
		bits_per_pixel = info->vfmt->BitsPerPixel;
	}
	int	flags = SDL_OPENGL | (fullscreen ? SDL_FULLSCREEN : 0);

	int	component_depth = 0;
	if (bits_per_pixel <= 16) {
		component_depth = 5;

	} else if (bits_per_pixel <= 32) {
		component_depth = 8;

	} else {
		component_depth = bits_per_pixel / 4;
		// Assume the user knows what they're trying to do.
	}

	SDL_GL_SetAttribute( SDL_GL_RED_SIZE, component_depth );
	SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, component_depth );
	SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, component_depth );
	SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 24 );
	SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

	// Set the video mode.
	if (SDL_SetVideoMode(window_width, window_height, bits_per_pixel, flags) == 0) {
		fprintf(stderr, "SDL_SetVideoMode() failed.");
		exit(1);
	}

	// Initialize the engine's opengl subsystem (loads extensions if possible).
	ogl::open();

	printf("Window: %d x %d x %d\n", window_width, window_height, bits_per_pixel);

	// Load a texture or a texture-quadtree object.
	tqt*	texture_quadtree = NULL;

	// Does it look like a .tqt file?
	if (tqt::is_tqt_file(texturefile)) {
		texture_quadtree = new tqt(texturefile);
	}

	if (texture_quadtree == NULL) {
		//
		// No texture quadtree; try to load the texture arg as an ordinary texture.
		//
		SDL_Surface*	texture = IMG_Load(texturefile);
		if (texture) {
			glEnable(GL_TEXTURE_2D);
			glBindTexture(GL_TEXTURE_2D, 1);

			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_WRAP_S, GL_REPEAT);
//			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
//			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		
			glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, texture->w, texture->h, 0, GL_RGB, GL_UNSIGNED_BYTE, texture->pixels);
			gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, texture->w, texture->h, GL_RGB, GL_UNSIGNED_BYTE, texture->pixels);

			SDL_FreeSurface(texture);

			glBindTexture(GL_TEXTURE_2D, 1);
		}
	}
	glEnable(GL_TEXTURE_2D);
	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);	// GL_MODULATE

// Sometimes (under Win32) for debugging it's better to not catch
// exceptions.
//#define CATCH_EXCEPTIONS
#ifdef CATCH_EXCEPTIONS
	try
#endif // CATCH_EXCEPTIONS
	{

		// Load our chunked model.
		SDL_RWops*	in = SDL_RWFromFile(chunkfile, "rb");
		if (in == NULL) {
			printf("Can't open '%s'\n", chunkfile);
			exit(1);
		}
		lod_chunk_tree*	model = new lod_chunk_tree(in);

		// Enable vertex array, and just leave it on.
		glEnableClientState(GL_VERTEX_ARRAY);

		view.m_frame_number = 1;

		if (texture_quadtree == NULL)
		{
			// Set up automatic texture-coordinate generation.
			// Basically we're just stretching the current texture
			// over the entire model.
			vec3	center, extent;
			model->get_bounding_box(&center, &extent);
			float	xsize = extent.get_x() * 2;
			float	zsize = extent.get_z() * 2;

			glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
			float	p[4] = { 0, 0, 0, 0 };
			p[0] = 1.0f / xsize;
			glTexGenfv(GL_S, GL_OBJECT_PLANE, p);
			p[0] = 0;

			glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
			p[2] = 1.0f / zsize;
			glTexGenfv(GL_T, GL_OBJECT_PLANE, p);

			glEnable(GL_TEXTURE_GEN_S);
			glEnable(GL_TEXTURE_GEN_T);
		}

		// Main loop.
		Uint32	last_ticks = SDL_GetTicks();
		for (;;) {
			Uint32	ticks = SDL_GetTicks();
			int	delta_ticks = ticks - last_ticks;
			float	delta_t = delta_ticks / 1000.f;
			last_ticks = ticks;

			process_events();

			if ( move_forward ) {
				// Drift the viewpoint forward.
				viewer_pos += viewer_dir * delta_t * (float) (1 << speed) * 0.50f;
			}

			model->set_parameters(max_pixel_error, (float) window_width, horizontal_fov_degrees);
			if (enable_update) {
				model->update(viewer_pos, texture_quadtree);
			}

			clear();

			frame_triangle_count += model->render(view, render_opt);

			SDL_GL_SwapBuffers();
			view.m_frame_number++;

			// Performance counting.
			if ( measure_performance ) {
				frame_count ++;
				total_triangle_count += frame_triangle_count;
				performance_timer += delta_ticks;

				// See if one second has elapsed.
				if ( performance_timer > 1000 ) {
					// Print out stats for the previous second.
					float	fps = frame_count / ( performance_timer / 1000.f );
					float	tps = total_triangle_count / ( performance_timer / 1000.f );
					printf( "fps = %3.1f : tri/s = %3.2fM : tri/frame = %2.3fM\n", fps, tps / 1000000.f, frame_triangle_count / 1000000.f );

					total_triangle_count = 0;
					performance_timer = 0;
					frame_count = 0;
				}

				frame_triangle_count = 0;
			}
		}

		SDL_RWclose(in);
	}
#ifdef CATCH_EXCEPTIONS
	catch (const char* message) {
		printf("run-time exception: %s\n", message);
		exit(1);
	}
	catch (...)
	{
		printf("run-time exception: unknown type\n");
		exit(1);
	}
#endif // CATCH_EXCEPTIONS

	return 0;
}