bool vmsSwfFile::Decompress(LPBYTE pbSwfData, UINT uSize, LPBYTE *ppbResult, UINT *puResultSize)
{
	assert (pbSwfData != NULL);
	assert (ppbResult != NULL && puResultSize != NULL);
	if (!pbSwfData)
		return false;
	if (ppbResult == NULL || puResultSize == NULL)
		return false;	
	
	assert (isCompressed (pbSwfData, uSize));
	if (!isCompressed (pbSwfData, uSize))
		return false;
	
	return vmsZlibHelper::DecompressGzip (pbSwfData + 8, uSize - 8, ppbResult, puResultSize) && 
		*ppbResult != NULL && *puResultSize != 0;		
}
示例#2
0
void Message::uncompress() {
	if (!isCompressed())
		return;

#ifdef BUILD_WITH_COMPRESSION_MINIZ
	int cmp_status;
	mz_ulong actualSize = strTo<size_t>(_meta["um.compressed"]);
	uint8_t *pUncmp;

	pUncmp = (mz_uint8 *)malloc((size_t)actualSize);
	cmp_status = mz_uncompress(pUncmp, &actualSize, (const unsigned char *)_data.get(), _size);

	_size = actualSize;
	_data = SharedPtr<char>((char*)pUncmp);
	_meta.erase("um.compressed");

#elif defined(BUILD_WITH_COMPRESSION_FASTLZ)

	int actualSize = strTo<size_t>(_meta["um.compressed"]);
	void* uncompressed = malloc((size_t)actualSize);

	// returns the size of the decompressed block.
	actualSize = fastlz_decompress(_data.get(), _size, uncompressed, actualSize);

	// If error occurs, e.g. the compressed data is corrupted or the output buffer is not large enough, then 0

	_size = actualSize;
	_data = SharedPtr<char>((char*)uncompressed);
	_meta.erase("um.compressed");

#endif

}
示例#3
0
/** Reads just the info header section.
 * 
 * @throw ImageException if not a valid bitmap info header 
 * @throw ImageException if bitmap is compressed
 * @throw ImageException if bitmap is not 24-bit
 */
void BmpImageReader::readInfoHeader() {
	
	file.read((char*)&infoHeader.biSize, 4);
	file.read((char*)&infoHeader.biWidth, 4);
	file.read((char*)&infoHeader.biHeight, 4);
	file.read((char*)&infoHeader.biPlanes, 2);
	file.read((char*)&infoHeader.biBitCount, 2);
	file.read((char*)&infoHeader.biCompression, 4);
	file.read((char*)&infoHeader.biSizeImage, 4);
	file.read((char*)&infoHeader.biXPelsPerMeter, 4);
	file.read((char*)&infoHeader.biYPelsPerMeter, 4);
	file.read((char*)&infoHeader.biClrUsed, 4);
	file.read((char*)&infoHeader.biClrImportant, 4);
	
	if (!isValidInfoHeader()) {
		ImageException e;
		e << "[BmpImageReader] Not a valid bitmap info header!";
		throw e;
	}
	
	if (isCompressed()) {
		ImageException e;
		e << "[BmpImageReader] Only supports uncompressed data.";
		throw e;
	}
	
	if (!is24Bit()) {
		ImageException e;
		e << "[BmpImageReader] Only supports 24-bit data.";
		throw e;
	}
}
示例#4
0
文件: Texture2D.cpp 项目: qqdiguo/ork
void Texture2D::init(int w, int h, TextureInternalFormat tf, TextureFormat f, PixelType t,
    const Parameters &params, const Buffer::Parameters &s, const Buffer &pixels)
{
    Texture::init(tf, params);

    this->w = w;
    this->h = h;

    pixels.bind(GL_PIXEL_UNPACK_BUFFER);

    if (isCompressed() && s.compressedSize() > 0) {
        glCompressedTexImage2D(textureTarget, 0, getTextureInternalFormat(internalFormat), w, h, 0, s.compressedSize(), pixels.data(0));
    } else {
        s.set();
        glTexImage2D(textureTarget, 0, getTextureInternalFormat(internalFormat), w, h, 0, getTextureFormat(f), getPixelType(t), pixels.data(0));
        s.unset();
    }
    pixels.unbind(GL_PIXEL_UNPACK_BUFFER);

    generateMipMap();

    if (FrameBuffer::getError() != 0) {
        throw exception();
    }
}
Variant BaseAssetObjectItem::getData(int column, ItemRole::Id roleId) const
{
	if (column != 0)
	{
		return Variant();
	}

	if (roleId == ValueRole::roleId_)
	{
		return getDisplayText(0);
	}
	else if (roleId == IndexPathRole::roleId_)
	{
		return getFullPath();
	}
	else if (roleId == ThumbnailRole::roleId_)
	{
		return getThumbnail(0);
	}
	else if (roleId == TypeIconRole::roleId_)
	{
		return getTypeIconResourceString();
	}
	else if (roleId == SizeRole::roleId_)
	{
		return getSize();
	}
	else if (roleId == CreatedTimeRole::roleId_)
	{
		return getCreatedTime();
	}
	else if (roleId == ModifiedTimeRole::roleId_)
	{
		return getModifiedTime();
	}
	else if (roleId == AccessedTimeRole::roleId_)
	{
		return getAccessedTime();
	}
	else if (roleId == IsDirectoryRole::roleId_)
	{
		return isDirectory();
	}
	else if (roleId == IsReadOnlyRole::roleId_)
	{
		return isReadOnly();
	}
	else if (roleId == IsCompressedRole::roleId_)
	{
		return isCompressed();
	}
	else if (roleId == ItemRole::itemIdId)
	{
		return intptr_t(this);
	}

	return Variant();
}
示例#6
0
shared_ptr<ZLOutputStream> ZLFile::outputStream() const {
	if (isCompressed()) {
          return shared_ptr<ZLOutputStream>();
	}
	if (ZLFSManager::instance().findArchiveFileNameDelimiter(myPath) != -1) {
          return shared_ptr<ZLOutputStream>();
	}
	return shared_ptr<ZLOutputStream>(ZLFSManager::instance().createOutputStream(myPath));
}
示例#7
0
void MCF::dlHeaderFromHttp(const char* url)
{
	gcTrace("Url: {0}", url);

	if (m_bStopped)
		return;

	if (!url)
		throw gcException(ERR_BADURL);

	//FIXME: Needs error checking on getweb
	HttpHandle wc(url);
	wc->setDownloadRange(0, MCFCore::MCFHeader::getSizeS());

	wc->setUserAgent(USERAGENT_UPDATE);
	wc->getWeb();

	if (wc->getDataSize() != MCFCore::MCFHeader::getSizeS())
		throw gcException(ERR_BADHEADER);

	MCFCore::MCFHeader webHeader(wc->getData());
	setHeader(&webHeader);

	if (!webHeader.isValid())
		throw gcException(ERR_BADHEADER);

	wc->cleanUp();
	wc->setUserAgent(USERAGENT_UPDATE);
	wc->setDownloadRange(webHeader.getXmlStart(), webHeader.getXmlSize());
	wc->getWeb();

	if (wc->getDataSize() == 0 || wc->getDataSize() != webHeader.getXmlSize())
		throw gcException(ERR_WEBDL_FAILED, "Failed to download MCF xml from web (size is ether zero or didnt match header size)");

	uint32 bz2BuffLen = webHeader.getXmlSize()*25;
	char* bz2Buff = nullptr;

	if ( isCompressed() )
	{
		bz2Buff = new char[bz2BuffLen];
		AutoDelete<char> ad(bz2Buff);

		UTIL::STRING::zeroBuffer(bz2Buff, bz2BuffLen);
		UTIL::BZIP::BZ2DBuff((char*)bz2Buff, &bz2BuffLen, const_cast<char*>(wc->getData()), wc->getDataSize());
		parseXml(bz2Buff, bz2BuffLen);
	}
	else
	{
		parseXml(const_cast<char*>(wc->getData()), wc->getDataSize());
	}

	//we remove the complete flag due to the files not existing in the MCF
	for (size_t x=0; x< m_pFileList.size(); x++)
	{
		m_pFileList[x]->delFlag(MCFCore::MCFFileI::FLAG_COMPLETE);
	}
}
示例#8
0
shared_ptr<ZLOutputStream> ZLFile::outputStream(bool writeThrough) const {
	if (!writeThrough && isCompressed()) {
		return 0;
	}
	if (ZLFSManager::Instance().findArchiveFileNameDelimiter(myPath) != -1) {
		return 0;
	}
	return ZLFSManager::Instance().createOutputStream(myPath);
}
示例#9
0
文件: Image.cpp 项目: boardwalk/bzr
void Image::scale(int newWidth, int newHeight)
{
    if(newWidth == width_ && newHeight == height_)
    {
        return;
    }

    if(isCompressed(format_))
    {
        throw runtime_error("Cannot scale compressed image");
    }

    int nchannels = bitsPerPixel(format_) / 8;

    vector<uint8_t> newData(newWidth * newHeight * nchannels);

    for(int dstY = 0; dstY < newHeight; dstY++)
    {
        for(int dstX = 0; dstX < newWidth; dstX++)
        {
            fp_t srcFX = static_cast<fp_t>(dstX) / static_cast<fp_t>(newWidth) * static_cast<fp_t>(width_);
            fp_t srcFY = static_cast<fp_t>(dstY) / static_cast<fp_t>(newHeight) * static_cast<fp_t>(height_);

            int srcX = static_cast<int>(srcFX);
            int srcY = static_cast<int>(srcFY);

            fp_t xDiff = srcFX - srcX;
            fp_t yDiff = srcFY - srcY;

            fp_t xOpposite = fp_t(1.0) - xDiff;
            fp_t yOpposite = fp_t(1.0) - yDiff;

#define SRCPX(x, y, cn) static_cast<fp_t>(data_[(min(x, width_ - 1) + min(y, height_ - 1) * width_) * nchannels + cn])
#define DSTPX(x, y, cn) newData[((x) + (y) * newWidth) * nchannels + cn]

            for(int c = 0; c < nchannels; c++)
            {
                DSTPX(dstX, dstY, c) = static_cast<uint8_t>(
                    (SRCPX(srcX, srcY, c) * xOpposite + SRCPX(srcX + 1, srcY, c) * xDiff) * yOpposite +
                    (SRCPX(srcX, srcY + 1, c) * xOpposite + SRCPX(srcX + 1, srcY + 1, c) * xDiff) * yDiff);
            }

#undef SRCPX
#undef DSTPX
        }
    }

    data_ = move(newData);
    width_ = newWidth;
    height_ = newHeight;
}
示例#10
0
void Message::compress() {
	if (isCompressed())
		return;
#ifdef BUILD_WITH_COMPRESSION_MINIZ

	mz_ulong compressedSize = mz_compressBound(_size);
	int cmp_status;
	uint8_t *pCmp;

	pCmp = (mz_uint8 *)malloc((size_t)compressedSize);

	// last argument is speed size tradeoff: BEST_SPEED [0-9] BEST_COMPRESSION
	cmp_status = mz_compress2(pCmp, &compressedSize, (const unsigned char *)_data.get(), _size, 5);
	if (cmp_status != Z_OK) {
		// error
		free(pCmp);
	}

	_data = SharedPtr<char>((char*)pCmp);
	_meta["um.compressed"] = toStr(_size);
	_size = compressedSize;

#elif defined(BUILD_WITH_COMPRESSION_FASTLZ)

	// The minimum input buffer size is 16.
	if (_size < 16)
		return;

	// The output buffer must be at least 5% larger than the input buffer and can not be smaller than 66 bytes.
	int compressedSize = _size + (double)_size * 0.06;
	if (compressedSize < 66)
		compressedSize = 66;

	char* compressedData = (char*)malloc(compressedSize);
	compressedSize = fastlz_compress(_data.get(), _size, compressedData);

	// If the input is not compressible, the return value might be larger than length
	if (compressedSize > _size) {
		free(compressedData);
		return;
	}

//	std::cout << _size << " -> " << compressedSize << " = " << ((float)compressedSize / (float)_size) << std::endl;

	_data = SharedPtr<char>((char*)compressedData);
	_meta["um.compressed"] = toStr(_size);
	_size = compressedSize;

#endif

}
示例#11
0
void Decoder::decompress() {
	if (!isCompressed())
		return;

	for (MipMaps::iterator m = _mipMaps.begin(); m != _mipMaps.end(); ++m) {
		MipMap decompressed;

		decompress(decompressed, **m, _format);

		decompressed.swap(**m);
	}

	_format = kPixelFormatR8G8B8A8;
}
示例#12
0
void Decoder::dumpTGA(const Common::UString &fileName) const {
	if (_mipMaps.size() < 1)
		throw Common::Exception("Image contains no mip maps");

	if (!isCompressed()) {
		Images::dumpTGA(fileName, *this);
		return;
	}

	Decoder decoder(*this);
	decoder.decompress();

	Images::dumpTGA(fileName, decoder);
}
示例#13
0
Hits Searcher::getHits(const string& term) {
    int size;
    char *val;
    try {
      val = depot.get(term.c_str(), -1, 0, -1, &size);
    } catch(Depot_error& e){
      //cerr << e << endl;
      return Hits(NULL, 0);
    }
    Node* nodes = (Node*) val;
    int num = size / sizeof(Node);

    if(isCompressed())
      nodes = gammaHits(val, size, num);

    return Hits(nodes, num);
}
void TextureRectangle::init(int w, int h, TextureInternalFormat tf, TextureFormat f, PixelType t,
    const Parameters &params, const Buffer::Parameters &s, const Buffer &pixels)
{
    Texture::init(tf, params);
    this->w = w;
    this->h = h;

    pixels.bind(GL_PIXEL_UNPACK_BUFFER);
    bool needToGenerateMipmaps = true;
    if (isCompressed() && s.compressedSize() > 0) {
        glCompressedTexImage2D(textureTarget, 0, getTextureInternalFormat(internalFormat), w, h, 0, s.compressedSize(), pixels.data(0));
    } else {
        s.set();
        glTexImage2D(textureTarget, 0, getTextureInternalFormat(internalFormat), w, h, 0, getTextureFormat(f), getPixelType(t), pixels.data(0));
        s.unset();

        GLsizei size = s.compressedSize(); // should work because size is retrieved from file descriptor.
        int pixelSize = getFormatSize(f, t);
        if (size > w * h * pixelSize) {
            // get the other levels from the same buffer
            int offset = w * h * pixelSize;
            int level = 0;
            int wl = w;
            int hl = h;
            while (wl % 2 == 0 && hl % 2 == 0 && size - offset >= (wl * hl / 4) * pixelSize) {
                level += 1;
                wl = wl / 2;
                hl = hl / 2;
                glTexImage2D(textureTarget, level, getTextureInternalFormat(internalFormat), wl, hl, 0, getTextureFormat(f), getPixelType(t), pixels.data(offset));
                offset += wl * hl * pixelSize;
                needToGenerateMipmaps = false;
            }
            this->params.lodMax(clamp(params.lodMax(), GLfloat(0.0f), GLfloat(level)));
        }
    }
    pixels.unbind(GL_PIXEL_UNPACK_BUFFER);

    if (needToGenerateMipmaps) {
        generateMipMap();
    }

    if (FrameBuffer::getError() != 0) {
        throw exception();
    }
}
示例#15
0
文件: Image.cpp 项目: boardwalk/bzr
void Image::flipVertical()
{
    if(isCompressed(format_))
    {
        throw runtime_error("Cannot flip compressed image");
    }

    int stride = width_ * bitsPerPixel(format_) / 8;

    vector<uint8_t> rowBuf(stride);

    for(int y = 0; y < height_ / 2; y++)
    {
        memcpy(rowBuf.data(), data_.data() + y * stride, stride);
        memcpy(data_.data() + stride * y, data_.data() + (height_ - y - 1) * stride, stride);
        memcpy(data_.data() + (height_ - y - 1) * stride, rowBuf.data(), stride);
    }
}
示例#16
0
void TextureCube::init(int w, int h, TextureInternalFormat tf, TextureFormat f, PixelType t,
    const Parameters &params, Buffer::Parameters s[6], ptr<Buffer> pixels[6])
{
    Texture::init(tf, params);
    this->w = w;
    this->h = h;

    const GLenum FACES[6] = {
        GL_TEXTURE_CUBE_MAP_POSITIVE_X,
        GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
        GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
        GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
        GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
        GL_TEXTURE_CUBE_MAP_NEGATIVE_Z
    };
    if (isCompressed()) {
        for (int i = 0; i < 6; ++i) {
            pixels[i]->bind(GL_PIXEL_UNPACK_BUFFER);
            if (s[i].compressedSize() > 0) {
                glCompressedTexImage2D(FACES[i], 0, getTextureInternalFormat(internalFormat), w, h, 0, s[i].compressedSize(), pixels[i]->data(0));
            } else {
                s[i].set();
                glTexImage2D(FACES[i], 0, getTextureInternalFormat(internalFormat), w, h, 0, getTextureFormat(f), getPixelType(t), pixels[i]->data(0));
                s[i].unset();
            }
            pixels[i]->unbind(GL_PIXEL_UNPACK_BUFFER);
        }
    } else {
        for (int i = 0; i < 6; ++i) {
            pixels[i]->bind(GL_PIXEL_UNPACK_BUFFER);
            s[i].set();
            glTexImage2D(FACES[i], 0, getTextureInternalFormat(internalFormat), w, h, 0, getTextureFormat(f), getPixelType(t), pixels[i]->data(0));
            s[i].unset();
            pixels[i]->unbind(GL_PIXEL_UNPACK_BUFFER);
        }
    }

    generateMipMap();

    if (FrameBuffer::getError() != 0) {
        throw exception();
    }
}
示例#17
0
bool Image::saveToFile(const char *pszFilePath, bool bIsToRGB)
{
	//only support for Texture2D::PixelFormat::RGB888 or Texture2D::PixelFormat::RGBA8888 uncompressed data
	if (isCompressed() || (m_eRenderFormat != Texture2D::PixelFormat::RGB888 && m_eRenderFormat != Texture2D::PixelFormat::RGBA8888))
	{
		CCLOG("cocos2d: Image: saveToFile is only support for Texture2D::PixelFormat::RGB888 or Texture2D::PixelFormat::RGBA8888 uncompressed data for now");
		return false;
	}

	bool bRet = false;

	do
	{
		CC_BREAK_IF(NULL == pszFilePath);

		std::string strFilePath(pszFilePath);
		CC_BREAK_IF(strFilePath.size() <= 4);

		std::string strLowerCasePath(strFilePath);
		for (unsigned int i = 0; i < strLowerCasePath.length(); ++i)
		{
			strLowerCasePath[i] = tolower(strFilePath[i]);
		}

		if (std::string::npos != strLowerCasePath.find(".png"))
		{
			CC_BREAK_IF(!saveImageToPNG(pszFilePath, bIsToRGB));
		}
		else if (std::string::npos != strLowerCasePath.find(".jpg"))
		{
			CC_BREAK_IF(!saveImageToJPG(pszFilePath));
		}
		else
		{
			break;
		}

		bRet = true;
	} while (0);

	return bRet;
}
示例#18
0
bool ossimNitfImageHeader::isSameAs(const ossimNitfImageHeader* hdr) const
{
   if (!hdr) return false;
   
   return ( (isCompressed() == hdr->isCompressed()) &&
            (getNumberOfRows() == hdr->getNumberOfRows()) &&
            (getNumberOfBands() == hdr->getNumberOfBands()) &&
            (getNumberOfCols() == hdr->getNumberOfCols()) &&
            (getNumberOfBlocksPerRow() == hdr->getNumberOfBlocksPerRow()) &&
            (getNumberOfBlocksPerCol() == hdr->getNumberOfBlocksPerCol()) &&
            (getNumberOfPixelsPerBlockHoriz() ==
             hdr->getNumberOfPixelsPerBlockHoriz()) &&
            (getNumberOfPixelsPerBlockVert() ==
             hdr->getNumberOfPixelsPerBlockVert()) &&
            (getBitsPerPixelPerBand() == hdr->getBitsPerPixelPerBand()) &&
            (getImageRect() == hdr->getImageRect()) &&
            (getIMode() == hdr->getIMode()) &&
            (getCoordinateSystem() == hdr->getCoordinateSystem()) &&
            (getGeographicLocation() == hdr->getGeographicLocation()) );
}
示例#19
0
void MCF::saveMCF_Header()
{
	//donot use getDLSize here as the file might have a gap in it. :(

	uint64 offset = 0;

	for (size_t x=0; x<m_pFileList.size(); x++)
	{
		MCFFile* file = m_pFileList[x];

		if (!file->isSaved())
			continue;

		uint64 pos = file->getOffSet() + file->getCurSize();

		if (offset < pos)
			offset = pos;

		uint64 diffpos = file->getDiffOffSet() + file->getDiffSize();

		if (file->hasDiff() && offset < diffpos)
			offset = diffpos;
	}

	if (offset == 0)
		offset = m_sHeader->getSize();

	UTIL::FS::recMakeFolder(UTIL::FS::PathWithFile(m_szFile));
	UTIL::FS::FileHandle hFile(m_szFile.c_str(), UTIL::FS::FILE_APPEND);

	hFile.seek(offset);

	XMLSaveAndCompress sac(&hFile, isCompressed());
	genXml(&sac);
	sac.finish();

	m_sHeader->setXmlStart(offset);	
	m_sHeader->setXmlSize((uint32)sac.getTotalSize());
	m_sHeader->saveToFile(hFile);
}
示例#20
0
文件: APC.cpp 项目: lltt90511/Fish
void APC::unCompress() {
	if (!isCompressed()) {
		return;
	}
    int dest_len = *(int *)data;
	char *dest = new char[dest_len+1];
    int ret = LZ4_decompress_safe(data+4, dest, data_len-4, dest_len);
//    int ret = LZ4_decompress_fast(data+4, dest, dest_len);
    if (ret < 0) {
        CCLOG("unCompress error ret=%d",ret);
		delete[] dest;
    } else {
        if (data != NULL) {
			delete[] data;
		}
        CCLOG("data len %d, dest len %d", data_len, dest_len);
        data = dest;
		data_len = dest_len;
        data[data_len] = '\0';
    }
	setUnCompressFlag();
}
示例#21
0
void GFXD3D11Cubemap::initStatic(GFXTexHandle *faces)
{
   AssertFatal( faces, "GFXD3D11Cubemap::initStatic - Got null GFXTexHandle!" );
	AssertFatal( *faces, "empty texture passed to CubeMap::create" );
  
	// NOTE - check tex sizes on all faces - they MUST be all same size
	mTexSize = faces->getWidth();
	mFaceFormat = faces->getFormat();
   bool compressed = isCompressed(mFaceFormat);

   UINT bindFlags = D3D11_BIND_SHADER_RESOURCE;
   UINT miscFlags = D3D11_RESOURCE_MISC_TEXTURECUBE;
   if (!compressed)
   {
      bindFlags |= D3D11_BIND_RENDER_TARGET;
      miscFlags |= D3D11_RESOURCE_MISC_GENERATE_MIPS;
   }

   U32 mipLevels = faces->getPointer()->getMipLevels();
   if (mipLevels > 1)
      mAutoGenMips = true;

	D3D11_TEXTURE2D_DESC desc;
	ZeroMemory(&desc, sizeof(D3D11_TEXTURE2D_DESC));
	desc.Width = mTexSize;
	desc.Height = mTexSize;
   desc.MipLevels = mAutoGenMips ? 0 : mipLevels;
	desc.ArraySize = 6;
	desc.Format = GFXD3D11TextureFormat[mFaceFormat];
	desc.SampleDesc.Count = 1;
	desc.SampleDesc.Quality = 0;
	desc.Usage = D3D11_USAGE_DEFAULT;
	desc.BindFlags = bindFlags;
	desc.MiscFlags = miscFlags;
	desc.CPUAccessFlags = 0;

	HRESULT hr = D3D11DEVICE->CreateTexture2D(&desc, NULL, &mTexture);

	if (FAILED(hr))
	{
		AssertFatal(false, "GFXD3D11Cubemap:initStatic(GFXTexhandle *faces) - failed to create texcube texture");
	}

   for (U32 i = 0; i < CubeFaces; i++)
   {
      GFXD3D11TextureObject *texObj = static_cast<GFXD3D11TextureObject*>((GFXTextureObject*)faces[i]);
      U32 subResource = D3D11CalcSubresource(0, i, mipLevels);
      D3D11DEVICECONTEXT->CopySubresourceRegion(mTexture, subResource, 0, 0, 0, texObj->get2DTex(), 0, NULL);
   }
   
	D3D11_SHADER_RESOURCE_VIEW_DESC SMViewDesc;
	SMViewDesc.Format = GFXD3D11TextureFormat[mFaceFormat];
	SMViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
   SMViewDesc.TextureCube.MipLevels = mAutoGenMips ? -1 : mipLevels;
	SMViewDesc.TextureCube.MostDetailedMip = 0;

	hr = D3D11DEVICE->CreateShaderResourceView(mTexture, &SMViewDesc, &mSRView);
	if (FAILED(hr))
	{
		AssertFatal(false, "GFXD3D11Cubemap::initStatic(GFXTexHandle *faces) - texcube shader resource view  creation failure");
	} 

   if (mAutoGenMips && !compressed)
      D3D11DEVICECONTEXT->GenerateMips(mSRView);
}
示例#22
0
int GenericChannel::handleRead(EncodeBuffer &encodeBuffer, const unsigned char *message,
                               unsigned int length)
{
#ifdef TEST
    *logofs << "handleRead: Called for FD#" << fd_
            << " with " << encodeBuffer.getLength()
            << " bytes already encoded.\n"
            << logofs_flush;
#endif

    //
    // Pointer to located message and
    // its size in bytes.
    //

    const unsigned char *inputMessage;
    unsigned int inputLength;

    //
    // Tag message as generic data in compression
    // routine. Opcode is not actually transferred
    // over the network.
    //

    unsigned char inputOpcode = X_NXInternalGenericData;

#if defined(TEST) || defined(INFO)
    *logofs << "handleRead: Trying to read from FD#"
            << fd_ << " at " << strMsTimestamp() << ".\n"
            << logofs_flush;
#endif

    int result = readBuffer_.readMessage();

#ifdef DEBUG
    *logofs << "handleRead: Read result on FD#" << fd_
            << " is " << result << ".\n"
            << logofs_flush;
#endif

    if (result < 0)
    {
        //
        // Let the proxy close the channel.
        //

        return -1;
    }
    else if (result == 0)
    {
#if defined(TEST) || defined(INFO)

        *logofs << "handleRead: PANIC! No data read from FD#"
                << fd_ << " while encoding messages.\n"
                << logofs_flush;

        HandleCleanup();

#endif

        return 0;
    }

#if defined(TEST) || defined(INFO) || defined(FLUSH)
    *logofs << "handleRead: Encoding messages for FD#" << fd_
            << " with " << readBuffer_.getLength() << " bytes "
            << "in the buffer.\n" << logofs_flush;
#endif

    //
    // Divide the available data in multiple
    // messages and encode them one by one.
    //

    if (proxy -> handleAsyncSwitch(fd_) < 0)
    {
        return -1;
    }

    while ((inputMessage = readBuffer_.getMessage(inputLength)) != NULL)
    {
        encodeBuffer.encodeValue(inputLength, 32, 14);

        if (isCompressed() == 1)
        {
            unsigned int compressedDataSize = 0;
            unsigned char *compressedData   = NULL;

            if (handleCompress(encodeBuffer, inputOpcode, 0,
                               inputMessage, inputLength, compressedData,
                               compressedDataSize) < 0)
            {
                return -1;
            }
        }
        else
        {
            encodeBuffer.encodeMemory(inputMessage, inputLength);
        }

        int bits = encodeBuffer.diffBits();

#if defined(TEST) || defined(OPCODES)
        *logofs << "handleRead: Handled generic data for FD#" << fd_
                << ". " << inputLength << " bytes in, " << bits << " bits ("
                << ((float) bits) / 8 << " bytes) out.\n" << logofs_flush;
#endif

        addProtocolBits(inputLength << 3, bits);

        if (isPrioritized() == 1)
        {
            priority_++;
        }

    } // End of while ((inputMessage = readBuffer_.getMessage(inputLength)) != NULL) ...

    //
    // All data has been read from the read buffer.
    // We still need to mark the end of the encode
    // buffer just before sending the frame. This
    // allows us to accomodate multiple reads in
    // a single frame.
    //

    if (priority_ > 0)
    {
#if defined(TEST) || defined(INFO)
        *logofs << "handleRead: WARNING! Requesting flush "
                << "because of " << priority_ << " prioritized "
                << "messages for FD#" << fd_ << ".\n"
                << logofs_flush;
#endif

        if (proxy -> handleAsyncPriority() < 0)
        {
            return -1;
        }

        //
        // Reset the priority flag.
        //

        priority_ = 0;
    }

    //
    // Flush if we produced enough data.
    //

    if (proxy -> canAsyncFlush() == 1)
    {
#if defined(TEST) || defined(INFO)
        *logofs << "handleRead: WARNING! Requesting flush "
                << "because of enough data or timeout on the "
                << "proxy link.\n" << logofs_flush;
#endif

        if (proxy -> handleAsyncFlush() < 0)
        {
            return -1;
        }
    }

#if defined(TEST) || defined(INFO)

    if (transport_ -> pending() != 0 ||
            readBuffer_.checkMessage() != 0)
    {
        *logofs << "handleRead: PANIC! Buffer for X descriptor FD#"
                << fd_ << " has " << transport_ -> pending()
                << " bytes to read.\n" << logofs_flush;

        HandleCleanup();
    }

#endif

    //
    // Reset the read buffer.
    //

    readBuffer_.fullReset();

    return 1;
}
示例#23
0
int GenericChannel::handleWrite(const unsigned char *message, unsigned int length)
{
#ifdef TEST
    *logofs << "handleWrite: Called for FD#" << fd_ << ".\n" << logofs_flush;
#endif

    //
    // Create the buffer from which to
    // decode messages.
    //

    DecodeBuffer decodeBuffer(message, length);

#if defined(TEST) || defined(INFO) || defined(FLUSH)
    *logofs << "handleWrite: Decoding messages for FD#" << fd_
            << " with " << length << " bytes in the buffer.\n"
            << logofs_flush;
#endif

    unsigned char *outputMessage;
    unsigned int outputLength;

    //
    // Tag message as generic data
    // in decompression.
    //

    unsigned char outputOpcode = X_NXInternalGenericData;

    for (;;)
    {
        decodeBuffer.decodeValue(outputLength, 32, 14);

        if (outputLength == 0)
        {
            break;
        }

        if (isCompressed() == 1)
        {
            if (writeBuffer_.getAvailable() < outputLength ||
                    (int) outputLength >= control -> TransportFlushBufferSize)
            {
#ifdef DEBUG
                *logofs << "handleWrite: Using scratch buffer for "
                        << "generic data with size " << outputLength << " and "
                        << writeBuffer_.getLength() << " bytes in buffer.\n"
                        << logofs_flush;
#endif

                outputMessage = writeBuffer_.addScratchMessage(outputLength);
            }
            else
            {
                outputMessage = writeBuffer_.addMessage(outputLength);
            }

            const unsigned char *compressedData = NULL;
            unsigned int compressedDataSize = 0;

            int decompressed = handleDecompress(decodeBuffer, outputOpcode, 0,
                                                outputMessage, outputLength, compressedData,
                                                compressedDataSize);
            if (decompressed < 0)
            {
                return -1;
            }
        }
        else
        {
#ifdef DEBUG
            *logofs << "handleWrite: Using scratch buffer for "
                    << "generic data with size " << outputLength << " and "
                    << writeBuffer_.getLength() << " bytes in buffer.\n"
                    << logofs_flush;
#endif

            writeBuffer_.addScratchMessage((unsigned char *)
                                           decodeBuffer.decodeMemory(outputLength), outputLength);
        }

#if defined(TEST) || defined(OPCODES)
        *logofs << "handleWrite: Handled generic data for FD#" << fd_
                << ". "  << outputLength << " bytes out.\n"
                << logofs_flush;
#endif

        handleFlush(flush_if_needed);
    }

    //
    // Write any remaining data to socket.
    //

    if (handleFlush(flush_if_any) < 0)
    {
        return -1;
    }

    return 1;
}
示例#24
0
void GFXD3D11Cubemap::initDynamic(U32 texSize, GFXFormat faceFormat)
{
	if(!mDynamic)
		GFXTextureManager::addEventDelegate(this, &GFXD3D11Cubemap::_onTextureEvent);

	mDynamic = true;
   mAutoGenMips = true;
	mTexSize = texSize;
	mFaceFormat = faceFormat;
   bool compressed = isCompressed(mFaceFormat);

   UINT bindFlags = D3D11_BIND_SHADER_RESOURCE;
   UINT miscFlags = D3D11_RESOURCE_MISC_TEXTURECUBE;
   if (!compressed)
   {
      bindFlags |= D3D11_BIND_RENDER_TARGET;
      miscFlags |= D3D11_RESOURCE_MISC_GENERATE_MIPS;
   }

	D3D11_TEXTURE2D_DESC desc;

	desc.Width = mTexSize;
	desc.Height = mTexSize;
	desc.MipLevels = 0;
	desc.ArraySize = 6;
	desc.Format = GFXD3D11TextureFormat[mFaceFormat];
	desc.SampleDesc.Count = 1;
	desc.SampleDesc.Quality = 0;
	desc.Usage = D3D11_USAGE_DEFAULT;
   desc.BindFlags = bindFlags;
	desc.CPUAccessFlags = 0;
   desc.MiscFlags = miscFlags;


	HRESULT hr = D3D11DEVICE->CreateTexture2D(&desc, NULL, &mTexture);

	D3D11_SHADER_RESOURCE_VIEW_DESC SMViewDesc;
	SMViewDesc.Format = GFXD3D11TextureFormat[mFaceFormat];
	SMViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
   SMViewDesc.TextureCube.MipLevels = -1;
	SMViewDesc.TextureCube.MostDetailedMip = 0;

	hr = D3D11DEVICE->CreateShaderResourceView(mTexture, &SMViewDesc, &mSRView);


	if(FAILED(hr)) 
	{
		AssertFatal(false, "GFXD3D11Cubemap::initDynamic - CreateTexture2D call failure");
	}

   D3D11_RENDER_TARGET_VIEW_DESC viewDesc;
	viewDesc.Format = desc.Format;
	viewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY;
	viewDesc.Texture2DArray.ArraySize = 1;
	viewDesc.Texture2DArray.MipSlice = 0;

   for (U32 i = 0; i < CubeFaces; i++)
	{
		viewDesc.Texture2DArray.FirstArraySlice = i;
      hr = D3D11DEVICE->CreateRenderTargetView(mTexture, &viewDesc, &mRTView[i]);

		if(FAILED(hr)) 
		{
			AssertFatal(false, "GFXD3D11Cubemap::initDynamic - CreateRenderTargetView call failure");
		}
	}

   D3D11_TEXTURE2D_DESC depthTexDesc;
   depthTexDesc.Width = mTexSize;
   depthTexDesc.Height = mTexSize;
   depthTexDesc.MipLevels = 1;
   depthTexDesc.ArraySize = 1;
   depthTexDesc.SampleDesc.Count = 1;
   depthTexDesc.SampleDesc.Quality = 0;
   depthTexDesc.Format = DXGI_FORMAT_D32_FLOAT;
   depthTexDesc.Usage = D3D11_USAGE_DEFAULT;
   depthTexDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
   depthTexDesc.CPUAccessFlags = 0;
   depthTexDesc.MiscFlags = 0;

   ID3D11Texture2D* depthTex = 0;
   hr = D3D11DEVICE->CreateTexture2D(&depthTexDesc, 0, &depthTex);

	if(FAILED(hr)) 
	{
		AssertFatal(false, "GFXD3D11Cubemap::initDynamic - CreateTexture2D for depth stencil call failure");
	}

   // Create the depth stencil view for the entire cube
   D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc;
   dsvDesc.Format = depthTexDesc.Format; //The format must match the depth texture we created above
   dsvDesc.Flags  = 0;
   dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
   dsvDesc.Texture2D.MipSlice = 0;
   hr = D3D11DEVICE->CreateDepthStencilView(depthTex, &dsvDesc, &mDSView);

	if(FAILED(hr)) 
	{
      AssertFatal(false, "GFXD3D11Cubemap::initDynamic - CreateDepthStencilView call failure");
	}

   SAFE_RELEASE(depthTex);

}
示例#25
0
bool NavMeshRecord::loadFromStream(std::ifstream& in_File, const bool localized, const StringTable& table)
{
  uint32_t readSize = 0;
  if (!loadSizeAndUnknownValues(in_File, readSize)) return false;
  if (isDeleted()) return true;
  uint32_t subRecName;
  uint16_t subLength;
  subRecName = subLength = 0;
  uint32_t bytesRead = 0;

  MWTP::BufferStream decompStream(NULL, 0);
  std::basic_istream<char>* actual_in = &in_File;

  if (isCompressed())
  {
    uint32_t decompressedSize = 0;
    //read size of decompressed data
    in_File.read((char*) &decompressedSize, 4);
    if (!in_File.good())
    {
      std::cout << "Error while reading decompression size of NAVM!\n";
      return false;
    }
    if (readSize<=4)
    {
      std::cout << "Error: size of compressed NAVM record is too small to contain any compressed data!\n";
      return false;
    }
    //buffer to read compressed data
    uint8_t * stream_buffer = new uint8_t[readSize-4];
    in_File.read((char*) stream_buffer, readSize-4);
    if (!in_File.good())
    {
      std::cout << "Error while reading compressed data of NAVM!\n";
      delete[] stream_buffer;
      return false;
    }
    //now decompress here
    uint8_t * decompBuffer = new uint8_t [decompressedSize];
    if (!MWTP::zlibDecompress(stream_buffer, readSize-4, decompBuffer, decompressedSize))
    {
      std::cout << "Error while executing decompression function!\n";
      delete[] stream_buffer;
      stream_buffer = NULL;
      delete[] decompBuffer;
      decompBuffer = NULL;
      return false;
    }
    delete[] stream_buffer;
    stream_buffer = NULL;
    //set underlying buffer for decompressed stream
    decompStream.buffer((char*) decompBuffer, decompressedSize);
    actual_in = &decompStream;
    //update read size
    readSize = decompressedSize;
  }//if is compressed record

  unknownNVNM.setPresence(false);
  uint32_t sizeXXXX = 0;
  unknownONAM.setPresence(false);
  unknownNNAM.setPresence(false);
  unknownPNAM.setPresence(false);

  while (bytesRead<readSize)
  {
    //read next header
    actual_in->read((char*) &subRecName, 4);
    bytesRead += 4;
    switch (subRecName)
    {
      case cNVNM:
           if (unknownNVNM.isPresent())
           {
             std::cout << "Error: NAVM seems to have more than one NVNM subrecord.\n";
             return false;
           }

           //read NVNM
           if (0==sizeXXXX)
           {
             if (!unknownNVNM.loadFromStream(*actual_in, cNVNM, false))
             {
               std::cout << "Error while reading subrecord NVNM of NAVM!\n";
               return false;
             }
           }
           else
           {
             if (!unknownNVNM.loadFromStreamExtended(*actual_in, cNVNM, false, sizeXXXX))
             {
               std::cout << "Error while reading subrecord NVNM of NAVM!\n";
               return false;
             }
             sizeXXXX = 0;
           }//else - load extended version of subrecord
           bytesRead += (2 /*length value*/ +unknownNVNM.getSize() /*data size*/);
           break;
      case cXXXX:
           if (sizeXXXX!=0)
           {
             std::cout << "Error: NAVM seems to have more than one XXXX subrecord in a row.\n";
             return false;
           }
           //read XXXX
           if (!loadUint32SubRecordFromStream(*actual_in, cXXXX, sizeXXXX, false)) return false;
           bytesRead += 6;
           if (0==sizeXXXX)
           {
             std::cout << "Error: subrecord XXXX of NAVM has value zero!\n";
             return false;
           }
           break;
      case cONAM:
           if (unknownONAM.isPresent())
           {
             std::cout << "Error: NAVM seems to have more than one ONAM subrecord.\n";
             return false;
           }
           //read ONAM
           if (!unknownONAM.loadFromStream(*actual_in, cONAM, false))
           {
             std::cout << "Error while reading subrecord ONAM of NAVM!\n";
             return false;
           }
           bytesRead += (2 + unknownONAM.getSize());
           break;
      case cNNAM:
           if (unknownNNAM.isPresent())
           {
             std::cout << "Error: NAVM seems to have more than one NNAM subrecord.\n";
             return false;
           }
           //read NNAM
           if (!unknownNNAM.loadFromStream(*actual_in, cNNAM, false))
           {
             std::cout << "Error while reading subrecord NNAM of NAVM!\n";
             return false;
           }
           bytesRead += (2 + unknownNNAM.getSize());
           break;
      case cPNAM:
           if (unknownPNAM.isPresent())
           {
             std::cout << "Error: NAVM seems to have more than one PNAM subrecord.\n";
             return false;
           }
           //read PNAM
           if (!unknownPNAM.loadFromStream(*actual_in, cPNAM, false))
           {
             std::cout << "Error while reading subrecord PNAM of NAVM!\n";
             return false;
           }
           bytesRead += (2 + unknownPNAM.getSize());
           break;
      default:
           std::cout << "Error: found unexpected subrecord \""<<IntTo4Char(subRecName)
                     << "\", but only NVNM, ONAM, NNAM, PNAM or XXXX are allowed here!\n";
           return false;
    }//swi
  }//while

  //presence check
  if (!unknownNVNM.isPresent())
  {
    std::cout << "Error: while reading NAVM record: subrecord NVNM is missing!\n";
    return false;
  }//if

  return in_File.good();
}
示例#26
0
void MCF::dlHeaderFromWeb()
{
	if (m_bStopped)
		return;

	if (m_vProviderList.size() == 0)
		throw gcException(ERR_ZEROFILE);

	gcException lastE;
	bool successful = false;

	OutBuffer out(MCF_HEADERSIZE_V2);
	MCFCore::Misc::MCFServerCon msc;

	for (size_t x=0; x<m_vProviderList.size(); x++)
	{
		try
		{
			msc.disconnect();
			msc.connect(m_vProviderList[x]->getUrl(), m_pFileAuth);

			msc.downloadRange(0, 5, &out); //4 id bytes and 1 version byte

			if (out.m_uiTotalSize != 5)
				throw gcException(ERR_BADHEADER, "Did not get any data from mcf server.");

			const char* data = out.m_szBuffer;

			if ( !(data[0] == 'L' && data[1] == 'M' && data[2] == 'C' && data[3] == 'F') )
				throw gcException(ERR_BADHEADER, "Failed magic check.");

			size_t headerSize = MCF_HEADERSIZE_V1;

			if (data[4] == 0x01)
				headerSize = MCF_HEADERSIZE_V1;
			else if (data[4] == 0x02)
				headerSize = MCF_HEADERSIZE_V2;
			else
				throw gcException(ERR_BADHEADER, "Bad version number");

			out.reset();
			msc.downloadRange(0, headerSize, &out);

			if (out.m_uiTotalSize != headerSize)
				throw gcException(ERR_BADHEADER, "Did not get correct ammount of data from server.");

			MCFCore::MCFHeader webHeader((uint8*)out.m_szBuffer);

			if (!webHeader.isValid())
				throw gcException(ERR_BADHEADER, "Mcf header was not valid.");

			uint32 ths = webHeader.getXmlSize();
			out = ths;

			msc.downloadRange(webHeader.getXmlStart(), webHeader.getXmlSize(), &out);

			if (out.m_uiTotalSize == 0 || out.m_uiTotalSize != webHeader.getXmlSize())
				throw gcException(ERR_WEBDL_FAILED, "Failed to download MCF xml from web (size is ether zero or didnt match header size)");

			data = out.m_szBuffer;

			if (data[0] == 'L' && data[1] == 'M' && data[2] == 'C' && data[3] == 'F')
				throw gcException(ERR_WEBDL_FAILED, "Server failed 4gb seek.");

			setHeader(&webHeader);
			successful = true;
			break;

		}
		catch (gcException &e)
		{
			lastE = e;
			Warning(gcString("Failed to download MCF Header from {1}: {0}\n", e, m_vProviderList[x]->getUrl()));
		}
	}

	if (!successful)
		throw lastE;

	uint32 bz2BuffLen = getHeader()->getXmlSize()*25;
	char* bz2Buff = NULL;

	if ( isCompressed() )
	{
		bz2Buff = new char[bz2BuffLen];
		UTIL::STRING::zeroBuffer(bz2Buff, bz2BuffLen);

		try
		{
			UTIL::BZIP::BZ2DBuff((char*)bz2Buff, &bz2BuffLen, out.m_szBuffer, out.m_uiTotalSize);
			parseXml(bz2Buff, bz2BuffLen);
			safe_delete(bz2Buff);
		}
		catch (gcException &)
		{
			safe_delete(bz2Buff);
			throw;
		}
	}
	else
	{
		parseXml(out.m_szBuffer, out.m_uiTotalSize);
	}

	//we remove the complete flag due to the files not existing in the MCF
	for (size_t x=0; x< m_pFileList.size(); x++)
	{
		m_pFileList[x]->delFlag(MCFCore::MCFFileI::FLAG_COMPLETE);
	}

	if (m_szFile != "")
		saveMCF_Header();
}
uint32_t TankFile::FileEntry::getChunkSize() const
{
	return isCompressed() ? getCompressedHeader().chunkSize : 0;
}
uint32_t TankFile::FileEntry::getCompressedSize() const
{
	return isCompressed() ? getCompressedHeader().compressedSize : size;
}
示例#29
0
文件: heplug.c 项目: wothke/webpsx
// slightly refactored original heplug.c logic here...
int he_install_bios(const char *he_bios_path) {
	
//	dumpComressedHeBios();		// tmp utility

	if ( !bios_get_imagesize() ) {
//		if ((he_bios_path == 0) || !strlen(he_bios_path)) {
#ifdef BUILTIN_HEBIOS	
			// use built-in hebios
			void * he_bios = malloc( HEBIOS_SIZE );
			long hebios_size= HEBIOS_SIZE;
			if (Z_OK !=  uncompress(he_bios, &hebios_size, zhebios, zhebios_size)) {
				trace( "he: BIOS uncompress error\n" );
				return -1;
			}
			if (hebios_size != HEBIOS_SIZE) {
				trace( "he: BIOS uncompress mismatch\n" );
				return -1;
			}
			bios_set_image( he_bios, hebios_size );
			trace( "he: using built-in hebios\n" );
#else
//		} else {
			// install specific bios 
			if ( !*he_bios_path ) {
				trace( "he: no BIOS set\n" );
				return -1;
			}
			
			FILE * f = psf_file_fopen( he_bios_path );
			if ( !f ) {
				trace( "he: failed to open bios %s\n", he_bios_path );
				return -1;
			}

			void * ps2_bios = malloc( 0x400000 );
			if ( !ps2_bios ) {
				psf_file_fclose( f );
				trace( "he: out of memory\n" );
				return -1;
			}
			
			int compressionEnabled= 1;
			
			size_t ps2_bios_size= 0;
			if (compressionEnabled && isCompressed(he_bios_path)) {
				size_t compressed_size = em_fgetlength( f );

				if (tmp_bios_buffer) { free(tmp_bios_buffer);}
				tmp_bios_buffer= malloc( compressed_size );

				if ( psf_file_fread( tmp_bios_buffer, 1, compressed_size, f ) < compressed_size ) {
					free( tmp_bios_buffer );
					psf_file_fclose( f );
					trace( "he: error reading compressed bios\n" );
					return -1;
				}
				
				ps2_bios_size= inflate2(tmp_bios_buffer, compressed_size, ps2_bios, 0x400000);
				if (ps2_bios_size < 0x400000) {
					free( ps2_bios );
					psf_file_fclose( f );
					trace( "he: could not uncompress bios\n" );
					return -1;
				}		
			} else {
				size_t ps2_bios_size = em_fgetlength( f );
				if ( ps2_bios_size != 0x400000 ) {
					psf_file_fclose( f );
					trace( "he: bios is wrong size\n" );
					return -1;
				}

				if ( psf_file_fread( ps2_bios, 1, 0x400000, f ) < 0x400000 ) {
					free( ps2_bios );
					psf_file_fclose( f );
					trace( "he: error reading bios\n" );
					return -1;
				}

				psf_file_fclose( f );
			}
			int bios_size = 0x400000;
			void * he_bios = mkhebios_create( ps2_bios, &bios_size );

			trace( "he: fucko - %p, %p, %u\n", ps2_bios, he_bios, bios_size );

			free( ps2_bios );

			if ( !he_bios )
			{
				trace( "he: error processing bios\n" );
				return -1;
			}

			bios_set_image( he_bios, bios_size );
//		}
#endif
	}
	return 0;
}
示例#30
0
文件: tony.cpp 项目: Cruel/scummvm
/**
 * Initialize the game
 */
Common::ErrorCode TonyEngine::init() {
	// Load DAT file (used by font manager)
	if (!loadTonyDat())
		return Common::kUnknownError;

	if (isCompressed()) {
		Common::SeekableReadStream *stream = SearchMan.createReadStreamForMember("data1.cab");
		if (!stream)
			error("Failed to open data1.cab");

		Common::Archive *cabinet = Common::makeInstallShieldArchive(stream);
		if (!cabinet)
			error("Failed to parse data1.cab");

		SearchMan.add("data1.cab", cabinet);
	}

	_hEndOfFrame = CoroScheduler.createEvent(false, false);

	_bPaused = false;
	_bDrawLocation = true;
	_startTime = g_system->getMillis();

	// Init static class fields
	RMText::initStatics();
	RMTony::initStatics();

	// Reset the scheduler
	CoroScheduler.reset();

	// Initialize the graphics window
	_window.init();

	// Initialize the function list
	Common::fill(_funcList, _funcList + 300, (LPCUSTOMFUNCTION)NULL);
	initCustomFunctionMap();

	// Initializes MPAL system, passing the custom functions list
	Common::File f;
	if (!f.open("ROASTED.MPC"))
		return Common::kReadingFailed;
	f.close();

	if (!mpalInit("ROASTED.MPC", "ROASTED.MPR", _funcList, _funcListStrings))
		return Common::kUnknownError;

	// Initialize the update resources
	_resUpdate.init("ROASTED.MPU");

	// Initialize the music
	initMusic();

	// Initialize the voices database
	if (!openVoiceDatabase())
		return Common::kReadingFailed;

	// Initialize the boxes
	_theBoxes.init();

	// Link to the custom graphics engine
	_theEngine.initCustomDll();
	_theEngine.init();

	// Allocate space for thumbnails when saving the game
	_curThumbnail = new uint16[160 * 120];

	_bQuitNow = false;

	return Common::kNoError;
}