Beispiel #1
0
AppSurface::AppSurface(SDL_Window* w) : 
	surface(ReferenceCounter<SDL_Surface>::create(SDL_GetWindowSurface(w), SDL_FreeSurface))
{}
Beispiel #2
0
SDL_Surface* Window::getSurface(void) {
    return SDL_GetWindowSurface(window);
}
Beispiel #3
0
SGEFONTFX *sgeFontFXNew(SGEFONT *f, Uint32 fxtype, Uint8 movement, Uint32 runtime, Uint32 charOffset, int startx, int starty, int endx, int endy, const char *text) {
	SGEFONTFX *ret;
	SDL_Surface *tmp;
	SGESPRITE *sprite;
	SGEFONTFXFADEINFO *fadeInfo;
	SGEFONTFXFADEINOUTINFO *fadeInOutInfo;
	SGEFONTFXCOUNTDOWNINFO *countdownInfo;
	int i;
	int lineheight;
	char buf[2];
	int charPos=0;
	int charWidth;
	const char *usedText;
	Uint32 tmpruntime;

	if (fxtype==SGEFONTFX_COUNTDOWN) {
		charOffset=0;
		usedText=(const char *)&"000000000000";
	} else {
		usedText=text;
	}

	sgeNew(ret,SGEFONTFX);

	ret->type=fxtype;
	ret->runtime=runtime;
	ret->startx=startx;
	ret->starty=starty;
	ret->endx=endx;
	ret->endy=endy;
	ret->charOffset=charOffset;
	ret->finished=0;
	ret->startTime=SDL_GetTicks();
	ret->font=f;
	ret->surface=SDL_GetWindowSurface(screen);
	ret->text=strdup(usedText);
	ret->textSprites=sgeArrayNew();
	ret->movement=movement;
	ret->preDelay=0;
	ret->postDelay=0;
	ret->hideOnPreDelay=0;

	lineheight=sgeFontGetLineHeight(ret->font);
	sgeFontIgnoreAlpha(ret->font);
	if (ret->charOffset==0) {
		tmp=sgeCreateSDLSurface(sgeFontGetWidth(ret->font,ret->text),lineheight,32, 0);
		sgeFontPrint(ret->font, tmp, 0, 0, ret->text);
		sprite=sgeSpriteNewSDLSurface(tmp);
		sprite->x=startx;
		sprite->y=starty;
		sgeArrayAdd(ret->textSprites, sprite);
	} else {
		strcpy(buf," ");
		for (i=0;i<strlen(text);i++) {
			sprintf(buf, "%c",ret->text[i]);
			charWidth=sgeFontGetWidth(ret->font,buf);
			tmp=sgeCreateSDLSurface(charWidth,lineheight,32, 0);
			sgeFontPrint(ret->font, tmp, 0, 0, buf);
			sprite=sgeSpriteNewSDLSurface(tmp);
			sprite->x=startx+charPos;
			sprite->y=starty;
			sgeArrayAdd(ret->textSprites, sprite);
			charPos+=charWidth;
		}
	}
	sgeFontUseAlpha(ret->font);

	switch (fxtype) {
		case SGEFONTFX_FADE_IN:
			fadeInfo=sgeFontFXFadeInfoNew(runtime);
			ret->data=(void *)fadeInfo;
			ret->updateFunction=sgeFontFXFadeInUpdate;
			ret->freeFunction=sgeFontFXFadeInDestroy;
			break;
		case SGEFONTFX_FADE_OUT:
			fadeInfo=sgeFontFXFadeInfoNew(runtime);
			ret->data=(void *)fadeInfo;
			ret->updateFunction=sgeFontFXFadeOutUpdate;
			ret->freeFunction=sgeFontFXFadeOutDestroy;
			break;
		case SGEFONTFX_FADE_INOUT:
			tmpruntime=runtime>>1;
			fadeInOutInfo=sgeFontFXFadeInOutInfoNew(ret,tmpruntime,runtime-tmpruntime,1);
			ret->data=(void *)fadeInOutInfo;
			ret->updateFunction=sgeFontFXFadeInOutUpdate;
			ret->freeFunction=sgeFontFXFadeInOutDestroy;
			break;
		case SGEFONTFX_MOVE_IN:
			fadeInfo=sgeFontFXFadeInfoNew(runtime);
			fadeInfo->fade=0;
			ret->data=(void *)fadeInfo;
			ret->updateFunction=sgeFontFXFadeInUpdate;
			ret->freeFunction=sgeFontFXFadeInDestroy;
			break;
		case SGEFONTFX_MOVE_OUT:
			fadeInfo=sgeFontFXFadeInfoNew(runtime);
			fadeInfo->fade=0;
			ret->data=(void *)fadeInfo;
			ret->updateFunction=sgeFontFXFadeOutUpdate;
			ret->freeFunction=sgeFontFXFadeOutDestroy;
			break;
		case SGEFONTFX_MOVE_INOUT:
			tmpruntime=runtime>>1;
			fadeInOutInfo=sgeFontFXFadeInOutInfoNew(ret,tmpruntime,runtime-tmpruntime,0);
			ret->data=(void *)fadeInOutInfo;
			ret->updateFunction=sgeFontFXFadeInOutUpdate;
			ret->freeFunction=sgeFontFXFadeInOutDestroy;
			break;
		case SGEFONTFX_COUNTDOWN:
			countdownInfo=sgeFontFXCountdownInfoNew(runtime);
			ret->data=(void *)countdownInfo;
			ret->updateFunction=sgeFontFXCountdownUpdate;
			ret->freeFunction=sgeFontFXCountdownDestroy;
			break;
		default:
			sgeBailOut("Unknown font effect: %d\n", fxtype);
	}
	return ret;
}
Beispiel #4
0
/****** Process hotkey input ******/
void AGB_core::handle_hotkey(SDL_Event& event)
{
	//Quit on Q or ESC
	if((event.type == SDL_KEYDOWN) && ((event.key.keysym.sym == SDLK_q) || (event.key.keysym.sym == SDLK_ESCAPE)))
	{
		running = false; 
		SDL_Quit();
	}

	//Mute or unmute sound on M
	else if((event.type == SDL_KEYDOWN) && (event.key.keysym.sym == config::hotkey_mute) && (!config::use_external_interfaces))
	{
		if(config::volume == 0)
		{
			update_volume(config::old_volume);
		}

		else
		{
			config::old_volume = config::volume;
			update_volume(0);
		}
	}

	//Screenshot on F9
	else if((event.type == SDL_KEYDOWN) && (event.key.keysym.sym == SDLK_F9)) 
	{
		std::stringstream save_stream;
		std::string save_name = config::ss_path;

		//Prefix SDL Ticks to screenshot name
		save_stream << SDL_GetTicks();
		save_name += save_stream.str();
		save_stream.str(std::string());

		//Append random number to screenshot name
		srand(SDL_GetTicks());
		save_stream << rand() % 1024 << rand() % 1024 << rand() % 1024;
		save_name += save_stream.str() + ".bmp";
	
		SDL_SaveBMP(core_cpu.controllers.video.final_screen, save_name.c_str());
	}

	//Toggle Fullscreen on F12
	else if((event.type == SDL_KEYDOWN) && (event.key.keysym.sym == SDLK_F12))
	{
		//Unset fullscreen
		if(config::flags & SDL_WINDOW_FULLSCREEN_DESKTOP)
		{
			config::flags &= ~SDL_WINDOW_FULLSCREEN_DESKTOP;
			config::scaling_factor = config::old_scaling_factor;
		}

		//Set fullscreen
		else
		{
			config::flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
			config::old_scaling_factor = config::scaling_factor;
		}

		//Destroy old window
		SDL_DestroyWindow(core_cpu.controllers.video.window);

		//Initialize new window - SDL
		if(!config::use_opengl)
		{
			core_cpu.controllers.video.window = SDL_CreateWindow("GBE+", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, config::sys_width, config::sys_height, config::flags);
			core_cpu.controllers.video.final_screen = SDL_GetWindowSurface(core_cpu.controllers.video.window);
			SDL_GetWindowSize(core_cpu.controllers.video.window, &config::win_width, &config::win_height);
		}

		//Initialize new window - OpenGL
		else
		{
			core_cpu.controllers.video.opengl_init();
		}
	}

	//Pause emulation
	else if((event.type == SDL_KEYDOWN) && (event.key.keysym.sym == SDLK_PAUSE))
	{
		config::pause_emu = true;
		SDL_PauseAudio(1);
		std::cout<<"EMU::Paused\n";

		//Delay until pause key is hit again
		while(config::pause_emu)
		{
			SDL_Delay(50);
			if((SDL_PollEvent(&event)) && (event.type == SDL_KEYDOWN) && (event.key.keysym.sym == SDLK_PAUSE))
			{
				config::pause_emu = false;
				SDL_PauseAudio(0);
				std::cout<<"EMU::Unpaused\n";
			}
		}
	}

	//Toggle turbo on
	else if((event.type == SDL_KEYDOWN) && (event.key.keysym.sym == config::hotkey_turbo)) { config::turbo = true; }

	//Toggle turbo off
	else if((event.type == SDL_KEYUP) && (event.key.keysym.sym == config::hotkey_turbo)) { config::turbo = false; }
		
	//Reset emulation on F8
	else if((event.type == SDL_KEYDOWN) && (event.key.keysym.sym == SDLK_F8)) { reset(); }
}
Beispiel #5
0
int main( int argc, char *argv[ ] )
{
    SDL_Window *window;
    if( SDL_Init( SDL_INIT_VIDEO ) == -1 )
    {
        printf( "Can't init SDL:  %s\n", SDL_GetError( ) );
        return EXIT_FAILURE;
    }

    if( SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1) == -1)
    {
        printf( "Can't set attribute DOUBLE BUFFER :  %s\n", SDL_GetError( ) );
        return EXIT_FAILURE;
    }
    atexit( SDL_Quit );
    SDL_Surface *surface;
    window = SDL_CreateWindow("Ma fenêtre de jeu", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_OPENGL );

    SDL_GLContext *glcontext;
    glcontext = SDL_GL_CreateContext(window);

    int nValue;
    if( SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &nValue) < 0)
    {
        printf("Echec de recuperation du parametre SDL_GL_DOUBLEBUFFER : %s\n", SDL_GetError());
        return (EXIT_FAILURE);
    }

    // assurons nous que le mode "double buffer" est bien actif
    if(nValue != 1)
    {
        printf("Erreur : SDL_GL_DOUBLEBUFFER inactif : %d\n", nValue);
        return (EXIT_FAILURE);
    }
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
    SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &nValue);
    printf("Depth %d\n", nValue);

    surface = SDL_GetWindowSurface(window);

    if( surface == NULL )
    {
        printf( "Can't set video mode: %s\n", SDL_GetError( ) );
        return EXIT_FAILURE;
    }   

    opengl_init();
    // Main loop
    SDL_Event event;
    while(1)
    {
        opengl_clear(window);

       // Check for messages
        if (SDL_PollEvent(&event))
        {
            // Check for the quit message
            switch (event.type)
            {
                case SDL_QUIT:
                    SDL_Quit();
                    return EXIT_SUCCESS;// Quit the program
                    break;
				case SDL_KEYUP:
				case SDL_KEYDOWN:
					//printf("keydown %d\n", event.key.keysym.sym);
					switch(event.key.keysym.sym)
					{
					case SDLK_DOWN:
						t_y += (event.type == SDL_KEYDOWN ? SPEED_RATE : 0);
                                                printf("y = %f\n", t_y);
						break;
					case SDLK_UP:
						t_y -= (event.type == SDL_KEYDOWN ? SPEED_RATE : 0);
                                                printf("y = %f\n", t_y);
						break;
					case SDLK_LEFT:
						t_x += (event.type == SDL_KEYDOWN ? SPEED_RATE : 0);
                                                printf("y = %f\n", t_x);
						break;
					case SDLK_RIGHT:
						t_x -= (event.type == SDL_KEYDOWN ? SPEED_RATE : 0);
                                                printf("x = %f\n", t_x);
						break;
					case SDLK_PAGEUP:
						t_z += (event.type == SDL_KEYDOWN ? SPEED_RATE : 0);
                                                printf("z = %f\n", t_z);
						break;
					case SDLK_PAGEDOWN:
						t_z -= (event.type == SDL_KEYDOWN ? SPEED_RATE : 0);
                                                printf("z = %f\n", t_z);
						break;


					case SDLK_ESCAPE:
						SDL_Quit();
						return EXIT_SUCCESS;// Quit the program
						break;
					}
					//printf("speed %f\n", rotationspeed);
					break;
            }
        }
       
        uint32_t new_tick = SDL_GetTicks();
        if(new_tick - delay > 100)
        {
            delay = new_tick;
            rotation += rotationspeed;
            if(rotation > 360)
                rotation -= 360;
            if(rotation < 0)
                rotation += 360;
            //printf("rotation of %f\n", rotation);
        }

        glRotatef(rotation, 1.0f, 1.5f, 0.0f);

        draw_cube();
        //Swap the GL bufers, front and back.
        SDL_GL_SwapWindow(window);
        
    }

    // Tell the SDL to clean up and shut down
    SDL_Quit();

    return EXIT_SUCCESS;
}
Beispiel #6
0
int main(int argc, char *argv[]) {

	const int windowWidth = 800;
	const int windowHeight = 600;

	if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_EVENTS) != 0) {
		fprintf(stderr, "Unable to initialize SDL: %s\n", SDL_GetError());
		return 1;
	}

	atexit(SDL_Quit);

	SDL_Window *window = SDL_CreateWindow("READY", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, windowWidth, windowHeight, 0);
	SDL_Surface *surface = SDL_GetWindowSurface(window);

	console_state_t consoleState;
	consoleInit(&consoleState);

	console_state_t consoleState2;
	consoleInit(&consoleState2);

	rootPanel = (panel_t*) malloc(sizeof(panel_t));
	rootPanel->x = 0;
	rootPanel->y = 0;
	rootPanel->width = windowWidth / 2;
	rootPanel->height = windowHeight;
	rootPanel->prev = NULL;
	rootPanel->color = SDL_MapRGB(surface->format, 0x01, 0x00, 0x7F);
	rootPanel->handler = consolePanelHandler;
	rootPanel->render = consolePanelRender;
	rootPanel->userdata = (void*)(&consoleState);

	rootPanel->next = (panel_t*) malloc(sizeof(panel_t));
	rootPanel->next->x = windowWidth / 2;
	rootPanel->next->y = 0;
	rootPanel->next->width = windowWidth / 2;
	rootPanel->next->height = windowHeight;
	rootPanel->next->prev = rootPanel;
	rootPanel->next->next = NULL;
	rootPanel->next->color = SDL_MapRGB(surface->format, 0x00, 0xFF, 0x00);
	rootPanel->next->handler = consolePanelHandler;
	rootPanel->next->render = consolePanelRender;
	rootPanel->next->userdata = (void*)&consoleState2;

	endPanel = rootPanel->next;

	loadFont("fonts/FJG.gif", &systemFont, 0xFF, 0xFF, 0xFF);

	blitString(surface, &systemFont, "Hello World\nREADY", 10, 10, 0xff, 0xff, 0x0b);
	
	while (1) {
		SDL_Event evt;
		while (SDL_PollEvent(&evt)) {
			if (evt.type == SDL_WINDOWEVENT && evt.window.event == SDL_WINDOWEVENT_CLOSE) {
				goto exit;
			}
			vec2 eventPos;
			if (eventIsSpatial(&evt, &eventPos)) {
				panel_t *eventPanel = findPanelAtPoint(eventPos);
				if (eventPanel) {
					eventPanel->handler(&evt, eventPanel);
				}
			} else if (keyPanel && eventIsKeyboard(&evt)) {
				keyPanel->handler(&evt, keyPanel);
			}
		}
		render(surface);
		// blitString(surface, &systemFont, "> (+ 20 30)\n 50", 10, 42, 0xff, 0xff, 0x00);
		SDL_UpdateWindowSurface(window);
		// TODO: proper timing loop
		SDL_Delay(33);
	}

exit:

	SDL_DestroyWindow(window);
	SDL_Quit();

	return 0;
}
Beispiel #7
0
SDL_Surface *
SDL_SetVideoMode(int width, int height, int bpp, Uint32 flags)
{
    SDL_DisplayMode desktop_mode;
    int display = GetVideoDisplay();
    int window_x = SDL_WINDOWPOS_UNDEFINED_DISPLAY(display);
    int window_y = SDL_WINDOWPOS_UNDEFINED_DISPLAY(display);
    int window_w;
    int window_h;
    Uint32 window_flags;
    Uint32 surface_flags;

    if (!SDL_GetVideoDevice()) {
        if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE) < 0) {
            return NULL;
        }
    }

    SDL_GetDesktopDisplayMode(display, &desktop_mode);

    if (width == 0) {
        width = desktop_mode.w;
    }
    if (height == 0) {
        height = desktop_mode.h;
    }
    if (bpp == 0) {
        bpp = SDL_BITSPERPIXEL(desktop_mode.format);
    }

    /* See if we can simply resize the existing window and surface */
    if (SDL_ResizeVideoMode(width, height, bpp, flags) == 0) {
        return SDL_PublicSurface;
    }

    /* Destroy existing window */
    SDL_PublicSurface = NULL;
    if (SDL_ShadowSurface) {
        SDL_ShadowSurface->flags &= ~SDL_DONTFREE;
        SDL_FreeSurface(SDL_ShadowSurface);
        SDL_ShadowSurface = NULL;
    }
    if (SDL_VideoSurface) {
        SDL_VideoSurface->flags &= ~SDL_DONTFREE;
        SDL_FreeSurface(SDL_VideoSurface);
        SDL_VideoSurface = NULL;
    }
    if (SDL_VideoContext) {
        /* SDL_GL_MakeCurrent(0, NULL); *//* Doesn't do anything */
        SDL_GL_DeleteContext(SDL_VideoContext);
        SDL_VideoContext = NULL;
    }
    if (SDL_VideoWindow) {
        SDL_GetWindowPosition(SDL_VideoWindow, &window_x, &window_y);
        SDL_DestroyWindow(SDL_VideoWindow);
    }

    /* Set up the event filter */
    if (!SDL_GetEventFilter(NULL, NULL)) {
        SDL_SetEventFilter(SDL_CompatEventFilter, NULL);
    }

    /* Create a new window */
    window_flags = SDL_WINDOW_SHOWN;
    if (flags & SDL_FULLSCREEN) {
        window_flags |= SDL_WINDOW_FULLSCREEN;
    }
    if (flags & SDL_OPENGL) {
        window_flags |= SDL_WINDOW_OPENGL;
    }
    if (flags & SDL_RESIZABLE) {
        window_flags |= SDL_WINDOW_RESIZABLE;
    }
    if (flags & SDL_NOFRAME) {
        window_flags |= SDL_WINDOW_BORDERLESS;
    }
    GetEnvironmentWindowPosition(width, height, &window_x, &window_y);
    SDL_VideoWindow =
        SDL_CreateWindow(wm_title, window_x, window_y, width, height,
                         window_flags);
    if (!SDL_VideoWindow) {
        return NULL;
    }
    SDL_SetWindowIcon(SDL_VideoWindow, SDL_VideoIcon);

    SetupScreenSaver(flags);

    window_flags = SDL_GetWindowFlags(SDL_VideoWindow);
    surface_flags = 0;
    if (window_flags & SDL_WINDOW_FULLSCREEN) {
        surface_flags |= SDL_FULLSCREEN;
    }
    if ((window_flags & SDL_WINDOW_OPENGL) && (flags & SDL_OPENGL)) {
        surface_flags |= SDL_OPENGL;
    }
    if (window_flags & SDL_WINDOW_RESIZABLE) {
        surface_flags |= SDL_RESIZABLE;
    }
    if (window_flags & SDL_WINDOW_BORDERLESS) {
        surface_flags |= SDL_NOFRAME;
    }

    SDL_VideoFlags = flags;

    /* If we're in OpenGL mode, just create a stub surface and we're done! */
    if (flags & SDL_OPENGL) {
        SDL_VideoContext = SDL_GL_CreateContext(SDL_VideoWindow);
        if (!SDL_VideoContext) {
            return NULL;
        }
        if (SDL_GL_MakeCurrent(SDL_VideoWindow, SDL_VideoContext) < 0) {
            return NULL;
        }
        SDL_VideoSurface =
            SDL_CreateRGBSurfaceFrom(NULL, width, height, bpp, 0, 0, 0, 0, 0);
        if (!SDL_VideoSurface) {
            return NULL;
        }
        SDL_VideoSurface->flags |= surface_flags;
        SDL_PublicSurface = SDL_VideoSurface;
        return SDL_PublicSurface;
    }

    /* Create the screen surface */
    SDL_WindowSurface = SDL_GetWindowSurface(SDL_VideoWindow);
    if (!SDL_WindowSurface) {
        return NULL;
    }

    /* Center the public surface in the window surface */
    SDL_GetWindowSize(SDL_VideoWindow, &window_w, &window_h);
    SDL_VideoViewport.x = (window_w - width)/2;
    SDL_VideoViewport.y = (window_h - height)/2;
    SDL_VideoViewport.w = width;
    SDL_VideoViewport.h = height;

    SDL_VideoSurface = SDL_CreateRGBSurfaceFrom(NULL, 0, 0, 32, 0, 0, 0, 0, 0);
    SDL_VideoSurface->flags |= surface_flags;
    SDL_VideoSurface->flags |= SDL_DONTFREE;
    SDL_FreeFormat(SDL_VideoSurface->format);
    SDL_VideoSurface->format = SDL_WindowSurface->format;
    SDL_VideoSurface->format->refcount++;
    SDL_VideoSurface->w = width;
    SDL_VideoSurface->h = height;
    SDL_VideoSurface->pitch = SDL_WindowSurface->pitch;
    SDL_VideoSurface->pixels = (void *)((Uint8 *)SDL_WindowSurface->pixels +
        SDL_VideoViewport.y * SDL_VideoSurface->pitch +
        SDL_VideoViewport.x  * SDL_VideoSurface->format->BytesPerPixel);
    SDL_SetClipRect(SDL_VideoSurface, NULL);

    /* Create a shadow surface if necessary */
    if ((bpp != SDL_VideoSurface->format->BitsPerPixel)
        && !(flags & SDL_ANYFORMAT)) {
        SDL_ShadowSurface =
            SDL_CreateRGBSurface(0, width, height, bpp, 0, 0, 0, 0);
        if (!SDL_ShadowSurface) {
            return NULL;
        }
        SDL_ShadowSurface->flags |= surface_flags;
        SDL_ShadowSurface->flags |= SDL_DONTFREE;

        /* 8-bit SDL_ShadowSurface surfaces report that they have exclusive palette */
        if (SDL_ShadowSurface->format->palette) {
            SDL_ShadowSurface->flags |= SDL_HWPALETTE;
            SDL_DitherColors(SDL_ShadowSurface->format->palette->colors,
                             SDL_ShadowSurface->format->BitsPerPixel);
        }
        SDL_FillRect(SDL_ShadowSurface, NULL,
            SDL_MapRGB(SDL_ShadowSurface->format, 0, 0, 0));
    }
    SDL_PublicSurface =
        (SDL_ShadowSurface ? SDL_ShadowSurface : SDL_VideoSurface);

    ClearVideoSurface();

    /* We're finally done! */
    return SDL_PublicSurface;
}
void Window::Render()
{
    //Get window surface
    gScreenSurface = SDL_GetWindowSurface(gWindow);

    //EVENT LOOP

    SDL_Event e;

    //core event loop, 1 frame of the rendering, outer loop in Main.cpp

    //Handle events on queue
    while (SDL_PollEvent(&e) != 0)
    {
        //User requests quit
        if (e.type == SDL_QUIT)
        {
            isCloseRequested = true;
        }
        else if (e.type == SDL_KEYDOWN)
        {
            if (inputManager == nullptr)
                return;
            //SDL_SCANCODE_UP etc
            inputManager->KeyDown(e.key.keysym.scancode);
        }
        else if (e.type == SDL_KEYUP)
        {
            if (inputManager == nullptr)
                return;
            inputManager->KeyUp(e.key.keysym.scancode);
        }
        else if (e.type == SDL_MOUSEBUTTONDOWN)
        {
            if (inputManager == nullptr) //TODO:Improve always calling InputManager
                return;
            inputManager->SetMouseDown(true);
        }
        else if (e.type == SDL_MOUSEBUTTONUP)
        {
            if (inputManager == nullptr) //TODO:Improve always calling InputManager
                return;
            inputManager->SetMouseDown(false);
        }
        else if (e.type == SDL_MOUSEMOTION)
        {
            if (inputManager == nullptr) //TODO:Improve always calling InputManager
                return;
            inputManager->SetMousePosition(e.motion.x,e.motion.y);
        }
    }

    //RenderModelTest();
    //renderQuad();

    //update screen
    SDL_GL_SwapWindow(gWindow);

    //Apply the image
    //SDL_BlitSurface(gHelloWorld, NULL, gScreenSurface, NULL);

    //Update the surface
    //SDL_UpdateWindowSurface(gWindow);
}
Beispiel #9
0
SDL_Surface* GameEngine::getScreenSurface() 
{
	return SDL_GetWindowSurface( window );
}
Beispiel #10
0
SDL_Surface *Renderer::getWindowSurface() const
{
    return SDL_GetWindowSurface(this->window);
}
Beispiel #11
0
Datei: main.c Projekt: Zix777/C
int main(int argc, char** argv)
{
    SDL_Init(SDL_INIT_VIDEO);
    SDL_Window* window = SDL_CreateWindow("SDL Practice4",
                                          SDL_WINDOWPOS_UNDEFINED,SDL_WINDOWPOS_UNDEFINED,
                                          800,700,
                                          SDL_WINDOW_SHOWN);
    SDL_Surface* surface = SDL_GetWindowSurface(window);
    SDL_Surface* image = SDL_LoadBMP("x.bmp");

    SDL_Event event;
    SDL_Rect pos;
    pos.x=0;
    pos.y=0;

    SDL_Rect image_pos;
    image_pos.x = 0;
    image_pos.y = 0;
    image_pos.w = image->w;
    image_pos.h = image->h;
    bool quit=false;
    bool pressed = false;
    SDL_BlitSurface(image, NULL, surface, &pos);
    SDL_UpdateWindowSurface(window);
    while(!quit)
    {
        while(SDL_PollEvent(&event))
        {
            if(event.type == SDL_QUIT)
                quit = true;
            if(event.type == SDL_MOUSEBUTTONDOWN)
            {
                if(event.button.button == SDL_BUTTON_LEFT)
                {
                    image_pos.x = event.motion.x - pos.x;
                    image_pos.y = event.motion.y - pos.y;
                    if(image_pos.x>=0 && image_pos.x<=image_pos.w && image_pos.y>0 && image_pos.y<image_pos.h)
                        pressed = true;
                }
            }
            if(pressed && event.type == SDL_MOUSEMOTION)
            {
                pos.x = event.motion.x - image_pos.x;
                pos.y = event.motion.y - image_pos.y;
                SDL_FillRect(surface, NULL, 0);
                SDL_BlitSurface(image, NULL, surface, &pos);
                SDL_UpdateWindowSurface(window);
            }
            if(event.type == SDL_MOUSEBUTTONUP)
            {
                if(pressed && event.button.button == SDL_BUTTON_LEFT)
                {
                    pressed = false;
                }
            }
        }
    }
    SDL_DestroyWindow(window);
    SDL_Quit();
    return 0;
}
Beispiel #12
0
int main()
#endif
{
	int quit = 0;
	int timer = 0;

	srand(time(NULL));
	Context context = FIRSTMENU;
	SDL_Event event;
	SDL_Window *window = NULL;
	SDL_Surface *windowSurface = NULL;
	SDL_Renderer *windowRenderer = NULL;
	Menu *menu = NULL;
	Game *game = NULL;
	
	/* Init the window or exit if failure. */
	if(!init(&window))
		return EXIT_FAILURE;

	/* Make the window renderer and the window surface */
	windowRenderer = SDL_CreateRenderer(window, 0, SDL_RENDERER_TARGETTEXTURE);
	if(windowRenderer == NULL)
		printf("%s \n", SDL_GetError());

	windowSurface = SDL_GetWindowSurface(window);

	/* Make all context of the game. */
	menu = initMenu(windowRenderer);
	game = initGame(windowRenderer);

	while(!quit)
	{
		/* event loop. */
		while(SDL_PollEvent(&event))
		{
			if(event.type == SDL_QUIT)
				quit = 1;

			else if(event.type == SDL_KEYDOWN)
			{
				const Uint8* keyPressed = SDL_GetKeyboardState(NULL);
				if(context == GAME)
				{
					/* Handle the translation of the blocks */
					if(event.key.keysym.scancode == SDL_SCANCODE_LEFT || event.key.keysym.scancode == SDL_SCANCODE_RIGHT || event.key.keysym.scancode == SDL_SCANCODE_DOWN)
					{
						if(event.key.keysym.scancode == SDL_SCANCODE_LEFT)
							moveCurrentBlock(game, LEFT);
						if(event.key.keysym.scancode == SDL_SCANCODE_RIGHT)
							moveCurrentBlock(game, RIGHT);
						if(event.key.keysym.scancode == SDL_SCANCODE_DOWN)
							moveCurrentBlock(game, DOWN);
					}

					/* Handle the rotation of the blocks */
					else if(event.key.keysym.sym == SDLK_w || event.key.keysym.sym == SDLK_x)
					{
						/* Check the direction the user want to move */
						Direction direction = NONE;
						if(keyPressed[SDL_SCANCODE_RIGHT])
							direction = RIGHT;
						else if(keyPressed[SDL_SCANCODE_LEFT])
							direction = LEFT;

						if(event.key.keysym.sym == SDLK_w)
						{
							rotateCurrentBlock(game, 1, direction);
						}
						else
							rotateCurrentBlock(game, -1, direction);
					}

					else if(event.key.keysym.scancode == SDL_SCANCODE_SPACE)
					{
						putDownCurrentBlock(game);
					}
				}
			}
		}

		SDL_RenderClear(windowRenderer);

		/* Call the correct context */
		if(context == FIRSTMENU)
			firstMenu(menu, windowRenderer, &context);
		else if(context == QUIT)
			quit = 1;
		else if(context == GAME)
			updateGame(game);

		SDL_RenderPresent(windowRenderer);
		fpsManager(&timer);
	}

	/* Clear the allocated memory */
	clearMenu(menu);
	clearGame(game);
	SDL_DestroyRenderer(windowRenderer);
	SDL_FreeSurface(windowSurface);
	SDL_DestroyWindow(window);
	clear();

	return 0;
}
Beispiel #13
0
	void Scene::drawBack(SDL_Window *window, bool updateFramebuffer) {
		SDL_Surface* screenSurface = SDL_GetWindowSurface(window);
		// Draw background
		SDL_FillRect(screenSurface, nullptr, SDL_MapRGB(screenSurface->format, mBackgroundColor.r, mBackgroundColor.g, mBackgroundColor.b));
	}
Beispiel #14
0
	void Scene::drawFront(SDL_Window *window, bool updateFramebuffer) {
		SDL_Surface* screenSurface = SDL_GetWindowSurface(window);
		// Draw UI overlay
		mUiManager->draw(window);
	}
Beispiel #15
0
int main(int argc, char* argv[])
{
	SetDirectory();

	behaviac::IMemAllocator& allocator = behaviac::GetDefaultMemoryAllocator();
	uint32_t allocatedSize = allocator.GetAllocatedSize();

	MyCommandLine cl(argc, argv);
	cl.PrintHelp();
	cl.ReadOptions();

	g_level = cl.Level();
	if (g_level == -1)
	{
		g_level = cl.SelectLevel();
	}

	behaviac::Workspace::GetInstance()->SetFilePath("../example/spaceship/data/bt/exported");
	behaviac::Workspace::GetInstance()->SetFileFormat(behaviac::Workspace::EFF_xml);
	
	//LogManager::GetInstance()->SetFlush(true);
	behaviac::Agent::Register<framework::WorldState>();

	behaviac::Agent::RegisterInstanceName<framework::WorldState>();
	framework::WorldState* pWorldState = behaviac::Agent::Create<framework::WorldState>();

	pWorldState->SetIdFlag(kIdMask_Wolrd);

	behaviac::Agent::Register<framework::Ship>();
	behaviac::Agent::Register<framework::Projectile>();
	
	behaviac::Workspace::GetInstance()->ExportMetas("../example/spaceship/data/ships.xml");

	if (!cl.IsProfiling())
	{
		behaviac::Agent::SetIdMask(kIdMask_Wolrd | kIdMask_Opponent);
	}

	behaviac::Config::SetLogging(true);

	printf("game starting...\n");

	/* initialize SDL */
	if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
	{
		printf("SDL_Init Failed : %s\n", SDL_GetError());
	}

	/* create window */
	SDL_Window* window = SDL_CreateWindow("Space Ship",
		SDL_WINDOWPOS_UNDEFINED,
		SDL_WINDOWPOS_UNDEFINED,
		kWIDTH,
		kHEIGHT,
		0);

	SDL_Surface* screen = SDL_GetWindowSurface(window);
	SDL_Renderer* sdlrenderer = SDL_CreateRenderer(window, -1, 0);
	SDL_SetRenderDrawColor(sdlrenderer, 0, 0, 0, 255);

	// Initialize SDL_ttf library
	if (TTF_Init() != 0)
	{
		printf("TTF_Init Failed : %s\n", TTF_GetError());
	}

	// Load a font
	TTF_Font* font = TTF_OpenFont("../example/spaceship/Resources/Fonts/arial.ttf", 14);
	if (font == NULL)
	{
		printf("TTF_OpenFont Failed : %s\n", TTF_GetError());
		TTF_Quit();
	}

	framework::ws = behaviac::Agent::GetInstance<framework::WorldState>(0);

	framework::renderer = BEHAVIAC_NEW framework::Renderer();
	framework::renderer->sdlrenderer = sdlrenderer;

	framework::GameLogic* logic = BEHAVIAC_NEW framework::GameLogic();
	framework::gl = logic;

	GFrameHandler frame_handler;
	frame_handler.set_fps_limit(60);

	//background and player
	{
		framework::GameObject* background = BEHAVIAC_NEW framework::GameObject();
		background->usesPhysics = false;
		background->setSprite("Backgrounds/background", true);

		framework::ws->addBackgroundObject(background);

		framework::Ship* player = behaviac::Agent::Create<framework::Ship>();
		player->SetIdFlag(kIdMask_Player);
		player->setSprite("Hulls/Sample Hull");
		player->isPlayer = true;
		player->projectileBrain = &makeBoringBrain;

		framework::ws->insertObject(player, framework::point(100, 300));
		framework::ws->SetPlayer(player);
	}

	framework::ws->time = SDL_GetTicks();
	framework::ws->ResetSyncSignal();

	bool par_a = false;
	int par_b = 0;

	/* message pump */
	while (!g_gameover)
	{
		HandleInput();

		if (cl.IsProfiling())
		{
			behaviac::Profiler::GetInstance()->BeginFrame();
		}

		frame_handler.limit_frame();
		frame_handler.calculate();

		if (g_level != g_level_last)
		{
			g_level_last = g_level;

			loadlevel(g_level);

			char title[_MAX_PATH];
			string_sprintf(title, "%s - press '0-9' to switch levels", gs_levels[g_level].name);
			SDL_SetWindowTitle(window, title);

			par_a = !par_a;
			par_b++;

			if (framework::ws->GetAI())
			{
				framework::ws->GetAI()->SetVariable("par_a", par_a);
				framework::ws->GetAI()->SetVariable("par_b", par_b);
			}
		}

		logic->step();

		// clear the screen
		SDL_RenderClear(sdlrenderer);

		// render all sprites
		framework::renderer->Render();

		// Write text to surface
		if (framework::ws->GetPlayer())
		{
			char playerHP[_MAX_PATH];
			string_sprintf(playerHP, "Player HP : %d", framework::ws->GetPlayer()->getHealth());
			renderText(sdlrenderer, font, playerHP, kWIDTH - 120, kHEIGHT - 60);

			char aiHP[_MAX_PATH];
			if (framework::ws->GetAI())
			{
				string_sprintf(aiHP, "AI HP : %d", framework::ws->GetAI()->getHealth());
			}
			else
			{
				string_sprintf(aiHP, "AI Dead");
			}
			renderText(sdlrenderer, font, aiHP, kWIDTH - 120, kHEIGHT - 40);
		}

		// Refreshing the screen
		SDL_RenderPresent(sdlrenderer);

		if (cl.IsProfiling())
		{
			behaviac::Profiler::GetInstance()->EndFrame();
		}
	}

	/* cleanup SDL */
	//SDL_DestroyRenderer(sdlrenderer);
	//SDL_DestroyWindow(window);
	SDL_Quit();

	behaviac::Agent::UnRegister<framework::Projectile>();
	behaviac::Agent::UnRegister<framework::Ship>();
	behaviac::Agent::UnRegister<framework::WorldState>();
	behaviac::Agent::Destroy(pWorldState);

	behaviac::Agent::UnRegisterInstanceName<framework::WorldState>();


	uint32_t allocatedSize1 = allocator.GetAllocatedSize();
	int32_t allocDiff = allocatedSize1 - allocatedSize;

	if (cl.IsProfiling())
	{
		const behaviac::string profile_data = behaviac::Profiler::GetInstance()->GetData(true, false);
		behaviac::string profile_data_m = "\n";
		profile_data_m += profile_data;
		profile_data_m += "\n";

		//BEHAVIAC_LOGMSG("\n%s\n", profile_data_m.c_str());
		behaviac::ConsoleOut::PrintLines(profile_data_m.c_str());
	}

	return 0;
}
Beispiel #16
0
bool sdl_set_video_mode(struct graphics_data *graphics, int width, int height,
 int depth, bool fullscreen, bool resize)
{
  struct sdl_render_data *render_data = graphics->render_data;

#if SDL_VERSION_ATLEAST(2,0,0)
  bool matched = false;
  Uint32 fmt;

  render_data->window = SDL_CreateWindow("MegaZeux",
   SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height,
   sdl_flags(depth, fullscreen, resize));

  if(!render_data->window)
  {
    warn("Failed to create window: %s\n", SDL_GetError());
    goto err_out;
  }

  render_data->renderer =
   SDL_CreateRenderer(render_data->window, -1, SDL_RENDERER_SOFTWARE);

  if(!render_data->renderer)
  {
    warn("Failed to create renderer: %s\n", SDL_GetError());
    goto err_destroy_window;
  }

  render_data->screen = SDL_GetWindowSurface(render_data->window);
  if(!render_data->screen)
  {
    warn("Failed to get window surface: %s\n", SDL_GetError());
    goto err_destroy_renderer;
  }

  /* SDL 2.0 allows the window system to offer up buffers of a specific
   * format, and expects the application to perform a blit if the format
   * doesn't match what the app wanted. To accomodate this, allocate a
   * shadow screen that we render to in the case the formats do not match,
   * and blit it at present time.
   */

  fmt = SDL_GetWindowPixelFormat(render_data->window);
  switch(depth)
  {
    case 8:
      matched = fmt == SDL_PIXELFORMAT_INDEX8;
      fmt = SDL_PIXELFORMAT_INDEX8;
      break;
    case 16:
      switch(fmt)
      {
        case SDL_PIXELFORMAT_RGB565:
        case SDL_PIXELFORMAT_BGR565:
          matched = true;
          break;
        default:
          fmt = SDL_PIXELFORMAT_RGB565;
          break;
      }
      break;
    case 32:
      switch(fmt)
      {
        case SDL_PIXELFORMAT_RGB888:
        case SDL_PIXELFORMAT_RGBX8888:
        case SDL_PIXELFORMAT_RGBA8888:
        case SDL_PIXELFORMAT_BGRX8888:
        case SDL_PIXELFORMAT_BGRA8888:
        case SDL_PIXELFORMAT_ARGB8888:
        case SDL_PIXELFORMAT_ABGR8888:
          matched = true;
          break;
        default:
          fmt = SDL_PIXELFORMAT_RGBA8888;
          break;
      }
      break;
  }

  if(!matched)
  {
    Uint32 Rmask, Gmask, Bmask, Amask;
    int bpp;

    SDL_PixelFormatEnumToMasks(fmt, &bpp, &Rmask, &Gmask, &Bmask, &Amask);

    render_data->shadow = SDL_CreateRGBSurface(0, width, height, bpp,
     Rmask, Gmask, Bmask, Amask);

    debug("Blitting enabled. Rendering performance will be reduced.\n");
  }
  else
  {
    render_data->shadow = NULL;
  }

  if(fmt == SDL_PIXELFORMAT_INDEX8)
  {
    SDL_PixelFormat *format =
      render_data->shadow ? render_data->shadow->format :
                            render_data->screen->format;

    render_data->palette = SDL_AllocPalette(SMZX_PAL_SIZE);
    if(!render_data->palette)
    {
      warn("Failed to allocate palette: %s\n", SDL_GetError());
      goto err_destroy_renderer;
    }

    if(SDL_SetPixelFormatPalette(format, render_data->palette))
    {
      warn("Failed to set pixel format palette: %s\n", SDL_GetError());
      goto err_free_palette;
    }
  }
  else
  {
    render_data->palette = NULL;
  }

  sdl_window_id = SDL_GetWindowID(render_data->window);

#else // !SDL_VERSION_ATLEAST(2,0,0)

  render_data->screen = SDL_SetVideoMode(width, height, depth,
   sdl_flags(depth, fullscreen, resize));

  if(!render_data->screen)
    return false;

  render_data->shadow = NULL;

#endif // !SDL_VERSION_ATLEAST(2,0,0)

  return true;

#if SDL_VERSION_ATLEAST(2,0,0)
err_free_palette:
  SDL_FreePalette(render_data->palette);
  render_data->palette = NULL;
err_destroy_renderer:
  SDL_DestroyRenderer(render_data->renderer);
  render_data->renderer = NULL;
err_destroy_window:
  SDL_DestroyWindow(render_data->window);
  render_data->window = NULL;
err_out:
  return false;
#endif // SDL_VERSION_ATLEAST(2,0,0)
}
Beispiel #17
0
extern "C" int main(int argcount, char* argvec[])
#endif
{
	{
		std::vector<std::string> args;
		for(int i = 0; i != argcount; ++i) {
			args.push_back(argvec[i]);
		}

		preferences::set_argv(args);
	}

#if defined(__native_client__)
	std::cerr << "Running game_main" << std::endl;

	chdir("/frogatto");
	{
		char buf[256];
		const char* const res = getcwd(buf,sizeof(buf));
		std::cerr << "Current working directory: " << res << std::endl;
	}
#endif 

#ifdef _MSC_VER
	freopen("CON", "w", stderr);
	freopen("CON", "w", stdout);
#endif

#if defined(__APPLE__) && TARGET_OS_MAC
    chdir([[[NSBundle mainBundle] resourcePath] fileSystemRepresentation]);
#endif

	#ifdef NO_STDERR
	std::freopen("/dev/null", "w", stderr);
	std::cerr.sync_with_stdio(true);
	#endif

	std::cerr << "Frogatto engine version " << preferences::version() << "\n";
	LOG( "After print engine version" );

	#if defined(TARGET_BLACKBERRY)
		chdir("app/native");
		std::cout<< "Changed working directory to: " << getcwd(0, 0) << std::endl;
	#endif

	game_logic::init_callable_definitions();

	std::string level_cfg = "titlescreen.cfg";
	bool unit_tests_only = false, skip_tests = false;
	bool run_benchmarks = false;
	std::vector<std::string> benchmarks_list;
	std::string utility_program;
	std::vector<std::string> util_args;
	std::string server = "wesnoth.org";
#if defined(UTILITY_IN_PROC)
	bool create_utility_in_new_process = false;
	std::string utility_name;
#endif
	bool is_child_utility = false;

	const char* profile_output = NULL;
	std::string profile_output_buf;

#if defined(__ANDROID__)
	//monstartup("libapplication.so");
#endif

	std::string orig_level_cfg = level_cfg;
	std::string override_level_cfg = "";

	int modules_loaded = 0;

	std::vector<std::string> argv;
	for(int n = 1; n < argcount; ++n) {
#if defined(UTILITY_IN_PROC)
		std::string sarg(argvec[n]);
		if(sarg.compare(0, 15, "--utility-proc=") == 0) {
			create_utility_in_new_process = true;
			utility_name = "--utility-child=" + sarg.substr(15);
		} else {
			argv.push_back(argvec[n]);
		}
#else
		argv.push_back(argvec[n]);
#endif
        
        if(argv.size() >= 2 && argv[argv.size()-2] == "-NSDocumentRevisionsDebugMode" && argv.back() == "YES") {
            //XCode passes these arguments by default when debugging -- make sure they are ignored.
            argv.resize(argv.size()-2);
        }
	}

	std::cerr << "Build Options:";
	for(auto bo : preferences::get_build_options()) {
		std::cerr << " " << bo;
	}
	std::cerr << std::endl;

#if defined(UTILITY_IN_PROC)
	if(create_utility_in_new_process) {
		argv.push_back(utility_name);
#if defined(_MSC_VER)
		// app name is ignored for windows, we get windows to tell us.
		is_child_utility = create_utility_process("", argv);
#else 
		is_child_utility = create_utility_process(argvec[0], argv);
#endif
		if(!is_child_utility) {
			argv.pop_back();
		}
#if defined(_MSC_VER)
		atexit(terminate_utility_process);
#endif
	}
#endif

	if(sys::file_exists("./master-config.cfg")) {
		std::cerr << "LOADING CONFIGURATION FROM master-config.cfg" << std::endl;
		variant cfg = json::parse_from_file("./master-config.cfg");
		if(cfg.is_map()) {
			if( cfg["id"].is_null() == false) {
				std::cerr << "SETTING MODULE PATH FROM master-config.cfg: " << cfg["id"].as_string() << std::endl;
				preferences::set_preferences_path_from_module(cfg["id"].as_string());
				//XXX module::set_module_name(cfg["id"].as_string(), cfg["id"].as_string());
			}
			if(cfg["arguments"].is_null() == false) {
				std::vector<std::string> additional_args = cfg["arguments"].as_list_string();
				argv.insert(argv.begin(), additional_args.begin(), additional_args.end());
				std::cerr << "ADDING ARGUMENTS FROM master-config.cfg:";
				for(size_t n = 0; n < cfg["arguments"].num_elements(); ++n) {
					std::cerr << " " << cfg["arguments"][n].as_string();
				}
				std::cerr << std::endl;
			}
		}
	}

	stats::record_program_args(argv);

	for(size_t n = 0; n < argv.size(); ++n) {
		const int argc = argv.size();
		const std::string arg(argv[n]);
		std::string arg_name, arg_value;
		std::string::const_iterator equal = std::find(arg.begin(), arg.end(), '=');
		if(equal != arg.end()) {
			arg_name = std::string(arg.begin(), equal);
			arg_value = std::string(equal+1, arg.end());
		}
		if(arg_name == "--module") {
			if(load_module(arg_value, &argv) != 0) {
				std::cerr << "FAILED TO LOAD MODULE: " << arg_value << "\n";
				return -1;
			}
			++modules_loaded;
		} else if(arg == "--tests") {
			unit_tests_only = true;
		}
	}

	if(modules_loaded == 0 && !unit_tests_only) {
		if(load_module(DEFAULT_MODULE, &argv) != 0) {
			std::cerr << "FAILED TO LOAD MODULE: " << DEFAULT_MODULE << "\n";
			return -1;
		}
	}

	preferences::load_preferences();
	LOG( "After load_preferences()" );

	// load difficulty settings after module, before rest of args.
	difficulty::manager();

	for(size_t n = 0; n < argv.size(); ++n) {
		const size_t argc = argv.size();
		const std::string arg(argv[n]);
		std::string arg_name, arg_value;
		std::string::const_iterator equal = std::find(arg.begin(), arg.end(), '=');
		if(equal != arg.end()) {
			arg_name = std::string(arg.begin(), equal);
			arg_value = std::string(equal+1, arg.end());
		}
		std::cerr << "ARGS: " << arg << std::endl;
		if(arg.substr(0,4) == "-psn") {
			// ignore.
		} else if(arg_name == "--module") {
			// ignore already processed.
		} else if(arg_name == "--profile" || arg == "--profile") {
			profile_output_buf = arg_value;
			profile_output = profile_output_buf.c_str();
		} else if(arg_name == "--utility" || arg_name == "--utility-child") {
			if(arg_name == "--utility-child") {
				is_child_utility = true;
			}
			utility_program = arg_value;
			for(++n; n < argc; ++n) {
				const std::string arg(argv[n]);
				util_args.push_back(arg);
			}

			break;
		} else if(arg == "--benchmarks") {
			run_benchmarks = true;
		} else if(arg_name == "--benchmarks") {
			run_benchmarks = true;
			benchmarks_list = util::split(arg_value);
		} else if(arg == "--tests") {
			// ignore as already processed.
		} else if(arg == "--no-tests") {
			skip_tests = true;
		} else if(arg_name == "--width") {
			std::string w(arg_value);
			preferences::set_actual_screen_width(boost::lexical_cast<int>(w));
		} else if(arg == "--width" && n+1 < argc) {
			std::string w(argv[++n]);
			preferences::set_actual_screen_width(boost::lexical_cast<int>(w));
		} else if(arg_name == "--height") {
			std::string h(arg_value);
			preferences::set_actual_screen_height(boost::lexical_cast<int>(h));
		} else if(arg == "--height" && n+1 < argc) {
			std::string h(argv[++n]);
			preferences::set_actual_screen_height(boost::lexical_cast<int>(h));
		} else if(arg_name == "--level") {
			override_level_cfg = arg_value;
		} else if(arg == "--level" && n+1 < argc) {
			override_level_cfg = argv[++n];
		} else if(arg_name == "--host") {
			server = arg_value;
		} else if(arg == "--host" && n+1 < argc) {
			server = argv[++n];
		} else if(arg == "--compiled") {
			preferences::set_load_compiled(true);
#ifndef NO_EDITOR
		} else if(arg == "--edit") {
			preferences::set_edit_on_start(true);
#endif
		} else if(arg == "--no-compiled") {
			preferences::set_load_compiled(false);
#if defined(TARGET_PANDORA)
		} else if(arg == "--no-fbo") {
			preferences::set_fbo(false);
		} else if(arg == "--no-bequ") {
			preferences::set_bequ(false);
#endif
		} else if(arg == "--help" || arg == "-h") {
			print_help(std::string(argvec[0]));
			return 0;
		} else {
			const bool res = preferences::parse_arg(argv[n].c_str());
			if(!res) {
				std::cerr << "unrecognized arg: '" << arg << "'\n";
				return -1;
			}
		}
	}

	preferences::expand_data_paths();

	if(g_auto_update_anura != "" && anura_exe_name != "" && sys::file_exists("manifest.cfg")) {
		std::string exe_name = argvec[0];
		if(exe_name.size() >= anura_exe_name.size() && std::equal(exe_name.end()-anura_exe_name.size(), exe_name.end(), anura_exe_name.begin())) {
			variant manifest = json::parse(sys::read_file("manifest.cfg"));
			if(manifest.is_map()) {
				variant anura_entry = manifest[anura_exe_name];
				if(anura_entry.is_map()) {
					std::string expected_md5 = anura_entry["md5"].as_string();
					std::string match;
					if(expected_md5 != md5::sum(sys::read_file(exe_name))) {
						for(auto fname : alternative_anura_exe_names()) {
							if(sys::file_exists(fname) && md5::sum(sys::read_file(fname)) == expected_md5) {
								match = fname;
								break;
							}
						}


						ASSERT_LOG(match != "", "anura.exe does not match md5 in manifest and no alternative anura.exe found");

						try {
							sys::move_file(exe_name, "anura.exe.tmp");
							sys::move_file(match, exe_name);
							match = exe_name;
						} catch(...) {
						}


						std::vector<char*> args;
						for(char** a = argvec; *a; ++a) {
							args.push_back(*a);
						}
						args.push_back(NULL);
				
						exe_name.resize(exe_name.size() - anura_exe_name.size());
						exe_name += match;
						args[0] = const_cast<char*>(exe_name.c_str());
						fprintf(stderr, "ZZZ: CALLING EXEC...\n");
						execv(args[0], &args[0]);
						fprintf(stderr, "Could not exec()\n");
					}
				}
			}
		}
	}

	background_task_pool::manager bg_task_pool_manager;
	LOG( "After expand_data_paths()" );

	std::cerr << "Preferences dir: " << preferences::user_data_path() << '\n';

	//make sure that the user data path exists.
	if(!preferences::setup_preferences_dir()) {
		std::cerr << "cannot create preferences dir!\n";
	}

	std::cerr << "\n";

	variant_builder update_info;
	if(g_auto_update_module || g_auto_update_anura != "") {

		//remove any .tmp files that may have been left from previous runs.
		std::vector<std::string> tmp_files;
		sys::get_files_in_dir(".", &tmp_files, NULL);
		for(auto f : tmp_files) {
			if(f.size() > 4 && std::equal(f.end()-4,f.end(),".tmp")) {
				try {
					sys::remove_file(f);
				} catch(...) {
				}
			}
		}

		boost::intrusive_ptr<module::client> cl, anura_cl;
		
		if(g_auto_update_module) {
			cl.reset(new module::client);
			cl->install_module(module::get_module_name(), g_force_auto_update);
			update_info.add("attempt_module", true);
		}

		if(g_auto_update_anura != "") {
			anura_cl.reset(new module::client);
			anura_cl->set_install_image(true);
			anura_cl->install_module(g_auto_update_anura, g_force_auto_update);
			update_info.add("attempt_anura", true);
		}

		SDL_Window* update_window = NULL;

		int nbytes_transferred = 0, nbytes_anura_transferred = 0;
		int start_time = SDL_GetTicks();
		int original_start_time = SDL_GetTicks();
		bool timeout = false;
		bool require_restart = false;
		fprintf(stderr, "Requesting update to module from server...\n");
		while(cl || anura_cl) {
			if(update_window == NULL && SDL_GetTicks() - original_start_time > 2000) {
				update_window = SDL_CreateWindow("Updating Anura...", 0, 0, 800, 600, SDL_WINDOW_SHOWN);
			}

			int nbytes_obtained = 0;
			int nbytes_needed = 0;

			if(cl) {
				const int transferred = cl->nbytes_transferred();
				nbytes_obtained += transferred;
				nbytes_needed += cl->nbytes_total();
				if(transferred != nbytes_transferred) {
					fprintf(stderr, "Transferred %d/%dKB\n", transferred/1024, cl->nbytes_total()/1024);
					start_time = SDL_GetTicks();
					nbytes_transferred = transferred;
				}
			}

			if(anura_cl) {
				const int transferred = anura_cl->nbytes_transferred();
				nbytes_obtained += transferred;
				nbytes_needed += anura_cl->nbytes_total();
				if(transferred != nbytes_anura_transferred) {
					fprintf(stderr, "Transferred (anura) %d/%dKB\n", transferred/1024, anura_cl->nbytes_total()/1024);
					start_time = SDL_GetTicks();
					nbytes_anura_transferred = transferred;
				}
			}

			const int time_taken = SDL_GetTicks() - start_time;
			if(time_taken > g_auto_update_timeout) {
				fprintf(stderr, "Timed out updating module. Canceling. %dms vs %dms\n", time_taken, g_auto_update_timeout);
				break;
			}

			if(update_window) {
				SDL_Surface* fb= SDL_GetWindowSurface(update_window);
				SDL_Rect area = {300, 290, 200, 20};
				SDL_FillRect(fb, &area, 0xFFFFFFFF);

				SDL_Rect inner_area = {303, 292, 194, 16};
				SDL_FillRect(fb, &inner_area, 0xFF000000);

				if(nbytes_needed != 0) {
					const float ratio = float(nbytes_obtained)/float(nbytes_needed);
					SDL_Rect area = {303, 292, int(194.0*ratio), 16};
					SDL_FillRect(fb, &area, 0xFFFFFFFF);
				}

				SDL_UpdateWindowSurface(update_window);
			}

			SDL_Event event;
			while(SDL_PollEvent(&event)) {
				if(event.type == SDL_QUIT) {
					cl.reset();
					anura_cl.reset();
					break;
				}
			}

			SDL_Delay(20);

			if(cl && !cl->process()) {
				if(cl->error().empty() == false) {
					fprintf(stderr, "Error while updating module: %s\n", cl->error().c_str());
					update_info.add("module_error", variant(cl->error()));
				} else {
					update_info.add("complete_module", true);
				}
				cl.reset();
			}

			if(anura_cl && !anura_cl->process()) {
				if(anura_cl->error().empty() == false) {
					fprintf(stderr, "Error while updating anura: %s\n", anura_cl->error().c_str());
					update_info.add("anura_error", variant(anura_cl->error()));
				} else {
					update_info.add("complete_anura", true);
					require_restart = anura_cl->nfiles_written() != 0;
				}
				anura_cl.reset();
			}
		}

		if(update_window) {
			SDL_DestroyWindow(update_window);
		}

		if(require_restart) {
			std::vector<char*> args;
			for(char** a = argvec; *a; ++a) {
				std::string arg(*a);
				if(arg != "--force-auto-update" && arg != "--force_auto_update") {
					args.push_back(*a);
				}
			}
			args.push_back(NULL);
			fprintf(stderr, "ZZZ: CALLING EXEC...\n");
			execv(args[0], &args[0]);
			fprintf(stderr, "Could not exec()\n");
		}
	}

	g_auto_update_info = update_info.build();

	checksum::manager checksum_manager;
#ifndef NO_EDITOR
	sys::filesystem_manager fs_manager;
#endif // NO_EDITOR

	const tbs::internal_server_manager internal_server_manager_scope(preferences::internal_tbs_server());

	if(utility_program.empty() == false 
		&& test::utility_needs_video(utility_program) == false) {
#if defined(UTILITY_IN_PROC)
		if(is_child_utility) {
			ASSERT_LOG(ipc::semaphore::create(shared_sem_name, 1) != false, 
				"Unable to create shared semaphore: " << errno);
			std::cerr.sync_with_stdio(true);
		}
#endif
		test::run_utility(utility_program, util_args);
		return 0;
	}

#if defined(TARGET_PANDORA)
    EGL_Open();
#endif

#if defined(__ANDROID__)
	std::freopen("stdout.txt","w",stdout);
	std::freopen("stderr.txt","w",stderr);
	std::cerr.sync_with_stdio(true);
#endif

	LOG( "Start of main" );

	if(!skip_tests && !test::run_tests()) {
		return -1;
	}

	if(unit_tests_only) {
		return 0;
	}

	// Create the main window.
	// Initalise SDL and Open GL.
	main_window = graphics::window_manager_ptr(new graphics::window_manager());
	main_window->create_window(preferences::actual_screen_width(), preferences::actual_screen_height());

#ifdef TARGET_OS_HARMATTAN
	g_type_init();
#endif
	i18n::init ();
	LOG( "After i18n::init()" );

#if TARGET_OS_IPHONE || defined(TARGET_BLACKBERRY) || defined(__ANDROID__)
	//on the iPhone and PlayBook, try to restore the auto-save if it exists
	if(sys::file_exists(preferences::auto_save_file_path()) && sys::read_file(std::string(preferences::auto_save_file_path()) + ".stat") == "1") {
		level_cfg = "autosave.cfg";
		sys::write_file(std::string(preferences::auto_save_file_path()) + ".stat", "0");
	}
#endif

	if(override_level_cfg.empty() != true) {
		level_cfg = override_level_cfg;
		orig_level_cfg = level_cfg;
	}

	const stats::manager stats_manager;
#ifndef NO_EDITOR
	const external_text_editor::manager editor_manager;
#endif // NO_EDITOR

#if defined(USE_BOX2D)
	box2d::manager b2d_manager;
#endif

	const load_level_manager load_manager;

	{ //manager scope
	const font::manager font_manager;
	const sound::manager sound_manager;
#if !defined(__native_client__)
	const joystick::manager joystick_manager;
#endif 
	
	graphics::texture::manager texture_manager;

#ifndef NO_EDITOR
	editor::manager editor_manager;
#endif

	variant preloads;
	loading_screen loader;
	try {
		variant gui_node = json::parse_from_file(preferences::load_compiled() ? "data/compiled/gui.cfg" : "data/gui.cfg");
		gui_section::init(gui_node);
		loader.draw_and_increment(_("Initializing GUI"));
		framed_gui_element::init(gui_node);

		sound::init_music(json::parse_from_file("data/music.cfg"));
		graphical_font::init_for_locale(i18n::get_locale());
		preloads = json::parse_from_file("data/preload.cfg");
		int preload_items = preloads["preload"].num_elements();
		loader.set_number_of_items(preload_items+7); // 7 is the number of items that will be loaded below
		custom_object::init();
		loader.draw_and_increment(_("Initializing custom object functions"));
		loader.draw_and_increment(_("Initializing textures"));
		loader.load(preloads);
		loader.draw_and_increment(_("Initializing tiles"));
		tile_map::init(json::parse_from_file("data/tiles.cfg"));


		game_logic::formula_object::load_all_classes();

	} catch(const json::parse_error& e) {
		std::cerr << "ERROR PARSING: " << e.error_message() << "\n";
		return 0;
	}
	loader.draw(_("Loading level"));

#if defined(__native_client__)
	while(1) {
	}
#endif

#if defined(__APPLE__) && !(TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE) && !defined(USE_SHADERS)
	GLint swapInterval = 1;
	CGLSetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &swapInterval);
#endif

	loader.finish_loading();
	//look to see if we got any quit events while loading.
	{
	SDL_Event event;
	while(input::sdl_poll_event(&event)) {
		if(event.type == SDL_QUIT) {
			return 0;
		}
	}
	}

	formula_profiler::manager profiler(profile_output);

#ifdef USE_SHADERS
	texture_frame_buffer::init(preferences::actual_screen_width(), preferences::actual_screen_height());
#else
	texture_frame_buffer::init();
#endif

	if(run_benchmarks) {
		if(benchmarks_list.empty() == false) {
			test::run_benchmarks(&benchmarks_list);
		} else {
			test::run_benchmarks();
		}
		return 0;
	} else if(utility_program.empty() == false && test::utility_needs_video(utility_program) == true) {
		test::run_utility(utility_program, util_args);
		return 0;
	}

	bool quit = false;

	while(!quit && !show_title_screen(level_cfg)) {
		boost::intrusive_ptr<level> lvl(load_level(level_cfg));
		

#if !defined(__native_client__)
		//see if we're loading a multiplayer level, in which case we
		//connect to the server.
		multiplayer::manager mp_manager(lvl->is_multiplayer());
		if(lvl->is_multiplayer()) {
			multiplayer::setup_networked_game(server);
		}

		if(lvl->is_multiplayer()) {
			last_draw_position() = screen_position();
			std::string level_cfg = "waiting-room.cfg";
			boost::intrusive_ptr<level> wait_lvl(load_level(level_cfg));
			wait_lvl->finish_loading();
			wait_lvl->set_multiplayer_slot(0);
			if(wait_lvl->player()) {
				wait_lvl->player()->set_current_level(level_cfg);
			}
			wait_lvl->set_as_current_level();

			level_runner runner(wait_lvl, level_cfg, orig_level_cfg);

			multiplayer::sync_start_time(*lvl, boost::bind(&level_runner::play_cycle, &runner));

			lvl->set_multiplayer_slot(multiplayer::slot());
		}
#endif

		last_draw_position() = screen_position();

		assert(lvl.get());
		if(!lvl->music().empty()) {
			sound::play_music(lvl->music());
		}

		if(lvl->player() && level_cfg != "autosave.cfg") {
			lvl->player()->set_current_level(level_cfg);
			lvl->player()->get_entity().save_game();
		}

		set_scene_title(lvl->title());

		try {
			quit = level_runner(lvl, level_cfg, orig_level_cfg).play_level();
			level_cfg = orig_level_cfg;
		} catch(multiplayer_exception&) {
		}
	}

	level::clear_current_level();

	} //end manager scope, make managers destruct before calling SDL_Quit
//	controls::debug_dump_controls();
#if defined(TARGET_PANDORA) || defined(TARGET_TEGRA)
    EGL_Destroy();
#endif

	preferences::save_preferences();

#if !defined(_MSC_VER) && defined(UTILITY_IN_PROC)
	if(create_utility_in_new_process) {
		terminate_utility_process();
	}
#endif

	std::set<variant*> loading;
	swap_variants_loading(loading);
	if(loading.empty() == false) {
		fprintf(stderr, "Illegal object: %p\n", (void*)(*loading.begin())->as_callable_loading());
		ASSERT_LOG(false, "Unresolved unserialized objects: " << loading.size());
	}

//#ifdef _MSC_VER
//	ExitProcess(0);
//#endif

	return 0;
}
Beispiel #18
0
int main(int argc, char **argv) {
    // Init stuff
    //srand((unsigned int) time(NULL));
    SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_GAMECONTROLLER);
    Hero_PrintSDLVersion();

    // Audio stuff
    Hero_AudioDef audio_def = Hero_InitAudio();

    // Create the window and renderer
    SDL_Window *window = SDL_CreateWindow(
            "Handmade Hero",
            SDL_WINDOWPOS_UNDEFINED,
            SDL_WINDOWPOS_UNDEFINED,
            k_window_width, k_window_height,
            SDL_WINDOW_RESIZABLE);

    // Get the window surface, make a copy of it and update the window
    SDL_Surface *source = SDL_GetWindowSurface(window);
    g_backbuffer = SDL_ConvertSurfaceFormat(source, source->format->format, 0);
    Hero_ResizeAndUpdateWindow(window, g_backbuffer, SDL_TRUE);
    SDL_FreeSurface(source);

    // Loop things
    SDL_bool sound_is_playing = SDL_FALSE;
    Uint32 frame_step = 0;
    SDL_bool running = SDL_TRUE;

    //SDL_SetCursor(Hero_InitSystemCursor(arrow));
    //SDL_ShowCursor(SDL_ENABLE);

    // Game Setup
    _Hero_UpdateGameState Hero_UpdateGameState = NULL;

    Hero_GameInput *game_input = SDL_malloc(sizeof(Hero_GameInput));
    SDL_zerop(game_input);

    Hero_GameState *game_state = SDL_malloc(sizeof(Hero_GameState));
    SDL_zerop(game_state);

    game_state->player_position.abs_tile_x = 3;
    game_state->player_position.abs_tile_y = 3;
    game_state->player_position.tile_rel_x = 5.0f;
    game_state->player_position.tile_rel_y = 5.0f;

    while (running) {
        // Performance
        Uint64 perf_freq = SDL_GetPerformanceFrequency();
        Uint64 perf_counter_start = SDL_GetPerformanceCounter();

#ifdef HERO_DYNLOAD
        // Load our library every n frames
        if ((frame_step % 30) == 0 || Hero_UpdateGameState == NULL) {
            SDL_UnloadObject(g_logic_lib);
            //log_debug("reloading symbols");
            g_logic_lib = SDL_LoadObject("libherologic.so");
            Hero_UpdateGameState = SDL_LoadFunction(g_logic_lib,
                                                    "Hero_UpdateGameState");
        }
#endif

        // Actual game stuff
        running = Hero_HandleEvents(game_input);
        //SDL_GetMouseState(&g_mouse_position.x, &g_mouse_position.y);
        SDL_assert(Hero_UpdateGameState);
        Hero_UpdateGameState(game_state, game_input, g_backbuffer, audio_def);
        Hero_ResizeAndUpdateWindow(window, g_backbuffer, SDL_FALSE);
        //Hero_DebugPlayTestSquareWave(audio_def);

        if (!sound_is_playing) {
            SDL_PauseAudioDevice(g_audio_device, 0);
            sound_is_playing = SDL_TRUE;
        }

        // Performance
        Uint64 perf_counter_end = SDL_GetPerformanceCounter();
        Uint64 perf_counter_elapsed = perf_counter_end - perf_counter_start;
        double perf_per_frame = ((
                (1000.0f * (double) perf_counter_elapsed) /
                (double) perf_freq));

        // Ensure we are at a constant framerate
        double fps_padding_time = k_display_msmax - perf_per_frame;
        // Save the value for movement speed adjustment
        game_input->frame_dt = (float) fps_padding_time * 0.01f;

        if (fps_padding_time > 0)
            SDL_Delay((Uint32) fps_padding_time);

        if ((frame_step % 30) == 0)
            log_debug("Frame stats: %f ms, max %f ms, padding %f ms",
                      perf_per_frame, k_display_msmax, fps_padding_time);

        frame_step++;
    }

    log_debug("Shutting down...");

    if (g_game_controller != NULL)
        SDL_GameControllerClose(g_game_controller);

    SDL_DestroyWindow(window);
    SDL_Quit();
    return 0;
}
Beispiel #19
0
static int
SDL_ResizeVideoMode(int width, int height, int bpp, Uint32 flags)
{
    int w, h;

    /* We can't resize something we don't have... */
    if (!SDL_VideoSurface) {
        return -1;
    }

    /* We probably have to recreate the window in fullscreen mode */
    if (flags & SDL_FULLSCREEN) {
        return -1;
    }

    /* I don't think there's any change we can gracefully make in flags */
    if (flags != SDL_VideoFlags) {
        return -1;
    }
    if (bpp != SDL_VideoSurface->format->BitsPerPixel) {
        return -1;
    }

    /* Resize the window */
    SDL_GetWindowSize(SDL_VideoWindow, &w, &h);
    if (w != width || h != height) {
        SDL_SetWindowSize(SDL_VideoWindow, width, height);
    }

    /* If we're in OpenGL mode, just resize the stub surface and we're done! */
    if (flags & SDL_OPENGL) {
        SDL_VideoSurface->w = width;
        SDL_VideoSurface->h = height;
        return 0;
    }

    SDL_WindowSurface = SDL_GetWindowSurface(SDL_VideoWindow);
    if (!SDL_WindowSurface) {
        return -1;
    }
    if (SDL_VideoSurface->format != SDL_WindowSurface->format) {
        return -1;
    }
    SDL_VideoSurface->w = width;
    SDL_VideoSurface->h = height;
    SDL_VideoSurface->pixels = SDL_WindowSurface->pixels;
    SDL_VideoSurface->pitch = SDL_WindowSurface->pitch;
    SDL_SetClipRect(SDL_VideoSurface, NULL);

    if (SDL_ShadowSurface) {
        SDL_ShadowSurface->w = width;
        SDL_ShadowSurface->h = height;
        SDL_ShadowSurface->pitch = SDL_CalculatePitch(SDL_ShadowSurface);
        SDL_ShadowSurface->pixels =
            SDL_realloc(SDL_ShadowSurface->pixels,
                        SDL_ShadowSurface->h * SDL_ShadowSurface->pitch);
        SDL_SetClipRect(SDL_ShadowSurface, NULL);
        SDL_InvalidateMap(SDL_ShadowSurface->map);
    } else {
        SDL_PublicSurface = SDL_VideoSurface;
    }

    ClearVideoSurface();

    return 0;
}
bool GameApp::Run() {
	if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
		return false;
	}
	
	mWindow = SDL_CreateWindow(mTitle, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, mWidth, mHeight, SDL_WINDOW_SHOWN);
	if (mWindow == 0) {
		SDL_Quit();
		return false;
	}
	else {
		mWindowSurface = SDL_GetWindowSurface(mWindow);
		mGraphics = new Graphics(mWindowSurface, mWidth, mHeight);
	}

	int currentUpdate = GetUpdateFrame();
	int nextUpdate = currentUpdate;

	while (!mShouldTerminate) {
		// Vänta.
		while (nextUpdate == currentUpdate) {
			nextUpdate = GetUpdateFrame();
            SDL_Delay(1);
        }
		// Uppdatera.
        int frames = nextUpdate - currentUpdate;
		if (frames > mMaxUpdates) frames = mMaxUpdates;
		while (frames--) {
			if (mNewScreen) {
				delete mScreen;
				mScreen = mNewScreen;
				mNewScreen = 0;
			}
			if (mScreen) {
				mScreen->Update();
			}
		}
		currentUpdate = nextUpdate;

		// Events ligger i en kö.
		SDL_Event e;
		while (SDL_PollEvent(&e) != 0 ) {
			if (e.type == SDL_QUIT ) {
				mShouldTerminate = true;
			}
			else if (e.type == SDL_KEYDOWN) {
				if (mScreen && !mNewScreen) {
					mScreen->KeyDown(e.key.keysym.sym);
				}
			}
			else if (e.type == SDL_KEYUP) {
				if (mScreen && !mNewScreen) {
					mScreen->KeyUp(e.key.keysym.sym);
				}
			}
		}	

		// Rita.
		if (mScreen && !mNewScreen) {
			mScreen->Draw(mGraphics);
		}
		SDL_UpdateWindowSurface(mWindow);
	}

	delete mScreen;
	delete mNewScreen;
	delete mGraphics;

	SDL_FreeSurface(mWindowSurface);
	mWindowSurface = 0;
	SDL_DestroyWindow(mWindow);
	mWindow = 0;
	SDL_Quit();

	return true;
}
Beispiel #21
0
int
SDL_WM_ToggleFullScreen(SDL_Surface * surface)
{
    int length;
    void *pixels;
    Uint8 *src, *dst;
    int row;
    int window_w;
    int window_h;

    if (!SDL_PublicSurface) {
        SDL_SetError("SDL_SetVideoMode() hasn't been called");
        return 0;
    }

    /* Copy the old bits out */
    length = SDL_PublicSurface->w * SDL_PublicSurface->format->BytesPerPixel;
    pixels = SDL_malloc(SDL_PublicSurface->h * length);
    if (pixels) {
        src = (Uint8*)SDL_PublicSurface->pixels;
        dst = (Uint8*)pixels;
        for (row = 0; row < SDL_PublicSurface->h; ++row) {
            SDL_memcpy(dst, src, length);
            src += SDL_PublicSurface->pitch;
            dst += length;
        }
    }

    /* Do the physical mode switch */
    if (SDL_GetWindowFlags(SDL_VideoWindow) & SDL_WINDOW_FULLSCREEN) {
        if (SDL_SetWindowFullscreen(SDL_VideoWindow, 0) < 0) {
            return 0;
        }
        SDL_PublicSurface->flags &= ~SDL_FULLSCREEN;
    } else {
        if (SDL_SetWindowFullscreen(SDL_VideoWindow, 1) < 0) {
            return 0;
        }
        SDL_PublicSurface->flags |= SDL_FULLSCREEN;
    }

    /* Recreate the screen surface */
    SDL_WindowSurface = SDL_GetWindowSurface(SDL_VideoWindow);
    if (!SDL_WindowSurface) {
        /* We're totally hosed... */
        return 0;
    }

    /* Center the public surface in the window surface */
    SDL_GetWindowSize(SDL_VideoWindow, &window_w, &window_h);
    SDL_VideoViewport.x = (window_w - SDL_VideoSurface->w)/2;
    SDL_VideoViewport.y = (window_h - SDL_VideoSurface->h)/2;
    SDL_VideoViewport.w = SDL_VideoSurface->w;
    SDL_VideoViewport.h = SDL_VideoSurface->h;

    /* Do some shuffling behind the application's back if format changes */
    if (SDL_VideoSurface->format->format != SDL_WindowSurface->format->format) {
        if (SDL_ShadowSurface) {
            if (SDL_ShadowSurface->format->format == SDL_WindowSurface->format->format) {
                /* Whee!  We don't need a shadow surface anymore! */
                SDL_VideoSurface->flags &= ~SDL_DONTFREE;
                SDL_FreeSurface(SDL_VideoSurface);
                SDL_free(SDL_ShadowSurface->pixels);
                SDL_VideoSurface = SDL_ShadowSurface;
                SDL_VideoSurface->flags |= SDL_PREALLOC;
                SDL_ShadowSurface = NULL;
            } else {
                /* No problem, just change the video surface format */
                SDL_FreeFormat(SDL_VideoSurface->format);
                SDL_VideoSurface->format = SDL_WindowSurface->format;
                SDL_VideoSurface->format->refcount++;
                SDL_InvalidateMap(SDL_ShadowSurface->map);
            }
        } else {
            /* We can make the video surface the shadow surface */
            SDL_ShadowSurface = SDL_VideoSurface;
            SDL_ShadowSurface->pitch = SDL_CalculatePitch(SDL_ShadowSurface);
            SDL_ShadowSurface->pixels = SDL_malloc(SDL_ShadowSurface->h * SDL_ShadowSurface->pitch);
            if (!SDL_ShadowSurface->pixels) {
                /* Uh oh, we're hosed */
                SDL_ShadowSurface = NULL;
                return 0;
            }
            SDL_ShadowSurface->flags &= ~SDL_PREALLOC;

            SDL_VideoSurface = SDL_CreateRGBSurfaceFrom(NULL, 0, 0, 32, 0, 0, 0, 0, 0);
            SDL_VideoSurface->flags = SDL_ShadowSurface->flags;
            SDL_VideoSurface->flags |= SDL_PREALLOC;
            SDL_FreeFormat(SDL_VideoSurface->format);
            SDL_VideoSurface->format = SDL_WindowSurface->format;
            SDL_VideoSurface->format->refcount++;
            SDL_VideoSurface->w = SDL_ShadowSurface->w;
            SDL_VideoSurface->h = SDL_ShadowSurface->h;
        }
    }

    /* Update the video surface */
    SDL_VideoSurface->pitch = SDL_WindowSurface->pitch;
    SDL_VideoSurface->pixels = (void *)((Uint8 *)SDL_WindowSurface->pixels +
        SDL_VideoViewport.y * SDL_VideoSurface->pitch +
        SDL_VideoViewport.x  * SDL_VideoSurface->format->BytesPerPixel);
    SDL_SetClipRect(SDL_VideoSurface, NULL);

    /* Copy the old bits back */
    if (pixels) {
        src = (Uint8*)pixels;
        dst = (Uint8*)SDL_PublicSurface->pixels;
        for (row = 0; row < SDL_PublicSurface->h; ++row) {
            SDL_memcpy(dst, src, length);
            src += length;
            dst += SDL_PublicSurface->pitch;
        }
        SDL_Flip(SDL_PublicSurface);
        SDL_free(pixels);
    }

    /* We're done! */
    return 1;
}
Beispiel #22
0
int main(int argc, char *argv[])
{
    if (argc < 2) {
        printf("Usage: ./CHIP-SDL rom\n");
        return -1;
    }

    srand(time(NULL));
    printf("Chip-SDL by xerpi\n");
    printf("Loading \"%s\"...", argv[1]);
    struct chip8_context chip8;
    chip8_init(&chip8, 64, 32);
    int ret = chip8_loadrom(&chip8, argv[1]);
    if (ret) printf("OK!\n");
    else {
        printf("ERROR.\n");
        chip8_fini(&chip8);
        return -1;
    }
    printf("Running \"%s\"...\n", argv[1]);
    
    SDL_Init(SDL_INIT_VIDEO);
    SDL_Window *window = SDL_CreateWindow("Chip-SDL",
       SDL_WINDOWPOS_CENTERED,
       SDL_WINDOWPOS_CENTERED,
       640,
       320,
       SDL_WINDOW_SHOWN);
    SDL_Surface *screen = SDL_GetWindowSurface(window);
    SDL_Surface *chip8_disp = CreateSurface(SDL_SWSURFACE, 64, 32, screen);
    SDL_Event event;
    int running = 1;
    
    while (running) {
        while (SDL_PollEvent(&event) != 0) {
            switch (event.type) {
            case SDL_QUIT:
                running = 0;
                break;
            case SDL_KEYDOWN:
                switch (event.key.keysym.sym) {
                    case SDLK_q:
                        running = 0;
                        break;
                    case SDLK_r:
                        chip8_reset(&chip8);
                        chip8_loadrom(&chip8, argv[1]);
                        break;
                    case SDLK_w:
                        chip8_key_press(&chip8, 1);
                        break;
                    case SDLK_s:
                        chip8_key_press(&chip8, 4);
                        break;
                    case SDLK_UP:
                        chip8_key_press(&chip8, 0xC);
                        break;
                    case SDLK_DOWN:
                        chip8_key_press(&chip8, 0xD);
                        break;
                }
                break;
            case SDL_KEYUP:
                switch (event.key.keysym.sym) {
                    case SDLK_q:
                        running = 0;
                        break;
                    case SDLK_w:
                        chip8_key_release(&chip8, 1);
                        break;
                    case SDLK_s:
                        chip8_key_release(&chip8, 4);
                        break;
                    case SDLK_UP:
                        chip8_key_release(&chip8, 0xC);
                        break;
                    case SDLK_DOWN:
                        chip8_key_release(&chip8, 0xD);
                        break;
                }
                break;
            }
        }
        
        chip8_step(&chip8);
        /*int x, y;
        for (y = 0; y < 32; y++) {
            for (x = 0; x < 8; x++) {
                int i;
                for (i = 0; i < 8; i++) {
                    printf("%c", (chip8.disp_mem[x+y*8]>>(7-i))&0b1 ? 'X' : 'O');
                }
                printf(" ");
            }
            printf("\n");
        }
        printf("\n\n");
        */
        
        //chip8_core_dump(&chip8);
        //usleep(16667);

        chip8_disp_to_SDL(&chip8, chip8_disp);
        SDL_BlitScaled(chip8_disp, NULL, screen, NULL);
        SDL_UpdateWindowSurface(window);
    }
    
    chip8_fini(&chip8);
    SDL_FreeSurface(chip8_disp);
    SDL_DestroyWindow(window);
    SDL_Quit();
    return 0;
}
Beispiel #23
0
bool ExtLoadApp::initApp()
{
	// flag to return
	bool success = true;
	
	/*****
	 * Use this function to initialize the SDL library. This must be called before using any other SDL function.
	 * INFO: http://wiki.libsdl.org/SDL_Init?highlight=%28\bCategoryAPI\b%29|%28SDLFunctionTemplate%29
	 *****/
	// Initialize SDL
	// see following for remarks on flag http://wiki.libsdl.org/SDL_Init#Remarks
	if (SDL_Init( SDL_INIT_VIDEO) < 0)
	{ 
		std::cout << "SDL ould not initalize! SDLError: " << SDL_GetError() << std::endl;
		success = false;
	}
	else 
	{
		/*****
		 * Returns the window that was created or NULL on failure
		 * INFO: http://wiki.libsdl.org/SDL_CreateWindow?highlight=%28\bCategoryAPI\b%29|%28SDLFunctionTemplate%29
		 ******/
		// Create Window
		// INFO: see following for remarks on flags http://wiki.libsdl.org/SDL_CreateWindow#flags
		
		gWindow = SDL_CreateWindow("SDL Tutorial 06", // the title of the window in UTF-8 encoding
									SDL_WINDOWPOS_UNDEFINED, // the x position of the window
									SDL_WINDOWPOS_UNDEFINED, // the y position of the window
									SCREEN_WIDTH, // the width of the window
									SCREEN_HEIGHT, // the height of the window
									SDL_WINDOW_SHOWN // 0 or more SDL_WindowFlags OR'd together
									);
		
		if (gWindow == nullptr)
		{
			std::cout << "Window could not be created! SDL_Error:" << SDL_GetError() << std::endl;
			success = false;
		}
		else
		{
			// initialize the SDL image
			auto imgFlags = IMG_INIT_PNG;
			if (!(IMG_Init(imgFlags) && imgFlags))
			{
				std::cout << "SDL Image could not be initialized! SDL Img Error: " << IMG_GetError() << std::endl;
			}
			else
			{
				// Get window surface
				// INFO: http://wiki.libsdl.org/SDL_GetWindowSurface?highlight=%28\bCategoryAPI\b%29|%28SDLFunctionTemplate%29
				
				gScreenSurface = SDL_GetWindowSurface(gWindow);
				
				if (gScreenSurface == nullptr)
				{
					std::cout << "Window surface could not be created! SDL_ERROR" << SDL_GetError() << std::endl;
					success = false;
				}
			}
		}
		
	}
	return success;	
}
Beispiel #24
0
 void Window::clear(const Color& col) const {
     SDL_Surface* wnd_srfc = SDL_GetWindowSurface(_wnd);
     SDL_FillRect(wnd_srfc, nullptr, col.mapFor(wnd_srfc->format));
 }
Beispiel #25
0
int
main(int argc, char *argv[])
{
    int done;
    SDL_Event event;
        Uint32 then, now, frames;
    SDL_Window *window;
    SDL_Surface *surface;
    SDL_Renderer *renderer;
    SDL_DisplayMode mode;
    
    #define nn 256 //number eurons
    //need new make random friend code below to use other than 255
    #define ns  3674//size neuro
  
 
 srand(time(NULL));
    Uint32 z,y,x;   
    Uint32* brain[nn];
    for (z=0;z<nn;z++) {
      brain[z]=malloc(ns*4+4);
    }
    Uint8 df[nn]; // did_fire
    Uint32 fia,fib,fic;
    fia=fib=fic=1;
    for (z = 0;z<nn;z++) {
      brain[z][0]=0;
      brain[z][1]=z*z*1000+10;//(rand()%8000000)+2000000;//(z%245)+10;//(rand()%250)+5;
    for (y = 2;y<ns;y++) {
    if (rand()%2){
//      brain[z][y] = (rand()%256); // so we have a random brain
brain[z][y]=z/2;//(z+1)%nn;//fic%nn;
      }else{
  //brain[z][y] = (Uint8)(((Uint8)z)-1+(rand()%33)); }
brain[z][y]= (z*2)%nn;//(Uint8)((z-1)%nn) ;// fic%nn;
    }

 fic=fia;
 fia=255*tan(fib);
 fib=255*tan(fic); 

    }
}
    /* Enable standard application logging */
    SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);

    /* Initialize parameters */
    num_objects = NUM_OBJECTS;

    /* Initialize SDL */
    if(SDL_Init(SDL_INIT_VIDEO) != 0)
    {
	SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_Init fail : %s\n", SDL_GetError());
	return 1;
    }

    SDL_GetDesktopDisplayMode(0, &mode);
    /* Create window and renderer for given surface */
    window = SDL_CreateWindow("Draw2", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, mode.w, mode.h, SDL_WINDOW_SHOWN);
    if(!window)
    {
	SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Window creation fail : %s\n",SDL_GetError());
	return 1;
    }	
    surface = SDL_GetWindowSurface(window);
    renderer = SDL_CreateSoftwareRenderer(surface);
    if(!renderer)
    {
	SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Render creation for surface fail : %s\n",SDL_GetError());
	return 1;
    }

    SDL_SetRenderDrawBlendMode(renderer, blendMode);
    SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF);
    SDL_RenderClear(renderer);

    srand((unsigned int)time(NULL));
 Uint32 cols = mode.w /zoom ;
 Uint32 rows= mode.h/zoom;
 
  Uint8 px[ (cols)][ rows ];
  for (x=0;x< cols ;x++){
    	for (y=0;y< rows;y++) {
    	  px[x][y]=((x+y+50)%256);//+(sin(x*y+y)*50);//rand()%((x+y)/10)%256);
    	}
   }
	// Initialize SDL.
	if (SDL_Init(SDL_INIT_AUDIO) < 0)
			return 1;
 
	// local variable

	// Load the WAV 
	// the specs, length and buffer of our wav are filled
	if( SDL_LoadWAV(MUS_PATH, &wav_spec, &wav_buffer, &wav_length) == NULL ){
	  return 1;
	}
 Uint8 sample = 0;
//3	wav_length=256;
	// set the callback function
	wav_spec.callback = my_audio_callback;
	wav_spec.userdata = NULL;
	// set our global static variables
	audio_pos = wav_buffer; // copy sound buffer
	audio_len = wav_length; // copy file length
	
	// Open the audio device 
	if ( SDL_OpenAudio(&wav_spec, NULL) < 0 ){
	  fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError());
	  exit(-1);
	}


SDL_PauseAudio(0);

	/*for (z=0;z<100;z++)
{	
	// Start playing 
	SDL_PauseAudio(0);
 
	// wait until we're don't playing
	while ( audio_len > 0 ) {
		SDL_Delay(100); 
	}
}*/

    /* Main render loop */
    frames = 0;
    then = SDL_GetTicks();
    done = 0;
    
    Uint8 spike=0;
    Uint8 oldspike=0;

    while (!done) {
        /* Check for events */
        ++frames;
       
       
if (rand()%1000==0){
/*
  for (x=0;x< ((mode.w)/zoom) ;x++){
    	for (y=0;y< ((mode.h)/zoom) ;y++) {
    	  px[x][y]=(x+y)/2+(sin(x*y+y)*((rand()%10)+50)) +(tan(x*y+y)*((rand()%10)+50)) //rand()%((x+y)/10)%256);
    	}
   } mappx(renderer,mode,px); } */
   float tanamp= ((rand()%24));
float sinamp= ((rand()%24));
float cosamp= ((rand()%24));
   float tandiv= (((rand()%40))+1)/10.0;
float sindiv= (((rand()%40))+1)/10.0;
float cosdiv= (((rand()%40))+1)/10.0;

  for (x=0;x< cols;x++){
    	for (y=0;y< rows;y++) {
    	  px[x][y]= (Uint8) (50+(x+y)+(sin(((float)(x*y+y))/sindiv)*sinamp) +(tan( ((float) (x*x+y*y))/tandiv)*tanamp) +(cos( ((float) (x*y*y+y))/cosdiv)*cosamp))%256 ;//rand()%((x+y)/10)%256);
    	}
   } mappx(renderer,mode,px); }
Uint8 ok=0;
       while (SDL_PollEvent(&event)) {
    //     while (SDL_PollEvent(&event)) {
      //  SDL_Delay(2);
      if (event.type == SDL_MOUSEBUTTONDOWN) {
    //  ok=0;
     //        for (z=209;z<243;z++){
         oldspike=spike;
         spike= event.motion.x/zoom%nn;
              brain[spike%nn][0]+= brain[spike%nn][1]+ event.motion.y* 10000;// 4100000000 ;
     //  if (!(rand()%10)){spike++; }      
     } //}
      
            if (event.type == SDL_MOUSEBUTTONUP) {
//      ok=0;
           //  for (z=112;z<146;z++){
   spike= event.motion.x/zoom%nn;
              brain[spike%nn][0]+= brain[spike%nn][1]+ event.motion.y* 10000;// 4100000000 ;
    //if (!(rand()%1)){spike++; }   
             }// }
            if (event.type == SDL_MOUSEMOTION) {
    oldspike=spike;
             spike= event.motion.x/zoom%nn;
              brain[spike%nn][0]+= brain[spike%nn][1]+event.motion.y*10000;
                }

            if (event.type == SDL_KEYDOWN &&
                    event.key.keysym.scancode == SDL_SCANCODE_AC_BACK) {
                done = 1;
            }

            if (event.type == SDL_WINDOWEVENT &&
                event.window.event == SDL_WINDOWEVENT_RESIZED) {
                SDL_Log("update screen size");
                SDL_DestroyRenderer(renderer);
                surface = SDL_GetWindowSurface(window);
                renderer = SDL_CreateSoftwareRenderer(surface);
                if(!renderer) {
                    SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Render creation for surface fail : %s\n",SDL_GetError());
                    done = 1;
                    break;
                }
                SDL_SetRenderDrawBlendMode(renderer, blendMode);
                SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF);
                SDL_RenderClear(renderer);
            }
        }

   //   SDL_SetRenderDrawColor(renderer, (Uint8) (255.0*((float)brain[0][0]/ (float) brain[0][1])) ,  (Uint8) (255.0*((float)brain[1][0]/ (float) brain[1][1])) ,(Uint8) (255.0*((float)brain[2][0]/ (float) brain[2][1])) , 0);
       
     //  SDL_RenderClear(renderer); 
for (z = 0;z<nn;z++) {
    SDL_SetRenderDrawColor(renderer, (df[z]) * 60, (Uint8) (255.0*((float)brain[z][0]/ (float) brain[z][1])) , (brain[z][1]/1000) , 0);
//  for (y=0;y<(mode.h/zoom)/20;   for 4y=0;y<(mode.h/zoom)/20;y++)
   for (y=0;y<30;y++){

zSDL_RenderDrawPoint(  renderer, z, y+25);   
   }
}  

  
   for (z = 0;z<nn;z++) {
     if (brain[z][0]>=brain[z][1]) {
       //df[z] = brain[z][0]/brain[z][1];
df[z] = ((brain[z][1]/1000))+( 10* (brain[z][0]/brain[z][1] ));
       brain[z][0] = brain[z][0]%brain[z][1];

  //if (brain[z][1]<= 4000000000 -(df[z])) {
 //  brain[z][1]*=tan(brain[z][1])+.999;//(pow(1.00044,((float)df[z])));
  brain[z][1]+=df[z]*120;
  for(x=0;x<df[z];x++){brain[z][(rand()%((ns-2)))+2]=(((Uint8) (((brain[z][1]/300) ) %nn) ));}
   // } else { brain[z][1]= 4000000000 ; }
     } else { df[z]=0;
       //if ( (brain[z][0]==0) && (brain[z][1]>=10+1)) {
    if ((brain[z][1]>=3)) {
     brain[z][1]*= 0.993;
   for(x=0;x<3;x++){ brain[z][(rand()%((ns-2)))+2]=((brain[z][1]/300))%nn;}
   //
   //  // brain[z][y]=//fic%nn; /[z][rand()%((ns-2)/2)]=brain[z][1];
   }// else if ( (brain[z][0]==0) ) { brain[z][1]=10; }
     }
   }
   

  for (z = 0;z<nn;z++) {
     if (brain[z][0]>0) {
           // brain[z][0]--; :-)i// no potential buffet
           brain[z][0]*=0.98;//03; // no potential to k
      }
    }
 
  for (z = 0;z<nn;z++) {
    for (y = 2;y<ns;y++) {
      //if ((df[brain[z][ (y) ]]>0)&&(brain[z][0]<= 4000000000 - df[brain[z][ (y) ]] )) {
           brain[z][0]+= df[brain[z][(y)]]; // 1-weight excitatory synapses only   
    //  }kg
    //  if ((df[z]>0)&&(brain[brain[z][ (y) ]][0]<= 4000000000 -df[z] )) {
          brain[brain[z][ (y) ]][0]+= df[z] ; // synapses are bidirectional   
//      }
      
    }
}

// and processed frame
 
      SDL_RenderPresent(renderer);
     SDL_UpdateWindowSurface(window);
/*
 for (z = 0;z<wav_length;z++) {
  Uint32 pot = brain[z][0]; 
if (pot > brain[z][1]) {pot= brain[z][1]; }

 pot=(Uint8) (0+(230*( (float) pot/(float) brain[z][1] )))+((df[z]>0)*16);
if ( (Sint16)sample+ ( (Sint16) 8- (Sint16)pot/16)>=0 && (Sint16)sample+ ( (Sint16) 8- (Sint16)pot/16)<=255 ){
wav_buffer[z]= (Uint8) sample+ (Sint16) ( (Sint16) 8- (Sint16)pot/16);//(Uint8) (0+(230*( (float) pot/(float) brain[z][1] )))+(df[z]>0)*24;

sample+= (Sint16) ( (Sint16) 8- (Sint16)pot/16) ;
} else if ( (Sint16)sample+ ( (Sint16) 8- (Sint16)pot/16)<0 ) {
wav_buffer[z]= 0;//(Uint8) sample+ (Sint16) ( (Sint16) 16- (Sint16)pot/8);//(Uint8) (0+(230*( (float) pot/(float) brain[z][1] )))+(df[z]>0)*24;

sample=128;// (Sint16) ( (Sint16) 16- (Sint16)pot/8) ;

}else { wav_buffer[z]= 255;//(Uint8) sample+ (Sint16) ( (Sint16) 16- (Sint16)pot/8);//(Uint8) (0+(230*( (float) pot/(float) brain[z][1] )))+(df[z]>0)*24;

sample=128; }
//zoom wav_buffer[z]=(Uint8)pot;
  } */
  
// trying a new way of making sound
// from just the selected neuron
Uint32 pot = brain[spike][0];
pot=(Uint8) (0+(230*( (float) pot/(float) brain[spike][1] )))+((df[spike]>0)*16);
Uint32 oldpot = brain[oldspike][0];
oldpot=(Uint8) (0+(230*( (float) oldpot/(float) brain[oldspike][1] )))+((df[ oldspike ]>0)*16);
for (z = 0;z<wav_length;z +=2) {
sample -= oldpot;
wav_buffer[z]= sample;
sample += pot;
wav_buffer[z+1]= sample;
}
  	audio_pos = wav_buffer; // copy sound buffer
 	audio_len = wav_length; // copy file length
	unloop=1;
//SDL_PauseAudio(0);
// SDL_Delay(2); 
//unloop=1;
/*SDL_PauseAudio(0);
while (unloop==1) {
		SDL_Delay(10); 
	}
	//SDL_PauseAudio(1);
	*/
//audio_pos = wav_buffer; // copy sound buffer
//audio_len = wav_length; // copy file length
//unloop=1;
    }

    /* Print out some timing information */
    now = SDL_GetTicks();
    if (now > then) {
        double fps = ((double) frames * 1000) / (now - then);
        SDL_LogError(0,"%2.2f frames per second\n", fps);
    }
	
	// shut everything down
	SDL_CloseAudio();
	SDL_FreeWAV(wav_buffer);

    SDL_Quit();

    return 0;
}
SDL_Surface* imagem_carregaImagem(Imagem* imagem, Tela* tela, char* endereco)
{
	int tamanho;
	if(imagem == NULL || tela == NULL)
	{
		printf(" EM: Imagem->imagem_carregaImagem(Imagem*, Tela*, char*)\n");
		printf(" \tERRO: Imagem ou Tela não inicializada, abortando\n");
		return NULL;
	}
	if(endereco == NULL)
	{
		printf(" EM: Imagem->imagem_carregaImagem(Imagem*, Tela*, char*)\n");
		printf(" \tERRO: Endereço inválido (char* == NULL), abortando\n");
		return NULL;
	}

	tamanho = strlen(endereco);

	if(!(tamanho < TAMANHO_MAX_ENDERECO))
	{
		printf(" EM: Imagem->imagem_carregaImagem(Imagem*, Tela*, char*)\n");
		printf(" \tERRO: Endereco muito grande\n");
		printf(" \t\t(sizeof(char*) == %d) > %d\n", tamanho, TAMANHO_MAX_ENDERECO);
		printf(" \tAbortando\n");
		return NULL;
	}



	imagem->endereco = malloc(tamanho * sizeof(char));
/*	imagem->endereco = endereco;*/
	strcpy(imagem->endereco, endereco);
	if(imagem->endereco == NULL)
	{
		printf(" EM: Imagem->imagem_carregaImagem(Imagem*, Tela*, char*)\n");
		printf(" \tERRO: não foi possível armazenar o endereço da imagem (memória insuficiente), abortando\n");
		return NULL;
	}
	


	SDL_Surface* surfaceOtimizada = NULL;
	SDL_Surface* surfacePrimaria = NULL;
	surfacePrimaria = IMG_Load(imagem->endereco);
	if(surfacePrimaria == NULL)
	{
		printf("Não foi possível carregar a imagem (1) \n");
		return NULL;
	}

	if(imagem->haveTransparency)/* Suporte a transparencia mesmo em não png */
	{
		SDL_SetColorKey(surfacePrimaria, SDL_TRUE, SDL_MapRGB(surfacePrimaria->format, imagem->rTransparency, imagem->gTransparency, imagem->bTransparency));
	}

	surfaceOtimizada = SDL_ConvertSurface( surfacePrimaria, SDL_GetWindowSurface(tela_getJanela(tela))->format , 0);
	if(surfaceOtimizada == NULL)
	{
		printf("Não foi possível otimizar imagem em relação à sua tela \n");
		return NULL;
	}
	SDL_FreeSurface(surfacePrimaria);
	return surfaceOtimizada;

}
Beispiel #27
0
int main()
{
    std::cout << "glslviewer" << std::endl;

    if(SDL_Init(SDL_INIT_VIDEO) != 0)
    {
        std::cerr << "SDL_Init Error" << std::endl;
        return 1;
    }

    SDL_Window *win = SDL_CreateWindow("glslviewer", 100, 100, 512, 512, SDL_WINDOW_SHOWN);
    if(win == nullptr)
    {
        std::cerr << "CreateWindow" << std::endl;
        SDL_Quit();
        return 1;
    }

    SDL_Surface *surface = SDL_GetWindowSurface(win);
    SDL_Renderer *renderer = SDL_CreateSoftwareRenderer(surface);
    if(renderer == nullptr)
    {
        std::cerr << "CreateRenderer" << std::endl;
        SDL_Quit();
        return 1;
    }

    SDL_SetRenderDrawColor(renderer, 0xFF, 0, 0xFF, 0xFF);


    State state;
    init(state);
    Program program;
    init(program);

    unsigned counter = 0;

    while(1)
    {
        SDL_Event e;
        if(SDL_PollEvent(&e))
        {
            if(e.type == SDL_QUIT)
                break;
        }

        SDL_SetRenderDrawColor(renderer, 0xFF, 0, counter & 0xFF, 0xFF);
        SDL_RenderClear(renderer);

        for(unsigned y = 0; y < 512; y++)
            for(unsigned x = 0; x < 512; x++)
            {
                State state;
                init(state);
                program.execute(state);
            }

        int *pixels = (int *)surface->pixels;
        for(unsigned i = 0; i < 100; i++)
            pixels[10000+i] = 0;

        SDL_UpdateWindowSurface(win);
        counter++;
    }

    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(win);

    SDL_Quit();

    return 0;
}
Beispiel #28
0
int main(int argn, char * args[])
{

// 	Serialise Loader;

// 	fstream emptyLevel("LevelOneTest.lvl");
// 	fstream savedLevel("LevelOneSave.lvl");

//	if (!savedLevel.good())
//	{
		Serialise Saver(DefaultCode);
		Saver.mFilename = "LevelOneTest";
		Saver.mGl_player.xloc = 1;
		Saver.mGl_player.yloc = 0;
		Saver.mGl_enemy.xloc = 15;
		Saver.mGl_enemy.yloc = 7;
		Saver.mGl_goal.xloc = 15;
		Saver.mGl_goal.yloc = 0;
		Saver.Save(Serialise::LEVEL);

		Serialise Loader;
		Loader.mFilename = "LevelOneTest";
		Loader.Load(Serialise::LEVEL);
//	}
//	else
//	{
//		Loader.mFilename = "LevelOneSave";
//		Loader.Load(Serialise::LEVEL);
//	}

	bool debugging = true;
	bool movedSinceSave = false;

	cMaze MazeOne(Loader.mLoadedLevel);						// Creates a maze instance from the loaded level.
	cPathfinder PathOne;									// Creates a pathfinder instance from the maze instance.
	PathOne.create(MazeOne, Loader.mGl_player, Loader.mGl_enemy, Loader.mGl_goal);								// Populates the nodemap for the pathfinding instance.

	// Load sprites as SDL surfaces
	SDL_Surface * spr_cells = SDL_LoadBMP("../Sprites/redsquare.bmp");
	SDL_Surface * spr_player = SDL_LoadBMP("../Sprites/bluesquare.bmp");
	SDL_Surface * spr_goal = SDL_LoadBMP("../Sprites/goal.bmp");
	SDL_Surface * spr_enemy = SDL_LoadBMP("../Sprites/enemy.bmp");

	// Create window with render surface
	SDL_Init(SDL_INIT_VIDEO);
	SDL_Window * window = SDL_CreateWindow("Train2Game Developer Course Portfolio 1 Project 2 - Ben Keenan | CD9000002O", 50, 80, spr_cells->w * 25, spr_cells->h * 25, SDL_WINDOW_SHOWN);
	SDL_Surface * renderSurface = SDL_GetWindowSurface(window);

	// Set up variables for event pipe
	SDL_Event event;
	bool quit = false;
	enum GAMESTATES { LOSE, PLAYING, WIN, QUIT };
	GAMESTATES gamestate = PLAYING;

	// Assign values for the player.
	gridloc gl_player = Loader.mGl_player;
	float fl_playerX = gl_player.xloc * spr_player->w;
	float fl_playerY = gl_player.yloc * spr_player->h;

	// Assign values for the enemy.
	gridloc gl_enemy = Loader.mGl_enemy;
	float fl_enemyX = gl_enemy.xloc * spr_enemy->w;
	float fl_enemyY = gl_enemy.yloc * spr_enemy->h;

	// Assign values for the goal.
	gridloc gl_goal = Loader.mGl_goal;
	float fl_goalX = gl_goal.xloc * spr_goal->w;
	float fl_goalY = gl_goal.yloc * spr_goal->h;

	// Assign variables to track the timing of the updates
	float fl_lastFrameTime = 0.0f;
	fl_lastFrameTime = SDL_GetTicks();

	// =========================== //
	//			Main loop	       //
	// =========================== //

	while (!quit)
	{
		// ============ //
		//  DRAW STAGE  //
		// ============ //

		// Temporary!! TODO fix blit solution
		SDL_FillRect(renderSurface, NULL, 0xffffffff);

		// Draw out maze from nodemap
		for (int y = 0; y < 25; y++)
		{
			for (int x = 0; x < 25; x++)
			{
				if (MazeOne.mCurrentMaze[x][y].state == cMaze::CLOSED || MazeOne.mCurrentMaze[x][y].state == cMaze::BLOCKED)
				{
					if (!MazeOne.mCurrentMaze[x][y].checked)
					{
						SDL_Rect rect_cells;

						rect_cells.x = x * spr_cells->w;
						rect_cells.y = y * spr_cells->h;
						rect_cells.w = spr_cells->w;
						rect_cells.h = spr_cells->h;

						SDL_BlitSurface(spr_cells, NULL, renderSurface, &rect_cells);
					}
					else
					{
							SDL_Rect rect_cells;

							rect_cells.x = x * spr_cells->w;
							rect_cells.y = y * spr_cells->h;
							rect_cells.w = spr_cells->w;
							rect_cells.h = spr_cells->h;

							SDL_BlitSurface(spr_cells, NULL, renderSurface, &rect_cells);
						
					}
				}
			}
		}

		// Draw player
		SDL_Rect rect_player;
		rect_player.h = spr_player->h;
		rect_player.w = spr_player->w;
		rect_player.x = (int)fl_playerX;
		rect_player.y = (int)fl_playerY;

		// Draw enemy
		SDL_Rect rect_enemy;
		rect_enemy.h = spr_enemy->h;
		rect_enemy.w = spr_enemy->w;
		rect_enemy.x = (int)fl_enemyX;
		rect_enemy.y = (int)fl_enemyY;

		// Draw goal
		SDL_Rect rect_goal;
		rect_goal.h = spr_goal->h;
		rect_goal.w = spr_goal->w;
		rect_goal.x = (int)fl_goalX;
		rect_goal.y = (int)fl_goalY;

		SDL_BlitSurface(spr_player, NULL, renderSurface, &rect_player);
		SDL_BlitSurface(spr_enemy, NULL, renderSurface, &rect_enemy);
		SDL_BlitSurface(spr_goal, NULL, renderSurface, &rect_goal);

		SDL_UpdateWindowSurface(window);


		// ============ //
		//    UPDATE    //
		// ============ //

		float fl_newFrameTime = SDL_GetTicks();
		float fl_timeSinceLastFrame = ((fl_newFrameTime - fl_lastFrameTime) / 1000.0f);	// The time the graphics update took, measured in seconds.

		// Hard clamping.
		if (fl_playerX < 0)
		{
			fl_playerX = 0.0f;
		}
		if (fl_playerY < 0)
		{
			fl_playerY = 0.0f;
		}
		if (fl_playerX >(rect_player.w * 25))
		{
			fl_playerX = (rect_player.w * 24);
		}
		if (fl_playerY > (rect_player.h * 25))
		{
			fl_playerY = (rect_player.h * 24);
		}


		// Keyboard input //
		const Uint8 * KeyboardState = SDL_GetKeyboardState(NULL);


			if (int_movement == NONE && bl_freeToMove)
			{
				if (KeyboardState[SDL_SCANCODE_RIGHT] || KeyboardState[SDL_SCANCODE_D])
				{
					int_movement = RIGHT;
				}
				if (KeyboardState[SDL_SCANCODE_DOWN] || KeyboardState[SDL_SCANCODE_S])
				{
					int_movement = DOWN;
				}
				if (KeyboardState[SDL_SCANCODE_LEFT] || KeyboardState[SDL_SCANCODE_A])
				{
					int_movement = LEFT;
				}
				if (KeyboardState[SDL_SCANCODE_UP] || KeyboardState[SDL_SCANCODE_W])
				{
					int_movement = UP;
				}
			}

			// Flag testing whether a turn has been taken.
			// Reset on every update to false to skip pathfinding.
			bool bl_turnFlag = false;

			// Moving the player
			switch (int_movement)
			{
			case UP:
				if (fl_playerY > 0
					&& TestForCollision((int)fl_playerX, (int)fl_playerY, PathOne, rect_player, UP)
					&& bl_freeToMove)
				{
					fl_playerY -= rect_player.h;						// Up
					int_movement = NONE;
					bl_freeToMove = false;
					// int_enemyMovement = UP;
					bl_turnFlag = true;
					PathOne.UpdateLocs(fl_playerX, fl_playerY, fl_enemyX, fl_enemyY, rect_player, rect_enemy);
					gridloc gl_nextMove = PathOne.NextMove();
					cout << "Next move is: " << gl_nextMove.xloc << ", " << gl_nextMove.yloc << endl;
					movedSinceSave = true;
					
				}
				break;

			case RIGHT:
				if (fl_playerX < (rect_player.w * 25)
					&& TestForCollision((int)fl_playerX, (int)fl_playerY, PathOne, rect_player, RIGHT)
					&& bl_freeToMove)
				{
					fl_playerX += rect_player.w;							// Right
					int_movement = NONE;
					bl_freeToMove = false;
					// int_enemyMovement = RIGHT;
					bl_turnFlag = true;
					PathOne.UpdateLocs(fl_playerX, fl_playerY, fl_enemyX, fl_enemyY, rect_player, rect_enemy);
					gridloc gl_nextMove = PathOne.NextMove();
					cout << "Next move is: " << gl_nextMove.xloc << ", " << gl_nextMove.yloc << endl;
					movedSinceSave = true;
				}
				break;

			case DOWN:
				if (fl_playerY < (rect_player.h * 25)
					&& TestForCollision((int)fl_playerX, (int)fl_playerY, PathOne, rect_player, DOWN)
					&& bl_freeToMove)
				{
					fl_playerY += rect_player.h;						// Down
					int_movement = NONE;
					bl_freeToMove = false;
					// int_enemyMovement = DOWN;
					bl_turnFlag = true;
					PathOne.UpdateLocs(fl_playerX, fl_playerY, fl_enemyX, fl_enemyY, rect_player, rect_enemy);
					gridloc gl_nextMove = PathOne.NextMove();
					cout << "Next move is: " << gl_nextMove.xloc << ", " << gl_nextMove.yloc << endl;
					movedSinceSave = true;
				}
				break;

			case LEFT:
				if (fl_playerX > 0
					&& TestForCollision((int)fl_playerX, (int)fl_playerY, PathOne, rect_player, LEFT)
					&& bl_freeToMove)
				{
					fl_playerX -= rect_player.w;						// Left
					int_movement = NONE;
					bl_freeToMove = false;
					// int_enemyMovement = LEFT;
					bl_turnFlag = true;
					PathOne.UpdateLocs(fl_playerX, fl_playerY, fl_enemyX, fl_enemyY, rect_player, rect_enemy);
					gridloc gl_nextMove = PathOne.NextMove();
					cout << "Next move is: " << gl_nextMove.xloc << ", " << gl_nextMove.yloc << endl;
					movedSinceSave = true;
				}
				break;
			}

			// Only run the below code segment if a turn has been made.
			if (bl_turnFlag == true)
			{
				gl_player.xloc = fl_playerX / rect_player.w;
				gl_player.yloc = fl_playerY / rect_player.h;
				gl_enemy.xloc = fl_enemyX / rect_player.w;
				gl_enemy.yloc = fl_enemyY / rect_player.h;

				// gridloc gl_nextMove = PathOne.NextMove(gl_enemy, gl_player);

				// Moving the enemy
				if (int_enemyMovement != NONE)
				{
					switch (int_enemyMovement)
					{
					case UP:
						if (fl_enemyY > 0)
						{
							fl_enemyY -= rect_enemy.h;
							int_enemyMovement = NONE;
						}
						break;
					case RIGHT:
						if (fl_enemyX < 24 * rect_enemy.w)
						{
							fl_enemyX += rect_player.w;
							int_enemyMovement = NONE;
						}
						break;
					case DOWN:
						if (fl_enemyY < 24 * rect_enemy.h)
						{
							fl_enemyY += rect_enemy.h;
							int_enemyMovement = NONE;
						}
						break;
					case LEFT:
						if (fl_enemyX > 0)
						{
							fl_enemyX -= rect_enemy.w;
							int_enemyMovement = NONE;
						}
						break;

					}
				}
			}

			// Release movement lock on player.
			if (
				!KeyboardState[SDL_SCANCODE_UP]
				&& !KeyboardState[SDL_SCANCODE_W]
				&& !KeyboardState[SDL_SCANCODE_RIGHT]
				&& !KeyboardState[SDL_SCANCODE_D]
				&& !KeyboardState[SDL_SCANCODE_DOWN]
				&& !KeyboardState[SDL_SCANCODE_S]
				&& !KeyboardState[SDL_SCANCODE_LEFT]
				&& !KeyboardState[SDL_SCANCODE_A]
				)
			{
				bl_freeToMove = true;
			}


			// Check if player and enemy are colliding.
			if (fl_playerX == fl_enemyX
				&& fl_playerY == fl_enemyY)
			{
				gamestate = LOSE;
			}

			// Check if player and goal are colliding.
			if (fl_playerX == fl_goalX
				&& fl_playerY == fl_goalY)
			{
				gamestate = WIN;
			}

			// Check if the escape key has been hit.
			if (KeyboardState[SDL_SCANCODE_ESCAPE])
			{
				gamestate = QUIT;
			}

		fl_lastFrameTime = fl_newFrameTime;

		// Check for changes in the state of the game.
		switch (gamestate)
		{
		case LOSE:
		{
						quit = true;
		}
			break;
		case PLAYING:
		{
						quit = false;
		}
			break;
		case WIN:
		{
						quit = true;
		}
			break;
		case QUIT:
		{
						quit = true;
						
						remove("LevelOneSave.lvl");
						Serialise Saver(DefaultCode);
						Saver.mFilename = "LevelOneSave";
						Saver.mGl_player.xloc = fl_playerX / rect_player.w;
						Saver.mGl_player.yloc = fl_playerY / rect_player.h;
						Saver.mGl_enemy.xloc = fl_enemyX / rect_enemy.w;
						Saver.mGl_enemy.yloc = fl_enemyY / rect_enemy.h;
						Saver.mGl_goal.xloc = fl_goalX / rect_goal.w;
						Saver.mGl_goal.yloc = fl_goalY / rect_goal.h;
						Saver.Save(Serialise::LEVEL);
						movedSinceSave = false;
						
		}
		}

		// ============ //
		//    EVENTS    //
		// ============ //

		while (SDL_PollEvent(&event) != 0)

		{
			if (event.type == SDL_QUIT)
			{
				quit = true;
			}
		}

	}

	SDL_Quit();

	return 0;
}
Beispiel #29
0
Context::Context(void)
{

	//Initialize SDL
	if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
	{
		printf( "SDL could not initialize! SDL_Error: %s\n", SDL_GetError() );
	}
	else
	{
		//Create window
		window = SDL_CreateWindow( "Pacman", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );

		if( window == NULL )
		{
			printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() );
		}
		else
		{
			//Update the surface
			SDL_UpdateWindowSurface( window );
		}
	}

	 
	 //The surface contained by the window 
	gScreenSurface = NULL; 
	//The image we will load and show on the screen 
	gHelloWorld = NULL;

	 //Create window 
 
	if( window == NULL ) { 
		printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() ); 
	
	} else { 
	//Get window 
		 gScreenSurface = SDL_GetWindowSurface( window ); 
	}

	gHelloWorld = SDL_LoadBMP( "picture/accueil.bmp" ); 
	if( gHelloWorld == NULL ) { 
	printf( "Unable to load image %s! SDL Error: %s\n", "02_getting_an_image_on_the_screen/hello_world.bmp", SDL_GetError() );
	 } 

	 SDL_BlitSurface( gHelloWorld, NULL, gScreenSurface, NULL );
	  SDL_UpdateWindowSurface( window );
	  audioEngine=new Audio();
	  audioEngine->playMenu();
	 
	  SDL_Delay(3000);

	  gHelloWorld = SDL_LoadBMP( "picture/control.bmp" ); 
	if( gHelloWorld == NULL ) { 
	printf( "Unable to load image %s! SDL Error: %s\n", "02_getting_an_image_on_the_screen/hello_world.bmp", SDL_GetError() );
	 } 

	 SDL_BlitSurface( gHelloWorld, NULL, gScreenSurface, NULL );
	  SDL_UpdateWindowSurface( window );
	  SDL_Delay(3000);

  audioEngine->playGunEffect();
   SDL_Delay(500);
	createRenderer();

	physicEngine=new Physic();

	graphicEngine=new Graphic(window, gRenderer);

	
	audioEngine->start(1);

	map=new Map(gRenderer);
	Hero* test = new Hero("ghost", 0, 1, 1, "ghost1.bmp", 0);
	test->setPosX(0);
	test->setPosY(0);
	map->addEntity(test);

	Pacman* test2 = new Pacman("Pacman", 4, 1, 10, "pacman.bmp", 0);
	map->addEntity(test2);

	for(int i = 0; i < 7; i ++){
		map->addEntity(new Mob("Pacman", 3, 1, 1, "junior.bmp", 0));
	}
	for(int i = 0; i < 6; i++){
		map->addEntity(new Mob("junior", 3, 1, 1, "junior.bmp", 0));
	}
	
}
Beispiel #30
0
  void ReinforcementPictures<T>::displayLoop()
  {
#if 0
    // initialization
    logging.info("Starting SDL init (0)..");

    SDL_Init(0);

    logging.info("Starting SDL subsystem init (events, video, audio)..");

    if(SDL_InitSubSystem(SDL_INIT_EVENTS) != 0){
      logging.error("SDL_Init(EVENTS) failed.");
      SDL_Quit();
      running = false;
      return;
    }

    if(SDL_InitSubSystem(SDL_INIT_VIDEO) != 0){
      logging.error("SDL_Init(VIDEO) failed.");
      SDL_Quit();
      running = false;
      return;
    }

    if(SDL_InitSubSystem(SDL_INIT_AUDIO) != 0){
      logging.error("SDL_Init(AUDIO) failed.");
      SDL_Quit();
      running = false;
      return;
    }

    logging.info("SDL_Init() events, video, audio successful.");
#endif
    
    // opens SDL display

    SDL_Window* window = NULL;
    
    int W = 640;
    int H = 480;

    SDL_DisplayMode mode;

    if(SDL_GetCurrentDisplayMode(0, &mode) == 0){
      W = (3*mode.w)/4;
      H = (3*mode.h)/4;
    }
    else{
      whiteice::logging.error("SDL_GetCurrentDisplayMode() failed");
      running = false;
      SDL_Quit();
      return;
    }

#if 0
    if(TTF_Init() != 0){
      char buffer[80];
      snprintf(buffer, 80, "TTF_Init failed: %s\n", TTF_GetError());
      logging.error(buffer);
      TTF_Quit();
      SDL_Quit();      
      running = false;      
      return;
    }
    else
      logging.info("Starting TTF_Init() done..");

    int flags = IMG_INIT_JPG | IMG_INIT_PNG;

    if(IMG_Init(flags) != flags){
      char buffer[80];
      snprintf(buffer, 80, "IMG_Init failed: %s\n", IMG_GetError());
      logging.error(buffer);
      IMG_Quit();
      TTF_Quit();
      SDL_Quit();
      running = false;
      return;
    }
#endif

    window = SDL_CreateWindow("Tranquility",
			      SDL_WINDOWPOS_CENTERED,
			      SDL_WINDOWPOS_CENTERED,
			      W, H,
			      SDL_WINDOW_ALWAYS_ON_TOP |
			      SDL_WINDOW_INPUT_FOCUS);

    if(window == NULL){
      whiteice::logging.error("SDL_CreateWindow() failed\n");
      running = false;
      return;
    }

    SDL_RaiseWindow(window);
    SDL_UpdateWindowSurface(window);
    SDL_RaiseWindow(window);

    // loads font
    TTF_Font* font  = NULL;
    TTF_Font* font2 = NULL;

    {
      double fontSize = 100.0*sqrt(((float)(W*H))/(640.0*480.0));
      unsigned int fs = (unsigned int)fontSize;
      if(fs <= 0) fs = 10;
      
      font = TTF_OpenFont(fontname.c_str(), fs);
      
      fontSize = 25.0*sqrt(((float)(W*H))/(640.0*480.0));
      fs = (unsigned int)fontSize;
      if(fs <= 0) fs = 10;

      font2 = TTF_OpenFont(fontname.c_str(), fs);
    }


    // loads all pictures
    std::vector<SDL_Surface*> images;
    images.resize(pictures.size());

    actionFeatures.resize(pictures.size());
    
    {
      for(unsigned int i=0;i<pictures.size();i++)
	images[i] = NULL;

      unsigned int numLoaded = 0;
      
#pragma omp parallel for shared(images) shared(numLoaded) schedule(dynamic)
      for(unsigned int i=0;i<pictures.size();i++)
      {
	if(running == false) continue;

	SDL_Surface* image = NULL;

#pragma omp critical
	{
	  // IMG_loader functions ARE NOT thread-safe so
	  // we cannot load files parallel
	  image = IMG_Load(pictures[i].c_str());
	}
	

	if(image == NULL){
	  char buffer[120];
	  snprintf(buffer, 120, "Loading image FAILED (%s): %s",
		   SDL_GetError(), pictures[i].c_str());
	  whiteice::logging.warn(buffer);
	  printf("ERROR: %s\n", buffer);

	  image = SDL_CreateRGBSurface(0, W, H, 32,
				       0x00FF0000, 0x0000FF00, 0x000000FF,
				       0xFF000000);

	  if(image == NULL){
	    whiteice::logging.error("Creating RGB surface failed");
	    running = false;
	    continue;
	  }
	  
	  SDL_FillRect(image, NULL, SDL_MapRGB(image->format, 0, 0, 0));
	}

	SDL_Rect imageRect;
	SDL_Surface* scaled = NULL;

	if(image->w >= image->h){
	  double wscale = ((double)W)/((double)image->w);
	  
	  scaled = SDL_CreateRGBSurface(0,
					(int)(image->w*wscale),
					(int)(image->h*wscale), 32,
					0x00FF0000, 0x0000FF00, 0x000000FF,
					0xFF000000);

	  if(scaled == NULL){
	    whiteice::logging.error("Creating RGB surface failed");
	    running = false;
	    continue;
	  }

	  if(SDL_BlitScaled(image, NULL, scaled, NULL) != 0)
	    whiteice::logging.warn("SDL_BlitScaled fails");
	}
	else{
	  double hscale = ((double)H)/((double)image->h);
	  
	  scaled = SDL_CreateRGBSurface(0,
					(int)(image->w*hscale),
					(int)(image->h*hscale), 32,
					0x00FF0000, 0x0000FF00, 0x000000FF,
					0xFF000000);

	  if(scaled == NULL){
	    whiteice::logging.error("Creating RGB surface failed");
	    running = false;
	    continue;
	  }
	  
	  if(SDL_BlitScaled(image, NULL, scaled, NULL) != 0)
	    whiteice::logging.warn("SDL_BlitScaled fails");
	}

	images[i] = scaled;

	if(image) SDL_FreeSurface(image);

	// creates feature vector (mini picture) of the image
	{
	  actionFeatures[i].resize(this->dimActionFeatures);
	  calculateFeatureVector(images[i], actionFeatures[i]);
	}

	numLoaded++;

	// displays pictures that are being loaded
#pragma omp critical
	{
	  imageRect.w = scaled->w;
	  imageRect.h = scaled->h;
	  imageRect.x = (W - scaled->w)/2;
	  imageRect.y = (H - scaled->h)/2;

	  SDL_Surface* surface = SDL_GetWindowSurface(window);

	  if(surface){
	    SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 0, 0, 0));
	    SDL_BlitSurface(scaled, NULL, surface, &imageRect);

	    if(font){
	      SDL_Color white = { 255, 255, 255 };
	      
	      char message[80];
	      snprintf(message, 80, "%d/%d", numLoaded, pictures.size());
	      
	      SDL_Surface* msg = TTF_RenderUTF8_Blended(font, message, white);
	      
	      if(msg != NULL){
		SDL_Rect messageRect;
		
		messageRect.x = (W - msg->w)/2;
		messageRect.y = (H - msg->h)/2;
		messageRect.w = msg->w;
		messageRect.h = msg->h;
		
		SDL_BlitSurface(msg, NULL, surface, &messageRect);
		
		SDL_FreeSurface(msg);
	      }
	    }

	    SDL_UpdateWindowSurface(window);
	    SDL_ShowWindow(window);
	    SDL_FreeSurface(surface);
	  }
	}

	SDL_Event event;

	while(SDL_PollEvent(&event)){
	  if(event.type == SDL_KEYDOWN){
	    keypresses++;
	    continue;
	  }
	}
      }

    }
    

    long long start_ms =
      duration_cast< milliseconds >(system_clock::now().time_since_epoch()).count();

    unsigned int index = 0;

    // selects HMM initial state randomly according to starting state probabilities
    auto pi = hmm.getPI();
    currentHMMstate = hmm.sample(pi);
    
    
    while(running){
      initialized = true;
      
      SDL_Event event;

      while(SDL_PollEvent(&event)){
	if(event.type == SDL_KEYDOWN){
	  keypresses++;
	  continue;
	}
      }

      if(dev->connectionOk() == false){
	whiteice::logging.info("ReinforcementPictures: Device connection failed");
	running = false;
	continue;
      }

      // waits for full picture show time
      {
	const long long end_ms =
	  duration_cast< milliseconds >(system_clock::now().time_since_epoch()).count();
	long long delta_ms = end_ms - start_ms;

	if(delta_ms < DISPLAYTIME){
	  std::this_thread::sleep_for(std::chrono::milliseconds(DISPLAYTIME - delta_ms));
	  // usleep((DISPLAYTIME - delta_ms)*1000);
	}
      }

      // updates HMM hidden state after action
      {
	std::vector<float> after;
	std::vector<T> state;

	after.resize(dev->getNumberOfSignals());
	for(auto& a : after) a = 0.0f;
	
	dev->data(after);

	state.resize(after.size());

	for(unsigned int i=0;i<state.size();i++){
	  state[i] = after[i];
	}

	const unsigned int o = clusters.getClusterIndex(state);

	unsigned int nextState = currentHMMstate;

	const double p = hmm.next_state(currentHMMstate, nextState, o);

	currentHMMstate = nextState;
      }

      
      // adds previous action to performedActionsQueue
      {
	std::lock_guard<std::mutex> lock(performedActionsMutex);
	performedActionsQueue.push_back(index);
      }
      
      
      
      // waits for a command (picture) to show
      index = 0;
      {
	while(running){
	  
	  {
	    std::lock_guard<std::mutex> lock(actionMutex);
	    if(actionQueue.size() > 0){
	      index = actionQueue.front();
	      actionQueue.pop_front();
	      break;
	    }
	  }
	  usleep(10);
	}

	if(!running) continue;
      }

      // if we are in random mode we choose random pictures
      if(random)
	index = rng.rand() % images.size();

      
      {
	SDL_Surface* surface = SDL_GetWindowSurface(window);

	if(surface != NULL){
	  SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 0, 0, 0));
	  
	  SDL_Rect imageRect;
	  imageRect.w = images[index]->w;
	  imageRect.h = images[index]->h;
	  imageRect.x = (W - images[index]->w)/2;
	  imageRect.y = (H - images[index]->h)/2;
	  
	  SDL_BlitSurface(images[index], NULL, surface, &imageRect);

	  if(font2 && message.size() > 0){
	    SDL_Color white = { 255, 255, 255 };
	    
	    SDL_Surface* msg = TTF_RenderUTF8_Blended(font2,
						      message.c_str(),
						      white);
	    
	    if(msg != NULL){
	      SDL_Rect messageRect;
	      
	      messageRect.x = (W - msg->w)/2;
	      messageRect.y = (H - msg->h)/2;
	      messageRect.w = msg->w;
	      messageRect.h = msg->h;
	      
	      SDL_BlitSurface(msg, NULL, surface, &messageRect);
	      
	      SDL_FreeSurface(msg);
	    }
	  }

	  SDL_UpdateWindowSurface(window);
	  SDL_ShowWindow(window);
	  SDL_FreeSurface(surface);
	}
      }

      start_ms =
	duration_cast< milliseconds >(system_clock::now().time_since_epoch()).count();
      
    }

    
    SDL_DestroyWindow(window);

    if(font){
      TTF_CloseFont(font);
      font = NULL;
    }

    if(font2){
      TTF_CloseFont(font2);
      font2 = NULL;
    }

#if 0
    logging.info("SDL deinitialization started");
    IMG_Quit();
    TTF_Quit();
    SDL_Quit();
    logging.info("SDL deinitialization.. DONE");
#endif
    
  }