Esempio n. 1
0
void Digits::Cleanup()
{
    SDL_DestroyTexture(digits);
}
Esempio n. 2
0
/*
*  Lesson 1: Hello world!
*/
int main(int argc, char** argv) {
    //First we need to start up SDL, and make sure it went ok
    if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
        std::cout << SDL_GetError() << std::endl;
        return 1;
    }

    //First we need to create a window to draw things in
    SDL_Window *win = nullptr;
    //Create a window with title "Hello World" at 100, 100 on the screen with w:640 h:480 and show it
    win = SDL_CreateWindow("Hello World!", 100, 100, 640, 480, SDL_WINDOW_SHOWN);
    //Make sure creating our window went ok
    if (win == nullptr) {
        std::cout << SDL_GetError() << std::endl;
        return 1;
    }

    //Now we create our renderer
    SDL_Renderer *ren = nullptr;
    //Create a renderer that will draw to window, -1 specifies that we want to load whichever
    //video driver supports the flags we're passing
    //Flags: SDL_RENDERER_ACCELERATED: We want to use hardware accelerated rendering, b/c it rocks!
    //SDL_RENDERER_PRESENTVSYNC: We want the renderer's present function (update screen) to be
    //synchornized with the monitor's refresh rate
    ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
    if (ren == nullptr) {
        std::cout << SDL_GetError() << std::endl;
        return 1;
    }

    //SDL 2.0 now uses textures to draw things, but without the SDL_image extension we still
    //must load the image as a bmp SDL_Surface and the convert it
    SDL_Surface *bmp = nullptr;
    bmp = SDL_LoadBMP("../res/Lesson1/hello.bmp");
    if (bmp == nullptr) {
        std::cout << SDL_GetError() << std::endl;
        return 1;
    }
    //The texture we'll be drawing
    SDL_Texture *tex = nullptr;
    //Now convert it to a texture that is optimized for our renderer
    tex = SDL_CreateTextureFromSurface(ren, bmp);
    //Now we no longer need the image so we can free it
    SDL_FreeSurface(bmp);

    //Now lets draw our image
    //First clear the renderer
    SDL_RenderClear(ren);
    //Now draw the texture
    SDL_RenderCopy(ren, tex, NULL, NULL);
    //Update the screen
    SDL_RenderPresent(ren);

    //Have the program wait for 2000ms
    SDL_Delay(2000);

    //Destroy our stuff
    SDL_DestroyTexture(tex);
    SDL_DestroyRenderer(ren);
    SDL_DestroyWindow(win);

    SDL_Quit();

    return 0;
}
Esempio n. 3
0
void dm_destroy_texcache( dm_tex_cache *tex_cache ) {
    SDL_DestroyTexture( tex_cache->texture );
    free( tex_cache->src );
    free( tex_cache );
}
Esempio n. 4
0
Player::~Player() {
	SDL_DestroyTexture(texture);
}
int main(int argc, char *argv[])
{
	char *title;
	SDL_Window *window;
	Uint32 flags;
	int x, y, width, height, shutdown;
	SDL_Renderer *renderer;
	SDL_Event event;
	SDL_AudioDeviceID sdl_audio_dev;
	struct timespec start, last_print, now, elapsed;
	unsigned long total_elapsed_seconds;
	double fps;
	unsigned long int frame_count, frames_since_print;
	struct game_memory mem;
	struct pixel_buffer *virtual_win;
	struct pixel_buffer blit_buf;
	struct human_input input[2];
	struct human_input *tmp_input;
	struct human_input *new_input;
	struct human_input *old_input;
	struct sdl_texture_buffer texture_buf;
	struct sdl_event_context event_ctx;
	struct audio_ring_buffer audio_ring_buf;
	struct audio_buffer audio_buf;

	pixel_buffer_init(&blit_buf);

	texture_buf.texture = NULL;
	texture_buf.pixel_buf = &blit_buf;

	flags =
	    SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_GAMECONTROLLER |
	    SDL_INIT_HAPTIC;
	if (SDL_Init(flags) != 0) {
		return 1;
	}

	height = 480;
	width = 640;

	mem.is_initialized = 0;
	mem.fixed_memory_size = 4 * 1024 * 1024;
	mem.transient_memory_size = 1 * 1024 * 1024;
	mem.fixed_memory =
	    platform_alloc(mem.fixed_memory_size + mem.transient_memory_size);
	if (mem.fixed_memory == 0) {
		debug(0, "did not alloc game memory\n");
		return 1;
	}

	mem.transient_memory = mem.fixed_memory + mem.fixed_memory_size;

	init_game(&mem, HANDMAIDEN_AUDIO_DEFAULT_VOLUME,
		  HANDMAIDEN_AUDIO_START_VOLUME);

	virtual_win = NULL;
	update_pixel_buffer(&mem, &virtual_win);
	if (!virtual_win) {
		debug(0, "did not assign virtual_win\n");
	}

	sdl_init_joysticks(&event_ctx);

	title = (argc > 1) ? argv[1] : "Handmaiden Hero";
	x = SDL_WINDOWPOS_UNDEFINED;
	y = SDL_WINDOWPOS_UNDEFINED;
	flags = SDL_WINDOW_RESIZABLE;
	window = SDL_CreateWindow(title, x, y, width, height, flags);
	if (!window) {
		debug(0, "Could not SDL_CreateWindow\n");
		return 2;
	}

	renderer = SDL_CreateRenderer(window, FIRST_SUPPORTING, NONE);
	if (!renderer) {
		return 3;
	}

	sdl_resize_texture_buf(window, renderer, &texture_buf);

	if (init_audio_ring_buffer(&audio_ring_buf)) {
		sdl_audio_dev = sdl_init_audio(&audio_ring_buf);
	} else {
		sdl_audio_dev = 0;
	}
	if (sdl_audio_dev && audio_ring_buf.buf_len) {
		audio_buf.stream_pos = 0;
		audio_buf.num_samples = 0;
		audio_buf.samples =
		    (int *)platform_alloc(audio_ring_buf.buf_len);
		if (!audio_buf.samples) {
			debug(0, "could not allocate audio_buf.samples[%u]\n",
			      audio_ring_buf.buf_len);
			audio_buf.buf_len = 0;
		} else {
			audio_buf.buf_len = audio_ring_buf.buf_len;
		}
	}

	/* start audio playing by setting "pause" to zero */
	if (sdl_audio_dev && audio_buf.samples) {
		SDL_PauseAudioDevice(sdl_audio_dev, 0);
	}

	event_ctx.event = &event;
	event_ctx.texture_buf = &texture_buf;
	event_ctx.renderer = renderer;
	event_ctx.window = window;
	event_ctx.win_id = SDL_GetWindowID(window);

	clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start);
	last_print.tv_sec = start.tv_sec;
	last_print.tv_nsec = start.tv_nsec;
	total_elapsed_seconds = 0;
	frames_since_print = 0;
	frame_count = 0;
	shutdown = 0;
	old_input = &input[0];
	new_input = &input[1];
	init_input(old_input);
	init_input(new_input);
	while (!shutdown) {
		tmp_input = new_input;
		new_input = old_input;
		old_input = tmp_input;
		init_input(new_input);

		while (SDL_PollEvent(&event)) {
			if ((shutdown = process_event(&event_ctx, new_input))) {
				break;
			}
		}
		process_joysticks(&event_ctx, old_input, new_input);

		if (shutdown || (shutdown = process_input(&mem, new_input))) {
			break;
		}
		update_pixel_buffer(&mem, &virtual_win);
		stretch_buffer(virtual_win, &blit_buf);
		sdl_blit_texture(renderer, &texture_buf);
		if (sdl_audio_dev && audio_buf.samples) {
			if ((audio_ring_buf.write_cursor -
			     audio_ring_buf.play_cursor) <
			    audio_ring_buf.buf_len) {
				SDL_LockAudio();
				if (fill_ring_buf
				    (&audio_ring_buf, &mem, &audio_buf) < 0) {
					shutdown = 1;
				}
				SDL_UnlockAudio();
			}
		}
		frame_count++;
		frames_since_print++;

		clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &now);
		diff_timespecs(last_print, now, &elapsed);
		if (((elapsed.tv_sec * 1000000000) + elapsed.tv_nsec) >
		    100000000) {
			fps =
			    ((double)frames_since_print) /
			    (((double)elapsed.tv_sec) * 1000000000.0 +
			     ((double)elapsed.tv_nsec) / 1000000000.0);
			frames_since_print = 0;
			last_print.tv_sec = now.tv_sec;
			last_print.tv_nsec = now.tv_nsec;
			diff_timespecs(start, now, &elapsed);
			total_elapsed_seconds = elapsed.tv_sec + 1;
			if (FPS_PRINTER) {
				debug(0, "fps: %.02f (avg fps: %.f) %u, %u%s",
				      fps,
				      (double)frame_count /
				      (double)total_elapsed_seconds,
				      audio_ring_buf.play_cursor,
				      audio_ring_buf.write_cursor,
				      ERIC_DEBUG ? "\n" : "\r");
			}
		}
	}
	debug(0, "\n");

	if (sdl_audio_dev) {
		SDL_CloseAudioDevice(sdl_audio_dev);
	}
	close_audio_debug_logging(&audio_ring_buf);
	sdl_close_joysticks(&event_ctx);

	/* we probably do not need to do these next steps */
	if (HANDMAIDEN_TRY_TO_MAKE_VALGRIND_HAPPY) {
		/* first cleanup SDL stuff */
		if (texture_buf.texture) {
			SDL_DestroyTexture(texture_buf.texture);
		}
		SDL_DestroyRenderer(renderer);
		SDL_DestroyWindow(window);
		SDL_Quit();

		/* then collect our own garbage */
		if (blit_buf.pixels) {
			platform_free(blit_buf.pixels,
				      blit_buf.pixels_bytes_len);
		}
		if (audio_ring_buf.buf) {
			platform_free(audio_ring_buf.buf,
				      audio_ring_buf.buf_len);
		}
		if (audio_buf.samples) {
			platform_free(audio_buf.samples, audio_buf.buf_len);
		}
		if (mem.fixed_memory) {
			platform_free(mem.fixed_memory,
				      mem.fixed_memory_size +
				      mem.transient_memory_size);
		}
	}

	return 0;
}
Esempio n. 6
0
void generateText(Main *main, Wind *wind, int *firstT, int *lastT, int *test)
{
    *lastT = SDL_GetTicks();
    if (*lastT > *firstT + 10)
    {
        SDL_Color black = {0, 0, 0};
        SDL_Surface *surfaceMessage;

        time_t now;
        time(&now);
        tm *myT = localtime(&now);

        *firstT = *lastT;
        

        /***** current time *****/
        sprintf(main->prog.genText, "current time %.2d:%.2d", myT->tm_hour, myT->tm_min);
        surfaceMessage = TTF_RenderText_Solid(main->draw.arial, main->prog.genText, black);
        if (main->timer.destroyTexture == 1)
            SDL_DestroyTexture(main->draw.tText[6].timeText);
        main->draw.tText[6].timeText = SDL_CreateTextureFromSurface(wind->renderer, surfaceMessage);
        SDL_FreeSurface(surfaceMessage);

    	/***** time when pressed *****/
    	sprintf(main->prog.genText, "time started %.2d:%.2d", main->timer.hPressed, main->timer.mPressed);
    	surfaceMessage = TTF_RenderText_Solid(main->draw.arial, main->prog.genText, black);
        if (main->timer.destroyTexture == 1)
            SDL_DestroyTexture(main->draw.tText[7].timeText);
    	main->draw.tText[7].timeText = SDL_CreateTextureFromSurface(wind->renderer, surfaceMessage);
        SDL_FreeSurface(surfaceMessage);


    	/***** time left *****/
    	sprintf(main->prog.genText, "time left %.2d:%.2d", main->timer.minCount, main->timer.secCount);
    	surfaceMessage = TTF_RenderText_Solid(main->draw.arial, main->prog.genText, black);
        if (main->timer.destroyTexture == 1)
            SDL_DestroyTexture(main->draw.tText[8].timeText);
    	main->draw.tText[8].timeText = SDL_CreateTextureFromSurface(wind->renderer, surfaceMessage);
        SDL_FreeSurface(surfaceMessage);

    	/***** show how long the session is *****/
    	sprintf(main->prog.genText, "%.2d minute session", main->timer.minutes);
    	surfaceMessage = TTF_RenderText_Solid(main->draw.arial, main->prog.genText, black);
        if (main->timer.destroyTexture == 1)
            SDL_DestroyTexture(main->draw.tText[9].timeText);
    	main->draw.tText[9].timeText = SDL_CreateTextureFromSurface(wind->renderer, surfaceMessage);
        SDL_FreeSurface(surfaceMessage);
    	

        /***** text for volume *****/
        sprintf(main->prog.genText, "%.2d", main->sound.volume);
        surfaceMessage = TTF_RenderText_Blended(main->draw.arial, main->prog.genText, black);
        if (main->timer.destroyTexture == 1)
            SDL_DestroyTexture(main->newText.volText);
        main->newText.volText = SDL_CreateTextureFromSurface(wind->renderer, surfaceMessage);
        SDL_FreeSurface(surfaceMessage);


        if (main->timer.destroyTexture == 0)
            main->timer.destroyTexture = 1;
       }
}
Esempio n. 7
0
void SDLWrapper::destroyTexture(int textureid){
    SDL_DestroyTexture(_textures[textureid]);
}
Esempio n. 8
0
Sprite::~Sprite()
{
	SDL_DestroyTexture(spriteTex);
}
Esempio n. 9
0
int main(int argc, char *argv[])
{
    char *argv0 = argv[0];
    SDL_Window *window;
    SDL_Renderer *renderer;
    TTF_Font *font;
    SDL_Surface *text;
    Scene scene;
    int ptsize;
    int i, done;
    SDL_Color white = { 0xFF, 0xFF, 0xFF, 0 };
    SDL_Color black = { 0x00, 0x00, 0x00, 0 };
    SDL_Color *forecol;
    SDL_Color *backcol;
    SDL_Event event;
    int rendersolid;
    int renderstyle;
    int outline;
    int hinting;
    int kerning;
    int dump;
    enum {
        RENDER_LATIN1,
        RENDER_UTF8,
        RENDER_UNICODE
    } rendertype;
    char *message, string[128];

    /* Look for special execution mode */
    dump = 0;
    /* Look for special rendering types */
    rendersolid = 0;
    renderstyle = TTF_STYLE_NORMAL;
    rendertype = RENDER_LATIN1;
    outline = 0;
    hinting = TTF_HINTING_NORMAL;
    kerning = 1;
    /* Default is black and white */
    forecol = &black;
    backcol = &white;
    for ( i=1; argv[i] && argv[i][0] == '-'; ++i ) {
        if ( strcmp(argv[i], "-solid") == 0 ) {
            rendersolid = 1;
        } else
        if ( strcmp(argv[i], "-utf8") == 0 ) {
            rendertype = RENDER_UTF8;
        } else
        if ( strcmp(argv[i], "-unicode") == 0 ) {
            rendertype = RENDER_UNICODE;
        } else
        if ( strcmp(argv[i], "-b") == 0 ) {
            renderstyle |= TTF_STYLE_BOLD;
        } else
        if ( strcmp(argv[i], "-i") == 0 ) {
            renderstyle |= TTF_STYLE_ITALIC;
        } else
        if ( strcmp(argv[i], "-u") == 0 ) {
            renderstyle |= TTF_STYLE_UNDERLINE;
        } else
        if ( strcmp(argv[i], "-s") == 0 ) {
            renderstyle |= TTF_STYLE_STRIKETHROUGH;
        } else
        if ( strcmp(argv[i], "-outline") == 0 ) {
            if ( sscanf (argv[++i], "%d", &outline) != 1 ) {
                fprintf(stderr, Usage, argv0);
                return(1);
            }
        } else
        if ( strcmp(argv[i], "-hintlight") == 0 ) {
            hinting = TTF_HINTING_LIGHT;
        } else
        if ( strcmp(argv[i], "-hintmono") == 0 ) {
            hinting = TTF_HINTING_MONO;
        } else
        if ( strcmp(argv[i], "-hintnone") == 0 ) {
            hinting = TTF_HINTING_NONE;
        } else
        if ( strcmp(argv[i], "-nokerning") == 0 ) {
            kerning = 0;
        } else
        if ( strcmp(argv[i], "-dump") == 0 ) {
            dump = 1;
        } else
        if ( strcmp(argv[i], "-fgcol") == 0 ) {
            int r, g, b;
            if ( sscanf (argv[++i], "%d,%d,%d", &r, &g, &b) != 3 ) {
                fprintf(stderr, Usage, argv0);
                return(1);
            }
            forecol->r = (Uint8)r;
            forecol->g = (Uint8)g;
            forecol->b = (Uint8)b;
        } else
        if ( strcmp(argv[i], "-bgcol") == 0 ) {
            int r, g, b;
            if ( sscanf (argv[++i], "%d,%d,%d", &r, &g, &b) != 3 ) {
                fprintf(stderr, Usage, argv0);
                return(1);
            }
            backcol->r = (Uint8)r;
            backcol->g = (Uint8)g;
            backcol->b = (Uint8)b;
        } else {
            fprintf(stderr, Usage, argv0);
            return(1);
        }
    }
    argv += i;
    argc -= i;

    /* Check usage */
    if ( ! argv[0] ) {
        fprintf(stderr, Usage, argv0);
        return(1);
    }

    /* Initialize the TTF library */
    if ( TTF_Init() < 0 ) {
        fprintf(stderr, "Couldn't initialize TTF: %s\n",SDL_GetError());
        SDL_Quit();
        return(2);
    }

    /* Open the font file with the requested point size */
    ptsize = 0;
    if ( argc > 1 ) {
        ptsize = atoi(argv[1]);
    }
    if ( ptsize == 0 ) {
        i = 2;
        ptsize = DEFAULT_PTSIZE;
    } else {
        i = 3;
    }
    font = TTF_OpenFont(argv[0], ptsize);
    if ( font == NULL ) {
        fprintf(stderr, "Couldn't load %d pt font from %s: %s\n",
                    ptsize, argv[0], SDL_GetError());
        cleanup(2);
    }
    TTF_SetFontStyle(font, renderstyle);
    TTF_SetFontOutline(font, outline);
    TTF_SetFontKerning(font, kerning);
    TTF_SetFontHinting(font, hinting);

    if( dump ) {
        for( i = 48; i < 123; i++ ) {
            SDL_Surface* glyph = NULL;

            glyph = TTF_RenderGlyph_Shaded( font, i, *forecol, *backcol );

            if( glyph ) {
                char outname[64];
                sprintf( outname, "glyph-%d.bmp", i );
                SDL_SaveBMP( glyph, outname );
            }

        }
        cleanup(0);
    }

    /* Create a window */
    if (SDL_CreateWindowAndRenderer(WIDTH, HEIGHT, 0, &window, &renderer) < 0) {
        fprintf(stderr, "SDL_CreateWindowAndRenderer() failed: %s\n", SDL_GetError());
        cleanup(2);
    }

    /* Show which font file we're looking at */
    sprintf(string, "Font file: %s", argv[0]);  /* possible overflow */
    if ( rendersolid ) {
        text = TTF_RenderText_Solid(font, string, *forecol);
    } else {
        text = TTF_RenderText_Shaded(font, string, *forecol, *backcol);
    }
    if ( text != NULL ) {
        scene.captionRect.x = 4;
        scene.captionRect.y = 4;
        scene.captionRect.w = text->w;
        scene.captionRect.h = text->h;
        scene.caption = SDL_CreateTextureFromSurface(renderer, text);
        SDL_FreeSurface(text);
    }

    /* Render and center the message */
    if ( argc > 2 ) {
        message = argv[2];
    } else {
        message = DEFAULT_TEXT;
    }
    switch (rendertype) {
        case RENDER_LATIN1:
        if ( rendersolid ) {
            text = TTF_RenderText_Solid(font,message,*forecol);
        } else {
            text = TTF_RenderText_Shaded(font,message,*forecol,*backcol);
        }
        break;

        case RENDER_UTF8:
        if ( rendersolid ) {
            text = TTF_RenderUTF8_Solid(font,message,*forecol);
        } else {
            text = TTF_RenderUTF8_Shaded(font,message,*forecol,*backcol);
        }
        break;

        case RENDER_UNICODE:
        {
            Uint16 *unicode_text = SDL_iconv_utf8_ucs2(message);
            if ( rendersolid ) {
                text = TTF_RenderUNICODE_Solid(font,
                    unicode_text, *forecol);
            } else {
                text = TTF_RenderUNICODE_Shaded(font,
                    unicode_text, *forecol, *backcol);
            }
            SDL_free(unicode_text);
        }
        break;
        default:
        text = NULL; /* This shouldn't happen */
        break;
    }
    if ( text == NULL ) {
        fprintf(stderr, "Couldn't render text: %s\n", SDL_GetError());
        TTF_CloseFont(font);
        cleanup(2);
    }
    scene.messageRect.x = (WIDTH - text->w)/2;
    scene.messageRect.y = (HEIGHT - text->h)/2;
    scene.messageRect.w = text->w;
    scene.messageRect.h = text->h;
    scene.message = SDL_CreateTextureFromSurface(renderer, text);
    printf("Font is generally %d big, and string is %d big\n",
                        TTF_FontHeight(font), text->h);

    draw_scene(renderer, &scene);

    /* Wait for a keystroke, and blit text on mouse press */
    done = 0;
    while ( ! done ) {
        if ( SDL_WaitEvent(&event) < 0 ) {
            fprintf(stderr, "SDL_PullEvent() error: %s\n",
                                SDL_GetError());
            done = 1;
            continue;
        }
        switch (event.type) {
            case SDL_MOUSEBUTTONDOWN:
                scene.messageRect.x = event.button.x - text->w/2;
                scene.messageRect.y = event.button.y - text->h/2;
                scene.messageRect.w = text->w;
                scene.messageRect.h = text->h;
                draw_scene(renderer, &scene);
                break;

            case SDL_KEYDOWN:
            case SDL_QUIT:
                done = 1;
                break;
            default:
                break;
        }
    }
    SDL_FreeSurface(text);
    TTF_CloseFont(font);
    SDL_DestroyTexture(scene.caption);
    SDL_DestroyTexture(scene.message);
    cleanup(0);

    /* Not reached, but fixes compiler warnings */
    return 0;
}
Esempio n. 10
0
void sdl2_2d_switch(DisplayChangeListener *dcl,
                    DisplaySurface *new_surface)
{
    struct sdl2_console *scon = container_of(dcl, struct sdl2_console, dcl);
    DisplaySurface *old_surface = scon->surface;
    int format = 0;

    assert(!scon->opengl);

    scon->surface = new_surface;

    if (scon->texture) {
        SDL_DestroyTexture(scon->texture);
        scon->texture = NULL;
    }

    if (!new_surface) {
        sdl2_window_destroy(scon);
        return;
    }

    if (!scon->real_window) {
        sdl2_window_create(scon);
    } else if (old_surface &&
               ((surface_width(old_surface)  != surface_width(new_surface)) ||
                (surface_height(old_surface) != surface_height(new_surface)))) {
        sdl2_window_resize(scon);
    }

    SDL_RenderSetLogicalSize(scon->real_renderer,
                             surface_width(new_surface),
                             surface_height(new_surface));

    switch (surface_format(scon->surface)) {
    case PIXMAN_x1r5g5b5:
        format = SDL_PIXELFORMAT_ARGB1555;
        break;
    case PIXMAN_r5g6b5:
        format = SDL_PIXELFORMAT_RGB565;
        break;
    case PIXMAN_x8r8g8b8:
        format = SDL_PIXELFORMAT_ARGB8888;
        break;
    case PIXMAN_r8g8b8x8:
        format = SDL_PIXELFORMAT_RGBA8888;
        break;
    case PIXMAN_b8g8r8x8:
        format = SDL_PIXELFORMAT_BGRX8888;
        break;
    default:
        g_assert_not_reached();
    }
    scon->texture = SDL_CreateTexture(scon->real_renderer, format,
                                      SDL_TEXTUREACCESS_STREAMING,
                                      surface_width(new_surface),
                                      surface_height(new_surface));
    sdl2_2d_redraw(scon);

#ifdef __LIMBO__
   	//TODO: Need to send the resolution to Java
    Android_JNI_SetSDLResolution(surface_width(new_surface), surface_height(new_surface));
#endif //__ANDROID__
}
Esempio n. 11
0
void Viewer::mainloop() {
    Timer timer;
    Timer total;

    if (m_print_perf)
        fmt::print("Rendering frame {}\n", m_frame);
    m_scene_changed = false;
    m_frame++;

    int current_time = SDL_GetTicks();
    double dt = (current_time - m_last_frame_time) / 1000.0;
    m_last_frame_time = current_time;
    auto fps = 1. / dt;

    // Input
    SDL_Event e;
    while (SDL_PollEvent(&e)) {
        if (e.type == SDL_QUIT) {
            shutdown();
        }

        if (e.type == SDL_KEYDOWN) {
            if (e.key.keysym.sym == SDLK_ESCAPE) {
                shutdown();
            }
            if (e.key.keysym.sym == SDLK_b) {
                m_debug = !m_debug;
            }
            if (e.key.keysym.sym == SDLK_n) {
                m_print_perf = !m_print_perf;
            }
            if (e.key.keysym.sym == SDLK_1) {
                m_stride_x = 1;
                m_stride_y = 1;
                m_scene_changed = true;
            }
            if (e.key.keysym.sym == SDLK_2) {
                m_stride_x = 2;
                m_stride_y = 2;
                m_scene_changed = true;
            }
            if (e.key.keysym.sym == SDLK_3) {
                m_stride_x = 4;
                m_stride_y = 4;
                m_scene_changed = true;
            }
        }

        if (e.type == SDL_MOUSEBUTTONDOWN) {
            if (e.button.button == SDL_BUTTON_RIGHT) {
                if (m_look_mode) {
                    m_look_mode = false;
                    SDL_SetRelativeMouseMode(SDL_FALSE);
                } else if (!m_look_mode) {
                    m_look_mode = true;
                    SDL_SetRelativeMouseMode(SDL_TRUE);
                }
            }
        }
    }

    float cam_speed = .8f * dt;

    // Left/right
    const uint8_t *keystates = SDL_GetKeyboardState(0);
    if (keystates[SDL_SCANCODE_A]) {
        m_scene_changed = true;
        Camera::set_pos(m_camera, Camera::pos(m_camera) - Camera::right(m_camera) * cam_speed);
    } else if (keystates[SDL_SCANCODE_D]) {
        Camera::set_pos(m_camera, Camera::pos(m_camera) + Camera::right(m_camera) * cam_speed);
        m_scene_changed = true;
    }

    // Up/down
    if (keystates[SDL_SCANCODE_SPACE]) {
        m_scene_changed = true;
        Camera::set_pos(m_camera, Camera::pos(m_camera) + glm::vec3{0, 1, 0} * cam_speed);
    } else if (keystates[SDL_SCANCODE_LCTRL]) {
        m_scene_changed = true;
        Camera::set_pos(m_camera, Camera::pos(m_camera) - glm::vec3{0, 1, 0} * cam_speed);
    }

    // Roll
    if (keystates[SDL_SCANCODE_Q]) {
        m_scene_changed = true;
        Camera::set_world_up(m_camera, glm::rotateZ(Camera::up(m_camera), 0.1f));
    } else if (keystates[SDL_SCANCODE_E]) {
        m_scene_changed = true;
        Camera::set_world_up(m_camera, glm::rotateZ(Camera::up(m_camera), -0.1f));
    }

    // Front/back
    if (keystates[SDL_SCANCODE_W]) {
        m_scene_changed = true;
        Camera::set_pos(m_camera, Camera::pos(m_camera) + Camera::dir(m_camera) * cam_speed);
    } else if (keystates[SDL_SCANCODE_S]) {
        m_scene_changed = true;
        Camera::set_pos(m_camera, Camera::pos(m_camera) - Camera::dir(m_camera) * cam_speed);
    }

    // Rendering here
    int width;
    int height;
    SDL_GetWindowSize(m_window, &width, &height);

    glm::ivec2 mouse_pos;
    if (m_look_mode) {
        // Yaw
        SDL_GetRelativeMouseState(&(mouse_pos.x), &(mouse_pos.y));
        if (mouse_pos.x != 0) {
            m_scene_changed = true;
            Camera::set_dir(m_camera, glm::rotateY(Camera::dir(m_camera), mouse_pos.x * 0.001f));
        }

        // Pitch
        if (mouse_pos.y != 0) {
            m_scene_changed = true;
            Camera::set_dir(m_camera,
                            glm::rotate(Camera::dir(m_camera), mouse_pos.y * 0.001f,
                                        glm::cross(Camera::up(m_camera), Camera::dir(m_camera))));
        }

    } else if (!m_look_mode) {
        SDL_GetMouseState(&(mouse_pos.x), &(mouse_pos.y));
    }

    if (m_scene_changed) {
        m_samples_accumulated = 0;
    }

    if (m_print_perf)
        fmt::print("    {:<15} {:>10.3f} ms\n", "Input handling", timer.elapsed());

    Scene::rebuild(m_scene);

    if (m_print_perf)
        fmt::print("    {:<15} {:=10.3f} ms\n", "Scene rebuild", timer.elapsed());

    const auto luminance = m_renderer->render(m_scene_changed, m_stride_x, m_stride_y);
    if (m_print_perf) {
        m_renderer->print_last_frame_timings();
    }

    m_samples_accumulated += 1;

    timer.reset();

// This striding is just for speeding up
// We're basically drawing really big pixels here
#pragma omp parallel for collapse(2) schedule(dynamic, 1024)
    for (auto x = 0; x < width; x += m_stride_x) {
        for (auto y = 0; y < height; y += m_stride_y) {
            glm::vec4 color = luminance[y * width + x] / static_cast<float>(m_samples_accumulated);
            for (auto u = 0; u < m_stride_x; u++) {
                for (auto v = 0; v < m_stride_y; v++) {
                    m_pixels[(y + v) * width + (x + u)] = trac0r::pack_color_argb(color);
                }
            }
        }
    }

    if (m_print_perf)
        fmt::print("    {:<15} {:>10.3f} ms\n", "Pixel transfer", timer.elapsed());

    // std::vector<uint32_t> m_pixels_filtered;
    // m_pixels_filtered.resize(m_screen_width * m_screen_height, 0);
    // trac0r::box_filter(m_pixels, width, height, m_pixels_filtered);
    // m_pixels = m_pixels_filtered;
    //
    // if (m_print_perf)
    //     fmt::print("    {:<15} {:>10.3f} ms\n", "Image filtering", timer.elapsed());

    SDL_RenderClear(m_render);
    SDL_UpdateTexture(m_render_tex, 0, m_pixels.data(), width * sizeof(uint32_t));
    SDL_RenderCopy(m_render, m_render_tex, 0, 0);

    if (m_debug) {
        // Lots of debug info
        glm::vec2 mouse_rel_pos =
            Camera::screenspace_to_camspace(m_camera, mouse_pos.x, mouse_pos.y);
        glm::vec3 mouse_canvas_pos = Camera::camspace_to_worldspace(m_camera, mouse_rel_pos);

        auto fps_debug_info = "FPS: " + std::to_string(int(fps));
        auto scene_changing_info = "Samples : " + std::to_string(m_samples_accumulated);
        scene_changing_info += " Scene Changing: " + std::to_string(m_scene_changed);
        auto cam_look_debug_info = "Cam Look Mode: " + std::to_string(m_look_mode);
        auto cam_pos_debug_info = "Cam Pos: " + glm::to_string(Camera::pos(m_camera));
        auto cam_dir_debug_info = "Cam Dir: " + glm::to_string(Camera::dir(m_camera));
        auto cam_up_debug_info = "Cam Up: " + glm::to_string(Camera::up(m_camera));
        auto cam_fov_debug_info =
            "Cam FOV (H/V): " +
            std::to_string(int(glm::degrees(Camera::horizontal_fov(m_camera)))) + "/";
        cam_fov_debug_info += std::to_string(int(glm::degrees(Camera::vertical_fov(m_camera))));
        auto cam_canvas_center_pos_info =
            "Cam Canvas Center: " + glm::to_string(Camera::canvas_center_pos(m_camera));
        auto mouse_pos_screen_info = "Mouse Pos Screen Space: " + glm::to_string(mouse_pos);
        auto mouse_pos_relative_info = "Mouse Pos Cam Space: " + glm::to_string(mouse_rel_pos);
        auto mouse_pos_canvas_info =
            "Mouse Pos Canvas World Space: " + glm::to_string(mouse_canvas_pos);

        auto fps_debug_tex =
            trac0r::make_text(m_render, m_font, fps_debug_info, {200, 100, 100, 200});
        auto scene_changing_tex =
            trac0r::make_text(m_render, m_font, scene_changing_info, {200, 100, 100, 200});
        auto cam_look_debug_tex =
            trac0r::make_text(m_render, m_font, cam_look_debug_info, {200, 100, 100, 200});
        auto cam_pos_debug_tex =
            trac0r::make_text(m_render, m_font, cam_pos_debug_info, {200, 100, 100, 200});
        auto cam_dir_debug_tex =
            trac0r::make_text(m_render, m_font, cam_dir_debug_info, {200, 100, 100, 200});
        auto cam_up_debug_tex =
            trac0r::make_text(m_render, m_font, cam_up_debug_info, {200, 100, 100, 200});
        auto cam_fov_debug_tex =
            trac0r::make_text(m_render, m_font, cam_fov_debug_info, {200, 100, 100, 200});
        auto cam_canvas_center_pos_tex =
            trac0r::make_text(m_render, m_font, cam_canvas_center_pos_info, {200, 100, 100, 200});
        auto mouse_pos_screen_tex =
            trac0r::make_text(m_render, m_font, mouse_pos_screen_info, {200, 100, 100, 200});
        auto mouse_pos_relative_tex =
            trac0r::make_text(m_render, m_font, mouse_pos_relative_info, {200, 100, 100, 200});
        auto mouse_pos_canvas_tex =
            trac0r::make_text(m_render, m_font, mouse_pos_canvas_info, {200, 100, 100, 200});

        trac0r::render_text(m_render, fps_debug_tex, 10, 10);
        trac0r::render_text(m_render, scene_changing_tex, 10, 25);
        trac0r::render_text(m_render, cam_look_debug_tex, 10, 40);
        trac0r::render_text(m_render, cam_pos_debug_tex, 10, 55);
        trac0r::render_text(m_render, cam_dir_debug_tex, 10, 70);
        trac0r::render_text(m_render, cam_up_debug_tex, 10, 85);
        trac0r::render_text(m_render, cam_fov_debug_tex, 10, 100);
        trac0r::render_text(m_render, cam_canvas_center_pos_tex, 10, 115);
        trac0r::render_text(m_render, mouse_pos_screen_tex, 10, 130);
        trac0r::render_text(m_render, mouse_pos_relative_tex, 10, 145);
        trac0r::render_text(m_render, mouse_pos_canvas_tex, 10, 160);

        // Let's draw some debug to the display (such as AABBs)
        if (m_debug) {
            auto &accel_struct = Scene::accel_struct(m_scene);
            for (auto &shape : FlatStructure::shapes(accel_struct)) {
                auto &aabb = Shape::aabb(shape);
                const auto &verts = AABB::vertices(aabb);
                std::array<glm::i8vec2, 12> pairs;
                pairs[0] = {0, 1};
                pairs[1] = {1, 3};
                pairs[2] = {2, 3};
                pairs[3] = {0, 2};
                pairs[4] = {4, 5};
                pairs[5] = {5, 7};
                pairs[6] = {6, 7};
                pairs[7] = {4, 6};
                pairs[8] = {0, 4};
                pairs[9] = {1, 5};
                pairs[10] = {2, 6};
                pairs[11] = {3, 7};
                for (auto pair : pairs) {
                    auto ws1 = Camera::worldpoint_to_worldspace(m_camera, verts[pair[0]]);
                    auto ss1 = glm::i32vec2(0);
                    if (ws1 != glm::vec3(0)) {
                        auto cs1 = Camera::worldspace_to_camspace(m_camera, ws1);
                        ss1 = Camera::camspace_to_screenspace(m_camera, cs1);
                    }
                    auto ws2 = Camera::worldpoint_to_worldspace(m_camera, verts[pair[1]]);
                    auto ss2 = glm::i32vec2(0);
                    if (ws2 != glm::vec3(0)) {
                        auto cs2 = Camera::worldspace_to_camspace(m_camera, ws2);
                        ss2 = Camera::camspace_to_screenspace(m_camera, cs2);
                    }
                    if (ss1 != glm::i32vec2(0) && ss2 != glm::i32vec2(0)) {
                        aalineRGBA(m_render, ss1.x, ss1.y, ss2.x, ss2.y, 255, 255, 0, 200);
                    }
                }
            }
        }

        SDL_DestroyTexture(fps_debug_tex);
        SDL_DestroyTexture(scene_changing_tex);
        SDL_DestroyTexture(cam_look_debug_tex);
        SDL_DestroyTexture(cam_pos_debug_tex);
        SDL_DestroyTexture(cam_dir_debug_tex);
        SDL_DestroyTexture(cam_up_debug_tex);
        SDL_DestroyTexture(cam_fov_debug_tex);
        SDL_DestroyTexture(cam_canvas_center_pos_tex);
        SDL_DestroyTexture(mouse_pos_screen_tex);
        SDL_DestroyTexture(mouse_pos_relative_tex);
        SDL_DestroyTexture(mouse_pos_canvas_tex);
    }

    SDL_RenderPresent(m_render);

    if (m_print_perf) {
        fmt::print("    {:<15} {:>10.3f} ms\n", "Rendering", timer.elapsed());
        fmt::print("    {:<15} {:>10.3f} ms\n", "=> Budget", 1000.f / 60.f - total.peek());
        fmt::print("    {:<15} {:>10.3f} ms\n\n", "=> Total", total.peek());
    }

    m_frame_total += total.elapsed();
    if (m_benchmark_mode < 0 && m_max_frames != 0 && m_frame > m_max_frames) {
        auto filename = std::string("trac0r-") + std::to_string(m_max_frames) + std::string(".bmp");
        SDL_Surface *sshot = SDL_CreateRGBSurface(0, m_screen_width, m_screen_height, 32,
                                                  0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000);
        SDL_RenderReadPixels(m_render, NULL, SDL_PIXELFORMAT_ARGB8888, sshot->pixels, sshot->pitch);
        SDL_SaveBMP(sshot, filename.c_str());
        SDL_FreeSurface(sshot);
        shutdown();
    } else if (m_benchmark_mode > 0 && m_max_frames != 0 && m_frame > m_max_frames) {
        fmt::print("Benchmark results:\n");
        fmt::print("    {:<15} {:>10}\n", "Frames rendered", m_max_frames);
        fmt::print("    {:<15} {:>10.3f} ms\n", "Total runtime", m_frame_total);
        fmt::print("    {:<15} {:>10.3f} ms\n", "Avg. frame", m_frame_total / m_max_frames);
        fmt::print("    {:<15} {:>10.3f} FPS\n", "Avg. FPS",
                   1.f / ((m_frame_total / 1000.f) / m_max_frames));
        shutdown();
    }
}
Esempio n. 12
0
static void CreateUpscaledTexture(boolean force)
{
    int w, h;
    int h_upscale, w_upscale;
    static int h_upscale_old, w_upscale_old;

    // Get the size of the renderer output. The units this gives us will be
    // real world pixels, which are not necessarily equivalent to the screen's
    // window size (because of highdpi).
    if (SDL_GetRendererOutputSize(renderer, &w, &h) != 0)
    {
        I_Error("Failed to get renderer output size: %s", SDL_GetError());
    }

    // When the screen or window dimensions do not match the aspect ratio
    // of the texture, the rendered area is scaled down to fit. Calculate
    // the actual dimensions of the rendered area.

    if (w * actualheight < h * SCREENWIDTH)
    {
        // Tall window.

        h = w * actualheight / SCREENWIDTH;
    }
    else
    {
        // Wide window.

        w = h * SCREENWIDTH / actualheight;
    }

    // Pick texture size the next integer multiple of the screen dimensions.
    // If one screen dimension matches an integer multiple of the original
    // resolution, there is no need to overscale in this direction.

    w_upscale = (w + SCREENWIDTH - 1) / SCREENWIDTH;
    h_upscale = (h + SCREENHEIGHT - 1) / SCREENHEIGHT;

    // Minimum texture dimensions of 320x200.

    if (w_upscale < 1)
    {
        w_upscale = 1;
    }
    if (h_upscale < 1)
    {
        h_upscale = 1;
    }

    LimitTextureSize(&w_upscale, &h_upscale);

    // Create a new texture only if the upscale factors have actually changed.

    if (h_upscale == h_upscale_old && w_upscale == w_upscale_old && !force)
    {
        return;
    }

    h_upscale_old = h_upscale;
    w_upscale_old = w_upscale;

    if (texture_upscaled)
    {
        SDL_DestroyTexture(texture_upscaled);
    }

    // Set the scaling quality for rendering the upscaled texture to "linear",
    // which looks much softer and smoother than "nearest" but does a better
    // job at downscaling from the upscaled texture to screen.

    SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear");

    texture_upscaled = SDL_CreateTexture(renderer,
                                pixel_format,
                                SDL_TEXTUREACCESS_TARGET,
                                w_upscale*SCREENWIDTH,
                                h_upscale*SCREENHEIGHT);
}
Esempio n. 13
0
static void SetVideoMode(void)
{
    int w, h;
    int x, y;
    unsigned int rmask, gmask, bmask, amask;
    int unused_bpp;
    int window_flags = 0, renderer_flags = 0;
    SDL_DisplayMode mode;

    w = window_width;
    h = window_height;

    // In windowed mode, the window can be resized while the game is
    // running.
    window_flags = SDL_WINDOW_RESIZABLE;

    // Set the highdpi flag - this makes a big difference on Macs with
    // retina displays, especially when using small window sizes.
    window_flags |= SDL_WINDOW_ALLOW_HIGHDPI;

    if (fullscreen)
    {
        if (fullscreen_width == 0 && fullscreen_height == 0)
        {
            // This window_flags means "Never change the screen resolution!
            // Instead, draw to the entire screen by scaling the texture
            // appropriately".
            window_flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
        }
        else
        {
            w = fullscreen_width;
            h = fullscreen_height;
            window_flags |= SDL_WINDOW_FULLSCREEN;
        }
    }

    I_GetWindowPosition(&x, &y, w, h);

    // Create window and renderer contexts. We set the window title
    // later anyway and leave the window position "undefined". If
    // "window_flags" contains the fullscreen flag (see above), then
    // w and h are ignored.

    if (screen == NULL)
    {
        screen = SDL_CreateWindow(NULL, x, y, w, h, window_flags);

        if (screen == NULL)
        {
            I_Error("Error creating window for video startup: %s",
            SDL_GetError());
        }

        pixel_format = SDL_GetWindowPixelFormat(screen);

        SDL_SetWindowMinimumSize(screen, SCREENWIDTH, actualheight);

        I_InitWindowTitle();
        I_InitWindowIcon();
    }

    // The SDL_RENDERER_TARGETTEXTURE flag is required to render the
    // intermediate texture into the upscaled texture.
    renderer_flags = SDL_RENDERER_TARGETTEXTURE;
	
    if (SDL_GetCurrentDisplayMode(video_display, &mode) != 0)
    {
        I_Error("Could not get display mode for video display #%d: %s",
        video_display, SDL_GetError());
    }

    // Turn on vsync if we aren't in a -timedemo
    if (!singletics && mode.refresh_rate > 0)
    {
        renderer_flags |= SDL_RENDERER_PRESENTVSYNC;
    }

    if (force_software_renderer)
    {
        renderer_flags |= SDL_RENDERER_SOFTWARE;
        renderer_flags &= ~SDL_RENDERER_PRESENTVSYNC;
    }

    if (renderer != NULL)
    {
        SDL_DestroyRenderer(renderer);
    }

    renderer = SDL_CreateRenderer(screen, -1, renderer_flags);

    if (renderer == NULL)
    {
        I_Error("Error creating renderer for screen window: %s",
                SDL_GetError());
    }

    // Important: Set the "logical size" of the rendering context. At the same
    // time this also defines the aspect ratio that is preserved while scaling
    // and stretching the texture into the window.

    if (aspect_ratio_correct || integer_scaling)
    {
        SDL_RenderSetLogicalSize(renderer,
                                 SCREENWIDTH,
                                 actualheight);
    }

    // Force integer scales for resolution-independent rendering.

#if SDL_VERSION_ATLEAST(2, 0, 5)
    SDL_RenderSetIntegerScale(renderer, integer_scaling);
#endif

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

    SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
    SDL_RenderClear(renderer);
    SDL_RenderPresent(renderer);

    // Create the 8-bit paletted and the 32-bit RGBA screenbuffer surfaces.

    if (screenbuffer == NULL)
    {
        screenbuffer = SDL_CreateRGBSurface(0,
                                            SCREENWIDTH, SCREENHEIGHT, 8,
                                            0, 0, 0, 0);
        SDL_FillRect(screenbuffer, NULL, 0);
    }

    // Format of argbbuffer must match the screen pixel format because we
    // import the surface data into the texture.
    if (argbbuffer == NULL)
    {
        SDL_PixelFormatEnumToMasks(pixel_format, &unused_bpp,
                                   &rmask, &gmask, &bmask, &amask);
        argbbuffer = SDL_CreateRGBSurface(0,
                                          SCREENWIDTH, SCREENHEIGHT, 32,
                                          rmask, gmask, bmask, amask);
        SDL_FillRect(argbbuffer, NULL, 0);
    }

    if (texture != NULL)
    {
        SDL_DestroyTexture(texture);
    }

    // Set the scaling quality for rendering the intermediate texture into
    // the upscaled texture to "nearest", which is gritty and pixelated and
    // resembles software scaling pretty well.

    SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "nearest");

    // Create the intermediate texture that the RGBA surface gets loaded into.
    // The SDL_TEXTUREACCESS_STREAMING flag means that this texture's content
    // is going to change frequently.

    texture = SDL_CreateTexture(renderer,
                                pixel_format,
                                SDL_TEXTUREACCESS_STREAMING,
                                SCREENWIDTH, SCREENHEIGHT);

    // Initially create the upscaled texture for rendering to screen

    CreateUpscaledTexture(true);
}
Esempio n. 14
0
void FPS::increment(SDL_Renderer * renderer) {
    unsigned int time_now = SDL_GetTicks();
    unsigned int delta_time = time_now - fps_start_time;
        
    // increment the number of frames rendered
    current_frame_count += 1;

    // if it's time to update the fps count then 
    if (delta_time > FRAME_RATE_PERIOD) {

        // change the current_fps 
        current_fps = current_frame_count / FRAME_RATE_PERIOD;

        // FIXME: remove this!
        //std::cout << "fps: " << get_fps() << std::endl;


        // FIXME WE NEED 
        //   method to blat dynamic floats (digits to texture then render).
        //   method to blat static strings (to texture then render)
        // 

        // FIXME: this is slow.. 
        // render on the GPU by making textures for each digit and displaying them 
        fps_text_surface = TTF_RenderText_Solid(
            fps_font, 
            // This doesn't work because of a bug in the current version of mingw/gcc!!
            // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52015
            // std::to_string(current_frame_count).c_str(), 
            "FIX THE FPS STUFF!!!", 
            fps_font_color);

        if (!fps_text_surface) {
            // handle error here, perhaps print TTF_GetError at least
            log_ttf_error("Problem displaying fps text!");
        } 
        else {

            fps_text_texture = SDL_CreateTextureFromSurface(renderer, fps_text_surface);
            if (!fps_text_texture) {
                log_sdl_error("SDL_CreateTextureFromSurface: ");
                //return 4;
            }        
            else {
                std::cout << "Draw FPS XXXX" << std::endl;
            }
                
            // draw the title
            SDL_Rect src = { 0, 0, fps_text_surface->w, fps_text_surface->h };
            SDL_Rect dest = { 30, 30, fps_text_surface->w, fps_text_surface->h};
            SDL_RenderCopy(renderer, fps_text_texture, &src, &dest);

            // perhaps we can reuse it, but I assume not for simplicity.
            SDL_FreeSurface(fps_text_surface);
            SDL_DestroyTexture(fps_text_texture);
        }
        


        // and reset the fps counters            
        current_frame_count = 0;
        fps_start_time = time_now;
    }
}
Esempio n. 15
0
void run(){
	
	SDL_Window* window;
	SDL_Renderer* renderer;
	SDL_Surface* temp;
	SDL_Texture* tbullet;
	SDL_Event e;
	int i, quit = 0;
	Bullet* bulletarray[MAXBULLETS];
	unsigned int lastshooting = 0;
	
	/* Initialise generic */
	SDL_Init(SDL_INIT_EVERYTHING);
	window = SDL_CreateWindow("Shoot", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN);
	renderer = SDL_CreateRenderer(window, -1, 0);
	SDL_SetRenderDrawColor(renderer, 90, 90, 90, 0);
	
	temp = SDL_LoadBMP("bullet.bmp");
	tbullet = SDL_CreateTextureFromSurface(renderer, temp);
	SDL_FreeSurface(temp);
	temp = NULL;
	
	/* Initialise bulletarray */
	for(i = 0; i < MAXBULLETS ; i++){
		bulletarray[i] = NULL;
	}
	
	/* Event loop */
	do{
		SDL_PollEvent(&e);
		if(e.type == SDL_QUIT){
			quit = 1;
		}
		
		/* Fire bullet from centre*/
		if(e.type == SDL_MOUSEBUTTONDOWN){
			if(e.button.button == SDL_BUTTON_LEFT && (SDL_GetTicks() - lastshooting) > TIMEBETWEENSHOOT){
				for(i = 0; i <MAXBULLETS; i++){
					if(bulletarray[i] == NULL){
						bulletarray[i] = createbullet((WIDTH-BULLETSIZE)/2, (HEIGHT-BULLETSIZE)/2);
						i = MAXBULLETS;
					}
				}
				lastshooting = SDL_GetTicks();
			}
		}
		
		deletebulletatboundary(bulletarray);		
		bulletmovement(bulletarray);
		
		/* Update Screen */
		SDL_RenderClear(renderer);
		renderbullets(renderer, tbullet, bulletarray);
		SDL_RenderPresent(renderer);
		SDL_Delay(20);
		
	}while(quit == 0);
	
	/* Memory Cleanup */
	SDL_DestroyTexture(tbullet);
	SDL_DestroyRenderer(renderer);
	SDL_DestroyWindow(window);
	tbullet = NULL;
	renderer = NULL;
	window = NULL;
	SDL_Quit();
}
Esempio n. 16
0
int main(int argc, char *argv[])
{
    SDL_Window* Main_Window;
    SDL_Renderer* Main_Renderer;
    SDL_Surface* Loading_Surf;
    SDL_Texture* Background_Tx;
    SDL_Texture* BlueShapes;

    /* Rectangles for drawing which will specify source (inside the texture)
       and target (on the screen) for rendering our textures. */
    SDL_Rect SrcR;
    SDL_Rect DestR;

    SrcR.x = 0;
    SrcR.y = 0;
    SrcR.w = SHAPE_SIZE;
    SrcR.h = SHAPE_SIZE;

    DestR.x = 640 / 2 - SHAPE_SIZE / 2;
    DestR.y = 580 / 2 - SHAPE_SIZE / 2;
    DestR.w = SHAPE_SIZE;
    DestR.h = SHAPE_SIZE;


    /* Before we can render anything, we need a window and a renderer */
    Main_Window = SDL_CreateWindow("SDL_RenderCopy Example",
            SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 580, 0);
    Main_Renderer = SDL_CreateRenderer(Main_Window, -1, SDL_RENDERER_ACCELERATED);

    /* The loading of the background texture. Since SDL_LoadBMP returns
       a surface, we convert it to a texture afterwards for fast accelerated
       blitting. */
    Loading_Surf = SDL_LoadBMP("1.bmp");
    Background_Tx = SDL_CreateTextureFromSurface(Main_Renderer, Loading_Surf);
    SDL_FreeSurface(Loading_Surf);  // we got the texture now -> free surface

    /* Load an additional texture */
    Loading_Surf = SDL_LoadBMP("2.bmp");
    BlueShapes = SDL_CreateTextureFromSurface(Main_Renderer, Loading_Surf);
    SDL_FreeSurface(Loading_Surf);

    /* now onto the fun part.
       This will render a rotating selection of the blue shapes
       in the middle of the screen */
    int i;
    int n;
    for(i=0;i<2;i++)
    {
        for(n=0;n<4;n++)
        {
            SrcR.x = SHAPE_SIZE * (n % 2);
            if(n > 1)
            {
                SrcR.y = SHAPE_SIZE;
            }
            else
            {
                SrcR.y = 0;
            }

            /* render background, whereas NULL for source and destination
               rectangles just means "use the default" */
            SDL_RenderCopy(Main_Renderer, Background_Tx, NULL, NULL);

            /* render the current animation step of our shape */
            SDL_RenderCopy(Main_Renderer, BlueShapes, &SrcR, &DestR);  
            SDL_RenderPresent(Main_Renderer);
            SDL_Delay(500);
        }
    }


    /* The renderer works pretty much like a big canvas:
       when you RenderCopy you are adding paint, each time adding it
       on top.
       You can change how it blends with the stuff that
       the new data goes over.
       When your 'picture' is complete, you show it
       by using SDL_RenderPresent. */

    /* SDL 1.2 hint: If you're stuck on the whole renderer idea coming
       from 1.2 surfaces and blitting, think of the renderer as your
       main surface, and SDL_RenderCopy as the blit function to that main
       surface, with SDL_RenderPresent as the old SDL_Flip function.*/

    SDL_DestroyTexture(BlueShapes);
    SDL_DestroyTexture(Background_Tx);
    SDL_DestroyRenderer(Main_Renderer);
    SDL_DestroyWindow(Main_Window);
    SDL_Quit();


    return 0;
}
/****************************************************************************
 * @function : This is the display thread function. It displays video locally
 *             using simple DirectMedia Layer(SDL2).
 *
 * @arg  : void
 * @return     : void
 * *************************************************************************/
void *displayThread(void)
{
	SDL_Window *win = NULL;
	SDL_Renderer *renderer = NULL;
	SDL_Texture *texture = NULL;
	char resolution[20] = {0};
	int kill = 0;
	SERVER_CONFIG *serverConfig = GetServerConfig();

	SDL_Init(SDL_INIT_VIDEO);
	snprintf(resolution, 20, "Capture : %dx%d", serverConfig->capture.width, 
			                                   serverConfig->capture.height);
	win = SDL_CreateWindow(resolution, 
			SDL_WINDOWPOS_CENTERED, 
			SDL_WINDOWPOS_CENTERED, 
			serverConfig->capture.width, 
			serverConfig->capture.height, 
			SDL_WINDOW_RESIZABLE);

	renderer = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED);
	texture = SDL_CreateTexture(renderer,
			SDL_PIXELFORMAT_YUY2,
			SDL_TEXTUREACCESS_STREAMING,
			serverConfig->capture.width,
			serverConfig->capture.height);

	while (!KillDisplayThread) {
		SDL_Event e;
		if (SDL_PollEvent(&e)) {
			if (e.type == SDL_QUIT) {
				break;
			} else if(e.key.type == SDL_KEYUP) {
				switch(e.key.keysym.sym) {
					case SDLK_RIGHT:
						if(e.key.state == SDL_RELEASED) {
							serverConfig->algo_type++; 
							if(serverConfig->algo_type > ALGO_MULTI_3) {
								serverConfig->algo_type = ALGO_NONE;
							}
						}
						break;
					case SDLK_LEFT:
						if(e.key.state == SDL_RELEASED) {
							serverConfig->algo_type--; 
							if(serverConfig->algo_type < ALGO_NONE) {
								serverConfig->algo_type = ALGO_MULTI_3;
							}
						}
						break;
					case SDLK_c:
						if(serverConfig->enable_imagesave_thread) {
							serverConfig->image.type = 0;
							serverConfig->image.recordenable = TRUE;
						}
						break;
					case SDLK_v:
						if(serverConfig->enable_videosave_thread) {
							serverConfig->video.recordenable ^= TRUE;
						}
						break;
					case SDLK_ESCAPE:
						kill = TRUE;
						break;
					default:
						break;
				}
				if(kill) break;
			}
		}
		if(serverConfig->enable_osd_thread) {
			SDL_UpdateTexture(texture,0,
					serverConfig->disp.display_frame,
					serverConfig->capture.width*BPP);
		} else {
			if(serverConfig->algo_type) {
				SDL_UpdateTexture(texture,0,
						serverConfig->disp.sdl_frame,
						serverConfig->capture.width*BPP);
			} else {
				SDL_UpdateTexture(texture,0,
						serverConfig->disp.display_frame,
						serverConfig->capture.width*BPP);
			}
		}
		usleep(30000);
		SDL_RenderClear(renderer);
		SDL_RenderCopy(renderer, texture, NULL, NULL);
		SDL_RenderPresent(renderer);
	}

	SDL_DestroyTexture(texture);
	SDL_DestroyRenderer(renderer);
	SDL_DestroyWindow(win);

	SDL_Quit();
	exit(0);
	return 0;
}
Esempio n. 18
0
void TextureManager::clearFromTextureMap(std::string id)
{
	m_textureMap.erase(id);
	SDL_DestroyTexture( m_textureMap [id]);
}
Esempio n. 19
0
void run(){
	
	SDL_Window* window;
	SDL_Renderer* renderer;
	SDL_Surface* mover;
	SDL_Texture *tmover, *tbullet;
	SDL_Rect rmover;
	SDL_Event e;
	int quit = 0, mx, my, cx, cy;
	double rotate = 0;
	Bullet **bulletarray;
	const Uint8* currentKeyStates;
	
	/* Creating Window */
	SDL_Init(SDL_INIT_EVERYTHING);
	window = SDL_CreateWindow("Player", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
	renderer = SDL_CreateRenderer(window, -1, 0);
	SDL_SetRenderDrawColor(renderer, 90, 90, 90, 0);
	bulletarray = initialiseshoot(renderer, &tbullet);
	
	
	/* Load Player */
	mover = SDL_LoadBMP("mover2.bmp");
	tmover = SDL_CreateTextureFromSurface(renderer, mover);
	SDL_FreeSurface(mover);
	mover = NULL;
	
	rmover.x = 320;
	rmover.y = 240;
	rmover.h = PLAYER_HEIGHT;
	rmover.w = PLAYER_WIDTH;

	/*Event loop*/
	do{
		SDL_PollEvent(&e);
		if(e.type == SDL_QUIT){
			quit = 1;
		}
		
		/* Moving Direction */
		currentKeyStates = SDL_GetKeyboardState(NULL);
		if( currentKeyStates[ SDL_SCANCODE_W ] )
		{
			rmover.y -= 2;
		}
		if( currentKeyStates[ SDL_SCANCODE_S ] )
		{
			rmover.y += 2;
		}
		if( currentKeyStates[ SDL_SCANCODE_A ] )
		{
			rmover.x -= 2;
		}
		if( currentKeyStates[ SDL_SCANCODE_D ] )
		{
			rmover.x += 2;
		}
		
		/* Rotation Angle */
		SDL_GetMouseState(&mx, &my);
		cy = rmover.y + PLAYER_HEIGHT/2;
		cx = rmover.x + PLAYER_WIDTH/2;
		rotate = (atan2(my-cy, mx-cx))*57.295;
		
		/* fire bullet */
		if(e.type == SDL_MOUSEBUTTONDOWN){
			if(e.button.button == SDL_BUTTON_LEFT){
				firebullet(bulletarray, cx, cy);
			}
		}
		
		deletebulletatboundary(bulletarray);
		bulletmovement(bulletarray);
		
		/* Update Screen */
		SDL_RenderClear(renderer);
		renderbullets(renderer, tbullet, bulletarray);
		SDL_RenderCopyEx(renderer, tmover, NULL, &rmover, rotate, NULL, SDL_FLIP_NONE);
		SDL_RenderPresent(renderer);
		
		SDL_Delay(20);
		
	}while(quit == 0);
	
	/* Memory Cleanup */
	SDL_DestroyTexture(tmover);
	SDL_DestroyRenderer(renderer);
	SDL_DestroyWindow(window);
	quitshoot(tbullet, bulletarray);
	tmover = NULL;
	renderer = NULL;
	window = NULL;
	SDL_Quit();
}
Esempio n. 20
0
void Video::WriteNextFrame()
{
    int frameFinished = 0;
    AVPacket packet;

    if (texturesRecreatedCount != gTexturesRecreatedCount)
    {
        texturesRecreatedCount = gTexturesRecreatedCount;

        SDL_DestroyTexture(pTexture);
        pTexture =
            SDL_CreateTexture(
                gpRenderer,
                IsYUVFormat(pCodecContext->pix_fmt) ? SDL_PIXELFORMAT_YV12 : SDL_PIXELFORMAT_ARGB8888,
                SDL_TEXTUREACCESS_STREAMING,
                width,
                height);
        SDL_SetTextureBlendMode(pTexture, SDL_BLENDMODE_BLEND);

        unsigned char *pPixels = NULL;
        int pitch = 0;

        SDL_LockTexture(pTexture, NULL, reinterpret_cast<void **>(&pPixels), &pitch);
        memcpy(pPixels, pCachedTexturePixels, pitch * height);
        SDL_UnlockTexture(pTexture);
    }

    while (!frameFinished)
    {
        if (av_read_frame(pFormatContext, &packet) != 0)
        {
            break;
        }

        if (packet.stream_index == videoStream && avcodec_decode_video2(pCodecContext, pFrame, &frameFinished, &packet) >= 0)
        {
            if (frameFinished)
            {
                AVPicture picture;
                unsigned char *pPixels = NULL;
                int pitch = 0;

                SDL_LockTexture(pTexture, NULL, reinterpret_cast<void **>(&pPixels), &pitch);

                if (IsYUVFormat(pCodecContext->pix_fmt))
                {
                    picture.data[0] = pFrame->data[0];
                    picture.data[1] = pFrame->data[1];
                    picture.data[2] = pFrame->data[2];
                    picture.linesize[0] = pFrame->linesize[0];
                    picture.linesize[1] = pFrame->linesize[1];
                    picture.linesize[2] = pFrame->linesize[2];
                }
                else
                {
                    picture.data[0] = pPixels;
                    picture.linesize[0] = pitch;
                }

                sws_scale(pImageConvertContext, pFrame->data, pFrame->linesize, 0, pFrame->height, picture.data, picture.linesize);

                if (IsYUVFormat(pCodecContext->pix_fmt))
                {
                    if (pitch == picture.linesize[0])
                    {
                        int size = pitch * pFrame->height;

                        memcpy(pPixels, picture.data[0], size);
                        memcpy(pPixels + size, picture.data[2], size / 4);
                        memcpy(pPixels + size * 5 / 4, picture.data[1], size / 4);
                    }
                    else
                    {
                        unsigned char *y1, *y2, *y3, *i1, *i2, *i3;
                        y1 = pPixels;
                        y3 = pPixels + pitch * pFrame->height;
                        y2 = pPixels + pitch * pFrame->height * 5 / 4;

                        i1 = picture.data[0];
                        i2 = picture.data[1];
                        i3 = picture.data[2];

                        for (int i = 0; i < pFrame->height / 2; i++)
                        {
                            memcpy(y1, i1, pitch);
                            i1 += picture.linesize[0];
                            y1 += pitch;
                            memcpy(y1, i1, pitch);

                            memcpy(y2, i2, pitch / 2);
                            memcpy(y3, i3, pitch / 2);

                            y1 += pitch;
                            y2 += pitch / 2;
                            y3 += pitch / 2;
                            i1 += picture.linesize[0];
                            i2 += picture.linesize[1];
                            i3 += picture.linesize[2];
                        }
                    }
                }

                memcpy(pCachedTexturePixels, pPixels, pitch * height);
                SDL_UnlockTexture(pTexture);
            }
        }

        av_free_packet(&packet);
    }
}
Esempio n. 21
0
SDL_TMXMap::~SDL_TMXMap()
{
    SDL_DestroyTexture(MapTex);
    for(vector<SDL_Surface*>::iterator it = LayerSurf.begin(); it != LayerSurf.end(); ++it )
        SDL_FreeSurface(*it);
}
Esempio n. 22
0
void Level::quit()
{
  SDL_DestroyTexture(force_texture);
  force_texture = NULL;
}
Esempio n. 23
0
int main()
{
    if(SDL_Init(SDL_INIT_VIDEO))
    {
        fprintf(stderr, "SDL_Init Error: %s\n", SDL_GetError());
        exit(1);
    }

    SDL_Window *win = SDL_CreateWindow("Moving start", 100, 100, SCREEN_HEIGHT, SCREEN_WIDTH, SDL_WINDOW_SHOWN);

    if(!win)
    {
        fprintf(stderr, "SDL_CreateWindow Error: %s\n", SDL_GetError());
        SDL_Quit();
        exit(1);
    }

    if(!IMG_Init(IMG_INIT_PNG))
    {
        fprintf(stderr, "IMG_Init Error: %s\n", IMG_GetError());
        SDL_DestroyWindow(win);
        SDL_Quit();
        exit(1);
    }

    SDL_Renderer *ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);

    if(!ren)
    {
        fprintf(stderr, "SDL_CreateRenderer Error: %s\n", SDL_GetError());
        IMG_Quit();
        SDL_DestroyWindow(win);
        SDL_Quit();
        exit(1);
    }

    SDL_Surface *png = IMG_Load("../../MediaResources/star.png");

    if(!png)
    {
        fprintf(stderr, "IMG_Load Error: %s\n", IMG_GetError());
        SDL_DestroyRenderer(ren);
        IMG_Quit();
        SDL_DestroyWindow(win);
        SDL_Quit();
        exit(1);
    }

    SDL_Texture *tex = SDL_CreateTextureFromSurface(ren, png);
    SDL_FreeSurface(png);

    if(!tex)
    {
        fprintf(stderr, "SDL_CreateTextureFromSurface Error: %s\n", SDL_GetError());
        SDL_DestroyRenderer(ren);
        IMG_Quit();
        SDL_DestroyWindow(win);
        SDL_Quit();
        exit(1);
    }

    int x0 = SCREEN_WIDTH / 2 - 32, y0 = SCREEN_HEIGHT / 2 - 32;
    SDL_Rect dstRect = {0, 0, 64, 64};
    SDL_SetRenderDrawColor(ren, 0xFF, 0xFF, 0x00, 0xFF);
    SDL_RenderClear(ren);

    for(double i = 0; i < 360; i += 30)
    {
        dstRect.x = x0 + sin(i * 3.14 / 180) * x0;
        dstRect.y = y0 + cos(i * 3.14 / 180) * y0;
        SDL_RenderCopy(ren, tex, NULL, &dstRect);
    }

    SDL_RenderPresent(ren);
    SDL_Delay(5000);

    SDL_DestroyTexture(tex);
    SDL_DestroyRenderer(ren);
    IMG_Quit();
    SDL_DestroyWindow(win);
    SDL_Quit();

    return 0;
}
Esempio n. 24
0
Sprite::~Sprite()
{
	SDL_DestroyTexture(image);
}