Esempio n. 1
0
GUI_Font::~GUI_Font()
{
  if (freefont)
    SDL_FreeSurface(fontStore);
}
Esempio n. 2
0
static void sdl2_init_font(sdl2_video_t *vid, const char *font_path,
                          unsigned font_size)
{
   if (!g_settings.video.font_enable)
      return;

   if (font_renderer_create_default(&vid->font_driver, &vid->font_data,
                                    *font_path ? font_path : NULL, font_size))
   {
         int r = g_settings.video.msg_color_r * 255;
         int g = g_settings.video.msg_color_g * 255;
         int b = g_settings.video.msg_color_b * 255;

         r = r < 0 ? 0 : (r > 255 ? 255 : r);
         g = g < 0 ? 0 : (g > 255 ? 255 : g);
         b = b < 0 ? 0 : (b > 255 ? 255 : b);

         vid->font_r = r;
         vid->font_g = g;
         vid->font_b = b;
   }
   else
   {
      RARCH_WARN("[SDL]: Could not initialize fonts.\n");
      return;
   }

   const struct font_atlas *atlas = vid->font_driver->get_atlas(vid->font_data);

   SDL_Surface *tmp = SDL_CreateRGBSurfaceFrom(atlas->buffer, atlas->width,
                                               atlas->height, 8, atlas->width,
                                               0, 0, 0, 0);
   SDL_Color colors[256];
   int i;

   for (i = 0; i < 256; ++i)
   {
      colors[i].r = colors[i].g = colors[i].b = i;
      colors[i].a = 255;
   }

   SDL_Palette *pal = SDL_AllocPalette(256);
   SDL_SetPaletteColors(pal, colors, 0, 256);
   SDL_SetSurfacePalette(tmp, pal);
   SDL_SetColorKey(tmp, SDL_TRUE, 0);

   vid->font.tex  = SDL_CreateTextureFromSurface(vid->renderer, tmp);

   if (vid->font.tex)
   {
      vid->font.w      = atlas->width;
      vid->font.h      = atlas->height;
      vid->font.active = true;

      SDL_SetTextureBlendMode(vid->font.tex, SDL_BLENDMODE_ADD);
   }
   else
      RARCH_WARN("[SDL]: Failed to initialize font texture: %s\n", SDL_GetError());

   SDL_FreePalette(pal);
   SDL_FreeSurface(tmp);
}
Esempio n. 3
0
/**
 * @brief Prepares the surface to be loaded as a texture.
 *
 *    @param surface to load that is freed in the process.
 *    @return New surface that is prepared for texture loading.
 */
SDL_Surface* gl_prepareSurface( SDL_Surface* surface )
{
   SDL_Surface* temp;
   int potw, poth;
   SDL_Rect rtemp;
#if ! SDL_VERSION_ATLEAST(1,3,0)
   Uint32 saved_flags;
#endif /* ! SDL_VERSION_ATLEAST(1,3,0) */

   /* Make size power of two. */
   potw = gl_pot(surface->w);
   poth = gl_pot(surface->h);
   if (gl_needPOT() && ((potw != surface->w) || (poth != surface->h))) {

      /* we must blit with an SDL_Rect */
      rtemp.x = rtemp.y = 0;
      rtemp.w = surface->w;
      rtemp.h = surface->h;

      /* saves alpha */
#if SDL_VERSION_ATLEAST(1,3,0)
      SDL_SetSurfaceBlendMode(surface, SDL_BLENDMODE_NONE);

      /* create the temp POT surface */
      temp = SDL_CreateRGBSurface( 0, potw, poth,
            surface->format->BytesPerPixel*8, RGBAMASK );
#else /* SDL_VERSION_ATLEAST(1,3,0) */
      saved_flags = surface->flags & (SDL_SRCALPHA | SDL_RLEACCELOK);
      if ((saved_flags & SDL_SRCALPHA) == SDL_SRCALPHA) {
         SDL_SetAlpha( surface, 0, SDL_ALPHA_OPAQUE );
         SDL_SetColorKey( surface, 0, surface->format->colorkey );
      }

      /* create the temp POT surface */
      temp = SDL_CreateRGBSurface( SDL_SRCCOLORKEY,
            potw, poth, surface->format->BytesPerPixel*8, RGBAMASK );
#endif /* SDL_VERSION_ATLEAST(1,3,0) */

      if (temp == NULL) {
         WARN("Unable to create POT surface: %s", SDL_GetError());
         return 0;
      }
      if (SDL_FillRect( temp, NULL,
               SDL_MapRGBA(surface->format,0,0,0,SDL_ALPHA_TRANSPARENT))) {
         WARN("Unable to fill rect: %s", SDL_GetError());
         return 0;
      }

      /* change the surface to the new blitted one */
      SDL_BlitSurface( surface, &rtemp, temp, &rtemp);
      SDL_FreeSurface( surface );
      surface = temp;

#if ! SDL_VERSION_ATLEAST(1,3,0)
      /* set saved alpha */
      if ( (saved_flags & SDL_SRCALPHA) == SDL_SRCALPHA )
         SDL_SetAlpha( surface, 0, 0 );
#endif /* ! SDL_VERSION_ATLEAST(1,3,0) */
   }

   return surface;
}
Esempio n. 4
0
void SDL::freeImage(SDL_Surface* image)
{
    if (image) SDL_FreeSurface(image);
}
Esempio n. 5
0
int main( int argc, char* args[] )
{
//SDL
    //Initialize all SDL subsystems
    if( SDL_Init( SDL_INIT_EVERYTHING ) == -1 )
    {
        return 1;
    }

    //Set up the screen
    screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE );

    //If there was an error in setting up the screen
    if( screen == NULL )
    {
        return 1;
    }

    //Set the window caption
    SDL_WM_SetCaption( "Hello World", NULL );

    //Load the images
    message = load_image( "data/hello.bmp" );
    background = load_image( "data/background.bmp" );
	sphere = load_image("data/Circle.bmp");

    
//SDL

//Physics
//=> World Creation
	// Specify the dynamic AABB tree broadphase algorithm to be used to work out what objects
	// to test collision for.
	btBroadphaseInterface* broadphase = new btDbvtBroadphase();

	// The collision configuration allows you to fine tune the algorithms used
	// for the full (not broadphase) collision detection. Here be dragons!
	btDefaultCollisionConfiguration* collisionConfiguration =
		new btDefaultCollisionConfiguration();

	btCollisionDispatcher* dispatcher =
		new btCollisionDispatcher(collisionConfiguration);

	// We also need a "solver". This is what causes the objects to interact
	// properly, taking into account gravity, game logic supplied forces,
	// collisions, and hinge constraints. It does a good job as long as you
	// don't push it to extremes, and is one of the bottlenecks in any high
	// performance simulation. There are parallel versions available for some
	// threading models.
	btSequentialImpulseConstraintSolver* solver =
		new btSequentialImpulseConstraintSolver;

	// Now, we can finally instantiate the dynamics world.
	btDiscreteDynamicsWorld* dynamicsWorld =
		new btDiscreteDynamicsWorld(dispatcher, broadphase, solver,
		collisionConfiguration);

	// Set the gravity. We have chosen the Y axis to be "up".
	dynamicsWorld->setGravity(btVector3(0, -10, 0));
//=> World Creation
//=> Ground Creation

	// In this demonstration, we will place a ground plane running through
	// the origin.
	btCollisionShape* groundShape = new btStaticPlaneShape(
		btVector3(0, 1, 0), 1);

	// Instantiate the ground. Its orientation is the identity, Bullet quaternions
	// are specified in x,y,z,w form. The position is 1 metre below the ground,
	// which compensates the 1m offset we had to put into the shape itself.
	btDefaultMotionState* groundMotionState = new btDefaultMotionState(
		btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, -1, 0)));

	// The first and last parameters of the following constructor are the mass and
	// inertia of the ground. Since the ground is static, we represent this by
	// filling these values with zeros. Bullet considers passing a mass of zero
	// equivalent to making a body with infinite mass - it is immovable.
	btRigidBody::btRigidBodyConstructionInfo
		groundRigidBodyCI(0, groundMotionState, groundShape, btVector3(0, 0, 0));

	btRigidBody* groundRigidBody = new btRigidBody(groundRigidBodyCI);

//=> Ground Creation
//=> Sphere Creation
	// The shape that we will let fall from the sky is a sphere with a radius
	// of 1 metre. 
	btCollisionShape* fallShape = new btSphereShape(1);

	// Adding the falling sphere is very similar. We will place it 50m above the
	// ground.
	btDefaultMotionState* fallMotionState =
		new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1),
		btVector3(0, 50, 0)));

	// Since it's dynamic we will give it a mass of 1kg. I can't remember how to
	// calculate the inertia of a sphere, but that doesn't matter because Bullet
	// provides a utility function.
	btScalar mass = 1;
	btVector3 fallInertia(0, 0, 0);
	fallShape->calculateLocalInertia(mass, fallInertia);

	// Construct the rigid body just like before, and add it to the world.
	btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass,
		fallMotionState, fallShape, fallInertia);

	btRigidBody* fallRigidBody = new btRigidBody(fallRigidBodyCI);
	
//=> Sphere Creation

	// Add the ground and sphere to the world.
	dynamicsWorld->addRigidBody(fallRigidBody);

	dynamicsWorld->addRigidBody(groundRigidBody);
//Physics
	bool go = true;
	while (go){
		SDL_Event incomingEvent;

		while (SDL_PollEvent(&incomingEvent))
		{

			switch (incomingEvent.type)
			{
			case SDL_QUIT:

				go = false;
				break;
			}
		}
		//Logic
		//Physics
		dynamicsWorld->stepSimulation(1 / 60.f, 10);

		btTransform trans;
		fallRigidBody->getMotionState()->getWorldTransform(trans);

		//std::cout << "sphere height: " << trans.getOrigin().getY() << std::endl;
		//Physics
		//SDL
			//Clear screen
			SDL_FillRect(screen, NULL, 0x000000);
			//Apply the background to the screen
			apply_surface(0, 0, background, screen);
			apply_surface(320, 0, background, screen);
			apply_surface(0, 240, background, screen);
			apply_surface(320, 240, background, screen);

			//Apply the message to the screen
			//apply_surface(180, 140, message, screen);

			apply_surface(50, -(trans.getOrigin().getY()), sphere, screen);
			//apply_surface(50, 50, sphere, screen);
			std::cout << "X: " << trans.getOrigin().getX() << " Y: " << trans.getOrigin().getY() << std::endl;
		//SDL
		//Update 
		SDL_Flip(screen);
		//Wait 2 seconds
	 SDL_Delay( 50 );
	}
    
    

    //Free the surfaces
    SDL_FreeSurface( message );
    SDL_FreeSurface( background );

    //Quit SDL
    SDL_Quit();

    return 0;
}
Esempio n. 6
0
SDL_bool
CommonInit(CommonState * state)
{
    int i, j, m, n;
    SDL_DisplayMode fullscreen_mode;

    if (state->flags & SDL_INIT_VIDEO) {
        if (state->verbose & VERBOSE_VIDEO) {
            n = SDL_GetNumVideoDrivers();
            if (n == 0) {
                fprintf(stderr, "No built-in video drivers\n");
            } else {
                fprintf(stderr, "Built-in video drivers:");
                for (i = 0; i < n; ++i) {
                    if (i > 0) {
                        fprintf(stderr, ",");
                    }
                    fprintf(stderr, " %s", SDL_GetVideoDriver(i));
                }
                fprintf(stderr, "\n");
            }
        }
        if (SDL_VideoInit(state->videodriver, 0) < 0) {
            fprintf(stderr, "Couldn't initialize video driver: %s\n",
                    SDL_GetError());
            return SDL_FALSE;
        }
        if (state->verbose & VERBOSE_VIDEO) {
            fprintf(stderr, "Video driver: %s\n",
                    SDL_GetCurrentVideoDriver());
        }

        /* Upload GL settings */
        SDL_GL_SetAttribute(SDL_GL_RED_SIZE, state->gl_red_size);
        SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, state->gl_green_size);
        SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, state->gl_blue_size);
        SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, state->gl_alpha_size);
        SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, state->gl_double_buffer);
        SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, state->gl_buffer_size);
        SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, state->gl_depth_size);
        SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, state->gl_stencil_size);
        SDL_GL_SetAttribute(SDL_GL_ACCUM_RED_SIZE, state->gl_accum_red_size);
        SDL_GL_SetAttribute(SDL_GL_ACCUM_GREEN_SIZE, state->gl_accum_green_size);
        SDL_GL_SetAttribute(SDL_GL_ACCUM_BLUE_SIZE, state->gl_accum_blue_size);
        SDL_GL_SetAttribute(SDL_GL_ACCUM_ALPHA_SIZE, state->gl_accum_alpha_size);
        SDL_GL_SetAttribute(SDL_GL_STEREO, state->gl_stereo);
        SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, state->gl_multisamplebuffers);
        SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, state->gl_multisamplesamples);
        if (state->gl_accelerated >= 0) {
            SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL,
                                state->gl_accelerated);
        }
        SDL_GL_SetAttribute(SDL_GL_RETAINED_BACKING, state->gl_retained_backing);
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, state->gl_major_version);
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, state->gl_minor_version);

        if (state->verbose & VERBOSE_MODES) {
            SDL_DisplayMode mode;
            int bpp;
            Uint32 Rmask, Gmask, Bmask, Amask;

            n = SDL_GetNumVideoDisplays();
            fprintf(stderr, "Number of displays: %d\n", n);
            for (i = 0; i < n; ++i) {
                fprintf(stderr, "Display %d:\n", i);
                SDL_SelectVideoDisplay(i);

                SDL_GetDesktopDisplayMode(&mode);
                SDL_PixelFormatEnumToMasks(mode.format, &bpp, &Rmask, &Gmask,
                                           &Bmask, &Amask);
                fprintf(stderr,
                        "  Current mode: %dx%d@%dHz, %d bits-per-pixel (%s)\n",
                        mode.w, mode.h, mode.refresh_rate, bpp,
                        SDL_GetPixelFormatName(mode.format));
                if (Rmask || Gmask || Bmask) {
                    fprintf(stderr, "      Red Mask   = 0x%.8x\n", Rmask);
                    fprintf(stderr, "      Green Mask = 0x%.8x\n", Gmask);
                    fprintf(stderr, "      Blue Mask  = 0x%.8x\n", Bmask);
                    if (Amask)
                        fprintf(stderr, "      Alpha Mask = 0x%.8x\n", Amask);
                }

                /* Print available fullscreen video modes */
                m = SDL_GetNumDisplayModes();
                if (m == 0) {
                    fprintf(stderr, "No available fullscreen video modes\n");
                } else {
                    fprintf(stderr, "  Fullscreen video modes:\n");
                    for (j = 0; j < m; ++j) {
                        SDL_GetDisplayMode(j, &mode);
                        SDL_PixelFormatEnumToMasks(mode.format, &bpp, &Rmask,
                                                   &Gmask, &Bmask, &Amask);
                        fprintf(stderr,
                                "    Mode %d: %dx%d@%dHz, %d bits-per-pixel (%s)\n",
                                j, mode.w, mode.h, mode.refresh_rate, bpp,
                                SDL_GetPixelFormatName(mode.format));
                        if (Rmask || Gmask || Bmask) {
                            fprintf(stderr, "        Red Mask   = 0x%.8x\n",
                                    Rmask);
                            fprintf(stderr, "        Green Mask = 0x%.8x\n",
                                    Gmask);
                            fprintf(stderr, "        Blue Mask  = 0x%.8x\n",
                                    Bmask);
                            if (Amask)
                                fprintf(stderr,
                                        "        Alpha Mask = 0x%.8x\n",
                                        Amask);
                        }
                    }
                }
            }
        }

        SDL_SelectVideoDisplay(state->display);
        if (state->verbose & VERBOSE_RENDER) {
            SDL_RendererInfo info;

            n = SDL_GetNumRenderDrivers();
            if (n == 0) {
                fprintf(stderr, "No built-in render drivers\n");
            } else {
                fprintf(stderr, "Built-in render drivers:\n");
                for (i = 0; i < n; ++i) {
                    SDL_GetRenderDriverInfo(i, &info);
                    PrintRenderer(&info);
                }
            }
        }

        SDL_zero(fullscreen_mode);
        switch (state->depth) {
        case 8:
            fullscreen_mode.format = SDL_PIXELFORMAT_INDEX8;
            break;
        case 15:
            fullscreen_mode.format = SDL_PIXELFORMAT_RGB555;
            break;
        case 16:
            fullscreen_mode.format = SDL_PIXELFORMAT_RGB565;
            break;
        case 24:
            fullscreen_mode.format = SDL_PIXELFORMAT_RGB24;
            break;
        default:
            fullscreen_mode.format = SDL_PIXELFORMAT_RGB888;
            break;
        }
        fullscreen_mode.refresh_rate = state->refresh_rate;

        state->windows =
            (SDL_Window **) SDL_malloc(state->num_windows *
                                        sizeof(*state->windows));
        if (!state->windows) {
            fprintf(stderr, "Out of memory!\n");
            return SDL_FALSE;
        }
        for (i = 0; i < state->num_windows; ++i) {
            char title[1024];

            if (state->num_windows > 1) {
                SDL_snprintf(title, SDL_arraysize(title), "%s %d",
                             state->window_title, i + 1);
            } else {
                SDL_strlcpy(title, state->window_title, SDL_arraysize(title));
            }
            state->windows[i] =
                SDL_CreateWindow(title, state->window_x, state->window_y,
                                 state->window_w, state->window_h,
                                 state->window_flags);
            if (!state->windows[i]) {
                fprintf(stderr, "Couldn't create window: %s\n",
                        SDL_GetError());
                return SDL_FALSE;
            }

            if (SDL_SetWindowDisplayMode(state->windows[i], &fullscreen_mode) < 0) {
                fprintf(stderr, "Can't set up fullscreen display mode: %s\n",
                        SDL_GetError());
                return SDL_FALSE;
            }

            if (state->window_icon) {
                SDL_Surface *icon = LoadIcon(state->window_icon);
                if (icon) {
                    SDL_SetWindowIcon(state->windows[i], icon);
                    SDL_FreeSurface(icon);
                }
            }

            SDL_ShowWindow(state->windows[i]);

            if (!state->skip_renderer
                && (state->renderdriver
                    || !(state->window_flags & SDL_WINDOW_OPENGL))) {
                m = -1;
                if (state->renderdriver) {
                    SDL_RendererInfo info;
                    n = SDL_GetNumRenderDrivers();
                    for (j = 0; j < n; ++j) {
                        SDL_GetRenderDriverInfo(j, &info);
                        if (SDL_strcasecmp(info.name, state->renderdriver) ==
                            0) {
                            m = j;
                            break;
                        }
                    }
                    if (m == n) {
                        fprintf(stderr,
                                "Couldn't find render driver named %s",
                                state->renderdriver);
                        return SDL_FALSE;
                    }
                }
                if (SDL_CreateRenderer
                    (state->windows[i], m, state->render_flags) < 0) {
                    fprintf(stderr, "Couldn't create renderer: %s\n",
                            SDL_GetError());
                    return SDL_FALSE;
                }
                if (state->verbose & VERBOSE_RENDER) {
                    SDL_RendererInfo info;

                    fprintf(stderr, "Current renderer:\n");
                    SDL_GetRendererInfo(&info);
                    PrintRenderer(&info);
                }
            }
        }
        SDL_SelectRenderer(state->windows[0]);
    }

    if (state->flags & SDL_INIT_AUDIO) {
        if (state->verbose & VERBOSE_AUDIO) {
            n = SDL_GetNumAudioDrivers();
            if (n == 0) {
                fprintf(stderr, "No built-in audio drivers\n");
            } else {
                fprintf(stderr, "Built-in audio drivers:");
                for (i = 0; i < n; ++i) {
                    if (i > 0) {
                        fprintf(stderr, ",");
                    }
                    fprintf(stderr, " %s", SDL_GetAudioDriver(i));
                }
                fprintf(stderr, "\n");
            }
        }
        if (SDL_AudioInit(state->audiodriver) < 0) {
            fprintf(stderr, "Couldn't initialize audio driver: %s\n",
                    SDL_GetError());
            return SDL_FALSE;
        }
        if (state->verbose & VERBOSE_VIDEO) {
            fprintf(stderr, "Audio driver: %s\n",
                    SDL_GetCurrentAudioDriver());
        }

        if (SDL_OpenAudio(&state->audiospec, NULL) < 0) {
            fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError());
            return SDL_FALSE;
        }
    }

    return SDL_TRUE;
}
Esempio n. 7
0
VistaLoop::~VistaLoop(void){
	if( this->pProxyEntidad != NULL ) delete this->pProxyEntidad;	
	if( this->pantalla != NULL ) SDL_FreeSurface(this->pantalla);
	ImageLoader::getInstance().cerrarSDL();	
}
Esempio n. 8
0
bool ReSaveImage(wchar_t* filename, char* buff, unsigned long len)
{
	if(!buff || !len)
		return false;
	
	SDL_RWops* fp = NULL;
	fp = SDL_RWFromMem(buff, len);
	if(fp == NULL)
	{
		printf("ImageEx: Failed to read memory\n");
		if(fp)
		{
			SDL_RWclose(fp);
		}
		return false;
	}
	SDL_Surface *back = nullptr;
	back = SDL_LoadBMP_RW(fp, 0);
	if(back == nullptr)
	{
		printf("ImageEx: Failed to load from memory\n");
		if(fp)
		{
			SDL_RWclose(fp);
		}
		return false;
	}

	BITMAPINFOHEADER *bmi = (BITMAPINFOHEADER*)(buff + sizeof(BITMAPFILEHEADER));


	Uint32 rmask, gmask, bmask, amask;

#if SDL_BYTEORDER == SDL_BIG_ENDIAN
    rmask = 0xff000000;
    gmask = 0x00ff0000;
    bmask = 0x0000ff00;
    amask = 0x000000ff;
#else
    rmask = 0x000000ff;
    gmask = 0x0000ff00;
    bmask = 0x00ff0000;
    amask = 0xff000000;
#endif

	SDL_Surface *out = SDL_CreateRGBSurface(0, back->w, back->h, bmi->biBitCount,rmask, gmask, bmask, amask);

	SDL_Rect  backRect;
	backRect.x = 0;
	backRect.y = 0;
	backRect.w = back->w;
	backRect.h = back->h;

	SDL_BlitSurface(back, &backRect, out, NULL);

	std::string OutPut = UnicodeToUtf8(filename);
	SDL_SaveBMP(out, OutPut.c_str());
	SDL_FreeSurface(back);
	SDL_RWclose(fp);
	return true;
}
Esempio n. 9
0
view::ChatView::~ChatView() {
	SDL_FreeSurface(closeButton);
	delete modelChat;
}
Esempio n. 10
0
static
void sdl_update (sdl_t *sdl)
{
	SDL_Surface         *s;
	Uint32              rmask, gmask, bmask;
	terminal_t          *trm;
	SDL_Rect            dst;
	const unsigned char *buf;
	unsigned            dw, dh;
	unsigned            ux, uy, uw, uh;
	unsigned            fx, fy;
	unsigned            bx, by;

	trm = &sdl->trm;

	trm_get_scale (&sdl->trm, trm->w, trm->h, &fx, &fy);

	dw = fx * trm->w;
	dh = fy * trm->h;

	bx = sdl->border[0] + sdl->border[2];
	by = sdl->border[1] + sdl->border[3];

	if (sdl_set_window_size (sdl, dw + bx, dh + by, 0)) {
		return;
	}

#if SDL_BYTEORDER == SDL_BIG_ENDIAN
	rmask = 0x00ff0000;
	gmask = 0x0000ff00;
	bmask = 0x000000ff;
#else
	rmask = 0x000000ff;
	gmask = 0x0000ff00;
	bmask = 0x00ff0000;
#endif

	buf = trm_scale (trm, trm->buf, trm->w, trm->h, fx, fy);

	ux = fx * trm->update_x;
	uy = fy * trm->update_y;
	uw = fx * trm->update_w;
	uh = fy * trm->update_h;

	s = SDL_CreateRGBSurfaceFrom (
		(char *) buf + 3 * (dw * uy + ux), uw, uh, 24, 3 * dw,
		rmask, gmask, bmask, 0
	);

	dst.x = ux + sdl->border[0];
	dst.y = uy + sdl->border[1];

	if (s == NULL) {
		return;
	}

	if (SDL_BlitSurface (s, NULL, sdl->scr, &dst) != 0) {
		fprintf (stderr, "sdl: blit error\n");
	}

	SDL_FreeSurface (s);

	SDL_Flip (sdl->scr);
}
Esempio n. 11
0
int main(int argc, char **argv)
{
	SDL_Window *window;
	SDL_GLContext context;
	SDL_Event evt;
	MOJOSHADER_glContext *shaderContext;
	MOJOSHADER_effect *effect;
	MOJOSHADER_glEffect *glEffect;
	SDL_Surface *bitmap;
	GLuint texture;
	GLuint buffers[2];
	FILE *fileIn;
	unsigned int fileLen;
	unsigned char *effectData;
	unsigned int passes;
	MOJOSHADER_effectStateChanges changes;
	Uint8 run = 1;

	/* Create the window and GL context */
	SDL_Init(SDL_INIT_VIDEO);
	SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
	SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
	window = SDL_CreateWindow(
		"Sprite Test",
		SDL_WINDOWPOS_CENTERED,
		SDL_WINDOWPOS_CENTERED,
		SCREEN_WIDTH,
		SCREEN_HEIGHT,
		SDL_WINDOW_OPENGL
	);
	context = SDL_GL_CreateContext(window);
	shaderContext = MOJOSHADER_glCreateContext(
		MOJOSHADER_PROFILE,
		GetGLProcAddress,
		NULL,
		NULL,
		NULL,
		NULL
	);
	MOJOSHADER_glMakeContextCurrent(shaderContext);

	/* ARB_debug_output setup */
	glDebugMessageCallbackARB(GLDebugCallback, NULL);
	glDebugMessageControlARB(
		GL_DONT_CARE,
		GL_DONT_CARE,
		GL_DONT_CARE,
		0,
		NULL,
		GL_TRUE
	);

	/* Set up the viewport, create the texture/buffer data */
	glViewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
	glGenTextures(1, &texture);
	glBindTexture(GL_TEXTURE_2D, texture);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_LOD_BIAS, 0.0f);
	bitmap = SDL_LoadBMP("../Sprite.bmp");
	glTexImage2D(
		GL_TEXTURE_2D,
		0,
		GL_RGB,
		bitmap->w,
		bitmap->h,
		0,
		GL_BGR,
		GL_UNSIGNED_BYTE,
		bitmap->pixels
	);
	SDL_FreeSurface(bitmap);
	glGenBuffersARB(2, buffers);
	glBindBufferARB(GL_ARRAY_BUFFER, buffers[0]);
	glBufferDataARB(
		GL_ARRAY_BUFFER,
		sizeof(vertexstruct_t) * 4,
		vertex_array,
		GL_STATIC_DRAW
	);
	glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER, buffers[1]);
	glBufferDataARB(
		GL_ELEMENT_ARRAY_BUFFER,
		12,
		index_array,
		GL_STATIC_DRAW
	);

	/* Load and read the SpriteBatch effect file */
	fileIn = fopen("../SpriteEffect.fxb", "rb");
	fseek(fileIn, 0, SEEK_END);
	fileLen = ftell(fileIn);
	fseek(fileIn, 0, SEEK_SET);
	effectData = (unsigned char*) malloc(fileLen);
	fread(effectData, 1, fileLen, fileIn);
	fclose(fileIn);
	effect = MOJOSHADER_parseEffect(
		MOJOSHADER_PROFILE,
		effectData,
		fileLen,
		NULL,
		0,
		NULL,
		0,
		NULL,
		NULL,
		NULL
	);
	free(effectData);
	glEffect = MOJOSHADER_glCompileEffect(effect);
	MOJOSHADER_effectSetRawValueName(
		effect,
		"MatrixTransform",
		transform_matrix,
		0,
		64
	);

	while (run)
	{
		while (SDL_PollEvent(&evt) > 0)
		{
			if (evt.type == SDL_QUIT)
			{
				run = 0;
			}
		}

		/* Clear the screen to black. */
		glClear(GL_COLOR_BUFFER_BIT);

		/* Bind the effect */
		MOJOSHADER_glEffectBegin(glEffect, &passes, 0, &changes);
		MOJOSHADER_glEffectBeginPass(glEffect, 0);

		/* Set the attrib pointers now, while the effect is bound */
		MOJOSHADER_glSetVertexAttribute(
			MOJOSHADER_USAGE_POSITION,
			0,
			3,
			MOJOSHADER_ATTRIBUTE_FLOAT,
			0,
			sizeof(vertexstruct_t),
			(void*) 0
		);
		MOJOSHADER_glSetVertexAttribute(
			MOJOSHADER_USAGE_COLOR,
			0,
			4,
			MOJOSHADER_ATTRIBUTE_UBYTE,
			1,
			sizeof(vertexstruct_t),
			(void*) 12
		);
		MOJOSHADER_glSetVertexAttribute(
			MOJOSHADER_USAGE_TEXCOORD,
			0,
			2,
			MOJOSHADER_ATTRIBUTE_FLOAT,
			0,
			sizeof(vertexstruct_t),
			(void*) 16
		);

		/* Flush all changes to the shader and constant buffers */
		MOJOSHADER_glProgramReady();

		/* Draw! */
		glDrawRangeElements(
			GL_TRIANGLES,
			0,
			3,
			6,
			GL_UNSIGNED_SHORT,
			NULL
		);

		/* We've finished drawing. Present what we've drawn. */
		MOJOSHADER_glEffectEndPass(glEffect);
		MOJOSHADER_glEffectEnd(glEffect);
		SDL_GL_SwapWindow(window);
	}

	/* Clean up. We out. */
	glDeleteBuffersARB(2, buffers);
	glDeleteTextures(1, &texture);
	MOJOSHADER_glDeleteEffect(glEffect);
	MOJOSHADER_freeEffect(effect);
	MOJOSHADER_glMakeContextCurrent(NULL);
	MOJOSHADER_glDestroyContext(shaderContext);
	SDL_GL_DeleteContext(context);
	SDL_DestroyWindow(window);
	SDL_Quit();
	return 0;
}
Esempio n. 12
0
void Zombie::Free_Memory()
{
	Mix_FreeChunk(spawn);
	Mix_FreeChunk(die);
	SDL_FreeSurface( SpriteZombie );
}
Esempio n. 13
0
//! presents a surface in the client area
bool CIrrDeviceSDL::present(video::IImage* surface, void* windowId, core::rect<s32>* srcClip)
{
	SDL_Surface *sdlSurface = SDL_CreateRGBSurfaceFrom(
			surface->lock(), surface->getDimension().Width, surface->getDimension().Height,
			surface->getBitsPerPixel(), surface->getPitch(),
			surface->getRedMask(), surface->getGreenMask(), surface->getBlueMask(), surface->getAlphaMask());
	if (!sdlSurface)
		return false;
	SDL_SetAlpha(sdlSurface, 0, 0);
	SDL_SetColorKey(sdlSurface, 0, 0);
	sdlSurface->format->BitsPerPixel=surface->getBitsPerPixel();
	sdlSurface->format->BytesPerPixel=surface->getBytesPerPixel();
	if ((surface->getColorFormat()==video::ECF_R8G8B8) ||
			(surface->getColorFormat()==video::ECF_A8R8G8B8))
	{
		sdlSurface->format->Rloss=0;
		sdlSurface->format->Gloss=0;
		sdlSurface->format->Bloss=0;
		sdlSurface->format->Rshift=16;
		sdlSurface->format->Gshift=8;
		sdlSurface->format->Bshift=0;
		if (surface->getColorFormat()==video::ECF_R8G8B8)
		{
			sdlSurface->format->Aloss=8;
			sdlSurface->format->Ashift=32;
		}
		else
		{
			sdlSurface->format->Aloss=0;
			sdlSurface->format->Ashift=24;
		}
	}
	else if (surface->getColorFormat()==video::ECF_R5G6B5)
	{
		sdlSurface->format->Rloss=3;
		sdlSurface->format->Gloss=2;
		sdlSurface->format->Bloss=3;
		sdlSurface->format->Aloss=8;
		sdlSurface->format->Rshift=11;
		sdlSurface->format->Gshift=5;
		sdlSurface->format->Bshift=0;
		sdlSurface->format->Ashift=16;
	}
	else if (surface->getColorFormat()==video::ECF_A1R5G5B5)
	{
		sdlSurface->format->Rloss=3;
		sdlSurface->format->Gloss=3;
		sdlSurface->format->Bloss=3;
		sdlSurface->format->Aloss=7;
		sdlSurface->format->Rshift=10;
		sdlSurface->format->Gshift=5;
		sdlSurface->format->Bshift=0;
		sdlSurface->format->Ashift=15;
	}

	SDL_Surface* scr = (SDL_Surface* )windowId;
	if (!scr)
		scr = Screen;
	if (scr)
	{
		if (srcClip)
		{
			SDL_Rect sdlsrcClip;
			sdlsrcClip.x = srcClip->UpperLeftCorner.X;
			sdlsrcClip.y = srcClip->UpperLeftCorner.Y;
			sdlsrcClip.w = srcClip->getWidth();
			sdlsrcClip.h = srcClip->getHeight();
			SDL_BlitSurface(sdlSurface, &sdlsrcClip, scr, NULL);
		}
		else
			SDL_BlitSurface(sdlSurface, NULL, scr, NULL);
		SDL_Flip(scr);
	}

	SDL_FreeSurface(sdlSurface);
	surface->unlock();
	return (scr != 0);
}
Esempio n. 14
0
FontEngine::~FontEngine() {
	SDL_FreeSurface(ttf);
	TTF_CloseFont(font);
	TTF_Quit();
}
Esempio n. 15
0
void clean_up()
{
     SDL_FreeSurface( image );
     
     SDL_Quit();
}
Esempio n. 16
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;
        }
    }

    // Running without window decorations is potentially useful if you're
    // playing in three window mode and want to line up three game windows
    // next to each other on a single desktop.
    // Deliberately not documented because I'm not sure how useful this is yet.
    if (M_ParmExists("-borderless"))
    {
        window_flags |= SDL_WINDOW_BORDERLESS;
    }

    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);
        // all associated textures get destroyed
        texture = NULL;
        texture_upscaled = NULL;
    }

    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)
    {
        SDL_FreeSurface(screenbuffer);
        screenbuffer = NULL;
    }

    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_FreeSurface(argbbuffer);
        argbbuffer = NULL;
    }

    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. 17
0
void GL_InitTexture(int _srcWidth, int _srcHeight)
{
    srcWidth = _srcWidth;
    srcHeight = _srcHeight;

    //delete it if we already have one
    if ( texture )
    {
        glDeleteTextures( 1, &texture );
        texture = 0;
    }
    if ( controller_tex )
    {
        glDeleteTextures( 1, &controller_tex );
        controller_tex = 0;
    }

    glGenTextures(1, &texture);
    checkError();
    glBindTexture(GL_TEXTURE_2D, texture);
    checkError();

    //sanity check
    int num;
    glGetIntegerv( GL_TEXTURE_BINDING_2D, &num );
    assert( num == texture );
    glGetIntegerv( GL_ACTIVE_TEXTURE, &num );
    assert( num == GL_TEXTURE0 );
    checkError();

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter );
    checkError();
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter );
    checkError();

    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
    checkError();
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
    checkError();

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, srcWidth, srcHeight, 0, GL_RGB,
                 GL_UNSIGNED_SHORT_5_6_5, NULL );
    checkError();

    if( !skin )
    {
        printf( "No skins found! Running without one...\n" );
        return;
    }

    //Load controller
    SDL_Surface * initial_surface = IMG_Load( skin->image_path );
    if ( !initial_surface )
    {
        printf( "No controller image found!  Running without one...\n" );
        return;
    }

    //Make sure the surface is the right format...
    SDL_Surface * controller_surface = SDL_CreateRGBSurface( SDL_SWSURFACE, initial_surface->w, initial_surface->h, 32,
                                       0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000);
    SDL_SetAlpha(initial_surface, 0, 0);
    SDL_BlitSurface( initial_surface, NULL, controller_surface, NULL );

    glGenTextures(1, &controller_tex );
    glBindTexture( GL_TEXTURE_2D, controller_tex );
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter );
    checkError();
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter );
    checkError();

    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
    checkError();
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
    checkError();

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, controller_surface->w, controller_surface->h, 0, GL_RGBA,
                 GL_UNSIGNED_BYTE, controller_surface->pixels );
    checkError();

    SDL_FreeSurface( initial_surface );
    SDL_FreeSurface( controller_surface );
}
Esempio n. 18
0
void Tetrimino::releaseResource()
{
    TTF_CloseFont(ResourceData::font);
    SDL_FreeSurface(ResourceData::background);
    delete ResourceData::sound;
}
Esempio n. 19
0
void libererImages(Sprites &sprites, Chien &chien, Boutons &boutons)
{
    SDL_FreeSurface(boutons.source);
    SDL_FreeSurface(sprites.background_menu.source);
    SDL_FreeSurface(sprites.background.source);
    SDL_FreeSurface(sprites.background_blit.source);
    SDL_FreeSurface(sprites.viseur.source);
    SDL_FreeSurface(sprites.hits.source);
    SDL_FreeSurface(sprites.shots.source);
    SDL_FreeSurface(sprites.canardSprite[DARK]);
    SDL_FreeSurface(sprites.canardSprite[CHESNUT]);
    SDL_FreeSurface(sprites.canardSprite[BLOOD]);
    SDL_FreeSurface(sprites.canardSprite[BLUISH_PURPLE]);
    SDL_FreeSurface(sprites.points.source);
    SDL_FreeSurface(chien.image[CHIEN_MARCHE].source);
    SDL_FreeSurface(chien.image[CHIEN_CONTENT].source);
    SDL_FreeSurface(chien.image[CHIEN_SAUTE_1].source);
    SDL_FreeSurface(chien.image[CHIEN_SAUTE_2].source);
    SDL_FreeSurface(chien.image[CHIEN_RIGOLE].source);
    SDL_FreeSurface(chien.image[CHIEN_CONTENT_SIMPLE].source);
    SDL_FreeSurface(chien.image[CHIEN_CONTENT_DOUBLE].source);
}
Esempio n. 20
0
FadeMessage::~FadeMessage()
{
	SDL_FreeSurface(text);
	delete r;
	delete font;
}
Esempio n. 21
0
void DrawPict(SDL_Surface *screen, char *bmpfile,
					int speedy, int flip, int nofade)
{
	SDL_Surface *picture;
	SDL_Rect dest, update;
	int i, centered;
	int ncolors;
	SDL_Color *colors, *cmap;

	/* Load the image into a surface */
	if ( bmpfile == NULL ) {
		bmpfile = "sample.bmp";		/* Sample image */
	}
fprintf(stderr, "Loading picture: %s\n", bmpfile);
	picture = SDL_LoadBMP(bmpfile);
	if ( picture == NULL ) {
		fprintf(stderr, "Couldn't load %s: %s\n", bmpfile,
							SDL_GetError());
		return;
	}

	/* Set the display colors -- on a hicolor display this is a no-op */
	if ( picture->format->palette ) {
		ncolors = picture->format->palette->ncolors;
		colors  = (SDL_Color *)malloc(ncolors*sizeof(SDL_Color));
		cmap    = (SDL_Color *)malloc(ncolors*sizeof(SDL_Color));
		memcpy(colors, picture->format->palette->colors,
						ncolors*sizeof(SDL_Color));
	} else {
		int       r, g, b;

		/* Allocate 256 color palette */
		ncolors = 256;
		colors  = (SDL_Color *)malloc(ncolors*sizeof(SDL_Color));
		cmap    = (SDL_Color *)malloc(ncolors*sizeof(SDL_Color));

		/* Set a 3,3,2 color cube */
		for ( r=0; r<8; ++r ) {
			for ( g=0; g<8; ++g ) {
				for ( b=0; b<4; ++b ) {
					i = ((r<<5)|(g<<2)|b);
					colors[i].r = r<<5;
					colors[i].g = g<<5;
					colors[i].b = b<<6;
				}
			}
		}
	}
NOTICE("testwin: setting colors\n");
	if ( ! SDL_SetColors(screen, colors, 0, ncolors) &&
				(screen->format->palette != NULL) ) {
		fprintf(stderr,
"Warning: Couldn't set all of the colors, but SDL will map the image\n"
"         (colormap fading will suffer - try the -warp option)\n"
		);
	}

	/* Set the screen to black (not really necessary) */
	if ( SDL_LockSurface(screen) == 0 ) {
		Uint32 black;
		Uint8 *pixels;

		black = SDL_MapRGB(screen->format, 0, 0, 0);
		pixels = (Uint8 *)screen->pixels;
		for ( i=0; i<screen->h; ++i ) {
			memset(pixels, black,
				screen->w*screen->format->BytesPerPixel);
			pixels += screen->pitch;
		}
		SDL_UnlockSurface(screen);
		SDL_UpdateRect(screen, 0, 0, 0, 0);
	}
	
	/* Display the picture */
	if ( speedy ) {
		SDL_Surface *displayfmt;

fprintf(stderr, "Converting picture\n");
		displayfmt = SDL_DisplayFormat(picture);
		if ( displayfmt == NULL ) {
			fprintf(stderr,
				"Couldn't convert image: %s\n", SDL_GetError());
			goto done;
		}
		SDL_FreeSurface(picture);
		picture = displayfmt;
	}
	printf("(image surface located in %s memory)\n", 
			(picture->flags&SDL_HWSURFACE) ? "video" : "system");
	centered = (screen->w - picture->w)/2;
	if ( centered < 0 ) {
		centered = 0;
	}
	dest.y = (screen->h - picture->h)/2;
	dest.w = picture->w;
	dest.h = picture->h;
NOTICE("testwin: moving image\n");
	for ( i=0; i<=centered; ++i ) {
		dest.x = i;
		update = dest;
		if ( SDL_BlitSurface(picture, NULL, screen, &update) < 0 ) {
			fprintf(stderr, "Blit failed: %s\n", SDL_GetError());
			break;
		}
		if ( flip ) {
			SDL_Flip(screen);
		} else {
			SDL_UpdateRects(screen, 1, &update);
		}
	}

#ifdef SCREENSHOT
	if ( SDL_SaveBMP(screen, "screen.bmp") < 0 )
		printf("Couldn't save screen: %s\n", SDL_GetError());
#endif

#ifndef BENCHMARK_SDL
	/* Let it sit there for a while */
	SDL_Delay(5*1000);
#endif
	/* Fade the colormap */
	if ( ! nofade ) {
		int maxstep;
		SDL_Color final;
		SDL_Color palcolors[256];
		struct {
			Sint16 r, g, b;
		} cdist[256];

NOTICE("testwin: fading out...\n");
		memcpy(cmap, colors, ncolors*sizeof(SDL_Color));
		maxstep = 32-1;
		final.r = 0xFF;
Esempio n. 22
0
//Player creation method
Player::Player(SDL_Renderer *renderer, int pNum, string filePath, string audioPath, float x, float y)
{

	//activate the player
	active = true;

	//set the player number 0 or 1
	playerNum = pNum;

	//set float for player speed
	speed = 500.0f;

	laser = Mix_LoadWAV((audioPath + "bullet.wav").c_str());

	// init score and lives vars
	oldScore = 0;
	playerScore = 0;
	oldLives = 0;
	playerLives = 3;

	//init the font system
	TTF_Init();

	//load the font
	font = TTF_OpenFont((audioPath + "Amperzand.ttf").c_str(), 40);

	//see if this is player 1 or player 2, and create the correct X and Y locations
	if (playerNum == 0)
	{
		//Create the score texture X and Y position
		scorePos.x = scorePos.y = 10;
		livesPos.x = 10;
		livesPos.y = 50;
	}
	else
	{
		scorePos.x = 650;
		scorePos.y = 10;
		livesPos.x = 650;
		livesPos.y = 50;
	}

	// update score method
	UpdateScore(renderer);

	//Update lives method
	UpdateLives(renderer);

	//see if this is player 1, or player 2, and create the correct file path
	if(playerNum == 0)
	{//Create the player 1 texture
		playerPath = filePath + "player.png";
	}else
	{//Create the player 2 texture
		playerPath = filePath + "player2.png";
	}
	//load the surface
	surface = IMG_Load(playerPath.c_str());

	//load the surface into the texture
	texture = SDL_CreateTextureFromSurface(renderer, surface);

	//free the surface for later use
	SDL_FreeSurface(surface);

	//set the SDL_Rect X and Y for the player
	posRect.x = x;
	posRect.y = y;

	//Use SDL_QueryTexture to get the kW and H of the player's texture
	int w, h;

	SDL_QueryTexture(texture, NULL, NULL, &w, &h);

	posRect.w = w;

	posRect.h = h;

	//Set the movement floats to the players original X and Y
	pos_X = x;
	pos_Y = y;

	//set the xDir and yDir for the joysticks
	xDir = 0;
	yDir = 0;

	//String to create the path to the player's bullet image
	string bulletPath;

	//see if this is player 1, or player 2, and create the correct file path
	if(playerNum == 0){
		//Create the bullet 1 texture
		bulletPath = filePath + "bullet.png";
	}else{
		//Create the bullet 2 texture
		bulletPath = filePath + "bullet2.png";
	}

	//Create the player's bullet pool
	for(int i = 0; i < 10; i++)
	{
		//create the bullet and move offscreen, out of the game play area
		Bullet tmpBullet(renderer, bulletPath, -1000, -1000);

		//add to bulletlist
		bulletList.push_back(tmpBullet);

	}


}
Esempio n. 23
0
void SDL::deleteSurface(SDL_Surface* surface)
{
    if (surface)
        SDL_FreeSurface(surface);
}
Esempio n. 24
0
int main(int argc, char *argv[])
{
    SDL_Event       event;
    SDL_TimerID     timer = 0;

    /* nacteni modelu */
    polymodel = modLoad((argc == 2) ? argv[1] : DEFAULT_MODEL);
    IZG_CHECK(polymodel, "Failed to read input model");

    /* vytvoreni default SW rendereru */
#ifdef USE_STUDENT_RENDERER
    renderer = studrenCreate();
#else
    renderer = renCreate();
#endif /* USE_STUDENT_RENDERER */

    /* pocatecni velikost bufferu */
    renderer->createBuffersFunc(renderer, DEFAULT_WIDTH, DEFAULT_HEIGHT);

    /* inicializace SDL knihovny */
    if( SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) == -1 )
    {
        IZG_SDL_ERROR("Could not initialize SDL library");
    }

    /* nastaveni titulku okna */
#ifdef USE_STUDENT_RENDERER
    SDL_WM_SetCaption(PROGRAM_TITLE_STUDENT, 0);
#else
    SDL_WM_SetCaption(PROGRAM_TITLE, 0);
#endif // USE_STUDENT_RENDERER

    /* screen */
    screen = SDL_SetVideoMode(DEFAULT_WIDTH, DEFAULT_HEIGHT, 32, SDL_HWSURFACE | SDL_DOUBLEBUF | SDL_RESIZABLE);

    /* enable Unicode translation */
    SDL_EnableUNICODE(1);

    /* dalsi inicializace */
    onInit(renderer, polymodel);

    /* nastavime timer, ktery bude volat zadanou callback fci */
    timer = SDL_AddTimer(TIMER_INTERVAL, timerCallback, NULL);

    /* kreslime dokud nenarazime na SDL_QUIT event */
    while( !quit )
    {
        /* vycteni udalosti */
        while( SDL_PollEvent(&event) )
        {
            switch( event.type )
            {
                /* udalost klavesnice */
                case SDL_KEYDOWN:
                    onKeyboard(&event.key);
                    break;

                /* zmena velikosti okna */
                case SDL_VIDEORESIZE:
                    onResize(&event.resize);
                    break;

                /* udalost mysi - pohyb */
                case SDL_MOUSEMOTION:
                    onMouseMotion(&event.motion);
                    break;

                /* udalost mysi - tlacitka */
                case SDL_MOUSEBUTTONDOWN:
                case SDL_MOUSEBUTTONUP:
                    onMouseButton(&event.button);
                    break;

                /* tiknuti timeru */
                case SDL_USEREVENT:
                    if( event.user.code == IZG_TIMER_EVENT )
                    {
                        onTimer((int)SDL_GetTicks());
                    }
                    break;

                /* SDL_QUIT event */
                case SDL_QUIT:
                    quit = 1;
                    break;

                default:
                    break;
            }
        }

        /* vykresleni pres SDL knihovnu */
        draw();
    }

    /* ukonceni timeru */
    SDL_RemoveTimer(timer);

    /* ukonceni SDL */
    SDL_FreeSurface(screen);

    /* shutdown all SDL subsystems */
    SDL_Quit();

    /* zrusime co jsme vytvorili a ukoncime program */
    modRelease(&polymodel);
    renderer->releaseFunc(&renderer);

    return 0;
}
Esempio n. 25
0
//void jeu_multi(SDL_Surface *ecran,FMOD_SYSTEM *system,SDL_Surface* menuc,FILE* Nom_joueur,FILE* enr,char Nom_fic[17],FILE* enr2)
void jeu_multi(SDL_Surface *ecran,SDL_Surface* menuc,FILE* enr,FILE* enr2)
    {
        SDL_Surface *carte=NULL, *moto1=NULL, *moto2=NULL,*p_win=NULL,*img_h=NULL,*img_c=NULL,*img_h2=NULL,*img_c2=NULL ;
        SDL_Event event;
        position pos_moto1, pos_moto2,pos_win,pos_b,pos_moto_pre;
        int grille[300][150];
        int continuer=1;
        int tempsPrecedent = 0, tempsActuel = 0;
        int i,j;
        int indice=2,indice2=2;
        SDL_Rect mem[500];
        SDL_Rect mem2[500];
        int cpt=0;
        int mur=500;
        int Scores_perso,Scores_perso2;
        int couleur_moto,couleur_moto2;
        int touche1=0, touche2=108;
        int touche3,touche4;

        char nom_perso_1[7]="";
        char nom_perso_2[7]="";

        rewind(enr);
        fgets(nom_perso_1,7,enr);
        nom_perso_1[strlen(nom_perso_1)-1]=0;
        fscanf(enr,"%d %d %d %d",&couleur_moto,&Scores_perso,&touche1,&touche2);

        rewind(enr2);
        fgets(nom_perso_1,7,enr2);
        nom_perso_2[strlen(nom_perso_2)-1]=0;
        fscanf(enr2,"%d %d %d %d",&couleur_moto2,&Scores_perso2,&touche3,&touche4);




    switch(abs(couleur_moto)) // Chargement de la coeulr de moto
    {
        case 0:
        moto1=SDL_LoadBMP("Moto2_rouge.bmp");
        img_h=SDL_LoadBMP("moto_rouge_h.bmp");
        img_c=SDL_LoadBMP("moto_rouge_v.bmp");
        break;

        case 1:
        moto1=SDL_LoadBMP("Moto2_bleue.bmp");
        img_h=SDL_LoadBMP("TRON_droite.bmp");
        img_c=SDL_LoadBMP("TRON_coucher.bmp");
        break;

        case 2:
        moto1=SDL_LoadBMP("Moto2_vert.bmp");
        img_h=SDL_LoadBMP("moto_vert_h.bmp");
        img_c=SDL_LoadBMP("moto_vert_v.bmp");
        break;

        default :
        break;

    }

    switch(abs(couleur_moto2)) // Chargement de la coeulr de moto
    {
        case 0:
        moto2=SDL_LoadBMP("Moto2_rouge.bmp");
        img_h2=SDL_LoadBMP("moto_rouge_h.bmp");
        img_c2=SDL_LoadBMP("moto_rouge_v.bmp");
        break;

        case 1:
        moto2=SDL_LoadBMP("Moto2_bleue.bmp");
        img_h2=SDL_LoadBMP("TRON_droite.bmp");
        img_c2=SDL_LoadBMP("TRON_coucher.bmp");
        break;

        case 2:
        moto2=SDL_LoadBMP("Moto2_vert.bmp");
        img_h2=SDL_LoadBMP("moto_vert_h.bmp");
        img_c2=SDL_LoadBMP("moto_vert_v.bmp");
        break;

        default :
        break;

    }


        carte=SDL_LoadBMP("carte.bmp");
        ecran = SDL_SetVideoMode(1200, 600, 32, SDL_HWSURFACE |SDL_DOUBLEBUF /*|SDL_FULLSCREEN*/);
        SDL_BlitSurface(menuc, NULL, ecran, NULL); // Chargement de l'image du menu
        SDL_Flip(ecran);

/*****************Debut du programme********************************************/
        pos_moto1.xc.x=100;
        pos_moto1.xc.y=100;
        pos_moto1.x.x=pos_moto1.xc.x*4;
        pos_moto1.x.y=pos_moto1.xc.y*4;


        pos_moto2.xc.x=200;
        pos_moto2.xc.y=100;
        pos_moto2.x.x=pos_moto2.xc.x*4;
        pos_moto2.x.y=pos_moto2.xc.y*4;

        for(i=0;i<mur;i++)
        {
            mem[i].x=pos_moto1.x.x;
            mem[i].y=pos_moto1.x.y;
            mem2[i].x=pos_moto2.x.x;
            mem2[i].y=pos_moto2.x.y;

        }

       // SDL_BlitSurface(moto1, NULL, ecran, &pos_moto1.x); // Chargement de l'image du menu
        SDL_Flip(ecran);

/*************************************initialisation de la grille a 0**************************/

        for(i=0;i<150;i++)
        {
            for(j=0;j<300;j++)
            {
                grille[j][i]=0;
            }
        }

i=0;

        while(continuer)
        {
            event.type=SDLK_UNKNOWN;
            SDL_PollEvent(&event);

            switch(event.type)
            {
                case SDL_QUIT:
                    continuer = 0;
                break;

                case SDL_KEYDOWN:


                    //switch(event.key.keysym.sym) //gestion des déplacement "normaux" du joueur ( droite, gauche, haut, bas)
                    if(abs(event.key.keysym.sym)==abs(touche3))
                    {
                        //case SDLK_d:
                         switch (indice2) // On se déplace vers la droite
                        {
                            case 4 :
                            grille[pos_moto2.xc.x][pos_moto2.xc.y]=-1;
                            pos_moto2.xc.y++;
                            indice2=-2;
                            i++;
                            break;

                            case -4 : // On se déplace vers la gauche

                            grille[pos_moto2.xc.x][pos_moto2.xc.y]=-1;
                            pos_moto2.xc.y--;
                            indice2=2;
                            i++;
                            break;

                            case 2 : // On se déplace vers le haut

                            grille[pos_moto2.xc.x][pos_moto2.xc.y]=-1;
                            pos_moto2.xc.x++;
                            indice2=4;
                            i++;
                            break;

                            case -2 : // On se déplace vers le bas

                            grille[pos_moto2.xc.x][pos_moto2.xc.y]=-1;
                            pos_moto2.xc.x--;
                            indice2=-4;
                            i++;
                            break;

                            default :
                            break;
                        }
                    }
                           // break;
                         //case SDLK_a:
                       //  if (grille[pos_moto1.xc.x-1][pos_moto1.xc.y]!=-1 && pos_moto1.xc.x<2)
                       if(abs(event.key.keysym.sym)==  abs(touche4))
                       {

                        switch (indice2) // On se déplace vers la droite
                        {
                            case 4 :
                            grille[pos_moto2.xc.x][pos_moto2.xc.y]=-1;
                            pos_moto2.xc.y--;
                            indice2=2;
                            i++;
                            break;

                            case -4 : // On se déplace vers la gauche

                            grille[pos_moto2.xc.x][pos_moto2.xc.y]=-1;
                            pos_moto2.xc.y++;
                            indice2=-2;
                            i++;
                            break;

                            case 2 : // On se déplace vers le haut

                            grille[pos_moto2.xc.x][pos_moto2.xc.y]=-1;
                            pos_moto2.xc.x--;
                            indice2=-4;
                            i++;
                            break;

                            case -2 : // On se déplace vers le bas

                            grille[pos_moto2.xc.x][pos_moto2.xc.y]=-1;
                            pos_moto2.xc.x++;
                            indice2=4;
                            i++;
                            break;

                            default :
                            break;
                        }
                           // break;


                    }
                    //break;

        if(abs(event.key.keysym.sym)==abs(touche1))
        {
            grille[pos_moto1.xc.x][pos_moto1.xc.y]=2;
            //grille[pos_moto_pre.xc.x][pos_moto_pre.xc.y]=1;
            pos_moto_pre.xc.x=pos_moto1.xc.x;
            pos_moto_pre.xc.y=pos_moto1.xc.y;



            switch (indice) // On se déplace vers la droite
                {
                    case 4 :

                    pos_b.x.x=pos_moto1.x.x+4;
                    pos_b.x.y=pos_moto1.x.y;
                    pos_moto1.xc.y++;



                    indice=-2;
                    break;

                    case -4 : // On se déplace vers la gauche

                    //grille[pos_moto1.xc.x][pos_moto1.xc.y]=1;



                    pos_moto1.xc.y--;


                    indice=2;
                    break;

                    case 2 : // On se déplace vers le haut

                    //grille[pos_moto1.xc.x][pos_moto1.xc.y]=1;
                    pos_moto1.xc.x++;


                    indice=4;
                    i++;


                    break;

                    case -2 : // On se déplace vers le bas

                    //grille[pos_moto1.xc.x][pos_moto1.xc.y]=1;
                    pos_b.x.x=pos_moto1.x.x;
                    pos_b.x.y=pos_moto1.x.y+4;
                    pos_moto1.xc.x--;

                    indice=-4;


                    break;
                    default:
                    break;
            }

        }
        else if (abs(event.key.keysym.sym)==abs(touche2))
        {
            grille[pos_moto1.xc.x][pos_moto1.xc.y]=2;
            //grille[pos_moto_pre.xc.x][pos_moto_pre.xc.y]=1;
            pos_moto_pre.xc.x=pos_moto1.xc.x;
            pos_moto_pre.xc.y=pos_moto1.xc.y;
            switch (indice) // On se déplace vers la droite
            {
                case 4 :

                pos_b.x.x=pos_moto1.x.x+4;
                pos_b.x.y=pos_moto1.x.y;
                pos_moto1.xc.y--;


                i++;


                indice=2;
                break;

                case -4 : // On se déplace vers la gauche


                indice=-2;
                pos_moto1.xc.y++;
                i++;
                break;

                case 2 : // On se déplace vers le haut


                pos_moto1.xc.x--;

                indice=-4;
                i++;
                break;

                case -2 : // On se déplace vers le bas

                pos_b.x.x=pos_moto1.x.x;
                pos_b.x.y=pos_moto1.x.y+4;
                pos_moto1.xc.x++;

                indice=4;
                i++;
                break;

                default :
                break;
            }

        }
        break;

                default:
                break;



                        break;
                        case SDLK_ESCAPE: // le joueur refusent de jouer et quitte le jeux.
                        continuer=0;
                        break;
                    }
                    pos_moto1.x.x=pos_moto1.xc.x*4;
                    pos_moto1.x.y=pos_moto1.xc.y*4;
                    pos_moto2.x.x=pos_moto2.xc.x*4;
                    pos_moto2.x.y=pos_moto2.xc.y*4;

                    cpt++;
                    if(cpt>mur-1)
                    {
                        grille[(mem[mur-1].x)/4][(mem[mur-1].y)/4]=0;
                        grille[(mem2[mur-1].x)/4][(mem2[mur-1].y)/4]=0;
                    }
                    for(i=mur-1;i>0;i--)
                    {
                        mem[i].x=mem[i-1].x;
                        mem[i].y=mem[i-1].y;
                        mem2[i].x=mem2[i-1].x;
                        mem2[i].y=mem2[i-1].y;
                    }
                     mem[0].x=pos_moto1.x.x;
                     mem[0].y=pos_moto1.x.y;
                     mem2[0].x=pos_moto2.x.x;
                     mem2[0].y=pos_moto2.x.y;

/***************************Avance automatique des joueurs*****************************/
            tempsActuel = SDL_GetTicks();

            if (tempsActuel - tempsPrecedent > 20)
            {
                    switch(indice) // On se déplace vers la droite
                    {
                        case 4 :
                        grille[pos_moto1.xc.x][pos_moto1.xc.y]=-1;
                        pos_moto1.xc.x++;
                        break;

                    case -4 : // On se déplace vers la gauche
                    grille[pos_moto1.xc.x][pos_moto1.xc.y]=-1;
                       pos_moto1.xc.x--;
                    break;


                    case 2 : // On se déplace vers le haut
                        grille[pos_moto1.xc.x][pos_moto1.xc.y]=-1;
                        pos_moto1.xc.y--;
                        break;

                    case -2: // On se déplace vers le bas
                        grille[pos_moto1.xc.x][pos_moto1.xc.y]=-1;
                        pos_moto1.xc.y++;
                        break;

                        default :
                        break;
                    }

                    switch(indice2) // On se déplace vers la droite
                    {
                        case 4 :
                        grille[pos_moto2.xc.x][pos_moto2.xc.y]=-1;
                        pos_moto2.xc.x++;
                        break;

                        case -4 : // On se déplace vers la gauche
                        grille[pos_moto2.xc.x][pos_moto2.xc.y]=-1;
                           pos_moto2.xc.x--;
                        break;


                        case 2 : // On se déplace vers le haut
                            grille[pos_moto2.xc.x][pos_moto2.xc.y]=-1;
                            pos_moto2.xc.y--;
                        break;

                        case -2: // On se déplace vers le bas
                            grille[pos_moto2.xc.x][pos_moto2.xc.y]=-1;
                            pos_moto2.xc.y++;
                        break;

                        default :
                        break;


                    }

                tempsPrecedent = tempsActuel;
            }else
            {
                SDL_Delay(20 - (tempsActuel - tempsPrecedent));
            }

        if (pos_moto1.xc.x>299 || pos_moto1.xc.x<1 || pos_moto1.xc.y<1 || pos_moto1.xc.y>149 || grille[pos_moto1.xc.x][pos_moto1.xc.y]==-1)
        {
           // son_court("water.wav", system);
            continuer=0;
            p_win=SDL_LoadBMP("p2_win.bmp");
            pos_win.x.x=400;
            pos_win.x.y=250;
            SDL_BlitSurface(p_win, NULL, ecran, &pos_win.x);
            SDL_Flip(ecran);
            SDL_Delay(2000);

        }

        if (pos_moto2.xc.x>299 || pos_moto2.xc.x<1 || pos_moto2.xc.y<1 || pos_moto2.xc.y>149 || grille[pos_moto2.xc.x][pos_moto2.xc.y]==-1)
        {
           // son_court("water.wav", system);
            continuer=0;
            p_win=SDL_LoadBMP("p1_win.bmp");
            pos_win.x.x=400;
            pos_win.x.y=250;
            SDL_BlitSurface(p_win, NULL, ecran, &pos_win.x);
            SDL_Flip(ecran);
            SDL_Delay(2000);
        }
        pos_moto1.x.x=pos_moto1.xc.x*4;
        pos_moto1.x.y=pos_moto1.xc.y*4;
        pos_moto2.x.x=pos_moto2.xc.x*4;
        pos_moto2.x.y=pos_moto2.xc.y*4;

        cpt++;
        if(cpt>mur-1)
        {
            grille[(mem[mur-1].x)/4][(mem[mur-1].y)/4]=0;
            grille[(mem2[mur-1].x)/4][(mem2[mur-1].y)/4]=0;
        }
        for(i=mur-1;i>0;i--)
        {
            mem[i].x=mem[i-1].x;
            mem[i].y=mem[i-1].y;
            mem2[i].x=mem2[i-1].x;
            mem2[i].y=mem2[i-1].y;
        }
         mem[0].x=pos_moto1.x.x;
         mem[0].y=pos_moto1.x.y;
         mem2[0].x=pos_moto2.x.x;
         mem2[0].y=pos_moto2.x.y;

/****** Pour afficher en carré, il faut blitter la surface a chaque fois que l'on tourne aussi !*********/
        SDL_BlitSurface(menuc, NULL, ecran, NULL);
        for(i=0;i<mur-1;i++)
        {
            SDL_BlitSurface(moto1, NULL, ecran, &mem[i]);
            SDL_BlitSurface(moto2, NULL, ecran, &mem2[i]);

        }


        if(indice==2||indice==-2)
         {


            SDL_BlitSurface(img_c, NULL, ecran, &pos_moto1.x);
         }
         else if (indice==4||indice==-4)
         {
            SDL_BlitSurface(img_h, NULL, ecran, &pos_moto1.x);
         }
         if(indice2==2||indice2==-2)
         {
            SDL_BlitSurface(img_c2, NULL, ecran, &pos_moto2.x);
         }
         else if (indice2==-4 || indice2==4)
         {
            SDL_BlitSurface(img_h2, NULL, ecran, &pos_moto2.x);
         }

        SDL_Flip(ecran);



        }
        //SDL_Delay(1000);
        SDL_FreeSurface(moto1);
        SDL_FreeSurface(moto2);
        SDL_FreeSurface(p_win);

    }
Esempio n. 26
0
Menu::~Menu()
{
    SDL_FreeSurface( image );
}
void ONScripter::setupAnimationInfo( AnimationInfo *anim, FontInfo *info, bool single_line, ScriptDecoder* decoder )
{
    if (anim->trans_mode != AnimationInfo::TRANS_STRING &&
        anim->file_name && anim->surface_name &&
        strcmp(anim->file_name, anim->surface_name) == 0 &&
        ((!anim->mask_file_name && !anim->mask_surface_name) ||
         (anim->mask_file_name && !anim->mask_surface_name &&
          strcmp(anim->mask_file_name, anim->mask_surface_name) == 0))) return;

    anim->deleteSurface();
    anim->abs_flag = true;

    anim->surface_name = new char[ strlen(anim->file_name) + 1 ];
    strcpy( anim->surface_name, anim->file_name );

    if (anim->mask_file_name){
        anim->mask_surface_name = new char[ strlen(anim->mask_file_name) + 1 ];
        strcpy( anim->mask_surface_name, anim->mask_file_name );
    }
    
    if ( anim->trans_mode == AnimationInfo::TRANS_STRING ){
        FontInfo f_info = sentence_font;
        if (info) f_info = *info;
        f_info.rubyon_flag = anim->is_ruby_drawable;

        if ( anim->font_size_xy[0] >= 0 ){ // in case of Sprite, not rclick menu
            f_info.setTateyokoMode(0);
            f_info.top_xy[0] = anim->orig_pos.x;
            f_info.top_xy[1] = anim->orig_pos.y;
            if (anim->is_single_line)
                f_info.setLineArea( strlen(anim->file_name)/2+1 );
            f_info.clear();
            
            f_info.font_size_xy[0] = anim->font_size_xy[0];
            f_info.font_size_xy[1] = anim->font_size_xy[1];
            f_info.pitch_xy[0] = anim->font_pitch[0];
            f_info.pitch_xy[1] = anim->font_pitch[1];

            f_info.ttf_font[0] = NULL;
            f_info.ttf_font[1] = NULL;
        }

        if (f_info.ttf_font[0] == NULL)
            f_info.openFont( font_file, screen_ratio1, screen_ratio2 );

        SDL_Rect pos;
        if (anim->is_tight_region){
            drawString( anim->file_name, anim->color_list[ anim->current_cell ], &f_info, false, NULL, &pos, NULL, single_line, decoder );
        }
        else{
            int xy_bak[2];
            xy_bak[0] = f_info.xy[0];
            xy_bak[1] = f_info.xy[1];
            
            int xy[2] = {0, 0};
            f_info.setXY(f_info.num_xy[0]-1, f_info.num_xy[1]-1);
            pos = f_info.calcUpdatedArea(xy, screen_ratio1, screen_ratio2);

            f_info.xy[0] = xy_bak[0];
            f_info.xy[1] = xy_bak[1];
        }
        
        if (info != NULL){
            info->xy[0] = f_info.xy[0];
            info->xy[1] = f_info.xy[1];
        }
        
        anim->orig_pos.w = pos.w;
        anim->orig_pos.h = pos.h;
        anim->scalePosWH( screen_ratio1, screen_ratio2 );
        anim->allocImage( anim->pos.w*anim->num_of_cells, anim->pos.h, texture_format );
        anim->fill( 0, 0, 0, 0 );
        
        f_info.top_xy[0] = f_info.top_xy[1] = 0;
        for ( int i=0 ; i<anim->num_of_cells ; i++ ){
            f_info.clear();
            drawString( anim->file_name, anim->color_list[i], &f_info, false, NULL, NULL, anim, single_line, decoder );
            f_info.top_xy[0] += anim->orig_pos.w;
        }
    }
    else{
        bool has_alpha;
        int location;
        SDL_Surface *surface = loadImage( anim->file_name, &has_alpha, &location );

        SDL_Surface *surface_m = NULL;
        if (anim->trans_mode == AnimationInfo::TRANS_MASK)
            surface_m = loadImage( anim->mask_file_name );
        
        surface = anim->setupImageAlpha(surface, surface_m, has_alpha);

        if (surface &&
            screen_ratio2 != screen_ratio1 &&
            (!disable_rescale_flag || location == BaseReader::ARCHIVE_TYPE_NONE))
        {
            SDL_Surface *src_s = surface;

            int w, h;
            if ( (w = src_s->w * screen_ratio1 / screen_ratio2) == 0 ) w = 1;
            if ( (h = src_s->h * screen_ratio1 / screen_ratio2) == 0 ) h = 1;
            SDL_PixelFormat *fmt = image_surface->format;
            surface = SDL_CreateRGBSurface( SDL_SWSURFACE, w, h,
                                            fmt->BitsPerPixel, fmt->Rmask, fmt->Gmask, fmt->Bmask, fmt->Amask );
        
            resizeSurface(src_s, surface);
            SDL_FreeSurface(src_s);
        }

        anim->setImage( surface, texture_format );

        if ( surface_m ) SDL_FreeSurface(surface_m);
    }
}
Esempio n. 28
0
void img_free(SDL_Surface* img)
{
  if (img) SDL_FreeSurface(img);
}
Esempio n. 29
0
/**
 * @brief Loads a surface into an opengl texture.
 *
 *    @param surface Surface to load into a texture.
 *    @param flags Flags to use.
 *    @param[out] rw Real width of the texture.
 *    @param[out] rh Real height of the texture.
 *    @return The opengl texture id.
 */
static GLuint gl_loadSurface( SDL_Surface* surface, int *rw, int *rh, unsigned int flags, int freesur )
{
   GLuint texture;
   GLfloat param;

   /* Prepare the surface. */
   surface = gl_prepareSurface( surface );
   if (rw != NULL)
      (*rw) = surface->w;
   if (rh != NULL)
      (*rh) = surface->h;

   /* opengl texture binding */
   glGenTextures( 1, &texture ); /* Creates the texture */
   glBindTexture( GL_TEXTURE_2D, texture ); /* Loads the texture */

   /* Filtering, LINEAR is better for scaling, nearest looks nicer, LINEAR
    * also seems to create a bit of artifacts around the edges */
   if ((gl_screen.scale != 1.) || (flags & OPENGL_TEX_MIPMAPS)) {
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
   }
   else {
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
   }

   /* Always wrap just in case. */
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

   /* now lead the texture data up */
   SDL_LockSurface( surface );
   if (gl_texHasCompress()) {
      glTexImage2D( GL_TEXTURE_2D, 0, GL_COMPRESSED_RGBA,
            surface->w, surface->h, 0, GL_RGBA,
            GL_UNSIGNED_BYTE, surface->pixels );
   }
   else {
      glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA,
            surface->w, surface->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, surface->pixels );
   }
   SDL_UnlockSurface( surface );

   /* Create mipmaps. */
   if ((flags & OPENGL_TEX_MIPMAPS) && gl_texHasMipmaps()) {
      /* Do fancy stuff. */
      if (gl_hasExt("GL_EXT_texture_filter_anisotropic")) {
         glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &param);
         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, param);
      }
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 9);

      /* Now generate the mipmaps. */
      nglGenerateMipmap(GL_TEXTURE_2D);
   }

   /* cleanup */
   if (freesur)
      SDL_FreeSurface( surface );
   gl_checkErr();

   return texture;
}
Esempio n. 30
0
File: main.c Progetto: Zix777/C
int main(int argc, char** argv)
{
    srand(time(0));
    int i = 0;
    SDL_Init(SDL_INIT_VIDEO);
    SDL_Window* window = SDL_CreateWindow("SDL Practice 6.2",
                                          SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
                                          WINDOW_WIDTH, WINDOW_HEIGHT,
                                          SDL_WINDOW_SHOWN);
    SDL_Renderer* rend = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

    SDL_Surface* surface[26];
    surface[0] = IMG_Load("alpha\\A.png");
    surface[1] = IMG_Load("alpha\\B.png");
    surface[2] = IMG_Load("alpha\\C.png");
    surface[3] = IMG_Load("alpha\\D.png");
    surface[4] = IMG_Load("alpha\\E.png");
    surface[5] = IMG_Load("alpha\\F.png");
    surface[6] = IMG_Load("alpha\\G.png");
    surface[7] = IMG_Load("alpha\\H.png");
    surface[8] = IMG_Load("alpha\\I.png");
    surface[9] = IMG_Load("alpha\\J.png");
    surface[10] = IMG_Load("alpha\\K.png");
    surface[11] = IMG_Load("alpha\\L.png");
    surface[12] = IMG_Load("alpha\\M.png");
    surface[13] = IMG_Load("alpha\\N.png");
    surface[14] = IMG_Load("alpha\\O.png");
    surface[15] = IMG_Load("alpha\\P.png");
    surface[16] = IMG_Load("alpha\\Q.png");
    surface[17] = IMG_Load("alpha\\R.png");
    surface[18] = IMG_Load("alpha\\S.png");
    surface[19] = IMG_Load("alpha\\T.png");
    surface[20] = IMG_Load("alpha\\U.png");
    surface[21] = IMG_Load("alpha\\V.png");
    surface[22] = IMG_Load("alpha\\W.png");
    surface[23] = IMG_Load("alpha\\X.png");
    surface[24] = IMG_Load("alpha\\Y.png");
    surface[25] = IMG_Load("alpha\\Z.png");

    SDL_Texture* texture[26];
    for(i=0; i<26; ++i)
        texture[i] = SDL_CreateTextureFromSurface(rend, surface[i]);

    SDL_Surface* black_surface = SDL_LoadBMP("black.bmp");
    SDL_Texture* black_texture = SDL_CreateTextureFromSurface(rend, black_surface);
    SDL_SetTextureBlendMode(black_texture, SDL_BLENDMODE_BLEND);
    SDL_SetTextureAlphaMod(black_texture, 50);

    bool quit = false;
    SDL_Event event;
    SDL_Rect window_rect;
    window_rect.h = WINDOW_HEIGHT;
    window_rect.w = WINDOW_WIDTH;
    window_rect.x = 0;
    window_rect.y = 0;

    SDL_Rect pos[NUMBER];
    for(i = 0; i<NUMBER; ++i)
    {
        pos[i].w = surface[0]->w;
        pos[i].h = surface[0]->h;
        pos[i].x = rand() % (WINDOW_WIDTH + 1);
        pos[i].y = rand() % (WINDOW_HEIGHT / 2) + WINDOW_HEIGHT / 2;
    }

    int alphabet[NUMBER];
    for(i = 0; i<NUMBER; ++i)
        alphabet[i] = rand() % 27;
    while(!quit)
    {
        while(SDL_PollEvent(&event))
        {
            if(event.type == SDL_QUIT)
                quit = true;
        }
        SDL_RenderCopy(rend, black_texture, NULL, &window_rect);
        for(i = 0; i<NUMBER; ++i)
        {
            SDL_RenderCopy(rend, texture[alphabet[i]], NULL, &pos[i]);
            pos[i].y += (rand() % 10 + 10);
            if(pos[i].y > WINDOW_HEIGHT)
            {
                alphabet[i] = rand() % 27;
                pos[i].x = rand() % (WINDOW_WIDTH + 1);
                pos[i].y = rand() % (WINDOW_HEIGHT + 1);
            }
        }
        SDL_RenderPresent(rend);
        SDL_Delay(100);
    }

    for(i=0; i<26; ++i)
        SDL_FreeSurface(surface[0]);
    SDL_FreeSurface(black_surface);
    SDL_DestroyWindow(window);
    SDL_Quit();
    return 0;
}