Exemplo n.º 1
0
SDL_Surface *GetCIcon(FrameBuf *screen, short cicn_id)
{
	char file[256];
	DataDir data_dir;
	SDL_Surface *cicn;
	SDL_RWops *cicn_src;
	Uint8 *pixels, *mask;
	Uint16 w, h;
	
	/* Open the cicn sprite file.. */
	snprintf(file, sizeof(file), "Images/Maelstrom_Icon#%hd.cicn", cicn_id);
	if ( (cicn_src=SDL_RWFromFile(data_dir.FullPath(file), "r")) == NULL ) {
		error("GetCIcon(%hd): Can't open CICN %s: ",
					cicn_id, data_dir.FullPath(file));
		return(NULL);
	}

	w = SDL_ReadBE16(cicn_src);
	h = SDL_ReadBE16(cicn_src);
        pixels = new Uint8[w*h];
        if ( SDL_RWread(cicn_src, pixels, 1, w*h) != (w*h) ) {
		error("GetCIcon(%hd): Corrupt CICN!\n", cicn_id);
		delete[] pixels;
		SDL_RWclose(cicn_src);
		return(NULL);
	}
        mask = new Uint8[(w/8)*h];
        if ( SDL_RWread(cicn_src, mask, 1, (w/8)*h) != ((w/8)*h) ) {
		error("GetCIcon(%hd): Corrupt CICN!\n", cicn_id);
		delete[] pixels;
		delete[] mask;
		SDL_RWclose(cicn_src);
		return(NULL);
	}
	SDL_RWclose(cicn_src);

	cicn = screen->LoadImage(w, h, pixels, mask);
	delete[] pixels;
	delete[] mask;
	if ( cicn == NULL ) {
		error("GetCIcon(%hd): Couldn't convert CICN!\n", cicn_id);
	}
	return(cicn);
}
Exemplo n.º 2
0
/* Given a file_path and buffer, attempts to load save data into the buffer
 * up to the suppled size in bytes. Returns the size of the file if successful, 
 * returns 0 if unsuccessful. Buffer should at least be of length size*/
unsigned long load_SRAM(const char *file_path, unsigned char *data, unsigned long size) {
    
    log_message(LOG_INFO, "Attempting to load SRAM for file: %s\n",file_path);
    
    SDL_RWops *rw = SDL_RWFromFile(file_path, "rb");
    
    if (rw == NULL) {
        log_message(LOG_ERROR, 
            "Error opening file %s: %s\n", file_path, SDL_GetError());       
        return 0;
    }

    Sint64 res_size = SDL_RWsize(rw);
    if (res_size > size) {
        log_message(LOG_ERROR,
            "Error opening file %s: File is too large to be SRAM snapshot\n",
            file_path);
        return 0;
    }

    if (res_size == 0) {
        log_message(LOG_WARN, "File %s has a size of 0 bytes\n", file_path);
        return 0;
    }

    Sint64 nb_read_total = 0, nb_read = 1;
    unsigned char* buf = data;
    while (nb_read_total < res_size && nb_read != 0) {
            nb_read = SDL_RWread(rw, buf, 1, (res_size - nb_read_total));
            nb_read_total += nb_read;
            buf += nb_read;
    }

        SDL_RWclose(rw);
        if (nb_read_total != res_size) {
                log_message(LOG_ERROR, 
                    "Bytes expected (%lu) is not equal to bytes read (%lu)\n",
                    res_size, nb_read_total);
                free(data);
                return 0;
        }
    
    return res_size;
}
Exemplo n.º 3
0
void SdlAudio::BGM_Play(std::string const& file, int volume, int /* pitch */, int fadein) {
	std::string const path = FileFinder::FindMusic(file);
	if (path.empty()) {
		Output::Debug("Music not found: %s", file.c_str());
		return;
	}

	SDL_RWops *rw = SDL_RWFromFile(path.c_str(), "rb");
#if SDL_MIXER_MAJOR_VERSION>1
	bgm.reset(Mix_LoadMUS_RW(rw, 1), &Mix_FreeMusic);
#else
	bgm.reset(Mix_LoadMUS_RW(rw), &Mix_FreeMusic);
#endif
	if (!bgm) {
		Output::Warning("Couldn't load %s BGM.\n%s\n", file.c_str(), Mix_GetError());
		return;
	}
#if SDL_MAJOR_VERSION>1
	// SDL2_mixer produces noise when playing wav.
	// Workaround: Use Mix_LoadWAV
	// https://bugzilla.libsdl.org/show_bug.cgi?id=2094
	if (bgs_playing) {
		BGS_Stop();
	}
	if (Mix_GetMusicType(bgm.get()) == MUS_WAV) {
		BGM_Stop();
		BGS_Play(file, volume, 0, fadein);
		return;
	}
#endif

	BGM_Volume(volume);
	if (!me_stopped_bgm &&
#ifdef _WIN32
	    (Mix_GetMusicType(bgm.get()) == MUS_MID && WindowsUtils::GetWindowsVersion() >= 6
	     ? Mix_PlayMusic(bgm.get(), -1) : Mix_FadeInMusic(bgm.get(), -1, fadein))
#else
	     Mix_FadeInMusic(bgm.get(), -1, fadein)
#endif
	     == -1) {
		Output::Warning("Couldn't play %s BGM.\n%s\n", file.c_str(), Mix_GetError());
		return;
	}
}
Exemplo n.º 4
0
    void Map::loadFromFile(const std::string filename){
        this->map = new Tmx::Map();
        this->map->ParseFile(filename);

        if(map->HasError() == true) { throw map->GetErrorText(); }
        if(this->renderer == nullptr) { throw new ExNoRenderer(); }
        
        // Load image files
        const std::vector<Tmx::Tileset*>& tileSets = map->GetTilesets();
        for(int i = 0; i < tileSets.size(); ++i) {
            const Tmx::Tileset * tileSet = tileSets[i];
            const Tmx::Image * image = tileSet->GetImage();
            const std::string source = image->GetSource();
            SDL_RWops * rwop = SDL_RWFromFile(source.c_str(),"r");
            SDL_Surface * surf = IMG_LoadPNG_RW(rwop);
            SDL_Texture * tex = SDL_CreateTextureFromSurface(this->renderer, surf);
            this->images.push_back(tex);
        }
    }
Exemplo n.º 5
0
int init_gaia(void)
{
  struct SDL_Surface *Z;
  struct SDL_RWops *F;
  Sint32 w;
  int i, x=0;

  
  if( (F = SDL_RWFromFile("data/hblk01.dat","r")) == NULL)
    abend(0);

  for(i=0; i < 256*6; i++) {
    w = SDL_ReadLE32(F);
    w = (w < 6144)? 0: (w - 6144) / 320;
    subtile_table[i] = w;
    x = (w > x)? w : x;
  }
  printf("Gaia tile module:\n  +  %d unique subtiles.\n", x);
  x++;
  
  if(!(Z = CreateZSurface(get_pal("data/hpal01.dat"), 32,16*x)) )
    SDL_RWclose(F), abend(0);

  load_subtiles(F, Z->pixels, x);
  if(1) subtiles = Z;
  else {
    if( (subtiles = SDL_CreateRGBSurface(SDL_HWSURFACE,
					 32,16*x,32,
					 RR,GG,BB,AA)) )
      SDL_BlitSurface(Z, NULL, subtiles, NULL);
    SDL_FreeSurface(Z);
  }

  SDL_RWclose(F);

  lua_pushnumber(L, SCALE); lua_setfield(L, LUA_GLOBALSINDEX, "scale");
  lua_register(L, "s2m", s2m);
  lua_register(L, "m2s", m2s);

  REG_CLASS(L, map);

  return subtiles != NULL;
}
Exemplo n.º 6
0
/*static*/ bool	tqt::is_tqt_file(const char* filename)
// Return true if the given file looks like a .tqt file of our
// appropriate version.  Do this by attempting to read the header.
{
	SDL_RWops*	in = SDL_RWFromFile(filename, "rb");
	if (in == NULL) {
		return false;
	}

	// Read header.
	tqt_header_info	info = read_tqt_header_info(in);
	SDL_RWclose(in);

	if (info.m_version != TQT_VERSION) {
		return false;
	}
	
	return true;
}
Exemplo n.º 7
0
Sound_Sample *Sound_NewSampleFromFile(const char *filename,
                                      Sound_AudioInfo *desired,
                                      Uint32 bufferSize)
{
    const char *ext;
    SDL_RWops *rw;

    BAIL_IF_MACRO(!initialized, ERR_NOT_INITIALIZED, NULL);
    BAIL_IF_MACRO(filename == NULL, ERR_INVALID_ARGUMENT, NULL);

    ext = strrchr(filename, '.');
    rw = SDL_RWFromFile(filename, "rb");
    BAIL_IF_MACRO(rw == NULL, SDL_GetError(), NULL);

    if (ext != NULL)
        ext++;

    return(Sound_NewSample(rw, ext, desired, bufferSize));
} /* Sound_NewSampleFromFile */
Exemplo n.º 8
0
Arquivo: font.c Projeto: cbhuber/Games
static int open_font(lua_State * L) {
	const char * filename;
	lua_Integer fontsize;
	TTF_Font * font;
	TTF_Font ** ud;
	char adjusted_filename[MAX_ADJUSTED_FILENAME_LEN];
	SDL_RWops * file;
	
	filename = luaL_checkstring(L, 1);
	prepend_data_path(adjusted_filename, filename, MAX_ADJUSTED_FILENAME_LEN);
	file = SDL_RWFromFile(adjusted_filename, "rt");
	fontsize = luaL_checkinteger(L, 2);
	font = TTF_OpenFontRW(file, 1, fontsize);
	if (!font) fatal(TTF_GetError());
	ud = (TTF_Font **) lua_newuserdata(L, sizeof(TTF_Font *));
	if (ud == NULL) fatal("ud NULL in open_font");
	*ud = font;
	return 1;
}
Exemplo n.º 9
0
BaseD::Profile::Profile(const char* spc_filename)
{
  is_profiling = true;
  old_gain_db = BaseD::player->gain_db;
  BaseD::player->pause(1, true, false);
  BaseD::reload();
  BaseD::player->pause(0, false, false);
  BaseD::player->pause(1, false, false);
  //BaseD::player->restart_track();
  // Set Volume to 0
  player->set_gain_db(Music_Player::min_gain_db, true);
  // get pointer to spc_file_t
  // open the SPC File
  //DEBUGLOG("spc file path = %s\n", BaseD::g_cfg.playlist[BaseD::g_cur_entry]);
  //const char *spc_filename = BaseD::g_cfg.playlist[BaseD::g_cur_entry];
  // need to open a file
  SDL_RWops *orig_spc_file = SDL_RWFromFile(spc_filename, "rb");
  if (orig_spc_file == NULL)
  {
    sprintf(BaseD::tmpbuf, "Warning: Unable to open file %s!\n %s", spc_filename, SDL_GetError() );
    SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR,
                   "Could not open FILE!",
                   BaseD::tmpbuf,
                   NULL);
    //return -1;
    is_profiling=false;
    delete this;
  }

  if (SDL_RWread(orig_spc_file, orig_spc_state, Snes_Spc::spc_file_size, 1) == 0)
  {
    sprintf(BaseD::tmpbuf, "Warning: Unable to read file %s!\n %s", spc_filename, SDL_GetError() );
    SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR,
                   "Could not read file!",
                   BaseD::tmpbuf,
                   NULL);
    SDL_RWclose(orig_spc_file);
    //return -1;
    is_profiling=false;
    delete this;
  }
  else SDL_RWclose(orig_spc_file);
}
Exemplo n.º 10
0
void *inhale_file(const char *name, Uint32 blk, Uint32 off)
{
  struct SDL_RWops *F = NULL;
  Uint32 x, *n;
  void *p;

  if(!(F = SDL_RWFromFile(name,"r"))) abend(0);

  /* determine size */
  x = SDL_RWseek(F, 0, SEEK_END), SDL_RWseek(F, 0, SEEK_SET);
  off += sizeof(Uint32);

  if((n = p = malloc(off+x)) == NULL) abend(0);

  *n = SDL_RWread(F, p+off, blk, x/blk);
  SDL_RWclose(F);

  return p;
}
Exemplo n.º 11
0
void raw_save_file(terrain* t, char* filename) {
  
  SDL_RWops* file = SDL_RWFromFile(filename, "wb");
  
  if (!file) {
    error("Could not load file %s\n", filename);
  }
  
  uint16_t* pixels = malloc(sizeof(uint16_t) * t->width * t->height);
  
  for(int i = 0; i < t->width * t->height; i++) {
    pixels[i] = t->heightmap[i] * (65536.0 / MAX_HEIGHT);
  }
  
  SDL_RWwrite(file, pixels, sizeof(uint16_t) * t->width * t->height, 1);
  
  SDL_RWclose(file);
  
}
void close()
{
	//Open data for writing
	SDL_RWops* file = SDL_RWFromFile( "33_file_reading_and_writing/nums.bin", "w+b" );
	if( file != NULL )
	{
		//Save data
		for( int i = 0; i < TOTAL_DATA; ++i )
		{
			SDL_RWwrite( file, &gData[ i ], sizeof(Sint32), 1 );
		}

		//Close file handler
		SDL_RWclose( file );
	}
	else
	{
		printf( "Error: Unable to save file! %s\n", SDL_GetError() );
	}

	//Free loaded images
	gPromptTextTexture.free();
	for( int i = 0; i < TOTAL_DATA; ++i )
	{
		gDataTextures[ i ].free();
	}

	//Free global font
	TTF_CloseFont( gFont );
	gFont = NULL;

	//Destroy window	
	SDL_DestroyRenderer( gRenderer );
	SDL_DestroyWindow( gWindow );
	gWindow = NULL;
	gRenderer = NULL;

	//Quit SDL subsystems
	TTF_Quit();
	IMG_Quit();
	SDL_Quit();
}
Exemplo n.º 13
0
static int
DISKAUD_OpenDevice(_THIS, const char *devname, int iscapture)
{
    const char *envr = SDL_getenv(DISKENVR_WRITEDELAY);
    const char *fname = DISKAUD_GetOutputFilename(devname);

    this->hidden = (struct SDL_PrivateAudioData *)
        SDL_malloc(sizeof(*this->hidden));
    if (this->hidden == NULL) {
        SDL_OutOfMemory();
        return 0;
    }
    SDL_memset(this->hidden, 0, sizeof(*this->hidden));

    /* Open the audio device */
    this->hidden->output = SDL_RWFromFile(fname, "wb");
    if (this->hidden->output == NULL) {
        DISKAUD_CloseDevice(this);
        return 0;
    }

    /* Allocate mixing buffer */
    this->hidden->mixbuf = (Uint8 *) SDL_AllocAudioMem(this->hidden->mixlen);
    if (this->hidden->mixbuf == NULL) {
        DISKAUD_CloseDevice(this);
        return 0;
    }
    SDL_memset(this->hidden->mixbuf, this->spec.silence, this->spec.size);

    this->hidden->mixlen = this->spec.size;
    this->hidden->write_delay =
        (envr) ? SDL_atoi(envr) : DISKDEFAULT_WRITEDELAY;

#if HAVE_STDIO_H
    fprintf(stderr,
            "WARNING: You are using the SDL disk writer audio driver!\n"
            " Writing to file [%s].\n", fname);
#endif

    /* We're ready to rock and roll. :-) */
    return 1;
}
Exemplo n.º 14
0
static SDL_RWops* get_standard_rwop(PyObject* obj)
{
	if(PyString_Check(obj) || PyUnicode_Check(obj))
	{
		int result;
		char* name;
		PyObject* tuple = PyTuple_New(1);
		PyTuple_SET_ITEM(tuple, 0, obj);
		Py_INCREF(obj);
		if(!tuple) return NULL;
		result = PyArg_ParseTuple(tuple, "s", &name);
		Py_DECREF(tuple);
		if(!result)
			return NULL;
		return SDL_RWFromFile(name, "rb");
	}
	// else if(PyFile_Check(obj))
        //     return SDL_RWFromFP(PyFile_AsFile(obj), 0);
        return NULL;
}
Exemplo n.º 15
0
static void extract_fork(SDL_RWops *fin, int req_id, const char *file_name, const char *fork_name)
{
	long id, fork_start, fork_size;
	int num_entries, fork_found;
	SDL_RWops *fout;

	// Look for fork in source file
	SDL_RWseek(fin, 0x18, SEEK_SET);
	num_entries = SDL_ReadBE16(fin);
	while (num_entries--) {
		Uint32 id = SDL_ReadBE32(fin);
		Sint32 ofs = SDL_ReadBE32(fin);
		Sint32 len = SDL_ReadBE32(fin);
		if (id == req_id) {
			fork_found = 1;
			fork_start = ofs;
			fork_size = len;
		}
	}
	if (!fork_found) {
		fprintf(stderr, "Warning: source file doesn't contain a %s fork.\n", fork_name);
		return;
	}

	// Found, open destination file
	fout = SDL_RWFromFile(file_name, "wb");
	if (fout == NULL) {
		perror("Can't open destination file");
		exit(1);
	}

	// Copy fork
	SDL_RWseek(fin, fork_start, SEEK_SET);
	while (fork_size) {
		long length = fork_size > BUFFER_SIZE ? BUFFER_SIZE : fork_size;
		SDL_RWread(fin, buffer, 1, length);
		SDL_RWwrite(fout, buffer, 1, length);
		fork_size -= length;
	}
	SDL_FreeRW(fout);
}
Exemplo n.º 16
0
texture* lut_load_file( char* filename ) {
  
  SDL_RWops* file = SDL_RWFromFile(filename, "r");
  if(file == NULL) {
    error("Cannot load file %s", filename);
  }
  
  long size = SDL_RWseek(file,0,SEEK_END);
  unsigned char* contents = malloc(size+1);
  contents[size] = '\0';
  SDL_RWseek(file, 0, SEEK_SET);
  SDL_RWread(file, contents, size, 1);
  
  SDL_RWclose(file);
  
  int head = sizeof("CORANGE-LUT")-1;
  int lut_size = (unsigned char)contents[head] | (unsigned char)contents[head + 1];
  
  int offset = head + 3;
  
  texture* t = malloc(sizeof(texture));
  
  texture tex_id;
  glEnable(GL_TEXTURE_3D);
  glGenTextures(1, &tex_id);
  glBindTexture(GL_TEXTURE_3D, tex_id);
  glTexImage3D(GL_TEXTURE_3D, 0, GL_RGB, lut_size, lut_size, lut_size, 0, GL_RGB, GL_UNSIGNED_BYTE, contents + offset);
  glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
  glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);
  glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_MIRRORED_REPEAT);
  glDisable(GL_TEXTURE_3D);
  
  *t = tex_id;
  
  free(contents);
  
  return t;
  
}
Exemplo n.º 17
0
/*  Given a file_path and buffer to store file data in, attempts to
 *  read the file into the buffer. Returns the size of the file if successful,
 *  returns 0 if unsuccessful. Buffer should be at minimum of size "MAX_FILE_SIZE"*/
unsigned long load_rom_from_file(const char* filename, unsigned char *data) {
        SDL_RWops *rw = SDL_RWFromFile(filename, "rb");
        
        if (rw == NULL) {
            log_message(LOG_ERROR, 
                "Error opening file %s: %s\n", filename, SDL_GetError());       
            return 0;
        }

        Sint64 res_size = SDL_RWsize(rw);
        if (res_size > MAX_FILE_SIZE) {
            log_message(LOG_ERROR,
                "Error opening file %s: File is too large to be a Gameboy ROM\n",
                filename);
            return 0;
        }

        if (res_size == 0) {
            log_message(LOG_WARN, "File %s has a size of 0 bytes\n", filename);
            return 0;
        }

        Sint64 nb_read_total = 0, nb_read = 1;
        unsigned char* buf = data;
        while (nb_read_total < res_size && nb_read != 0) {
                nb_read = SDL_RWread(rw, buf, 1, (res_size - nb_read_total));
                nb_read_total += nb_read;
                buf += nb_read;
        }

        SDL_RWclose(rw);
        if (nb_read_total != res_size) {
                log_message(LOG_ERROR, 
                    "Bytes expected (%lu) is not equal to bytes read (%lu)\n",
                    res_size, nb_read_total);
                free(data);
                return 0;
        }

        return res_size;
}
Exemplo n.º 18
0
int savePNG(const std::string &filename,
			const unsigned char * data,int w,int h,_XColorMode color,
			int compression)
{
	if(data == NULL) return XFalse;
	SDL_RWops *fp;
	int ret;

	if((fp = SDL_RWFromFile(filename.c_str(),"wb")) == NULL) return -1;
	SDL_Surface * picArm = NULL;
	switch(color)
	{
	case COLOR_RGB:
	case COLOR_BGR:
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
		picArm = SDL_CreateRGBSurface(SDL_SWSURFACE,w,h,24,0xff000000, 0x00ff0000, 0x0000ff00, 0x00000000);
#else
		picArm = SDL_CreateRGBSurface(SDL_SWSURFACE,w,h,24,0x000000ff, 0x0000ff00, 0x00ff0000, 0x00000000);
#endif
		break;
	case COLOR_RGBA:
	case COLOR_BGRA:
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
		picArm = SDL_CreateRGBSurface(SDL_SWSURFACE,w,h,32,0xff000000, 0x00ff0000, 0x0000ff00, 0x00000000);
#else
		picArm = SDL_CreateRGBSurface(SDL_SWSURFACE,w,h,32,0x000000ff, 0x0000ff00, 0x00ff0000, 0x00000000);
#endif
		break;
	default:	//其他格式不支持
		return -1;
		break;
	}
	//这里可以考虑保存成24位色提升效率
	memcpy(picArm->pixels,data,w * h * picArm->format->BytesPerPixel);

	ret = IMG_SavePNG_RW(fp,picArm,compression);
	SDL_FreeSurface(picArm);
	picArm = NULL;
	SDL_RWclose(fp);
	return ret;
}
Exemplo n.º 19
0
int main(int argc, char *argv[])
{
    if (argc != 2) {
        fprintf(stderr, "usage: %s <filename>\n", argv[0]);
        return 1;
    }

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

    if (Sound_Init() == 0) {
        fprintf(stderr, "Error: %s\n", Sound_GetError());
        return 1;
    }

    SDL_RWops* rw = SDL_RWFromFile(argv[1], "r");
    if (rw == NULL) {
        fprintf(stderr, "Error: %s\n", SDL_GetError());
        return 1;
    }

    Sound_AudioInfo wantedFormat;
    wantedFormat.channels = 2;
    wantedFormat.rate = 44100;
    wantedFormat.format = AUDIO_S16LSB;

    Sound_Sample* sample = Sound_NewSample(rw, 0, &wantedFormat, 8192);
    if (sample == 0) {
        fprintf(stderr, "Error: %s\n", Sound_GetError());
        return 1;
    }

    Sound_DecodeAll(sample);
    printf("Format: %s\n", sample->decoder->description);
    printf("Decoded %d bytes of data.\n", sample->buffer_size);
    Sound_FreeSample(sample);

    return 0;
}
Exemplo n.º 20
0
bool Sample::Load(const char* filename)
{
	Unload();
	SDL_RWops* rw = SDL_RWFromFile(filename, "rb");
	if (!rw) {
		SDL_RWclose(rw);
		return false;
	}
	SDL_AudioSpec audiospec;
	memset(&audiospec, 0, sizeof(audiospec));
	SDL_AudioSpec* spec = SDL_LoadWAV_RW(rw, false, &audiospec, &data, (Uint32*)&length);
	if (spec != NULL) {
		format.freq = spec->freq;
		format.format = spec->format;
		format.channels = spec->channels;
		issdlwav = true;
	} else {
		return false;
	}
	return true;
}
Exemplo n.º 21
0
Arquivo: file.cpp Projeto: tkochi/xm8
//
// Open()
// open file
//
bool FileIO::Open(const _TCHAR* filename, uint flg)
{
	SDL_RWops *ops;

	Close();

	// support readonly mode
	if (flg != readonly) {
		return false;
	}

	// open with 'rb' mode
	ops = SDL_RWFromFile(filename, "rb");
	if (ops == NULL) {
		return false;
	}

	// return
	hfile = ops;
	return true;
}
Exemplo n.º 22
0
void *FontInfo::openFont( char *font_file, int ratio1, int ratio2 )
{
    int font_size;
    if ( font_size_xy[0] < font_size_xy[1] )
        font_size = font_size_xy[0];
    else
        font_size = font_size_xy[1];

    FontContainer *fc = &root_font_container;
    while( fc->next ){
        if ( fc->next->size == font_size ) break;
        fc = fc->next;
    }
    if ( !fc->next ){
        fc->next = new FontContainer();
        fc->next->size = font_size;
        FILE *fp = fopen( font_file, "r" );
        if ( fp == NULL ) return NULL;
        fclose( fp );
#if defined(PSP)
        fc->next->rw_ops = SDL_RWFromFile(font_file, "r");
        fc->next->font = TTF_OpenFontRW( fc->next->rw_ops, SDL_TRUE, font_size * ratio1 / ratio2 );
        fc->next->power_resume_number = psp_power_resume_number;
        strcpy(fc->next->name, font_file);
#else
        fc->next->font = TTF_OpenFont( font_file, font_size * ratio1 / ratio2 );
#endif
    }
#if defined(PSP)
    else if (fc->next->power_resume_number != psp_power_resume_number){
        FILE *fp = fopen(fc->next->name, "r");
        fc->next->rw_ops->hidden.stdio.fp = fp;
        fc->next->power_resume_number = psp_power_resume_number;
    }
#endif

    ttf_font = (void*)fc->next->font;
    
    return fc->next->font;
}
Exemplo n.º 23
0
void LoadFile(const String& fileName, const String& reference, SDL_Renderer* renderer)
{
	//Setup the text data filename
	String dataFileName = fileName.substr(0, fileName.length() - 4) + ".txt";

	#ifdef __ANDROID__

		//Open the file with RWops function and process each line
		SDL_RWops *rw = SDL_RWFromFile(dataFileName.c_str(), "rb");

		if(rw > 0)
		{
			__android_log_write(ANDROID_LOG_INFO, "Chain Drop", "Loading texture file");
			ProcessAndroidTextFile(rw, reference);
			SDL_FreeRW(rw);
			textureReferences[reference] = LoadTextureFromFile(fileName, renderer);
		}
		else
			logError(std::cout, "LoadFile: error opening: " + dataFileName);

	#elif _WIN32

		//Open the file with a filestream and process each line
		std::ifstream file(dataFileName);

		if (file.is_open())
		{
			String line;

			while(getline(file, line))
			{
				ProcessFileLine(line, reference);
			}
			file.close();
			textureReferences[reference] = LoadTextureFromFile(fileName, renderer);
		}
		else
			logError(std::cout, "LoadFile: error opening: " + dataFileName);
	#endif
}
Exemplo n.º 24
0
static void mavlink_parseDoc (char *docname) {
	xmlDocPtr doc;
	xmlNodePtr cur;
	if (strncmp(docname, "./", 2) == 0) {
		docname += 2;
	}
	char *buffer = NULL;
	int len = 0;
	SDL_RWops *ops_file = SDL_RWFromFile(docname, "r");
	if (ops_file == NULL) {
		SDL_Log("map: Document open failed: %s\n", docname);
		return;
	}
	len = SDL_RWseek(ops_file, 0, SEEK_END);
	SDL_RWseek(ops_file, 0, SEEK_SET);
	buffer = malloc(len);
	SDL_RWread(ops_file, buffer, 1, len);
	doc = xmlParseMemory(buffer, len);
	SDL_RWclose(ops_file);
	free(buffer);
	if (doc == NULL) {
		SDL_Log("mavlink: Document parsing failed: %s\n", docname);
		return;
	}
	cur = xmlDocGetRootElement(doc);
	if (cur == NULL) {
		xmlFreeDoc(doc);
		SDL_Log("mavlink: Document is Empty!!!\n");
		return;
	}
	cur = cur->xmlChildrenNode;
	while (cur != NULL) {
		if ((xmlStrcasecmp(cur->name, (const xmlChar *)"text"))) {
			mavlink_parseParams(doc, cur);
		}
		cur = cur->next;
	}
	xmlFreeDoc(doc);
	return;
}
Exemplo n.º 25
0
static int audiosourcefile_Read(struct audiosource* source, char* buffer, unsigned int bytes) {
    struct audiosourcefile_internaldata* idata = source->internaldata;

    if (idata->file == NULL) {
        if (idata->eof) {
            return -1;
        }
#ifdef SDLRW
        idata->file = SDL_RWFromFile(idata->path, "rb");
#else
        idata->file = fopen(idata->path,"rb");
#endif
        if (!idata->file) {
            idata->file = NULL;
            return -1;
        }
    }

#ifdef SDLRW
    int bytesread = idata->file->read(idata->file, buffer, 1, bytes);
#else
    int bytesread = fread(buffer, 1, bytes, idata->file);
#endif
    if (bytesread > 0) {
        return bytesread;
    }else{
#ifdef SDLRW
        idata->file->close(idata->file);
#else
        fclose(idata->file);
#endif
        idata->file = NULL;
        idata->eof = 1;
        if (bytesread < 0) {
            return -1;
        }
        return 0;
    }
}
Exemplo n.º 26
0
//------------------------------------------------------------------------------------
// Проверка наличия файла в VFS или FS
//------------------------------------------------------------------------------------
int FileDetect(const char *FileName)
{
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// поиск в VFS
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	eVFS_Entry *Tmp = StarVFSArray;
	while (Tmp != 0)
	{
		eVFS_Entry *Tmp1 = Tmp->Next;

		if(strcmp(FileName, Tmp->Name) == 0)
		{
			// нашли
			return VFS_FILE_VFS;
		}

		Tmp = Tmp1;
	}




	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// поиск в FS
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	SDL_RWops *temp = SDL_RWFromFile(FileName, "rb");
	// смогли открыть файл
	if (temp != NULL)
	{
		SDL_RWclose(temp);
        return VFS_FILE_FS;
	}


	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// Файл не найден
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	return -1;
}
Exemplo n.º 27
0
/**
 * @brief Tests writing from file.
 *
 * \sa
 * http://wiki.libsdl.org/moin.cgi/SDL_RWFromFile
 * http://wiki.libsdl.org/moin.cgi/SDL_RWClose
 */
int
rwops_testFileWrite(void)
{
   SDL_RWops *rw;
   int result;

   /* Write test. */
   rw = SDL_RWFromFile(RWopsWriteTestFilename, "w+");
   SDLTest_AssertPass("Call to SDL_RWFromFile(..,\"w+\") succeeded");
   SDLTest_AssertCheck(rw != NULL, "Verify opening file with SDL_RWFromFile in write mode does not return NULL");

   /* Bail out if NULL */
   if (rw == NULL) return TEST_ABORTED;

   /* Check type */
#if defined(ANDROID)
   SDLTest_AssertCheck(
      rw->type == SDL_RWOPS_STDFILE || rw->type == SDL_RWOPS_JNIFILE,
      "Verify RWops type is SDL_RWOPS_STDFILE or SDL_RWOPS_JNIFILE; expected: %d|%d, got: %d", SDL_RWOPS_STDFILE, SDL_RWOPS_JNIFILE, rw->type);
#elif defined(__WIN32__)
   SDLTest_AssertCheck(
      rw->type == SDL_RWOPS_WINFILE,
      "Verify RWops type is SDL_RWOPS_WINFILE; expected: %d, got: %d", SDL_RWOPS_WINFILE, rw->type);
#else
   SDLTest_AssertCheck(
      rw->type == SDL_RWOPS_STDFILE,
      "Verify RWops type is SDL_RWOPS_STDFILE; expected: %d, got: %d", SDL_RWOPS_STDFILE, rw->type);
#endif

   /* Run generic tests */
   _testGenericRWopsValidations( rw, 1 );

   /* Close handle */
   result = SDL_RWclose(rw);
   SDLTest_AssertPass("Call to SDL_RWclose() succeeded");
   SDLTest_AssertCheck(result == 0, "Verify result value is 0; got: %d", result);

   return TEST_COMPLETED;
}
Exemplo n.º 28
0
//------------------------------------------------------------------------------------
// запись данных в VFS
//------------------------------------------------------------------------------------
int vw_WriteIntoVFSfromFile(const char *SrcName, const char *DstName)
{
	if (SrcName == 0) return -1;
	if (DstName == 0) return -1;

	// читаем данные файла в буфер
	SDL_RWops *Ftmp = SDL_RWFromFile(SrcName, "rb");
	// Если файл не найден - выходим
	if (Ftmp == NULL)
    {
		fprintf(stderr, "Can't find file %s !!!\n", SrcName);
        return -1;
    }

	// получаем размер файла
	SDL_RWseek(Ftmp, 0, SEEK_END);
	int tmpLength = SDL_RWtell(Ftmp);
	SDL_RWseek(Ftmp, 0, SEEK_SET);

	// копируем все данные файла в массив
	BYTE *tmp = 0;
	tmp = new BYTE[tmpLength];
	SDL_RWread(Ftmp, tmp, tmpLength, 1);
	SDL_RWclose(Ftmp);

	// запись в VFS
	if (0 != vw_WriteIntoVFSfromMemory(DstName, tmp, tmpLength))
	{
		// какая-то ошибка, не можем записать в VFS
		delete [] tmp; tmp = 0;
		fprintf(stderr, "Can't write into VFS from memory %s !!!\n", DstName);
		return -1;
	}

	// Освобождаем память
	delete [] tmp; tmp = 0;

	return 0;
}
Exemplo n.º 29
0
// Apple provides both stream and file loading functions in ImageIO.
// Potentially, Apple can optimize for either case.
SDL_Surface* IMG_Load(const char *file)
{
	SDL_Surface* sdl_surface = NULL;

	sdl_surface = LoadImageFromFile(file);
	if(NULL == sdl_surface)
	{
		// Either the file doesn't exist or ImageIO doesn't understand the format.
		// For the latter case, fallback to the native SDL_image handlers.
		SDL_RWops *src = SDL_RWFromFile(file, "rb");
		char *ext = strrchr(file, '.');
		if(ext) {
			ext++;
		}
		if(!src) {
			/* The error message has been set in SDL_RWFromFile */
			return NULL;
		}
		sdl_surface = IMG_LoadTyped_RW(src, 1, ext);
	}
	return sdl_surface;
}
Exemplo n.º 30
0
  void SourceMusic::CreateSample(void) {
    _rwops = SDL_RWFromFile(_filename, "rb");
	char *ext = _filename;
	for(int i = 0; *(_filename + i); i++)
	{
		if(*(_filename + i) == '.')
			ext = _filename + i + 1;
	}
    _sample = Sound_NewSample(_rwops, ext,
															_system->GetAudioInfo(),
															_sample_buffersize );

    if(_sample == NULL) {
		fprintf(stderr, "[error] failed loading sample type %s, from %s: %s\n", ext,
			_filename, Sound_GetError());
		return;
	}

    _read = 0;
    _decoded = 0;
    // fprintf(stderr, "created sample\n");
  }