Beispiel #1
0
 TestArchive()
 {
   {
   Archive* archive = OpenArchive("");
   archive->release();
   }
   {
   Archive* archive = OpenArchive("NONEXISTANTFILE");
   archive->release();
   }
   {
   Archive* archive = OpenArchive("c:/quake/id1/quake101.wad");
   ArchiveFile* file = archive->openFile("textures/sky1.mip");
   if(file != 0)
   {
     unsigned char* buffer = new unsigned char[file->size()];
     file->getInputStream().read((InputStream::byte_type*)buffer, file->size());
     delete[] buffer;
     file->release();
   }
   TestVisitor visitor;
   archive->forEachFile(Archive::VisitorFunc(&visitor, Archive::eFilesAndDirectories, 1), "");
   archive->forEachFile(Archive::VisitorFunc(&visitor, Archive::eFilesAndDirectories, 0), "");
   archive->forEachFile(Archive::VisitorFunc(&visitor, Archive::eFilesAndDirectories, 0), "textures/");
   archive->forEachFile(Archive::VisitorFunc(&visitor, Archive::eFilesAndDirectories, 1), "textures/");
   archive->release();
   }
 }
Beispiel #2
0
NodeSmartReference ModelResource_load(ModelLoader* loader, const char* name)
{
  ScopeDisableScreenUpdates disableScreenUpdates(path_get_filename_start(name), "Loading Model");

  NodeSmartReference model(g_nullModel);

  {
    ArchiveFile* file = GlobalFileSystem().openFile(name);

    if(file != 0)
    {
      globalOutputStream() << "Loaded Model: \"" << name << "\"\n";
      model = loader->loadModel(*file);
      file->release();
    }
    else
    {
      globalErrorStream() << "Model load failed: \"" << name << "\"\n";
    }
  }

  model.get().m_isRoot = true;

  return model;
}
Beispiel #3
0
bool ArchiveManager::ExtractArchiveFile( const char* InPath, const char* OutPath, bool AppendFilePath /*= false*/ )
{
	bool Result = false;

	if (InPath)
	{
		std::string Path(InPath); 
		SME::StringHelpers::MakeLower(Path);

		if (Path.find("data\\") != -1)
			Path = Path.substr(Path.find("data\\") + 5);

		if (_FILEFINDER->FindFile(Path.c_str()) == 2)
		{
			ArchiveFile* ArchiveFileStream = CS_CAST(_FILEFINDER->GetFileStream(Path.c_str(), false, 0x50000), NiBinaryStream, ArchiveFile);
			if (ArchiveFileStream)
			{
				UInt32 FileSize = ArchiveFileStream->GetFileSize();
				std::string ArchiveFilePath = ArchiveFileStream->fileName;
				std::string ArchiveFileName = ArchiveFilePath.substr(ArchiveFilePath.rfind("\\") + 1);
				std::string FileOut = OutPath;

				if (AppendFilePath)
					FileOut += "\\" + ArchiveFilePath;

				DeleteFile(FileOut.c_str());		// delete file as BSFile::Ctor doesn't create it anew

				BSFile* TempFile = BSFile::CreateInstance(FileOut.c_str(), NiFile::kFileMode_WriteOnly, FileSize);
				SME_ASSERT(TempFile);

				void* Buffer = FormHeap_Allocate(FileSize);
				ZeroMemory(Buffer, FileSize);

				if (!ArchiveFileStream->DirectRead(Buffer, FileSize))
				{
					BGSEECONSOLE_MESSAGE("ArchiveManager::ExtractArchiveFile - Couldn't read file %s from archive %s", ArchiveFileStream->fileName, ArchiveFileStream->parentArchive->fileName);
				}
				else
				{
					if (!TempFile->DirectWrite(Buffer, FileSize))
					{
						BGSEECONSOLE_MESSAGE("ArchiveManager::ExtractArchiveFile - Couldn't write to file %s", TempFile->fileName);
					}
					else
						Result = true;
				}

				TempFile->Flush();
				TempFile->DeleteInstance();
				ArchiveFileStream->DeleteInstance();
				FormHeap_Free(Buffer);
			}
		}
	}

	return Result;
}
Beispiel #4
0
	void RoutingLumpLoader::loadRoutingLump (ArchiveFile& file)
	{
		/* load the file */
		InputStream &stream = file.getInputStream();
		const std::size_t size = file.size();
		byte *buf = (byte*) malloc(size + 1);
		dBspHeader_t *header = (dBspHeader_t *) buf;
		stream.read(buf, size);

		CMod_LoadRouting(_routingLump, file.getName(), &header->lumps[LUMP_ROUTING], (byte *) buf, 0, 0, 0);
		free(buf);
	}
Beispiel #5
0
 void test1()
 {
   Archive* archive = OpenArchive("d:/quake/id1/");
   ArchiveFile* file = archive->openFile("quake101.wad");
   if(file != 0)
   {
     char buffer[1024];
     file->getInputStream().read(buffer, 1024);
     file->release();
   }
   TestVisitor visitor;
   archive->forEachFile(Archive::VisitorFunc(&visitor, Archive::eFilesAndDirectories, 0), "");
   archive->release();
 }
Beispiel #6
0
// NOTE: when loading a file, you have to allocate one extra byte and set it to \0
std::size_t LoadFile (const char *filename, void **bufferptr, int index)
{
  char fixed[PATH_MAX+1];

  strncpy (fixed, filename, PATH_MAX);
  fixed[PATH_MAX] = '\0';
  FixDOSName (fixed);

  ArchiveFile* file = OpenFile(fixed);
  
  if(file != 0)
  {
    *bufferptr = malloc (file->size()+1);
    // we need to end the buffer with a 0
    ((char*) (*bufferptr))[file->size()] = 0;

    std::size_t length = file->getInputStream().read((InputStream::byte_type*)*bufferptr, file->size());
    file->release();
    return length;
  }

  *bufferptr = 0;
  return 0;
}
Beispiel #7
0
ImagePtr LoadImageGDK(ArchiveFile& file) {
	
	// Allocate a new GdkPixBuf and create an alpha-channel with alpha=1.0
	GdkPixbuf* rawPixbuf = gdk_pixbuf_new_from_file(file.getName().c_str(), NULL);
	
	// Only create an alpha channel if the other rawPixbuf could be loaded
	GdkPixbuf* img = (rawPixbuf != NULL) ? gdk_pixbuf_add_alpha(rawPixbuf, TRUE, 255, 0, 255) : NULL;
	
	if (img != NULL) {
		// Allocate a new image
		RGBAImagePtr image (new RGBAImage(gdk_pixbuf_get_width(img), gdk_pixbuf_get_height(img)));
		
		// Initialise the source buffer pointers
		guchar* gdkStart = gdk_pixbuf_get_pixels(img);
		int rowstride = gdk_pixbuf_get_rowstride(img);
		int numChannels = gdk_pixbuf_get_n_channels(img);
		
		// Set the target buffer pointer to the first RGBAPixel
		RGBAPixel* targetPixel = image->pixels;
		
		// Now do an unelegant cycle over all the pixels and move them into the target
		for (unsigned int y = 0; y < image->height; y++) {
			for (unsigned int x = 0; x < image->width; x++) {
				guchar* gdkPixel = gdkStart + y*rowstride + x*numChannels;
				
				// Copy the values from the GdkPixel
				targetPixel->red = gdkPixel[0];
				targetPixel->green = gdkPixel[1];
				targetPixel->blue = gdkPixel[2];
				targetPixel->alpha = gdkPixel[3];
				
				// Increase the pointer
				targetPixel++;
			}
		}
		
		// Free the GdkPixbufs from the memory
		g_object_unref(G_OBJECT(img)); 
		g_object_unref(G_OBJECT(rawPixbuf));

		return image;
	}
	
	// No image could be loaded, return NULL	
	return ImagePtr();
}
Beispiel #8
0
void SymbolTable::addLazyArchive(StringRef Name, ArchiveFile &File,
                                 const object::Archive::Symbol Sym) {
  Symbol *S;
  bool WasInserted;
  std::tie(S, WasInserted) = insertName(Name);
  if (WasInserted) {
    replaceSymbol<LazyArchive>(S, File, STT_NOTYPE, Sym);
    return;
  }
  if (!S->isUndefined())
    return;

  // An undefined weak will not fetch archive members. See comment on Lazy in
  // Symbols.h for the details.
  if (S->isWeak()) {
    replaceSymbol<LazyArchive>(S, File, S->Type, Sym);
    S->Binding = STB_WEAK;
    return;
  }

  if (InputFile *F = File.fetch(Sym))
    parseFile<ELFT>(F);
}
Beispiel #9
0
// example input Name:          "C:\games.zip"
// example output LogicalName:  "C:\games.zip|Sonic.smd"
// example output PhysicalName: "C:\Documents and Settings\User\Local Settings\Temp\Gens\dec3.tmp"
// assumes arguments are character buffers with 1024 bytes each
bool ObtainFile(const char* Name, char *const & LogicalName, char *const & PhysicalName, const char* category, const char** ignoreExtensions, int numIgnoreExtensions)
{
	char ArchivePaths [1024];
	strcpy(LogicalName, Name);
	strcpy(PhysicalName, Name);
	strcpy(ArchivePaths, Name);
	char* bar = strchr(ArchivePaths, '|');
	if(bar)
	{
		PhysicalName[bar - ArchivePaths] = 0; // doesn't belong in the physical name
		LogicalName[bar - ArchivePaths] = 0; // we'll reconstruct the logical name as we go
		*bar++ = 0; // bar becomes the next logical archive path component
	}

	while(true)
	{
		ArchiveFile archive (PhysicalName);
		if(!archive.IsCompressed())
		{
			return archive.GetNumItems() > 0;
		}
		else
		{
			int item = -1;
			bool forceManual = false;
			if(bar && *bar) // try following the in-archive part of the logical path
			{
				char* bar2 = strchr(bar, '|');
				if(bar2) *bar2++ = 0;
				int numItems = archive.GetNumItems();
				for(int i = 0; i < numItems; i++)
				{
					if(archive.GetItemSize(i))
					{
						const char* itemName = archive.GetItemName(i);
						if(!_stricmp(itemName, bar))
						{
							item = i; // match found, now we'll auto-follow the path
							break;
						}
					}
				}
				if(item < 0)
				{
					forceManual = true; // we don't want it choosing something else without user permission
					bar = NULL; // remaining archive path is invalid
				}
				else
					bar = bar2; // advance to next archive path part
			}
			if(item < 0)
				item = ChooseItemFromArchive(archive, !forceManual, ignoreExtensions, numIgnoreExtensions);

			const char* TempFileName = s_tempFiles.GetFile(category, strrchr(archive.GetItemName(item), '.'));
			if(!archive.ExtractItem(item, TempFileName))
				s_tempFiles.ReleaseFile(TempFileName);
			s_tempFiles.ReleaseFile(PhysicalName);
			strcpy(PhysicalName, TempFileName);
			_snprintf(LogicalName + strlen(LogicalName), 1024 - (strlen(LogicalName)+1), "|%s", archive.GetItemName(item));
		}
	}
}
Beispiel #10
0
ImagePtr LoadDDS(ArchiveFile& file) {
	return LoadDDSFromStream(file.getInputStream());
}
Beispiel #11
0
void MD2Surface_read( Model& model, const byte* buffer, ArchiveFile& file ){
	Surface& surface = model.newSurface();
	md2Header_t header;
	{
		PointerInputStream inputStream( buffer );
		istream_read_md2Header( inputStream, header );
	}

	{

		md2Frame_t frame;
		PointerInputStream frameStream( buffer + header.ofs_frames );
		istream_read_md2Frame( frameStream, frame );


		surface.indices().reserve( header.num_tris * 3 );

		Array<md2XyzNormal_t> md2Xyz( header.num_xyz );
		for ( Array<md2XyzNormal_t>::iterator i = md2Xyz.begin(); i != md2Xyz.end(); ++i )
		{
			istream_read_md2XyzNormal( frameStream, *i );
		}

		Array<md2St_t> md2St( header.num_st );
		PointerInputStream stStream( buffer + header.ofs_st );
		for ( Array<md2St_t>::iterator i = md2St.begin(); i != md2St.end(); ++i )
		{
			istream_read_md2St( stStream, *i );
		}

		UniqueVertexBuffer<ArbitraryMeshVertex> inserter( surface.vertices() );
		inserter.reserve( header.num_st );

		PointerInputStream triangleStream( buffer + header.ofs_tris );
		for ( int i = 0; i < header.num_tris; ++i )
		{
			md2Triangle_t triangle;
			istream_read_md2Triangle( triangleStream, triangle );
			surface.indices().insert( inserter.insert( MD2Vertex_construct( &header, &frame, &md2Xyz[triangle.index_xyz[0]], &md2St[triangle.index_st[0]] ) ) );
			surface.indices().insert( inserter.insert( MD2Vertex_construct( &header, &frame, &md2Xyz[triangle.index_xyz[1]], &md2St[triangle.index_st[1]] ) ) );
			surface.indices().insert( inserter.insert( MD2Vertex_construct( &header, &frame, &md2Xyz[triangle.index_xyz[2]], &md2St[triangle.index_st[2]] ) ) );
		}
	}

	char skinname[MD2_MAX_SKINNAME];
	char skinnameRelative[MD2_MAX_SKINNAME];
	char path[MD2_MAX_SKINNAME];
	int i = MD2_MAX_SKINNAME;
	PointerInputStream inputStream( buffer + header.ofs_skins );
	inputStream.read( reinterpret_cast<byte*>( skinnameRelative ), MD2_MAX_SKINNAME );
	// relative texture path - allows moving of models in game dir structure without changing the skinpath
	// e.g. used in ufo:ai
	if ( skinnameRelative[0] == '.' ) {
		strncpy( path, file.getName(), MD2_MAX_SKINNAME );
		for (; i--; )
		{
			// skip filename
			if ( path[i] == '/' || path[i] == '\\' ) {
				break;
			}
			path[i] = '\0';
		}
//	globalErrorStream() << "modified skinname: " << path << " (path) and " << skinnameRelative << " (texture)" << "\n";
		snprintf( skinname, MD2_MAX_SKINNAME, "%s%s", path, &skinnameRelative[1] );
//	globalErrorStream() << skinname << "\n";
	}
	else
	{
		strcpy( skinname, skinnameRelative );
	}
	surface.setShader( skinname );
	surface.updateAABB();
}
int ChooseItemFromArchive(ArchiveFile& archive, bool autoChooseIfOnly1, const char** ignoreExtensions, int numIgnoreExtensions)
{
    int prevNumIgnoreExtensions = numIgnoreExtensions;
    archive.m_userMadeSelection = false;

    // prepare a list of files to choose from the archive
    ArchiveFileChooserInfo info (archive, ignoreExtensions, numIgnoreExtensions);

    // based on our list, decide which item in the archive to choose

    // check if there's nothing
    if(info.files.size() < 1)
    {
        MessageBox(GetArchiveParentHWND(), "The archive is either empty or encrypted.", "Nothing to load!", MB_OK | MB_ICONWARNING);
        return -1;
    }

    // warn if all the files in the archive have extensions we should ignore
    if(numIgnoreExtensions != prevNumIgnoreExtensions)
    {
        CString msg;
        msg.Format("The archive appears to only contain the wrong type of files.\n\n(in \"%s\")", archive.GetArchiveFileName());
        int answer = MessageBox(GetArchiveParentHWND(), msg, "Warning", MB_OKCANCEL | MB_ICONWARNING | MB_DEFBUTTON2);
        if(answer == IDCANCEL)
            return -1;
    }

    // if there's only 1 item, choose it
    if(info.files.size() == 1 && autoChooseIfOnly1 && numIgnoreExtensions == prevNumIgnoreExtensions)
        return info.files[0].itemIndex;

    // bring up a dialog to choose the index if there's more than 1
    DialogBoxParam(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDD_ARCHIVEFILECHOOSER), GetArchiveParentHWND(), (DLGPROC) ArchiveFileChooser,(LPARAM) &info);
    archive.m_userMadeSelection = (s_archiveFileChooserResult != -1);
    return s_archiveFileChooserResult;
}
Beispiel #13
0
void SoundPlayer::play(ArchiveFile& file) {
	// If we're not initialised yet, do it now
	if (!_initialised) {
		initialise();
    }

	// Stop any previous playback operations, that might be still active
	clearBuffer();

	// Retrieve the extension
	std::string ext = os::getExtension(file.getName());

	if (boost::algorithm::to_lower_copy(ext) == "ogg") {
		// Convert the file into a buffer, self-destructs at end of scope
		ScopedArchiveBuffer buffer(file);

		// This is an OGG Vorbis file, decode it
		vorbis_info* vorbisInfo;
  		OggVorbis_File oggFile;

  		// Initialise the wrapper class
  		OggFileStream stream(buffer);

  		// Setup the callbacks and point them to the helper class
  		ov_callbacks callbacks;
  		callbacks.read_func = OggFileStream::oggReadFunc;
  		callbacks.seek_func = OggFileStream::oggSeekFunc;
  		callbacks.close_func = OggFileStream::oggCloseFunc;
  		callbacks.tell_func = OggFileStream::oggTellFunc;

  		// Open the OGG data stream using the custom callbacks
  		int res = ov_open_callbacks(static_cast<void*>(&stream), &oggFile,
									NULL, 0, callbacks);

  		if (res == 0) {
  			// Open successful

  			// Get some information about the OGG file
			vorbisInfo = ov_info(&oggFile, -1);

			// Check the number of channels
			ALenum format = (vorbisInfo->channels == 1) ? AL_FORMAT_MONO16
														: AL_FORMAT_STEREO16;

			// Get the sample Rate
			ALsizei freq = (vorbisInfo->rate);
			//std::cout << "Sample rate is " << freq << "\n";

			long bytes;
			char smallBuffer[4096];
			DecodeBufferPtr largeBuffer(new DecodeBuffer());
			do {
				int bitStream;
				// Read a chunk of decoded data from the vorbis file
				bytes = ov_read(&oggFile, smallBuffer, sizeof(smallBuffer),
								0, 2, 1, &bitStream);

				if (bytes == OV_HOLE) {
					rError() << "SoundPlayer: Error decoding OGG: OV_HOLE.\n";
				}
				else if (bytes == OV_EBADLINK) {
					rError() << "SoundPlayer: Error decoding OGG: OV_EBADLINK.\n";
				}
				else {
					// Stuff this into the variable-sized buffer
					largeBuffer->insert(largeBuffer->end(), smallBuffer, smallBuffer + bytes);
				}
			} while (bytes > 0);

			// Allocate a new buffer
			alGenBuffers(1, &_buffer);

			DecodeBuffer& bufferRef = *largeBuffer;

			// Upload sound data to buffer
			alBufferData(_buffer,
						 format,
						 &bufferRef[0],
						 static_cast<ALsizei>(bufferRef.size()),
						 freq);

			// Clean up the OGG routines
  			ov_clear(&oggFile);
  		}
  		else {
  			rError() << "SoundPlayer: Error opening OGG file.\n";
  		}
	}
	else {
		// Must be a wave file
		try {
			// Create an AL sound buffer directly from the buffer in memory
			_buffer = WavFileLoader::LoadFromStream(file.getInputStream());
		}
		catch (std::runtime_error& e) {
			rError() << "SoundPlayer: Error opening WAV file: " << e.what() << std::endl;
			_buffer = 0;
		}
	}

	if (_buffer != 0) {
		alGenSources(1, &_source);
		// Assign the buffer to the source and play it
		alSourcei(_source, AL_BUFFER, _buffer);

		// greebo: Wait 10 msec. to fix a problem with buffers not being played
		// maybe the AL needs time to push the data?
		usleep(10000);

		alSourcePlay(_source);

		// Enable the periodic buffer check, this destructs the buffer
		// as soon as the playback has finished
		_timer.enable();
	}
}
//Load----------------------------------------------------------------------
bool TextureItem::Load( GLuint minFilter, GLuint maxFilter, bool forceMipmap, bool resizeIfNeeded )
{
    /** NOTE: This is a test of using an archive file.  This will need to
        be modified to allow direct file access, or archived file access.
    */
    ArchiveFile* file = ArchiveManager::GetSingleton().CreateArchiveFile( mImageFileName );
    if ( file )
    {
        UInt32 fileSize = file->Length();
        unsigned char* buf = new unsigned char [ fileSize ];
        if ( !buf )
        {
            delete file;
            return false;
        }
        file->Read( buf, fileSize );

        // Load the texture:

        //****
        ilInit();
        iluInit();

        // Make sure the DevIL version is valid:
        if ( ilGetInteger( IL_VERSION_NUM ) < IL_VERSION || iluGetInteger( ILU_VERSION_NUM ) < ILU_VERSION )
        {
            // Invalid version...
            delete file;
            delete buf;
            return false;
        }


        // Get the decompressed data
        ILuint imageID;
        ilGenImages( 1, &imageID );
        ilBindImage( imageID );
        //if ( ilLoadImage( const_cast< char* >( mImageFileName.c_str() ) ) )
        if ( ilLoadL( IL_TYPE_UNKNOWN, buf, fileSize ) )
        {
            // Convert the image to unsigned bytes:
            ilConvertImage( IL_RGBA, IL_UNSIGNED_BYTE );

            // Generate the GL texture
            glGenTextures( 1, &mTextureID );
            glBindTexture( GL_TEXTURE_2D, mTextureID );
            mWidth  = ilGetInteger( IL_IMAGE_WIDTH );
            mHeight = ilGetInteger( IL_IMAGE_HEIGHT );
            mOriginalWidth  = mWidth;
            mOriginalHeight = mHeight;

            // OpenGL will work better with textures that have dimensions
            // that are a power of 2.  If doing a scrolling tile map, then
            // this is pretty much a necessity.  However, there are times
            // when using a mipmap instead is perfectly fine (ie, when NOT
            // doing tiles, or in cases where we might be running out of
            // video memory...
            if ( resizeIfNeeded && !forceMipmap )
            {
                UInt32 newWidth = mWidth, newHeight = mHeight;
                if ( !Math::IsPowerOf2( mWidth ) )
                {
                    // Find the next power of 2:
                    newWidth = Math::FindNextPowerOf2( mWidth );
                }

                if ( !Math::IsPowerOf2( mHeight ) )
                {
                    // Find the next power of 2:
                    newHeight = Math::FindNextPowerOf2( mHeight );
                }

                if ( newWidth != mWidth || newHeight != mHeight )
                {
                    // Resize the canvas:
                    ilClearColor( 0, 0, 0, 0 );
                    iluImageParameter( ILU_PLACEMENT, ILU_UPPER_LEFT );
                    iluEnlargeCanvas( newWidth, newHeight, ilGetInteger( IL_IMAGE_DEPTH ) );
                    mWidth  = ilGetInteger( IL_IMAGE_WIDTH );
                    mHeight = ilGetInteger( IL_IMAGE_HEIGHT );
                }
            }

            // If forcing mipmap generation, or if the size is not a power of 2,
            // generate as mipmaps
            if ( forceMipmap || !Math::IsPowerOf2( mWidth ) || !Math::IsPowerOf2( mHeight ) )
            {
                gluBuild2DMipmaps( GL_TEXTURE_2D,
                                   ilGetInteger( IL_IMAGE_BPP ),
                                   mWidth,
                                   mHeight,
                                   ilGetInteger( IL_IMAGE_FORMAT ),
                                   GL_UNSIGNED_BYTE,
                                   ilGetData() );
            }
            else
            {
                glTexImage2D(   GL_TEXTURE_2D,
                                0,
                                ilGetInteger( IL_IMAGE_BPP ),
                                mWidth,
                                mHeight,
                                0,
                                ilGetInteger( IL_IMAGE_FORMAT ),
                                GL_UNSIGNED_BYTE,
                                ilGetData() );
            }

            // Set the minification and magnification filters
            glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter );
            glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, maxFilter );
            glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP );
            glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP );

            mIsLoaded = true;
        }
        else
        {
            ILenum error;
            error = ilGetError();
            //std::string errString = iluErrorString( error );
        }

        ilDeleteImages( 1, &imageID );

        //***

        // Free memory:
        delete buf;
        delete file;
    }
    else
        return false;

    return true;
}