Example #1
0
 inline void write(const T & n) {
     static_assert(std::is_pod<T>::value, "Type must be POD.");
     const auto result = write(reinterpret_cast<const char *>(&n), sizeof(T));
     SDL_assert(1 == result);
 }
Example #2
0
void SpeedLines::Update(double dt)
{
	auto dc = m_owner.component<DynamicsComponent>();
	SDL_assert(dc);
	vector3f vel(dc->vel);
	const float absVel = vel.Length();

	//alter line color to give overall idea of speed
	//slow lines down at higher speeds
	float mult;
	if (absVel > 100000.f) {
		m_color = VERYFAST_COLOR;
		mult = 0.001f;
	} else if (absVel > 10000.f) {
		m_color = VERYFAST_COLOR;
		mult = 0.01f;
	} else if (absVel > 5000.f) {
		m_color = FAST_COLOR;
		mult = 0.1f;
	} else {
		m_color = DEFAULT_COLOR;
		mult = 1.f;
	}

	//rate of change (incl. time acceleration)
	float d = absVel * dt * mult;

	//don't draw when almost stopped
	if (d < 0.0001f) {
		m_visible = false;
		return;
	}
	m_visible = true;

	m_lineLength = Clamp(absVel * 0.1f, 2.f, 100.f);
	m_dir = vel.Normalized();

	vel = vel * dt * mult;

	//too fast to draw - cap
	if (d > MAX_VEL)
		vel = m_dir * MAX_VEL;

	for (Uint16 i = 0; i < m_points.size(); i++) {

		vector3f& pt = m_points[i];

		pt -= vel;

		//wrap around
		if (pt.x > BOUNDS)
			pt.x -= BOUNDS * 2.f;
		if (pt.x < -BOUNDS)
			pt.x += BOUNDS * 2.f;
		if (pt.y > BOUNDS)
			pt.y -= BOUNDS * 2.f;
		if (pt.y < -BOUNDS)
			pt.y += BOUNDS * 2.f;
		if (pt.z > BOUNDS)
			pt.z -= BOUNDS * 2.f;
		if (pt.z < -BOUNDS)
			pt.z += BOUNDS * 2.f;
	}
}
Example #3
0
SdlFile::SdlFile()
{
    p = new SdlFile_private;
    SDL_assert(p);
}
Example #4
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;
}
Example #5
0
int main(int argc, char** argv) 
#endif
{
#ifdef _WIN32
	LPSTR *argv = __argv;
	int argc = __argc;
	(void) argv;
	(void) argc;
#endif 
	SDL_Window *screen;
	SDL_Renderer *renderer;
	SDL_Shader *shader;

	if ( SDL_Init(SDL_INIT_VIDEO) < 0 ){
		fprintf(stderr, "Error: %s \n", SDL_GetError());
		return 1;
	}

    SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 );
    SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 0 );
    SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
    SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 24 );

	SDL_SetHint( SDL_HINT_RENDER_DRIVER, getenv("RENDER_DRIVER") ); 

	int width = 500;
	int height = 700;
	screen = SDL_CreateWindow("Caption",
			SDL_WINDOWPOS_CENTERED,
			SDL_WINDOWPOS_CENTERED,
			width, height,
			SDL_WINDOW_RESIZABLE);
			// SDL_WINDOW_FULLSCREEN_DESKTOP );
	if ( screen == NULL ) {
		fprintf(stderr, "Error: %s \n", SDL_GetError());
		return 2;
	}
	renderer = SDL_CreateRenderer( screen, -1, SDL_RENDERER_ACCELERATED|SDL_RENDERER_TARGETTEXTURE );
	//renderer = SDL_CreateRenderer( screen, -1, SDL_RENDERER_SOFTWARE|SDL_RENDERER_TARGETTEXTURE );
	if ( renderer == NULL ) {
		fprintf(stderr, "Error: %s \n", SDL_GetError());
		return 3;
	}

	SDL_RenderSetLogicalSize(renderer, width, height);

	SDL_SetWindowTitle( screen, renderer->info.name );

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


	printf("renderer name: %s\n" , renderer->info.name );
	printf("SDL_PIXELFORMAT_UNKNOWN=    %d\n",SDL_PIXELFORMAT_UNKNOWN);
	printf("SDL_PIXELFORMAT_INDEX1LSB=  %d\n",SDL_PIXELFORMAT_INDEX1LSB);
	printf("SDL_PIXELFORMAT_INDEX1MSB=  %d\n",SDL_PIXELFORMAT_INDEX1MSB);
	printf("SDL_PIXELFORMAT_INDEX4LSB=  %d\n",SDL_PIXELFORMAT_INDEX4LSB);
	printf("SDL_PIXELFORMAT_INDEX4MSB=  %d\n",SDL_PIXELFORMAT_INDEX4MSB);
	printf("SDL_PIXELFORMAT_INDEX8=     %d\n",SDL_PIXELFORMAT_INDEX8);
	printf("SDL_PIXELFORMAT_RGB332=     %d\n",SDL_PIXELFORMAT_RGB332);
	printf("SDL_PIXELFORMAT_RGB444=     %d\n",SDL_PIXELFORMAT_RGB444);
	printf("SDL_PIXELFORMAT_RGB555=     %d\n",SDL_PIXELFORMAT_RGB555);
	printf("SDL_PIXELFORMAT_BGR555=     %d\n",SDL_PIXELFORMAT_BGR555);
	printf("SDL_PIXELFORMAT_ARGB4444=   %d\n",SDL_PIXELFORMAT_ARGB4444);
	printf("SDL_PIXELFORMAT_RGBA4444=   %d\n",SDL_PIXELFORMAT_RGBA4444);
	printf("SDL_PIXELFORMAT_ABGR4444=   %d\n",SDL_PIXELFORMAT_ABGR4444);
	printf("SDL_PIXELFORMAT_BGRA4444=   %d\n",SDL_PIXELFORMAT_BGRA4444);
	printf("SDL_PIXELFORMAT_ARGB1555=   %d\n",SDL_PIXELFORMAT_ARGB1555);
	printf("SDL_PIXELFORMAT_RGBA5551=   %d\n",SDL_PIXELFORMAT_RGBA5551);
	printf("SDL_PIXELFORMAT_ABGR1555=   %d\n",SDL_PIXELFORMAT_ABGR1555);
	printf("SDL_PIXELFORMAT_BGRA5551=   %d\n",SDL_PIXELFORMAT_BGRA5551);
	printf("SDL_PIXELFORMAT_RGB565=     %d\n",SDL_PIXELFORMAT_RGB565);
	printf("SDL_PIXELFORMAT_BGR565=     %d\n",SDL_PIXELFORMAT_BGR565);
	printf("SDL_PIXELFORMAT_RGB24=      %d\n",SDL_PIXELFORMAT_RGB24);
	printf("SDL_PIXELFORMAT_BGR24=      %d\n",SDL_PIXELFORMAT_BGR24);
	printf("SDL_PIXELFORMAT_RGB888=     %d\n",SDL_PIXELFORMAT_RGB888);
	printf("SDL_PIXELFORMAT_RGBX8888=   %d\n",SDL_PIXELFORMAT_RGBX8888);
	printf("SDL_PIXELFORMAT_BGR888=     %d\n",SDL_PIXELFORMAT_BGR888);
	printf("SDL_PIXELFORMAT_BGRX8888=   %d\n",SDL_PIXELFORMAT_BGRX8888);
	printf("SDL_PIXELFORMAT_ARGB8888=   %d\n",SDL_PIXELFORMAT_ARGB8888);
	printf("SDL_PIXELFORMAT_RGBA8888=   %d\n",SDL_PIXELFORMAT_RGBA8888);
	printf("SDL_PIXELFORMAT_ABGR8888=   %d\n",SDL_PIXELFORMAT_ABGR8888);
	printf("SDL_PIXELFORMAT_BGRA8888=   %d\n",SDL_PIXELFORMAT_BGRA8888);
	printf("SDL_PIXELFORMAT_ARGB2101010=%d\n",SDL_PIXELFORMAT_ARGB2101010);

	shader = SDL_createShader( renderer, "../shaders/do_nothing/do_nothing" );
	if ( shader == NULL ){
		fprintf(stderr, "Error: %s \n", SDL_GetError());
		return 4;
	}

	SDL_Surface* srf;
	srf = IMG_Load( "../img.png" );
	if ( !srf ) {
		fprintf(stderr, "Error: %s \n", SDL_GetError());
		return 5;
	}

	int i;
	Uint32 formats[] = {
		/* Indexed formats and YUV are not supported */
		SDL_PIXELFORMAT_RGB332,
		SDL_PIXELFORMAT_RGB444,
		SDL_PIXELFORMAT_RGB555,
		SDL_PIXELFORMAT_BGR555,
		SDL_PIXELFORMAT_ARGB4444,
		SDL_PIXELFORMAT_RGBA4444,
		SDL_PIXELFORMAT_ABGR4444,
		SDL_PIXELFORMAT_BGRA4444,
		SDL_PIXELFORMAT_ARGB1555,
		SDL_PIXELFORMAT_RGBA5551,
		SDL_PIXELFORMAT_ABGR1555,
		SDL_PIXELFORMAT_BGRA5551,
		SDL_PIXELFORMAT_RGB565,
		SDL_PIXELFORMAT_BGR565,
		SDL_PIXELFORMAT_RGB24,
		SDL_PIXELFORMAT_BGR24,
		SDL_PIXELFORMAT_RGB888,
		SDL_PIXELFORMAT_RGBX8888,
		SDL_PIXELFORMAT_BGR888,
		SDL_PIXELFORMAT_BGRX8888,
		SDL_PIXELFORMAT_ARGB8888,
		SDL_PIXELFORMAT_RGBA8888,
		SDL_PIXELFORMAT_ABGR8888,
		SDL_PIXELFORMAT_BGRA8888,
		SDL_PIXELFORMAT_ARGB2101010
	};
	
	char fmt_names[][NUM_OF_TEXTURES] = {
		"RGB332",
		"RGB444",
		"RGB555",
		"BGR555",
		"ARGB4444",
		"RGBA4444",
		"ABGR4444",
		"BGRA4444",
		"ARGB1555",
		"RGBA5551",
		"ABGR1555",
		"BGRA5551",
		"RGB565",
		"BGR565",
		"RGB24",
		"BGR24",
		"RGB888",
		"RGBX8888",
		"BGR888",
		"BGRX8888",
		"ARGB8888",
		"RGBA8888",
		"ABGR8888",
		"BGRA8888",
		"ARGB2101010"
	};

	SDL_BlendMode blendModes[] = {
		SDL_BLENDMODE_NONE,
		SDL_BLENDMODE_BLEND,
		SDL_BLENDMODE_ADD,
		SDL_BLENDMODE_MOD
	};
	char* blendNames[] = {
		"NONE",
		"BLEND",
		"ADD",
		"MOD"
	};
	int current_blend = 0;

	int colors[][4] = {
		{255,255,255,255},
		{255,  0,  0,255},
		{  0,255,  0,255},
		{  0,  0,255,255},
		{255,255,255,127}
	};
	char* colorNames[] = {
		"white",
		"red",
		"green",
		"blue",
		"semi transp."
	};
	int current_color = 0;

	SDL_Texture* textures[ NUM_OF_TEXTURES ];
	
	for ( i=0; i< (int)(NUM_OF_TEXTURES); i++) {
		SDL_PixelFormat* fmt = SDL_AllocFormat( formats[i] );
			SDL_assert(fmt != NULL);
		SDL_Surface* srf2 = SDL_ConvertSurface(srf, fmt, 0);
			SDL_assert(srf2 != NULL);
		textures[i] = SDL_CreateTextureFromSurface(renderer, srf2 );

		SDL_SetTextureBlendMode(textures[i], blendModes[current_blend]);
		SDL_FreeSurface( srf2 );
		SDL_FreeFormat(fmt);

		if ( !textures[i] ){
			return 1000 + i;
		}

		if ( textures[i]->native ){
			printf("native_tex: %d \n",textures[i]->native->format );
		}else{
			printf("SDL_tex: %d \n",textures[i]->format );
		}

	}
	SDL_FreeSurface(srf);

	SDL_SetRenderTarget( renderer, NULL );
	SDL_Event e;
	SDL_SetRenderDrawColor(renderer, 0,0,0,1);
	int ret = 0;
	int quit = 0;

	while ( !quit ) {
		SDLTest_DrawString( renderer,   8,   8, blendNames[current_blend] );
		SDLTest_DrawString( renderer, 108,   8, colorNames[current_color] );
		for ( i=0; i< (int)(NUM_OF_TEXTURES); i++) {
			int x=30+(i%8)*55;
			int y=30+(i/8)*75;
			SDL_Rect dst = {x,y,50,50};
			ret = SDL_renderCopyShd( shader, textures[i], NULL, &dst );
			if ( ret!=0 ){
				fprintf(stderr,"Err: %s\n", SDL_GetError());
			}
			SDLTest_DrawString( renderer, dst.x,dst.y+55 + (i%2==0 ? 10 : 0), fmt_names[i] );
			
			dst.y += (NUM_OF_TEXTURES)/8 * 75 + 85;
			SDL_RenderCopy( renderer, textures[i], NULL, &dst );
			SDLTest_DrawString( renderer, dst.x,dst.y+55 + (i%2==0 ? 10 : 0), fmt_names[i] );

		}
		while (SDL_PollEvent(&e)){
			switch ( e.type ) {
				case SDL_QUIT: 
					quit = 1; 
					break;
				case SDL_KEYDOWN: 
					switch ( e.key.keysym.sym ) {
						case SDLK_SPACE:
							current_blend = (current_blend+1)%4;
							for ( i=0; i< (int)(NUM_OF_TEXTURES); i++) {
								SDL_SetTextureBlendMode(textures[i], blendModes[current_blend]);
							}
							break;
						case SDLK_TAB:
							current_color = (current_color+1)%5;
							for ( i=0; i< (int)(NUM_OF_TEXTURES); i++) {
								SDL_SetTextureColorMod(textures[i], 
										colors[current_color][0],
										colors[current_color][1],
										colors[current_color][2]);
								SDL_SetTextureAlphaMod(textures[i], colors[current_color][3] );
							}
							break;
					}
					break;
				case SDL_WINDOWEVENT:
					SDL_updateViewport( shader );
			}
		}

		SDL_RenderPresent(renderer);

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

	}
	for ( i=0; i<(int)NUM_OF_TEXTURES; i++ ) {
		SDL_DestroyTexture( textures[i] );
		textures[i] = NULL;
	}
	SDL_destroyShader( shader );
	SDL_DestroyRenderer( renderer );
	SDL_DestroyWindow( screen );
	SDL_Quit();

	return 0;
}
Example #6
0
int AtlasLayer_GetAtlasColumns(AtlasLayer * ptr)
{
    SDL_assert(ptr);
    return ptr->atlasColumnCount;
}
Example #7
0
static
void RunEpicTest()
{
    int b;
    atomicValue v;
 
    printf("\nepic test---------------------------------------\n\n");

    printf("Size asserted to be >= 32-bit\n");
    SDL_assert(sizeof(atomicValue)>=4);
 
    printf("Check static initializer\n");
    v=SDL_AtomicGet(&good);
    SDL_assert(v==42);
 
    SDL_assert(bad==42);
 
    printf("Test negative values\n");
    SDL_AtomicSet(&good, -5);
    v=SDL_AtomicGet(&good);
    SDL_assert(v==-5);
 
    printf("Verify maximum value\n");
    SDL_AtomicSet(&good, CountTo);
    v=SDL_AtomicGet(&good);
    SDL_assert(v==CountTo);
 
    printf("Test compare and exchange\n");
 
    b=SDL_AtomicCAS(&good, 500, 43);
    SDL_assert(!b); /* no swap since CountTo!=500 */
    v=SDL_AtomicGet(&good);
    SDL_assert(v==CountTo); /* ensure no swap */
 
    b=SDL_AtomicCAS(&good, CountTo, 44);
    SDL_assert(!!b); /* will swap */
    v=SDL_AtomicGet(&good);
    SDL_assert(v==44);
 
    printf("Test Add\n");
 
    v=SDL_AtomicAdd(&good, 1);
    SDL_assert(v==44);
    v=SDL_AtomicGet(&good);
    SDL_assert(v==45);
 
    v=SDL_AtomicAdd(&good, 10);
    SDL_assert(v==45);
    v=SDL_AtomicGet(&good);
    SDL_assert(v==55);
 
    printf("Test Add (Negative values)\n");
 
    v=SDL_AtomicAdd(&good, -20);
    SDL_assert(v==55);
    v=SDL_AtomicGet(&good);
    SDL_assert(v==35);
 
    v=SDL_AtomicAdd(&good, -50); /* crossing zero down */
    SDL_assert(v==35);
    v=SDL_AtomicGet(&good);
    SDL_assert(v==-15);
 
    v=SDL_AtomicAdd(&good, 30); /* crossing zero up */
    SDL_assert(v==-15);
    v=SDL_AtomicGet(&good);
    SDL_assert(v==15);
 
    printf("Reset before count down test\n");
    SDL_AtomicSet(&good, CountTo);
    v=SDL_AtomicGet(&good);
    SDL_assert(v==CountTo);
 
    bad=CountTo;
    SDL_assert(bad==CountTo);
 
    printf("Counting down from %d, Expect %d remaining\n",CountTo,Expect);
    runAdder();
 
    v=SDL_AtomicGet(&good);
    printf("Atomic %d Non-Atomic %d\n",v,bad);
    SDL_assert(v==Expect);
    SDL_assert(bad!=Expect);
}
Example #8
0
void config_load(void)
{
    fs_file fh;

    SDL_assert(SDL_WasInit(SDL_INIT_VIDEO));

    if ((fh = fs_open(USER_CONFIG_FILE, "r")))
    {
        char *line, *key, *val;

        while (read_line(&line, fh))
        {
            if (scan_key_and_value(&key, &val, line))
            {
                int i;

                /* Look up an integer option by that name. */

                for (i = 0; i < ARRAYSIZE(option_d); i++)
                {
                    if (strcmp(key, option_d[i].name) == 0)
                    {
                        /* Translate some strings to integers. */

                        if (i == CONFIG_MOUSE_CAMERA_1      ||
                            i == CONFIG_MOUSE_CAMERA_2      ||
                            i == CONFIG_MOUSE_CAMERA_3      ||
                            i == CONFIG_MOUSE_CAMERA_TOGGLE ||
                            i == CONFIG_MOUSE_CAMERA_L      ||
                            i == CONFIG_MOUSE_CAMERA_R)
                        {
                            config_mouse(val, i);
                        }
                        else if (i == CONFIG_KEY_FORWARD       ||
                                 i == CONFIG_KEY_BACKWARD      ||
                                 i == CONFIG_KEY_LEFT          ||
                                 i == CONFIG_KEY_RIGHT         ||
                                 i == CONFIG_KEY_CAMERA_1      ||
                                 i == CONFIG_KEY_CAMERA_2      ||
                                 i == CONFIG_KEY_CAMERA_3      ||
                                 i == CONFIG_KEY_CAMERA_TOGGLE ||
                                 i == CONFIG_KEY_CAMERA_R      ||
                                 i == CONFIG_KEY_CAMERA_L      ||
                                 i == CONFIG_KEY_RESTART       ||
                                 i == CONFIG_KEY_SCORE_NEXT    ||
                                 i == CONFIG_KEY_ROTATE_FAST)
                        {
                            config_key(val, i);
                        }
                        else
                            config_set_d(i, atoi(val));

                        /* Stop looking. */

                        break;
                    }
                }

                /* Look up a string option by that name.*/

                for (i = 0; i < ARRAYSIZE(option_s); i++)
                {
                    if (strcmp(key, option_s[i].name) == 0)
                    {
                        config_set_s(i, val);
                        break;
                    }
                }
            }
            free(line);
        }
        fs_close(fh);

        dirty = 0;
    }
}
Example #9
0
void config_save(void)
{
    fs_file fh;

    SDL_assert(SDL_WasInit(SDL_INIT_VIDEO));

    if (dirty && (fh = fs_open(USER_CONFIG_FILE, "w")))
    {
        int i;

        /* Write out integer options. */

        for (i = 0; i < ARRAYSIZE(option_d); i++)
        {
            const char *s = NULL;

            /* Translate some integers to strings. */

            if (i == CONFIG_MOUSE_CAMERA_1      ||
                i == CONFIG_MOUSE_CAMERA_2      ||
                i == CONFIG_MOUSE_CAMERA_3      ||
                i == CONFIG_MOUSE_CAMERA_TOGGLE ||
                i == CONFIG_MOUSE_CAMERA_L      ||
                i == CONFIG_MOUSE_CAMERA_R)
            {
                s = config_mouse_name(option_d[i].cur);
            }
            else if (i == CONFIG_KEY_FORWARD       ||
                     i == CONFIG_KEY_BACKWARD      ||
                     i == CONFIG_KEY_LEFT          ||
                     i == CONFIG_KEY_RIGHT         ||
                     i == CONFIG_KEY_CAMERA_1      ||
                     i == CONFIG_KEY_CAMERA_2      ||
                     i == CONFIG_KEY_CAMERA_3      ||
                     i == CONFIG_KEY_CAMERA_TOGGLE ||
                     i == CONFIG_KEY_CAMERA_R      ||
                     i == CONFIG_KEY_CAMERA_L      ||
                     i == CONFIG_KEY_RESTART       ||
                     i == CONFIG_KEY_SCORE_NEXT    ||
                     i == CONFIG_KEY_ROTATE_FAST)
            {
                s = SDL_GetKeyName((SDL_Keycode) option_d[i].cur);
            }
            else if (i == CONFIG_CHEAT)
            {
                if (!config_cheat())
                    continue;
            }

            if (s)
                fs_printf(fh, "%-25s %s\n", option_d[i].name, s);
            else
                fs_printf(fh, "%-25s %d\n", option_d[i].name, option_d[i].cur);
        }

        /* Write out string options. */

        for (i = 0; i < ARRAYSIZE(option_s); i++)
            fs_printf(fh, "%-25s %s\n", option_s[i].name, option_s[i].cur);

        fs_close(fh);
    }

    dirty = 0;
}
Example #10
0
Frame* Space::MakeFrameFor(double time, SystemBody* sbody, Entity e, Frame* f)
{
	if (!sbody->GetParent()) {
		e.assign<FrameComponent>(f);
		f->SetBodies(sbody, 0);
		return f;
	}

	if (sbody->GetType() == SystemBody::TYPE_GRAVPOINT) {
		Frame* orbFrame = new Frame(f, sbody->GetName().c_str());
		orbFrame->SetBodies(sbody, 0);
		orbFrame->SetRadius(sbody->GetMaxChildOrbitalDistance() * 1.1);
		return orbFrame;
	}

	const SystemBody::BodySuperType supertype = sbody->GetSuperType();

	if ((supertype == SystemBody::SUPERTYPE_GAS_GIANT) ||
	        (supertype == SystemBody::SUPERTYPE_ROCKY_PLANET)) {
		// for planets we want an non-rotating frame for a few radii
		// and a rotating frame with no radius to contain attached objects
		double frameRadius = std::max(4.0 * sbody->GetRadius(), sbody->GetMaxChildOrbitalDistance() * 1.05);
		Frame* orbFrame = new Frame(f, sbody->GetName().c_str(), Frame::FLAG_HAS_ROT);

		orbFrame->SetBodies(sbody, 0);
		orbFrame->SetRadius(frameRadius);

		assert(sbody->IsRotating() != 0);
		Frame* rotFrame = new Frame(orbFrame, sbody->GetName().c_str(), Frame::FLAG_ROTATING);
		rotFrame->SetBodies(sbody, 0);

		// rotating frame has atmosphere radius or feature height, whichever is larger
		rotFrame->SetRadius(frameRadius * 0.5); //ZZZ should be body->physRadius

		matrix3x3d rotMatrix = matrix3x3d::RotateX(sbody->GetAxialTilt());
		double angSpeed = 2.0 * M_PI / sbody->GetRotationPeriod();
		rotFrame->SetAngSpeed(angSpeed);

		if (sbody->HasRotationPhase())
			rotMatrix = rotMatrix * matrix3x3d::RotateY(sbody->GetRotationPhaseAtStart());
		rotFrame->SetInitialOrient(rotMatrix, time);

		e.assign<FrameComponent>(rotFrame);
		return orbFrame;
	} else if (supertype == SystemBody::SUPERTYPE_STAR) {
		// stars want a single small non-rotating frame
		// bigger than it's furtherest orbiting body.
		// if there are no orbiting bodies use a frame of several radii.
		Frame* orbFrame = new Frame(f, sbody->GetName().c_str());
		orbFrame->SetBodies(sbody, 0);
		double frameRadius = std::max(10.0 * sbody->GetRadius(), sbody->GetMaxChildOrbitalDistance() * 1.1);
		// Respect the frame of other stars in the multi-star system. We still make sure that the frame ends outside
		// the body. For a minimum separation of 1.236 radii, nothing will overlap (see StarSystem::StarSystem()).
		if (sbody->GetParent() && frameRadius > AU * 0.11 * sbody->GetOrbMin())
			frameRadius = std::max(1.1 * sbody->GetRadius(), AU * 0.11 * sbody->GetOrbMin());
		orbFrame->SetRadius(frameRadius);
		e.assign<FrameComponent>(orbFrame);
		return orbFrame;
	} else {
		SDL_assert(false);
	}
}
Example #11
0
void Space::CreateTestScene(Entity player, double time)
{
	auto renderer = p3::game->GetRenderer();
	m_renderer = renderer;

	StarSystemCache::ShrinkCache(SystemPath(), true);
	Sector::cache.ClearCache();
	SystemPath path(10,0,0,0);
	m_starSystem = StarSystemCache::GetCached(path);

	GenBody(time, m_starSystem->m_rootBody.Get(), m_rootFrame.get());
	m_rootFrame->UpdateOrbitRails(time, 1.0);

	//init "player"
	{
		auto model = p3::game->GetModelCache()->FindModel("kanara");
		SDL_assert(model);
		player.assign<GraphicComponent>(new ModelGraphic(renderer, model));
		player.assign<PosOrientComponent>(vector3d(0,0,1e6), matrix3x3d(1.0));
		player.assign<MassComponent>(10.0);
		player.assign<DynamicsComponent>();
		player.assign<ThrusterComponent>();
		player.assign<WeaponComponent>();
		player.assign<PlayerInputComponent>();
		player.assign<CollisionMeshComponent>(player, model->GetCollisionMesh());
		player.assign<FrameComponent>(GetRootFrame());
		//player.assign<ColorComponent>(Color(0,255,255,255));
		player.assign<ShipAIComponent>();
		player.assign<NameComponent>("Player");

		GetRootFrame()->GetCollisionSpace()->AddGeom(player.component<CollisionMeshComponent>()->geom.get());
	}

	//init "AI"
	{
		auto model = p3::game->GetModelCache()->FindModel("natrix");
		SDL_assert(model);
		Entity ship = m_entities->create();
		ship.assign<GraphicComponent>(new ModelGraphic(renderer, model));
		ship.assign<PosOrientComponent>(vector3d(0,0,1e6 - 200), matrix3x3d(1.0));
		ship.assign<MassComponent>(10.0);
		ship.assign<DynamicsComponent>();
		ship.assign<ThrusterComponent>();
		ship.assign<WeaponComponent>();
		ship.assign<CollisionMeshComponent>(ship, model->GetCollisionMesh());
		ship.assign<FrameComponent>(GetRootFrame());
		ship.assign<ColorComponent>(Color(255,0,0,255));
		ship.assign<ShipAIComponent>();
		ship.assign<NameComponent>("Drone");
		ship.assign<AICommandComponent>(); //kamikaze
		auto aicmd = ship.component<AICommandComponent>();
		aicmd->SetKamikaze(player);

		GetRootFrame()->GetCollisionSpace()->AddGeom(ship.component<CollisionMeshComponent>()->geom.get());
	}

	//some scenery
	//Entity obstacle = m_entities->create();
	if (0)
	{
		Entity obstacle = m_entities->create();
		auto model = p3::game->GetModelCache()->FindModel("kbuilding02");
		obstacle.assign<PosOrientComponent>(vector3d(0, 0, -200), matrix3x3d(1.0));
		obstacle.assign<GraphicComponent>(new ModelGraphic(renderer, model));
		obstacle.assign<MassComponent>(100.0);
		obstacle.assign<DynamicsComponent>();
		obstacle.assign<CollisionMeshComponent>(obstacle, model->GetCollisionMesh());
		obstacle.assign<FrameComponent>(GetRootFrame());

		GetRootFrame()->GetCollisionSpace()->AddGeom(obstacle.component<CollisionMeshComponent>()->geom.get());

		Entity hangAroundMember = m_entities->create();
		hangAroundMember.assign<PosOrientComponent>(vector3d(0.0), matrix3x3d(1.0));
		hangAroundMember.assign<AttachToEntityComponent>(obstacle, vector3d(0, 50, 0));
		hangAroundMember.assign<GraphicComponent>(new ModelGraphic(renderer, model));
		hangAroundMember.assign<FrameComponent>(GetRootFrame());
	}

	//init camera
	//left camera
	if (0)
	{
		Entity camera = m_entities->create();
		ent_ptr<CameraComponent> camc(new CameraComponent());
		camc->camera.reset(new Camera());
		camc->camera->viewport = vector4f(0.f, 0.f, 0.5f, 1.f);
		camc->camera->clearColor = Color(0, 40, 0, 0);
		camera.assign(camc);
		camera.assign<PosOrientComponent>(vector3d(0, 50, 100), matrix3x3d(1.0));
		camera.assign<CameraLookAtComponent>(player);
		camera.assign<FrameComponent>(GetRootFrame());
		//camera.assign<AttachToEntityComponent>(player, vector3d(0, 5, 50));
	}

	//right top camera
	if (0)
	{
		Entity camera = m_entities->create();
		ent_ptr<CameraComponent> camc(new CameraComponent());
		camc->camera.reset(new Camera());
		camc->camera->viewport = vector4f(0.5f, 0.5f, 0.5f, 0.5f);
		camera.assign(camc);
		camera.assign<PosOrientComponent>(vector3d(100, -10, -10), matrix3x3d(1.0));
		//camera.assign<CameraLookAtComponent>(obstacle);
		camera.assign<FrameComponent>(GetRootFrame());
	}
	//right bottom camera
	{
		Entity camera = m_entities->create();
		ent_ptr<CameraComponent> camc(new CameraComponent());
		camc->camera.reset(new Camera());
		//camc->camera->clearColor = Color(10, 10, 10, 0);
		camc->camera->viewport = vector4f(0.0f, 0.f, 1.0f, 1.0f);
		//camc->camera->viewport = vector4f(0.5f, 0.f, 0.5f, 1.0f);
		camera.assign(camc);
		camera.assign<PosOrientComponent>(vector3d(0, 0, 0), matrix3x3d(1.0));
		camera.assign<AttachToEntityComponent>(player, vector3d(0, 5, 10));
		camera.assign<FrameComponent>(GetRootFrame());
	}
}
int
main(int argc, char *argv[])
{
    int i;
    int nController = 0;
    int retcode = 0;
    char guid[64];
    SDL_GameController *gamecontroller;

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

    /* Initialize SDL (Note: video is required to start event loop) */
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER ) < 0) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
        return 1;
    }
    
    SDL_GameControllerAddMappingsFromFile("gamecontrollerdb.txt");

    /* Print information about the controller */
    for (i = 0; i < SDL_NumJoysticks(); ++i) {
        const char *name;
        const char *description;

        SDL_JoystickGetGUIDString(SDL_JoystickGetDeviceGUID(i),
                                  guid, sizeof (guid));

        if ( SDL_IsGameController(i) )
        {
            nController++;
            name = SDL_GameControllerNameForIndex(i);
            description = "Controller";
        } else {
            name = SDL_JoystickNameForIndex(i);
            description = "Joystick";
        }
        SDL_Log("%s %d: %s (guid %s)\n", description, i, name ? name : "Unknown", guid);
    }
    SDL_Log("There are %d game controller(s) attached (%d joystick(s))\n", nController, SDL_NumJoysticks());

    if (argv[1]) {
        SDL_bool reportederror = SDL_FALSE;
        SDL_bool keepGoing = SDL_TRUE;
        SDL_Event event;
        int device = atoi(argv[1]);
        if (device >= SDL_NumJoysticks()) {
            SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "%i is an invalid joystick index.\n", device);
            retcode = 1;
        } else {
            SDL_JoystickGetGUIDString(SDL_JoystickGetDeviceGUID(device),
                                      guid, sizeof (guid));
            SDL_Log("Attempting to open device %i, guid %s\n", device, guid);
            gamecontroller = SDL_GameControllerOpen(device);

            if (gamecontroller != NULL) {
                SDL_assert(SDL_GameControllerFromInstanceID(SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(gamecontroller))) == gamecontroller);
            }

            while (keepGoing) {
                if (gamecontroller == NULL) {
                    if (!reportederror) {
                        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't open gamecontroller %d: %s\n", device, SDL_GetError());
                        retcode = 1;
                        keepGoing = SDL_FALSE;
                        reportederror = SDL_TRUE;
                    }
                } else {
                    reportederror = SDL_FALSE;
                    keepGoing = WatchGameController(gamecontroller);
                    SDL_GameControllerClose(gamecontroller);
                }

                gamecontroller = NULL;
                if (keepGoing) {
                    SDL_Log("Waiting for attach\n");
                }
                while (keepGoing) {
                    SDL_WaitEvent(&event);
                    if ((event.type == SDL_QUIT) || (event.type == SDL_FINGERDOWN)
                        || (event.type == SDL_MOUSEBUTTONDOWN)) {
                        keepGoing = SDL_FALSE;
                    } else if (event.type == SDL_CONTROLLERDEVICEADDED) {
                        gamecontroller = SDL_GameControllerOpen(event.cdevice.which);
                        if (gamecontroller != NULL) {
                            SDL_assert(SDL_GameControllerFromInstanceID(SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(gamecontroller))) == gamecontroller);
                        }
                        break;
                    }
                }
            }
        }
    }

    SDL_QuitSubSystem(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER);

    return retcode;
}
Example #13
0
/* Public functions */
static int
SDL_QuitInit_Internal(void)
{
#ifdef HAVE_SIGACTION
    struct sigaction action;
    sigaction(SIGINT, NULL, &action);
#ifdef HAVE_SA_SIGACTION
    if ( action.sa_handler == SIG_DFL && (void (*)(int))action.sa_sigaction == SIG_DFL ) {
#else
    if ( action.sa_handler == SIG_DFL ) {
#endif
        action.sa_handler = SDL_HandleSIG;
        sigaction(SIGINT, &action, NULL);
    }
    sigaction(SIGTERM, NULL, &action);

#ifdef HAVE_SA_SIGACTION
    if ( action.sa_handler == SIG_DFL && (void (*)(int))action.sa_sigaction == SIG_DFL ) {
#else
    if ( action.sa_handler == SIG_DFL ) {
#endif
        action.sa_handler = SDL_HandleSIG;
        sigaction(SIGTERM, &action, NULL);
    }
#elif HAVE_SIGNAL_H
    void (*ohandler) (int);

    /* Both SIGINT and SIGTERM are translated into quit interrupts */
    ohandler = signal(SIGINT, SDL_HandleSIG);
    if (ohandler != SIG_DFL)
        signal(SIGINT, ohandler);
    ohandler = signal(SIGTERM, SDL_HandleSIG);
    if (ohandler != SIG_DFL)
        signal(SIGTERM, ohandler);
#endif /* HAVE_SIGNAL_H */

    /* That's it! */
    return 0;
}

int
SDL_QuitInit(void)
{
    if (!SDL_GetHintBoolean(SDL_HINT_NO_SIGNAL_HANDLERS, SDL_FALSE)) {
        return SDL_QuitInit_Internal();
    }
    return 0;
}

static void
SDL_QuitQuit_Internal(void)
{
#ifdef HAVE_SIGACTION
    struct sigaction action;
    sigaction(SIGINT, NULL, &action);
    if ( action.sa_handler == SDL_HandleSIG ) {
        action.sa_handler = SIG_DFL;
        sigaction(SIGINT, &action, NULL);
    }
    sigaction(SIGTERM, NULL, &action);
    if ( action.sa_handler == SDL_HandleSIG ) {
        action.sa_handler = SIG_DFL;
        sigaction(SIGTERM, &action, NULL);
    }
#elif HAVE_SIGNAL_H
    void (*ohandler) (int);

    ohandler = signal(SIGINT, SIG_DFL);
    if (ohandler != SDL_HandleSIG)
        signal(SIGINT, ohandler);
    ohandler = signal(SIGTERM, SIG_DFL);
    if (ohandler != SDL_HandleSIG)
        signal(SIGTERM, ohandler);
#endif /* HAVE_SIGNAL_H */
}

void
SDL_QuitQuit(void)
{
    if (!disable_signals) {
        SDL_QuitQuit_Internal();
    }
}

/* This function returns 1 if it's okay to close the application window */
int
SDL_SendQuit(void)
{
    send_quit_pending = SDL_FALSE;
    return SDL_SendAppEvent(SDL_QUIT);
}

void
SDL_SendPendingQuit(void)
{
    if (send_quit_pending) {
        SDL_SendQuit();
        SDL_assert(!send_quit_pending);
    }
}
Example #14
0
		void CreateDisplay( void ) {
			Uint32 windowFlags = SDL_WINDOW_OPENGL | SDL_WINDOW_ALLOW_HIGHDPI;

			if ( SDL_Init( SDL_INIT_VIDEO ) != 0 ) {
				return;
			}

			if ( vid_noBorder->GetBool() ) {
				windowFlags |= SDL_WINDOW_BORDERLESS;
			}

			// targeting OpenGL 3.1 core
			SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 );
			SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 1 );
			SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE );
			uint32_t contextFlags = SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG;
			if ( Common::com_developer->GetBool() ) {
				contextFlags |= SDL_GL_CONTEXT_DEBUG_FLAG;
			}
#ifdef _DEBUG
			contextFlags |= SDL_GL_CONTEXT_DEBUG_FLAG;
#endif
			SDL_GL_SetAttribute( SDL_GL_CONTEXT_FLAGS, contextFlags );

			int multisample = r_multisample->GetInt32();
			if ( multisample > 0 ) {
				SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, 1 );
				//TODO: find the highest significant bit to ensure samples^2
				SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, multisample );
			}
			else {
				SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, 0 );
			}

			int32_t width = vid_width->GetInt32();
			int32_t height = vid_height->GetInt32();
			window = SDL_CreateWindow(
				WINDOW_TITLE,
				SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
				width, height,
				windowFlags
			);
			SDL_assert( window && "Failed to create window" );

			// when creating a fullscreen window, the actual width/height may not be what was requested
			// certain drawing code relies on knowing the width/height of the display, so we'll update it with the
			//      proper values
			SDL_GetWindowSize( window, &width, &height );
			vid_width->Set( width );
			vid_height->Set( height );

			context = SDL_GL_CreateContext( window );
			SDL_assert( context && "Failed to create OpenGL context on window" );

			SDL_GL_MakeCurrent( window, context );
			rdState.window.valid = true;
			rdState.window.width = static_cast<uint32_t>( width );
			rdState.window.height = static_cast<uint32_t>( height );
			rdState.window.aspectRatio = vid_width->GetReal64() / vid_height->GetReal64();

			SDL_GL_SetSwapInterval( r_swapInterval->GetInt32() );
		#if defined(XS_OS_MAC)
			//TODO: force vsync flag in CGL, seems to only have an Obj-C API?
			/*
			CGLContextObj cglContext = CGLGetCurrentContext();
			if ( cglContext ) {
				// ...
			}
			*/
		#endif

			rdState.driver.vendor = reinterpret_cast<const char *>( glGetString( GL_VENDOR ) );
			rdState.driver.renderer = reinterpret_cast<const char *>( glGetString( GL_RENDERER ) );
			rdState.driver.coreVersion = reinterpret_cast<const char *>( glGetString( GL_VERSION ) );
			rdState.driver.shaderVersion = reinterpret_cast<const char *>( glGetString( GL_SHADING_LANGUAGE_VERSION ) );

			console.Print( PrintLevel::Normal, "OpenGL device: %s %s\n",
				rdState.driver.vendor,
				rdState.driver.renderer
			);
			console.Print( PrintLevel::Normal, "OpenGL version: %s with GLSL %s\n",
				rdState.driver.coreVersion,
				rdState.driver.shaderVersion
			);
		}
Example #15
0
SDL_Surface *
SDL_LoadBMP_RW(SDL_RWops * src, int freesrc)
{
    SDL_bool was_error;
    Sint64 fp_offset = 0;
    int bmpPitch;
    int i, pad;
    SDL_Surface *surface;
    Uint32 Rmask = 0;
    Uint32 Gmask = 0;
    Uint32 Bmask = 0;
    Uint32 Amask = 0;
    SDL_Palette *palette;
    Uint8 *bits;
    Uint8 *top, *end;
    SDL_bool topDown;
    int ExpandBMP;
    SDL_bool haveRGBMasks = SDL_FALSE;
    SDL_bool haveAlphaMask = SDL_FALSE;
    SDL_bool correctAlpha = SDL_FALSE;

    /* The Win32 BMP file header (14 bytes) */
    char magic[2];
    /* Uint32 bfSize = 0; */
    /* Uint16 bfReserved1 = 0; */
    /* Uint16 bfReserved2 = 0; */
    Uint32 bfOffBits = 0;

    /* The Win32 BITMAPINFOHEADER struct (40 bytes) */
    Uint32 biSize = 0;
    Sint32 biWidth = 0;
    Sint32 biHeight = 0;
    /* Uint16 biPlanes = 0; */
    Uint16 biBitCount = 0;
    Uint32 biCompression = 0;
    /* Uint32 biSizeImage = 0; */
    /* Sint32 biXPelsPerMeter = 0; */
    /* Sint32 biYPelsPerMeter = 0; */
    Uint32 biClrUsed = 0;
    /* Uint32 biClrImportant = 0; */

    /* Make sure we are passed a valid data source */
    surface = NULL;
    was_error = SDL_FALSE;
    if (src == NULL) {
        was_error = SDL_TRUE;
        goto done;
    }

    /* Read in the BMP file header */
    fp_offset = SDL_RWtell(src);
    SDL_ClearError();
    if (SDL_RWread(src, magic, 1, 2) != 2) {
        SDL_Error(SDL_EFREAD);
        was_error = SDL_TRUE;
        goto done;
    }
    if (SDL_strncmp(magic, "BM", 2) != 0) {
        SDL_SetError("File is not a Windows BMP file");
        was_error = SDL_TRUE;
        goto done;
    }
    /* bfSize = */ SDL_ReadLE32(src);
    /* bfReserved1 = */ SDL_ReadLE16(src);
    /* bfReserved2 = */ SDL_ReadLE16(src);
    bfOffBits = SDL_ReadLE32(src);

    /* Read the Win32 BITMAPINFOHEADER */
    biSize = SDL_ReadLE32(src);
    if (biSize == 12) {   /* really old BITMAPCOREHEADER */
        biWidth = (Uint32) SDL_ReadLE16(src);
        biHeight = (Uint32) SDL_ReadLE16(src);
        /* biPlanes = */ SDL_ReadLE16(src);
        biBitCount = SDL_ReadLE16(src);
        biCompression = BI_RGB;
    } else if (biSize >= 40) {  /* some version of BITMAPINFOHEADER */
        Uint32 headerSize;
        biWidth = SDL_ReadLE32(src);
        biHeight = SDL_ReadLE32(src);
        /* biPlanes = */ SDL_ReadLE16(src);
        biBitCount = SDL_ReadLE16(src);
        biCompression = SDL_ReadLE32(src);
        /* biSizeImage = */ SDL_ReadLE32(src);
        /* biXPelsPerMeter = */ SDL_ReadLE32(src);
        /* biYPelsPerMeter = */ SDL_ReadLE32(src);
        biClrUsed = SDL_ReadLE32(src);
        /* biClrImportant = */ SDL_ReadLE32(src);

        /* 64 == BITMAPCOREHEADER2, an incompatible OS/2 2.x extension. Skip this stuff for now. */
        if (biSize == 64) {
            /* ignore these extra fields. */
            if (biCompression == BI_BITFIELDS) {
                /* this value is actually huffman compression in this variant. */
                SDL_SetError("Compressed BMP files not supported");
                was_error = SDL_TRUE;
                goto done;
            }
        } else {
            /* This is complicated. If compression is BI_BITFIELDS, then
               we have 3 DWORDS that specify the RGB masks. This is either
               stored here in an BITMAPV2INFOHEADER (which only differs in
               that it adds these RGB masks) and biSize >= 52, or we've got
               these masks stored in the exact same place, but strictly
               speaking, this is the bmiColors field in BITMAPINFO immediately
               following the legacy v1 info header, just past biSize. */
            if (biCompression == BI_BITFIELDS) {
                haveRGBMasks = SDL_TRUE;
                Rmask = SDL_ReadLE32(src);
                Gmask = SDL_ReadLE32(src);
                Bmask = SDL_ReadLE32(src);

                /* ...v3 adds an alpha mask. */
                if (biSize >= 56) {  /* BITMAPV3INFOHEADER; adds alpha mask */
                    haveAlphaMask = SDL_TRUE;
                    Amask = SDL_ReadLE32(src);
                }
            } else {
                /* the mask fields are ignored for v2+ headers if not BI_BITFIELD. */
                if (biSize >= 52) {  /* BITMAPV2INFOHEADER; adds RGB masks */
                    /*Rmask = */ SDL_ReadLE32(src);
                    /*Gmask = */ SDL_ReadLE32(src);
                    /*Bmask = */ SDL_ReadLE32(src);
                }
                if (biSize >= 56) {  /* BITMAPV3INFOHEADER; adds alpha mask */
                    /*Amask = */ SDL_ReadLE32(src);
                }
            }

            /* Insert other fields here; Wikipedia and MSDN say we're up to
               v5 of this header, but we ignore those for now (they add gamma,
               color spaces, etc). Ignoring the weird OS/2 2.x format, we
               currently parse up to v3 correctly (hopefully!). */
        }

        /* skip any header bytes we didn't handle... */
        headerSize = (Uint32) (SDL_RWtell(src) - (fp_offset + 14));
        if (biSize > headerSize) {
            SDL_RWseek(src, (biSize - headerSize), RW_SEEK_CUR);
        }
    }
    if (biHeight < 0) {
        topDown = SDL_TRUE;
        biHeight = -biHeight;
    } else {
        topDown = SDL_FALSE;
    }

    /* Check for read error */
    if (SDL_strcmp(SDL_GetError(), "") != 0) {
        was_error = SDL_TRUE;
        goto done;
    }

    /* Expand 1 and 4 bit bitmaps to 8 bits per pixel */
    switch (biBitCount) {
    case 1:
    case 4:
        ExpandBMP = biBitCount;
        biBitCount = 8;
        break;
    default:
        ExpandBMP = 0;
        break;
    }

    /* We don't support any BMP compression right now */
    switch (biCompression) {
    case BI_RGB:
        /* If there are no masks, use the defaults */
        SDL_assert(!haveRGBMasks);
        SDL_assert(!haveAlphaMask);
        /* Default values for the BMP format */
        switch (biBitCount) {
        case 15:
        case 16:
            Rmask = 0x7C00;
            Gmask = 0x03E0;
            Bmask = 0x001F;
            break;
        case 24:
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
            Rmask = 0x000000FF;
            Gmask = 0x0000FF00;
            Bmask = 0x00FF0000;
#else
            Rmask = 0x00FF0000;
            Gmask = 0x0000FF00;
            Bmask = 0x000000FF;
#endif
            break;
        case 32:
            /* We don't know if this has alpha channel or not */
            correctAlpha = SDL_TRUE;
            Amask = 0xFF000000;
            Rmask = 0x00FF0000;
            Gmask = 0x0000FF00;
            Bmask = 0x000000FF;
            break;
        default:
            break;
        }
        break;

    case BI_BITFIELDS:
        break;  /* we handled this in the info header. */

    default:
        SDL_SetError("Compressed BMP files not supported");
        was_error = SDL_TRUE;
        goto done;
    }

    /* Create a compatible surface, note that the colors are RGB ordered */
    surface =
        SDL_CreateRGBSurface(0, biWidth, biHeight, biBitCount, Rmask, Gmask,
                             Bmask, Amask);
    if (surface == NULL) {
        was_error = SDL_TRUE;
        goto done;
    }

    /* Load the palette, if any */
    palette = (surface->format)->palette;
    if (palette) {
        SDL_assert(biBitCount <= 8);
        if (biClrUsed == 0) {
            biClrUsed = 1 << biBitCount;
        }
        if ((int) biClrUsed > palette->ncolors) {
            SDL_Color *colors;
            int ncolors = biClrUsed;
            colors =
                (SDL_Color *) SDL_realloc(palette->colors,
                                          ncolors *
                                          sizeof(*palette->colors));
            if (!colors) {
                SDL_OutOfMemory();
                was_error = SDL_TRUE;
                goto done;
            }
            palette->ncolors = ncolors;
            palette->colors = colors;
        } else if ((int) biClrUsed < palette->ncolors) {
            palette->ncolors = biClrUsed;
        }
        if (biSize == 12) {
            for (i = 0; i < (int) biClrUsed; ++i) {
                SDL_RWread(src, &palette->colors[i].b, 1, 1);
                SDL_RWread(src, &palette->colors[i].g, 1, 1);
                SDL_RWread(src, &palette->colors[i].r, 1, 1);
                palette->colors[i].a = SDL_ALPHA_OPAQUE;
            }
        } else {
            for (i = 0; i < (int) biClrUsed; ++i) {
                SDL_RWread(src, &palette->colors[i].b, 1, 1);
                SDL_RWread(src, &palette->colors[i].g, 1, 1);
                SDL_RWread(src, &palette->colors[i].r, 1, 1);
                SDL_RWread(src, &palette->colors[i].a, 1, 1);

                /* According to Microsoft documentation, the fourth element
                   is reserved and must be zero, so we shouldn't treat it as
                   alpha.
                */
                palette->colors[i].a = SDL_ALPHA_OPAQUE;
            }
        }
    }

    /* Read the surface pixels.  Note that the bmp image is upside down */
    if (SDL_RWseek(src, fp_offset + bfOffBits, RW_SEEK_SET) < 0) {
        SDL_Error(SDL_EFSEEK);
        was_error = SDL_TRUE;
        goto done;
    }
    top = (Uint8 *)surface->pixels;
    end = (Uint8 *)surface->pixels+(surface->h*surface->pitch);
    switch (ExpandBMP) {
    case 1:
        bmpPitch = (biWidth + 7) >> 3;
        pad = (((bmpPitch) % 4) ? (4 - ((bmpPitch) % 4)) : 0);
        break;
    case 4:
        bmpPitch = (biWidth + 1) >> 1;
        pad = (((bmpPitch) % 4) ? (4 - ((bmpPitch) % 4)) : 0);
        break;
    default:
        pad = ((surface->pitch % 4) ? (4 - (surface->pitch % 4)) : 0);
        break;
    }
    if (topDown) {
        bits = top;
    } else {
        bits = end - surface->pitch;
    }
    while (bits >= top && bits < end) {
        switch (ExpandBMP) {
        case 1:
        case 4: {
            Uint8 pixel = 0;
            int shift = (8 - ExpandBMP);
            for (i = 0; i < surface->w; ++i) {
                if (i % (8 / ExpandBMP) == 0) {
                    if (!SDL_RWread(src, &pixel, 1, 1)) {
                        SDL_SetError("Error reading from BMP");
                        was_error = SDL_TRUE;
                        goto done;
                    }
                }
                *(bits + i) = (pixel >> shift);
                pixel <<= ExpandBMP;
            }
        }
        break;

        default:
            if (SDL_RWread(src, bits, 1, surface->pitch)
                    != surface->pitch) {
                SDL_Error(SDL_EFREAD);
                was_error = SDL_TRUE;
                goto done;
            }
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
            /* Byte-swap the pixels if needed. Note that the 24bpp
               case has already been taken care of above. */
            switch (biBitCount) {
            case 15:
            case 16: {
                Uint16 *pix = (Uint16 *) bits;
                for (i = 0; i < surface->w; i++)
                    pix[i] = SDL_Swap16(pix[i]);
                break;
            }

            case 32: {
                Uint32 *pix = (Uint32 *) bits;
                for (i = 0; i < surface->w; i++)
                    pix[i] = SDL_Swap32(pix[i]);
                break;
            }
            }
#endif
            break;
        }
        /* Skip padding bytes, ugh */
        if (pad) {
            Uint8 padbyte;
            for (i = 0; i < pad; ++i) {
                SDL_RWread(src, &padbyte, 1, 1);
            }
        }
        if (topDown) {
            bits += surface->pitch;
        } else {
            bits -= surface->pitch;
        }
    }
    if (correctAlpha) {
        CorrectAlphaChannel(surface);
    }
done:
    if (was_error) {
        if (src) {
            SDL_RWseek(src, fp_offset, RW_SEEK_SET);
        }
        SDL_FreeSurface(surface);
        surface = NULL;
    }
    if (freesrc && src) {
        SDL_RWclose(src);
    }
    return (surface);
}
Example #16
0
static void STDMETHODCALLTYPE
VoiceCBOnVoiceError(THIS_ void *data, HRESULT Error)
{
    /* !!! FIXME: attempt to recover, or mark device disconnected. */
    SDL_assert(0 && "write me!");
}
Example #17
0
/* Function to convert Android keyCodes into SDL ones.
 * This code manipulation is done to get a sequential list of codes.
 * FIXME: This is only suited for the case where we use a fixed number of buttons determined by ANDROID_MAX_NBUTTONS
 */
static int
keycode_to_SDL(int keycode)
{
    /* FIXME: If this function gets too unwiedly in the future, replace with a lookup table */
    int button = 0;
    switch(keycode) 
    {
        /* Some gamepad buttons (API 9) */
        case AKEYCODE_BUTTON_A:
            button = SDL_CONTROLLER_BUTTON_A;
            break;
        case AKEYCODE_BUTTON_B:
            button = SDL_CONTROLLER_BUTTON_B;
            break;
        case AKEYCODE_BUTTON_X:
            button = SDL_CONTROLLER_BUTTON_X;
            break;
        case AKEYCODE_BUTTON_Y:
            button = SDL_CONTROLLER_BUTTON_Y;
            break;
        case AKEYCODE_BUTTON_L1:
            button = SDL_CONTROLLER_BUTTON_LEFTSHOULDER;
            break;
        case AKEYCODE_BUTTON_R1:
            button = SDL_CONTROLLER_BUTTON_RIGHTSHOULDER;
            break;
        case AKEYCODE_BUTTON_THUMBL:
            button = SDL_CONTROLLER_BUTTON_LEFTSTICK;
            break;
        case AKEYCODE_BUTTON_THUMBR:
            button = SDL_CONTROLLER_BUTTON_RIGHTSTICK;
            break;
        case AKEYCODE_BUTTON_START:
            button = SDL_CONTROLLER_BUTTON_START;
            break;
        case AKEYCODE_BUTTON_SELECT:
            button = SDL_CONTROLLER_BUTTON_BACK;
            break;
        case AKEYCODE_BUTTON_MODE:
            button = SDL_CONTROLLER_BUTTON_GUIDE;
            break;
        case AKEYCODE_BUTTON_L2:
            button = SDL_CONTROLLER_BUTTON_MAX; /* Not supported by GameController */
            break;
        case AKEYCODE_BUTTON_R2:
            button = SDL_CONTROLLER_BUTTON_MAX+1; /* Not supported by GameController */
            break;
        case AKEYCODE_BUTTON_C:
            button = SDL_CONTROLLER_BUTTON_MAX+2; /* Not supported by GameController */
            break;
        case AKEYCODE_BUTTON_Z:
            button = SDL_CONTROLLER_BUTTON_MAX+3; /* Not supported by GameController */
            break;
                        
        /* D-Pad key codes (API 1) */
        case AKEYCODE_DPAD_UP:
            button = SDL_CONTROLLER_BUTTON_DPAD_UP;
            break;
        case AKEYCODE_DPAD_DOWN:
            button = SDL_CONTROLLER_BUTTON_DPAD_DOWN;
            break;
        case AKEYCODE_DPAD_LEFT:
            button = SDL_CONTROLLER_BUTTON_DPAD_LEFT;
            break;
        case AKEYCODE_DPAD_RIGHT:
            button = SDL_CONTROLLER_BUTTON_DPAD_RIGHT;
            break;
        case AKEYCODE_DPAD_CENTER:
            button = SDL_CONTROLLER_BUTTON_MAX+4; /* Not supported by GameController */
            break;

        /* More gamepad buttons (API 12), these get mapped to 20...35*/
        case AKEYCODE_BUTTON_1:
        case AKEYCODE_BUTTON_2:
        case AKEYCODE_BUTTON_3:
        case AKEYCODE_BUTTON_4:
        case AKEYCODE_BUTTON_5:
        case AKEYCODE_BUTTON_6:
        case AKEYCODE_BUTTON_7:
        case AKEYCODE_BUTTON_8:
        case AKEYCODE_BUTTON_9:
        case AKEYCODE_BUTTON_10:
        case AKEYCODE_BUTTON_11:
        case AKEYCODE_BUTTON_12:
        case AKEYCODE_BUTTON_13:
        case AKEYCODE_BUTTON_14:
        case AKEYCODE_BUTTON_15:
        case AKEYCODE_BUTTON_16:
            button = keycode - AKEYCODE_BUTTON_1 + SDL_CONTROLLER_BUTTON_MAX + 5;
            break;
            
        default:
            return -1;
            break;
    }
    
    /* This is here in case future generations, probably with six fingers per hand, 
     * happily add new cases up above and forget to update the max number of buttons. 
     */
    SDL_assert(button < ANDROID_MAX_NBUTTONS);
    return button;
    
}
/* !
 *  Tests surface conversion across all pixel formats.
 */
int
surface_testCompleteSurfaceConversion(void *arg)
{
    Uint32 pixel_formats[] = {
        SDL_PIXELFORMAT_INDEX8,
        SDL_PIXELFORMAT_RGB332,
        SDL_PIXELFORMAT_RGB444,
        SDL_PIXELFORMAT_RGB555,
        SDL_PIXELFORMAT_BGR555,
        SDL_PIXELFORMAT_ARGB4444,
        SDL_PIXELFORMAT_RGBA4444,
        SDL_PIXELFORMAT_ABGR4444,
        SDL_PIXELFORMAT_BGRA4444,
        SDL_PIXELFORMAT_ARGB1555,
        SDL_PIXELFORMAT_RGBA5551,
        SDL_PIXELFORMAT_ABGR1555,
        SDL_PIXELFORMAT_BGRA5551,
        SDL_PIXELFORMAT_RGB565,
        SDL_PIXELFORMAT_BGR565,
        SDL_PIXELFORMAT_RGB24,
        SDL_PIXELFORMAT_BGR24,
        SDL_PIXELFORMAT_RGB888,
        SDL_PIXELFORMAT_RGBX8888,
        SDL_PIXELFORMAT_BGR888,
        SDL_PIXELFORMAT_BGRX8888,
        SDL_PIXELFORMAT_ARGB8888,
        SDL_PIXELFORMAT_RGBA8888,
        SDL_PIXELFORMAT_ABGR8888,
        SDL_PIXELFORMAT_BGRA8888,
        SDL_PIXELFORMAT_ARGB2101010,
    };
    SDL_Surface *face = NULL, *cvt1, *cvt2, *final;
    SDL_PixelFormat *fmt1, *fmt2;
    int i, j, ret = 0;

    /* Create sample surface */
    face = SDLTest_ImageFace();
    SDLTest_AssertCheck(face != NULL, "Verify face surface is not NULL");
    if (face == NULL)
        return TEST_ABORTED;

    /* Set transparent pixel as the pixel at (0,0) */
    if (face->format->palette) {
       ret = SDL_SetColorKey(face, SDL_RLEACCEL, *(Uint8 *) face->pixels);
       SDLTest_AssertPass("Call to SDL_SetColorKey()");
       SDLTest_AssertCheck(ret == 0, "Verify result from SDL_SetColorKey, expected: 0, got: %i", ret);
    }

    for ( i = 0; i < SDL_arraysize(pixel_formats); ++i ) {
        for ( j = 0; j < SDL_arraysize(pixel_formats); ++j ) {
            fmt1 = SDL_AllocFormat(pixel_formats[i]);
            SDL_assert(fmt1 != NULL);
            cvt1 = SDL_ConvertSurface(face, fmt1, 0);
            SDL_assert(cvt1 != NULL);

            fmt2 = SDL_AllocFormat(pixel_formats[j]);
            SDL_assert(fmt1 != NULL);
            cvt2 = SDL_ConvertSurface(cvt1, fmt2, 0);
            SDL_assert(cvt2 != NULL);

            if ( fmt1->BytesPerPixel == face->format->BytesPerPixel &&
                 fmt2->BytesPerPixel == face->format->BytesPerPixel &&
                 (fmt1->Amask != 0) == (face->format->Amask != 0) &&
                 (fmt2->Amask != 0) == (face->format->Amask != 0) ) {
                final = SDL_ConvertSurface( cvt2, face->format, 0 );
                SDL_assert(final != NULL);

                /* Compare surface. */
                ret = SDLTest_CompareSurfaces( face, final, 0 );
                SDLTest_AssertCheck(ret == 0, "Validate result from SDLTest_CompareSurfaces, expected: 0, got: %i", ret);
                SDL_FreeSurface(final);
            }

            SDL_FreeSurface(cvt1);
            SDL_FreeFormat(fmt1);
            SDL_FreeSurface(cvt2);
            SDL_FreeFormat(fmt2);
        }
    }
Example #19
0
static SDL_Cursor *
WIN_CreateSystemCursor(SDL_SystemCursor id)
{
    SDL_Cursor *cursor;
    LPCTSTR name;

    switch(id)
    {
    default:
        SDL_assert(0);
        return NULL;
    case SDL_SYSTEM_CURSOR_ARROW:
        name = IDC_ARROW;
        break;
    case SDL_SYSTEM_CURSOR_IBEAM:
        name = IDC_IBEAM;
        break;
    case SDL_SYSTEM_CURSOR_WAIT:
        name = IDC_WAIT;
        break;
    case SDL_SYSTEM_CURSOR_CROSSHAIR:
        name = IDC_CROSS;
        break;
    case SDL_SYSTEM_CURSOR_WAITARROW:
        name = IDC_WAIT;
        break;
    case SDL_SYSTEM_CURSOR_SIZENWSE:
        name = IDC_SIZENWSE;
        break;
    case SDL_SYSTEM_CURSOR_SIZENESW:
        name = IDC_SIZENESW;
        break;
    case SDL_SYSTEM_CURSOR_SIZEWE:
        name = IDC_SIZEWE;
        break;
    case SDL_SYSTEM_CURSOR_SIZENS:
        name = IDC_SIZENS;
        break;
    case SDL_SYSTEM_CURSOR_SIZEALL:
        name = IDC_SIZEALL;
        break;
    case SDL_SYSTEM_CURSOR_NO:
        name = IDC_NO;
        break;
    case SDL_SYSTEM_CURSOR_HAND:
        name = IDC_HAND;
        break;
    }

    cursor = SDL_calloc(1, sizeof(*cursor));
    if (cursor) {
        HICON hicon;

        hicon = LoadCursor(NULL, name);

        cursor->driverdata = hicon;
    } else {
        SDL_OutOfMemory();
    }

    return cursor;
}
Example #20
0
	void Receive( void ) {
		SDL_assert( peer );

		RakNet::Packet *packet = nullptr;
		while ( (packet = peer->Receive()) ) {
			if ( net_debug->GetUInt32() & 0x2u ) {
				console.Print( PrintLevel::Normal, "Receive: %i (%i)\n",
					packet->data[0],
					ID_USER_PACKET_ENUM
				);
			}

			switch ( packet->data[0] ) {

			case ID_REMOTE_DISCONNECTION_NOTIFICATION: {
				// another client has disconnected gracefully
				console.Print( PrintLevel::Normal, "another client disconnected\n" );
				//TODO: grab meaningful info
			} break;

			case ID_CONNECTION_ATTEMPT_FAILED: {
				// connection attempt failed
				console.Print( PrintLevel::Normal, "error: connection attempt failed (%s)\n",
					packet->systemAddress.ToString()
				);
			} break;

			case ID_REMOTE_CONNECTION_LOST: {
				// another client has lost connection
				console.Print( PrintLevel::Normal, "another client lost connection\n" );
				//TODO: grab meaningful info
			} break;

			case ID_NEW_INCOMING_CONNECTION: {
				// another client has connected
				if ( isServer ) {
					const GUID guid = packet->guid.g;
					console.Print( PrintLevel::Normal, "client connecting with IP %s and GUID %" PRIX64 "\n",
						packet->systemAddress.ToString(),
						guid
					);
					Server::IncomingConnection( Connection::Get( guid ) );
				}
				else {
					SDL_assert( !"unexpected connection as client" );
				}
			} break;

			case ID_REMOTE_NEW_INCOMING_CONNECTION: {
				// another client has connected
				console.Print( PrintLevel::Normal, "client connecting with IP %s and GUID %s\n",
					packet->systemAddress.ToString(),
					packet->guid.ToString()
				);
			} break;

			case ID_ALREADY_CONNECTED: {
				// a client with our GUID is already connected, wait for timeout because we probably disconnected
				//	ungracefully
				//TODO: filter for server/client?
				console.Print( PrintLevel::Normal, "error: already connected, wait for timeout\n" );
				connected = false;
			} break;

			case ID_CONNECTION_REQUEST_ACCEPTED: {
				// out connection request has been accepted
				console.Print( PrintLevel::Developer, "connection accepted\n" );
				connected = true;
				if ( !isServer ) {
					const GUID guid = packet->guid.g;
					Client::Connect( Connection::Get( guid ) );
				}
			} break;

			case ID_NO_FREE_INCOMING_CONNECTIONS: {
				// the server is full
				console.Print( PrintLevel::Normal, "error: server is full\n" );
				connected = false;
			} break;

			case ID_DISCONNECTION_NOTIFICATION: {
				const GUID guid = packet->guid.g;
				// we have been disconnected
				if ( isServer ) {
					console.Print( PrintLevel::Normal, "client disconnected (%s)\n",
						packet->systemAddress.ToString()
					);
					Server::DropClient( guid );
					connections.erase( guid );
				}
				else {
					console.Print( PrintLevel::Normal, "disconnected from server (%s)\n",
						packet->systemAddress.ToString()
					);
					Client::Disconnect( guid );
					Disconnect();
				}
			} break;

			case ID_CONNECTION_LOST: {
				// our connection was lost
				console.Print( PrintLevel::Normal, "error: connection lost\n" );
				connected = false;
			} break;

			default: {
				if ( isServer ) {
					if ( Server::ReceivePacket( packet ) ) {
						return;
					}
				}
				else {
					if ( Client::ReceivePacket( packet ) ) {
						return;
					}
				}

				console.Print( PrintLevel::Developer, "Unknown message from %s (ID: %i, base: %i)\n",
					packet->systemAddress.ToString(),
					packet->data[0],
					ID_USER_PACKET_ENUM
				);
			} break;

			}

			peer->DeallocatePacket( packet );
		}
	}
Example #21
0
void Texture::RenderStretch(Renderer& renderer, SDL_Rect* pDestRect /*= nullptr*/, SDL_Rect* pClipRect /*= nullptr*/)
{
	SDL_assert(renderer.GetRenderPtr() && m_pTexture);
	
	SDL_RenderCopyEx(renderer.GetRenderPtr(), m_pTexture, pClipRect, pDestRect, 0.0, nullptr, SDL_FLIP_NONE);
}
Example #22
0
static int
SW_RunCommandQueue(SDL_Renderer * renderer, SDL_RenderCommand *cmd, void *vertices, size_t vertsize)
{
    SW_RenderData *data = (SW_RenderData *) renderer->driverdata;
    SDL_Surface *surface = SW_ActivateRenderer(renderer);
    const SDL_Rect *viewport = NULL;
    const SDL_Rect *cliprect = NULL;

    if (!surface) {
        return -1;
    }

    while (cmd) {
        switch (cmd->command) {
            case SDL_RENDERCMD_SETDRAWCOLOR: {
                break;  /* Not used in this backend. */
            }

            case SDL_RENDERCMD_SETVIEWPORT: {
                viewport = &cmd->data.viewport.rect;
                SDL_SetClipRect(data->surface, viewport);
                break;
            }

            case SDL_RENDERCMD_SETCLIPRECT: {
                SDL_assert(viewport != NULL);
                cliprect = cmd->data.cliprect.enabled ? &cmd->data.cliprect.rect : NULL;
                if (cliprect) {
                    SDL_Rect clip_rect;
                    clip_rect.x = cliprect->x + viewport->x;
                    clip_rect.y = cliprect->y + viewport->y;
                    clip_rect.w = cliprect->w;
                    clip_rect.h = cliprect->h;
                    SDL_IntersectRect(viewport, &clip_rect, &clip_rect);
                    SDL_SetClipRect(surface, &clip_rect);
                } else {
                    SDL_SetClipRect(surface, viewport);
                }
                break;
            }

            case SDL_RENDERCMD_CLEAR: {
                const Uint8 r = cmd->data.color.r;
                const Uint8 g = cmd->data.color.g;
                const Uint8 b = cmd->data.color.b;
                const Uint8 a = cmd->data.color.a;
                const SDL_Rect clip_rect = surface->clip_rect;
                /* By definition the clear ignores the clip rect */
                SDL_SetClipRect(surface, NULL);
                SDL_FillRect(surface, NULL, SDL_MapRGBA(surface->format, r, g, b, a));
                SDL_SetClipRect(surface, &clip_rect);
                break;
            }

            case SDL_RENDERCMD_DRAW_POINTS: {
                const Uint8 r = cmd->data.draw.r;
                const Uint8 g = cmd->data.draw.g;
                const Uint8 b = cmd->data.draw.b;
                const Uint8 a = cmd->data.draw.a;
                const int count = (int) cmd->data.draw.count;
                const SDL_Point *verts = (SDL_Point *) (((Uint8 *) vertices) + cmd->data.draw.first);
                const SDL_BlendMode blend = cmd->data.draw.blend;
                if (blend == SDL_BLENDMODE_NONE) {
                    SDL_DrawPoints(surface, verts, count, SDL_MapRGBA(surface->format, r, g, b, a));
                } else {
                    SDL_BlendPoints(surface, verts, count, blend, r, g, b, a);
                }
                break;
            }

            case SDL_RENDERCMD_DRAW_LINES: {
                const Uint8 r = cmd->data.draw.r;
                const Uint8 g = cmd->data.draw.g;
                const Uint8 b = cmd->data.draw.b;
                const Uint8 a = cmd->data.draw.a;
                const int count = (int) cmd->data.draw.count;
                const SDL_Point *verts = (SDL_Point *) (((Uint8 *) vertices) + cmd->data.draw.first);
                const SDL_BlendMode blend = cmd->data.draw.blend;
                if (blend == SDL_BLENDMODE_NONE) {
                    SDL_DrawLines(surface, verts, count, SDL_MapRGBA(surface->format, r, g, b, a));
                } else {
                    SDL_BlendLines(surface, verts, count, blend, r, g, b, a);
                }
                break;
            }

            case SDL_RENDERCMD_FILL_RECTS: {
                const Uint8 r = cmd->data.draw.r;
                const Uint8 g = cmd->data.draw.g;
                const Uint8 b = cmd->data.draw.b;
                const Uint8 a = cmd->data.draw.a;
                const int count = (int) cmd->data.draw.count;
                const SDL_Rect *verts = (SDL_Rect *) (((Uint8 *) vertices) + cmd->data.draw.first);
                const SDL_BlendMode blend = cmd->data.draw.blend;
                if (blend == SDL_BLENDMODE_NONE) {
                    SDL_FillRects(surface, verts, count, SDL_MapRGBA(surface->format, r, g, b, a));
                } else {
                    SDL_BlendFillRects(surface, verts, count, blend, r, g, b, a);
                }
                break;
            }

            case SDL_RENDERCMD_COPY: {
                SDL_Rect *verts = (SDL_Rect *) (((Uint8 *) vertices) + cmd->data.draw.first);
                const SDL_Rect *srcrect = verts;
                SDL_Rect *dstrect = verts + 1;
                SDL_Texture *texture = cmd->data.draw.texture;
                SDL_Surface *src = (SDL_Surface *) texture->driverdata;

                PrepTextureForCopy(cmd);

                if ( srcrect->w == dstrect->w && srcrect->h == dstrect->h ) {
                    SDL_BlitSurface(src, srcrect, surface, dstrect);
                } else {
                    /* If scaling is ever done, permanently disable RLE (which doesn't support scaling)
                     * to avoid potentially frequent RLE encoding/decoding.
                     */
                    SDL_SetSurfaceRLE(surface, 0);
                    SDL_BlitScaled(src, srcrect, surface, dstrect);
                }
                break;
            }

            case SDL_RENDERCMD_COPY_EX: {
                const CopyExData *copydata = (CopyExData *) (((Uint8 *) vertices) + cmd->data.draw.first);
                PrepTextureForCopy(cmd);
                SW_RenderCopyEx(renderer, surface, cmd->data.draw.texture, &copydata->srcrect,
                                &copydata->dstrect, copydata->angle, &copydata->center, copydata->flip);
                break;
            }

            case SDL_RENDERCMD_NO_OP:
                break;
        }

        cmd = cmd->next;
    }

    return 0;
}
Example #23
0
/* glXChooseVisual and glXChooseFBConfig have some small differences in
 * the attribute encoding, it can be chosen with the for_FBConfig parameter.
 */
int
X11_GL_GetAttributes(_THIS, Display * display, int screen, int * attribs, int size, Bool for_FBConfig)
{
    int i = 0;
    const int MAX_ATTRIBUTES = 64;

    /* assert buffer is large enough to hold all SDL attributes. */
    SDL_assert(size >= MAX_ATTRIBUTES);

    /* Setup our GLX attributes according to the gl_config. */
    if( for_FBConfig ) {
        attribs[i++] = GLX_RENDER_TYPE;
        attribs[i++] = GLX_RGBA_BIT;
    } else {
        attribs[i++] = GLX_RGBA;
    }
    attribs[i++] = GLX_RED_SIZE;
    attribs[i++] = _this->gl_config.red_size;
    attribs[i++] = GLX_GREEN_SIZE;
    attribs[i++] = _this->gl_config.green_size;
    attribs[i++] = GLX_BLUE_SIZE;
    attribs[i++] = _this->gl_config.blue_size;

    if (_this->gl_config.alpha_size) {
        attribs[i++] = GLX_ALPHA_SIZE;
        attribs[i++] = _this->gl_config.alpha_size;
    }

    if (_this->gl_config.double_buffer) {
        attribs[i++] = GLX_DOUBLEBUFFER;
        if( for_FBConfig ) {
            attribs[i++] = True;
        }
    }

    attribs[i++] = GLX_DEPTH_SIZE;
    attribs[i++] = _this->gl_config.depth_size;

    if (_this->gl_config.stencil_size) {
        attribs[i++] = GLX_STENCIL_SIZE;
        attribs[i++] = _this->gl_config.stencil_size;
    }

    if (_this->gl_config.accum_red_size) {
        attribs[i++] = GLX_ACCUM_RED_SIZE;
        attribs[i++] = _this->gl_config.accum_red_size;
    }

    if (_this->gl_config.accum_green_size) {
        attribs[i++] = GLX_ACCUM_GREEN_SIZE;
        attribs[i++] = _this->gl_config.accum_green_size;
    }

    if (_this->gl_config.accum_blue_size) {
        attribs[i++] = GLX_ACCUM_BLUE_SIZE;
        attribs[i++] = _this->gl_config.accum_blue_size;
    }

    if (_this->gl_config.accum_alpha_size) {
        attribs[i++] = GLX_ACCUM_ALPHA_SIZE;
        attribs[i++] = _this->gl_config.accum_alpha_size;
    }

    if (_this->gl_config.stereo) {
        attribs[i++] = GLX_STEREO;
        if( for_FBConfig ) {
            attribs[i++] = True;
        }
    }

    if (_this->gl_config.multisamplebuffers) {
        attribs[i++] = GLX_SAMPLE_BUFFERS_ARB;
        attribs[i++] = _this->gl_config.multisamplebuffers;
    }

    if (_this->gl_config.multisamplesamples) {
        attribs[i++] = GLX_SAMPLES_ARB;
        attribs[i++] = _this->gl_config.multisamplesamples;
    }

    if (_this->gl_config.accelerated >= 0 &&
            _this->gl_data->HAS_GLX_EXT_visual_rating) {
        attribs[i++] = GLX_VISUAL_CAVEAT_EXT;
        attribs[i++] = _this->gl_config.accelerated ? GLX_NONE_EXT :
                       GLX_SLOW_VISUAL_EXT;
    }

    /* If we're supposed to use DirectColor visuals, and we've got the
       EXT_visual_info extension, then add GLX_X_VISUAL_TYPE_EXT. */
    if (X11_UseDirectColorVisuals() &&
            _this->gl_data->HAS_GLX_EXT_visual_info) {
        attribs[i++] = GLX_X_VISUAL_TYPE_EXT;
        attribs[i++] = GLX_DIRECT_COLOR_EXT;
    }

    attribs[i++] = None;

    SDL_assert(i <= MAX_ATTRIBUTES);

    return i;
}
Example #24
0
void Entity::AddComponent(ComponentType type, std::unique_ptr<Component> c)
{
    SDL_assert(type != ComponentType::None);
    c->RegisterEventHandler(this);
    mComponents[type] = std::move(c);
}
Example #25
0
static SDL_Cursor *
WIN_CreateCursor(SDL_Surface * surface, int hot_x, int hot_y)
{
    /* msdn says cursor mask has to be padded out to word alignment. Not sure
        if that means machine word or WORD, but this handles either case. */
    const size_t pad = (sizeof (size_t) * 8);  /* 32 or 64, or whatever. */
    SDL_Cursor *cursor;
    HICON hicon;
    HDC hdc;
    BITMAPV4HEADER bmh;
    LPVOID pixels;
    LPVOID maskbits;
    size_t maskbitslen;
    ICONINFO ii;

    SDL_zero(bmh);
    bmh.bV4Size = sizeof(bmh);
    bmh.bV4Width = surface->w;
    bmh.bV4Height = -surface->h; /* Invert the image */
    bmh.bV4Planes = 1;
    bmh.bV4BitCount = 32;
    bmh.bV4V4Compression = BI_BITFIELDS;
    bmh.bV4AlphaMask = 0xFF000000;
    bmh.bV4RedMask   = 0x00FF0000;
    bmh.bV4GreenMask = 0x0000FF00;
    bmh.bV4BlueMask  = 0x000000FF;

    maskbitslen = ((surface->w + (pad - (surface->w % pad))) / 8) * surface->h;
    maskbits = SDL_stack_alloc(Uint8,maskbitslen);
    if (maskbits == NULL) {
        SDL_OutOfMemory();
        return NULL;
    }

    /* AND the cursor against full bits: no change. We already have alpha. */
    SDL_memset(maskbits, 0xFF, maskbitslen);

    hdc = GetDC(NULL);
    SDL_zero(ii);
    ii.fIcon = FALSE;
    ii.xHotspot = (DWORD)hot_x;
    ii.yHotspot = (DWORD)hot_y;
    ii.hbmColor = CreateDIBSection(hdc, (BITMAPINFO*)&bmh, DIB_RGB_COLORS, &pixels, NULL, 0);
    ii.hbmMask = CreateBitmap(surface->w, surface->h, 1, 1, maskbits);
    ReleaseDC(NULL, hdc);
    SDL_stack_free(maskbits);

    SDL_assert(surface->format->format == SDL_PIXELFORMAT_ARGB8888);
    SDL_assert(surface->pitch == surface->w * 4);
    SDL_memcpy(pixels, surface->pixels, surface->h * surface->pitch);

    hicon = CreateIconIndirect(&ii);

    DeleteObject(ii.hbmColor);
    DeleteObject(ii.hbmMask);

    if (!hicon) {
        WIN_SetError("CreateIconIndirect()");
        return NULL;
    }

    cursor = SDL_calloc(1, sizeof(*cursor));
    if (cursor) {
        cursor->driverdata = hicon;
    } else {
        DestroyIcon(hicon);
        SDL_OutOfMemory();
    }

    return cursor;
}
Example #26
0
void Entity::RegisterCallback(EventType type, std::function<void(Event *)> callback)
{
	SDL_assert(type != EventType::None);
	mEventCallbacks[type].push_back(callback);
}
Example #27
0
/*
	Possible ways to call render_texture from Lua:

	render_texture(ud)
	render_texture(ud, dst_x, dst_y) 
	render_texture(ud, dst_x, dst_y, dst_w, dst_h) 
	render_texture(ud, src_x, src_y, src_w, src_h, dst_x, dst_y) 
	render_texture(ud, src_x, src_y, src_w, src_h, dst_x, dst_y, dst_w, dst_h) 
*/
static int render_texture(lua_State * L) {
	int numargs;
	SDL_Texture ** ud;
	SDL_Texture * texture;
	SDL_Rect src;
	SDL_Rect dst;

	if (!drawing) return 0;

	// Check arguments.
	numargs = lua_gettop(L);
	if (numargs != 1 && numargs != 3 && numargs != 5 && numargs != 7 && numargs != 9) {
		luaL_error(L, "render_texture called with wrong number of arguments");
	}
	if (lua_type(L, 1) != LUA_TUSERDATA) {
		luaL_error(L, "First argument to render_texture not userdata.");
	}
	
	// Extract userdata argument.
	ud = (SDL_Texture **) lua_touserdata(L, 1);
	if (!ud) {
		luaL_error(L, "Userdata pointer unexpectedly null.");
	}
	texture = *ud;
	if (texture == NULL) {
		luaL_error(L, "Null texture passed to render_texture");
	}

	// Extract rectangle arguments and do it.
	if (numargs == 1) {
	        SDL_RenderCopy(renderer, texture, NULL, NULL);
	} else if (numargs == 3) {
	        dst.x = luaL_checknumber(L, 2);
	        dst.y = luaL_checknumber(L, 3);
		SDL_QueryTexture(texture, NULL, NULL, &dst.w, &dst.h);
	        SDL_RenderCopy(renderer, texture, NULL, &dst);
	} else if (numargs == 5) {
	        dst.x = luaL_checknumber(L, 2);
	        dst.y = luaL_checknumber(L, 3);
		dst.w = luaL_checknumber(L, 4);
		dst.h = luaL_checknumber(L, 5);
	        SDL_RenderCopy(renderer, texture, NULL, &dst);
	} else if (numargs == 7) {
		src.x = luaL_checknumber(L, 2);
		src.y = luaL_checknumber(L, 3);
		src.w = luaL_checknumber(L, 4);
		src.h = luaL_checknumber(L, 5);
		dst.x = luaL_checknumber(L, 6);
		dst.y = luaL_checknumber(L, 7);
		dst.w = src.w;
		dst.h = src.h;
		SDL_RenderCopy(renderer, texture, &src, &dst);
	} else if (numargs == 9) {
		src.x = luaL_checknumber(L, 2);
		src.y = luaL_checknumber(L, 3);
		src.w = luaL_checknumber(L, 4);
		src.h = luaL_checknumber(L, 5);
		dst.x = luaL_checknumber(L, 6);
		dst.y = luaL_checknumber(L, 7);
		dst.w = luaL_checknumber(L, 8);
		dst.h = luaL_checknumber(L, 9);
		SDL_RenderCopy(renderer, texture, &src, &dst);
	} else {
		SDL_assert(false);
	}
	return 0;
}
Example #28
0
static Cursor
X11_CreatePixmapCursor(SDL_Surface * surface, int hot_x, int hot_y)
{
    Display *display = GetDisplay();
    XColor fg, bg;
    Cursor cursor = None;
    Uint32 *ptr;
    Uint8 *data_bits, *mask_bits;
    Pixmap data_pixmap, mask_pixmap;
    int x, y;
    unsigned int rfg, gfg, bfg, rbg, gbg, bbg, fgBits, bgBits;
    unsigned int width_bytes = ((surface->w + 7) & ~7) / 8;

    data_bits = SDL_calloc(1, surface->h * width_bytes);
    mask_bits = SDL_calloc(1, surface->h * width_bytes);
    if (!data_bits || !mask_bits) {
        SDL_OutOfMemory();
        return None;
    }

    /* Code below assumes ARGB pixel format */
    SDL_assert(surface->format->format == SDL_PIXELFORMAT_ARGB8888);

    rfg = gfg = bfg = rbg = gbg = bbg = fgBits = bgBits = 0;
    for (y = 0; y < surface->h; ++y) {
        ptr = (Uint32 *)((Uint8 *)surface->pixels + y * surface->pitch);
        for (x = 0; x < surface->w; ++x) {
            int alpha = (*ptr >> 24) & 0xff;
            int red   = (*ptr >> 16) & 0xff;
            int green = (*ptr >> 8) & 0xff;
            int blue  = (*ptr >> 0) & 0xff;
            if (alpha > 25) {
                mask_bits[y * width_bytes + x / 8] |= (0x01 << (x % 8));

                if ((red + green + blue) > 0x40) {
                    fgBits++;
                    rfg += red;
                    gfg += green;
                    bfg += blue;
                    data_bits[y * width_bytes + x / 8] |= (0x01 << (x % 8));
                } else {
                    bgBits++;
                    rbg += red;
                    gbg += green;
                    bbg += blue;
                }
            }
            ++ptr;
        }
    }

    if (fgBits) {
        fg.red   = rfg * 257 / fgBits;
        fg.green = gfg * 257 / fgBits;
        fg.blue  = bfg * 257 / fgBits;
    }
    else fg.red = fg.green = fg.blue = 0;

    if (bgBits) {
        bg.red   = rbg * 257 / bgBits;
        bg.green = gbg * 257 / bgBits;
        bg.blue  = bbg * 257 / bgBits;
    }
    else bg.red = bg.green = bg.blue = 0;

    data_pixmap = XCreateBitmapFromData(display, DefaultRootWindow(display),
                                        (char*)data_bits,
                                        surface->w, surface->h);
    mask_pixmap = XCreateBitmapFromData(display, DefaultRootWindow(display),
                                        (char*)mask_bits,
                                        surface->w, surface->h);
    cursor = XCreatePixmapCursor(display, data_pixmap, mask_pixmap,
                                 &fg, &bg, hot_x, hot_y);
	XFreePixmap(display, data_pixmap);
	XFreePixmap(display, mask_pixmap);

    return cursor;
}
int
SDL_XINPUT_HapticNewEffect(SDL_Haptic * haptic, struct haptic_effect *effect, SDL_HapticEffect * base)
{
    SDL_assert(base->type == SDL_HAPTIC_LEFTRIGHT);  /* should catch this at higher level */
    return SDL_XINPUT_HapticUpdateEffect(haptic, effect, base);
}
Example #30
0
	inline std::size_t write(const void * src, std::size_t object_count,
							 std::size_t object_size = 1) {
		SDL_assert(nullptr != ops);
		return ops->write(ops, src, object_count, object_size);
	}