// ---------------------------------------------------------------------- std::string FontSerializer::loadString(Ogre::DataStreamPtr& stream) { uint16 strsize; stream->read(&strsize, sizeof(uint16)); char * stringbuffer = new char[strsize+1]; stream->read((char*)stringbuffer, strsize); stringbuffer[strsize] = '\0'; std::string rstring = stringbuffer; delete[] stringbuffer; return rstring; }
void FvFTDTerrainPageSerializerImpl::ReadLayerMap(Ogre::DataStreamPtr &spStream, FvTerrainPage *pkDest, FvUInt32 uiLayerIndex) { FTDLayerMapHeader kHeader; spStream->read(&kHeader,sizeof(FTDLayerMapHeader)); FvTerrainPage::TextureLayerPtr spLayer = new FvTerrainPage::TextureLayer; FvUInt32 uiNameSize; spStream->read(&uiNameSize,sizeof(FvUInt32)); char acTextureName[256]; FV_ASSERT(uiNameSize < 256); spStream->read(acTextureName,uiNameSize); acTextureName[uiNameSize] = 0; spLayer->m_kTextureName = acTextureName; if(kHeader.m_uiVersion == VERSION_PNG) { spLayer->m_pkBlends = new Ogre::Image; spLayer->m_pkBlends->load(spStream,"png"); } if(kHeader.m_uiVersion == VERSION_DDS) { spLayer->m_pkBlends = new Ogre::Image; spLayer->m_pkBlends->load(spStream,"dds"); } FV_ASSERT(spLayer->m_pkBlends); try { spLayer->m_spTexture = Ogre::TextureManager::getSingleton().load(spLayer->m_kTextureName, pkDest->m_spTerrainSettings->TextureGroup()); } catch (...){} if(spLayer->m_spTexture.isNull()) { FV_ERROR_MSG("FvFTDTerrainPageSerializerImpl::ReadLayerMap texture %s not exist", spLayer->m_kTextureName.c_str()); } spLayer->m_uiWidth = kHeader.m_uiWidth; spLayer->m_uiHeight = kHeader.m_uiHeight; memcpy(&spLayer->m_kUProjection, kHeader.m_kUProjection, sizeof(Ogre::Vector4)); memcpy(&spLayer->m_kVProjection, kHeader.m_kVProjection, sizeof(Ogre::Vector4)); pkDest->m_kTextureLayers.push_back(spLayer); }
//----------------------------------------------------------------------------// size_t OggBuffer::vorbisRead(void *ptr, size_t byteSize, size_t sizeToRead, void *datasource ) { size_t spaceToEOF; // How much more we can read till we hit the EOF marker size_t actualSizeToRead; // How much data we are actually going to read from memory Ogre::DataStreamPtr vorbisData; // Our vorbis data, for the typecast // Get the data in the right format vorbisData = *(Ogre::DataStreamPtr*)datasource; // Calculate how much we need to read. This can be sizeToRead*byteSize or less depending on how near the EOF marker we are spaceToEOF = vorbisData->size() - vorbisData->tell(); if ((sizeToRead * byteSize) < spaceToEOF) actualSizeToRead = (sizeToRead * byteSize); else actualSizeToRead = spaceToEOF; // A simple copy of the data from memory to the datastruct that the vorbis libs will use if (actualSizeToRead) { // Copy the data from the start of the file PLUS how much we have already read in vorbisData->read(ptr, actualSizeToRead); } // Return how much we read (in the same way fread would) return actualSizeToRead; }
void CollisionShapeManager::LoadAllShapesFromBinaryFile(const String& FileName, const String& Group) { btBulletWorldImporter Importer; Ogre::DataStreamPtr Stream = Ogre::ResourceGroupManager::getSingleton().openResource(FileName,Group); char* buffer = new char[Stream->size()]; Stream->read((void*)buffer, Stream->size()); if(!Importer.loadFileFromMemory(buffer, Stream->size())) { MEZZ_EXCEPTION(ExceptionBase::IO_FILE_EXCEPTION,"Failed to load file: " + FileName + ".") } delete[] buffer; for( Whole X = 0 ; X < Importer.getNumCollisionShapes() ; ++X ) { btCollisionShape* Shape = Importer.getCollisionShapeByIndex(X); const char* MaybeAName = Importer.getNameForPointer((void*)Shape); String Name; if(MaybeAName) { Name = String(MaybeAName); ShapeMapIterator it = this->CollisionShapes.find(Name); if(it == this->CollisionShapes.end()) { CollisionShape* NewShape = this->WrapShape(Name,Shape); this->CollisionShapes.insert( std::pair<String,CollisionShape*>(Name,NewShape) ); } }else{ static Whole NameCount = 0; Name = String("Unnamed") += StringTools::ConvertToString(NameCount++); CollisionShape* NewShape = this->WrapShape(Name,Shape); this->UnnamedShapes.push_back(NewShape); } } }
bool gkAndroidApp::setup(void) { AAssetManager* assetMgr = m_state->activity->assetManager; if (assetMgr) { Ogre::ArchiveManager::getSingleton().addArchiveFactory(new Ogre::APKFileSystemArchiveFactory(assetMgr)); Ogre::ArchiveManager::getSingleton().addArchiveFactory(new Ogre::APKZipArchiveFactory(assetMgr)); Ogre::ResourceGroupManager::getSingleton().addResourceLocation("/", "APKFileSystem", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); } Ogre::DataStreamPtr stream = Ogre::ResourceGroupManager::getSingleton(). openResource(m_blend, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); if (stream.isNull()) { gkPrintf("Error: Can't open file %s.\n", m_blend.c_str()); return false; } size_t size = stream->size(); char* buf = new char[size]; stream->read(buf, size); gkBlendFile* blend = gkBlendLoader::getSingleton().loadFromMemory(buf,size,gkBlendLoader::LO_ALL_SCENES); gkScene* scene = blend->getMainScene(); if (!scene) { gkPrintf("No usable scenes found in blend.\n"); return false; } scene->createInstance(); scene->getMainCamera()->getCamera()->setAutoAspectRatio(true); return true; }
//--------------------------------------------------------------------- void BackgroundFileSerializer::readPallete( Ogre::DataStreamPtr &stream ,BackgroundFile *pDest ) { readSectionHeader( stream, SECTION_NAME_PALETTE ); stream->read( pDest->getPalette().data(), BackgroundFile::PALETTE_ENTRY_COUNT ); }
//--------------------------------------------------------------------- void BackgroundFileSerializer::readObject( Ogre::DataStreamPtr &stream, Page &pDest ) { read2ByteBool( stream, pDest.enabled ); if( !pDest.enabled ) return; readShort( stream, pDest.unknown_02 ); readShort( stream, pDest.value_size ); if( pDest.value_size != 1 && pDest.value_size != 2 ) { OGRE_EXCEPT(Ogre::Exception::ERR_INVALIDPARAMS ,"Page value_size other then 1 and 2 is not supported" ,"BackgroundFileSerializer::readObject" ); } size_t color_count( BackgroundFile::PAGE_DATA_SIZE ); pDest.colors.clear(); pDest.data.clear(); if( pDest.value_size == 2 ) { pDest.colors.reserve( color_count ); for( size_t i( color_count ); i--; ) { Color colourDest; readObject( stream, colourDest ); pDest.colors.push_back( colourDest ); } } else { pDest.data.resize( color_count ); stream->read( &pDest.data[0], color_count ); } }
std::string getString(size_t length) { std::string str; str.resize(length); if(inp->read(&str[0], length) != length) return std::string(); return str.substr(0, str.find('\0')); }
size_t RocketInterface::Read(void* buffer, size_t size, Rocket::Core::FileHandle file) { if (!file) return 0; Ogre::DataStreamPtr stream = *reinterpret_cast<Ogre::DataStreamPtr*>(file); return stream->read(buffer, size); }
// OgreScriptBuilder int OgreScriptBuilder::LoadScriptSection(const char* full_path_cstr) { // Get filename - required to retrieve file from OGRe's resource system. // This function received filename in older AngelScript versions, but now receives full path // (reconstructed wrong by CScriptBuilder because it doesn't know about OGRE's ZIP files). // TODO: Refactor the entire script building logic // - create fully RoR-custom builder instead of hacked stock CScriptBuilder + our overload. ~ only_a_ptr, 08/2017 std::string full_path(full_path_cstr); std::string filename; size_t slash_pos = full_path.rfind('/'); // AngelScript always uses forward slashes in paths. if (slash_pos != std::string::npos) { filename = full_path.substr(slash_pos+1); } else { filename = full_path; } Ogre::DataStreamPtr ds; try { ds = Ogre::ResourceGroupManager::getSingleton().openResource(filename, Ogre::ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME); //TODO: do not use `AUTODETECT_RESOURCE_GROUP_NAME`, use specific group, lookups are slow! //see also https://github.com/OGRECave/ogre/blob/master/Docs/1.10-Notes.md#resourcemanager-strict-mode ~ only_a_ptr, 08/2017 } catch (Ogre::Exception e) { LOG("[RoR|Scripting] exception upon loading script file '"+filename+"', message: " + e.getFullDescription()); return -1; } // In some cases (i.e. when fed a full path with '/'-s on Windows), `openResource()` will silently return NULL for datastream. ~ only_a_ptr, 08/2017 if (ds.isNull()) { LOG("[RoR|Scripting] Failed to load file '"+filename+"', reason unknown."); return -1; } // Read the entire file std::string code; code.resize(ds->size()); ds->read(&code[0], ds->size()); // hash it { char hash_result[250]; memset(hash_result, 0, 249); RoR::CSHA1 sha1; sha1.UpdateHash((uint8_t *)code.c_str(), (uint32_t)code.size()); sha1.Final(); sha1.ReportHash(hash_result, RoR::CSHA1::REPORT_HEX_SHORT); hash = Ogre::String(hash_result); } return ProcessScriptSection(code.c_str(), code.length(), filename.c_str(), 0); }
void GlobalMap::write(ESM::GlobalMap& map) { map.mBounds.mMinX = mMinX; map.mBounds.mMaxX = mMaxX; map.mBounds.mMinY = mMinY; map.mBounds.mMaxY = mMaxY; Ogre::DataStreamPtr encoded = mOverlayImage.encode("png"); map.mImageData.resize(encoded->size()); encoded->read(&map.mImageData[0], encoded->size()); }
//----------------------------------------------------------------------- void ExpatParser::parseXMLFile(XMLHandler& handler, const Ogre::String& xmlName, const Ogre::String& xmlResourceGroup, const Ogre::String& schemaName, const Ogre::String& schemaResourceGroup) { XML_Parser parser = XML_ParserCreate(NULL); try { MyUserData myUserData; myUserData.handler = &handler; if (_locale.get()) myUserData.converter = boost::bind(&expat_to_local, _1, _2, boost::ref(*_locale)); else myUserData.converter = boost::bind(&expat_to_local_win32, _1, _2, boost::ref(_buffer)); XML_SetUserData(parser, &myUserData); XML_SetElementHandler(parser, expatStartElementHandler, expatEndElementHandler); XML_SetCharacterDataHandler(parser, expatCharacterDataHandler); const size_t MaxBufferSize = 64*1024; Ogre::DataStreamPtr dataStream = Ogre::ResourceGroupManager::getSingleton().openResource(xmlName, xmlResourceGroup); bool done; do { void* buffer = XML_GetBuffer(parser, MaxBufferSize); if (!buffer) { OGRE_EXCEPT(Ogre::Exception::ERR_INTERNAL_ERROR, "Can't allocate buffer while parse XML file '" + xmlName + "'.", "ExpatParser::parseXMLFile"); } size_t count = dataStream->read(buffer, MaxBufferSize); done = dataStream->eof(); if (XML_ParseBuffer(parser, count, done) != XML_STATUS_OK) { OGRE_EXCEPT(Ogre::Exception::ERR_INTERNAL_ERROR, "An error occurred while parsing XML file '" + xmlName + "' at line " + Ogre::StringConverter::toString(XML_GetCurrentLineNumber(parser)) + ". Additional information: " + XML_ErrorString(XML_GetErrorCode(parser)), "ExpatParser::parseXMLFile"); } } while (!done); } catch(...) { XML_ParserFree(parser); throw; } XML_ParserFree(parser); }
/*void TestStream() { //String fname( "../../media/packs/chiropteraDM.txt"); std::ifstream* roStream = new std::ifstream; roStream ->open ("../../media/packs/chiropteraDM.txt", std::ios::in | std::ios::binary); //fptr = new FileStreamDataStream("tt", roStream, true); //fstrm = DataStreamPtr(fptr); DataStreamPtr ss = DataStreamPtr(new LodDataStream( Ogre::SharedPtr<std::ifstream>(roStream), 0x203,500)); std::cout << ss -> size() << endl; while(!ss->eof()) { cout << ss->getLine(false) << endl; } cout << ss->getAsString() << endl; }*/ void SaveStreamToFile(const Ogre::String& fname, Ogre::DataStreamPtr data) { char*buff = new char[data->size()]; std::ios::openmode mode = std::ios::binary | std::ios::out; std::ofstream rwStream; data->read(buff,data->size()); rwStream.open(fname, mode); rwStream.write(buff,data->size()); rwStream.close(); delete[] buff; std::cout << "Saved: " << fname << " size: "<<data->size() << std::endl; }
//-------------------------------------------------------------------------- void FLevelFileSerializer::readSectionData( Ogre::DataStreamPtr &stream ,Ogre::DataStreamPtr &out_buffer ) { uint32 length( 0 ); readInt( stream, length ); // TODO: implement SubDataStream class to restrict access size etc // so we don't have to copy the whole memory Ogre::MemoryDataStream *buffer( new Ogre::MemoryDataStream( length ) ); stream->read( buffer->getPtr(), length ); out_buffer = Ogre::DataStreamPtr( buffer ); }
qint64 OgreNetworkReply::readData(char *data, qint64 maxSize) { if (mDataStream.isNull()) { setErrorString("This network request is closed."); return -1; } if (mDataStream->eof()) return -1; return mDataStream->read(data, maxSize); }
/* void TextureAsset::RegenerateAllMipLevels() { if (ogreTexture.isNull()) return; ///\todo This function does not quite work, since ogreTexture->getNumMipmaps() will return 0 to denote a "full mipmap chain". for(int f = 0; f < ogreTexture->getNumFaces(); ++f) for(int i = 1; i < ogreTexture->getNumMipmaps(); ++i) { Ogre::HardwarePixelBufferSharedPtr src = ogreTexture->getBuffer(f, i-1); Ogre::Box srcSize(0, 0, src->getWidth(), src->getHeight()); Ogre::HardwarePixelBufferSharedPtr dst = ogreTexture->getBuffer(f, i); Ogre::Box dstSize(0, 0, dst->getWidth(), dst->getHeight()); dst->blit(src, srcSize, dstSize); } } */ bool TextureAsset::SerializeTo(std::vector<u8> &data, const QString &serializationParameters) const { if (ogreTexture.isNull()) { LogWarning("SerializeTo: Called on an unloaded texture \"" + Name().toStdString() + "\"."); return false; } try { Ogre::Image new_image; // From Ogre 1.7 Texture::convertToImage() size_t numMips = 1; size_t dataSize = Ogre::Image::calculateSize(numMips, ogreTexture->getNumFaces(), ogreTexture->getWidth(), ogreTexture->getHeight(), ogreTexture->getDepth(), ogreTexture->getFormat()); void* pixData = OGRE_MALLOC(dataSize, Ogre::MEMCATEGORY_GENERAL); // if there are multiple faces and mipmaps we must pack them into the data // faces, then mips void* currentPixData = pixData; for (size_t face = 0; face < ogreTexture->getNumFaces(); ++face) { for (size_t mip = 0; mip < numMips; ++mip) { size_t mipDataSize = Ogre::PixelUtil::getMemorySize(ogreTexture->getWidth(), ogreTexture->getHeight(), ogreTexture->getDepth(), ogreTexture->getFormat()); Ogre::PixelBox pixBox(ogreTexture->getWidth(), ogreTexture->getHeight(), ogreTexture->getDepth(), ogreTexture->getFormat(), currentPixData); ogreTexture->getBuffer(face, mip)->blitToMemory(pixBox); currentPixData = (void*)((char*)currentPixData + mipDataSize); } } // load, and tell Image to delete the memory when it's done. new_image.loadDynamicImage((Ogre::uchar*)pixData, ogreTexture->getWidth(), ogreTexture->getHeight(), ogreTexture->getDepth(), ogreTexture->getFormat(), true, ogreTexture->getNumFaces(), numMips - 1); Ogre::DataStreamPtr imageStream = new_image.encode(serializationParameters.toStdString()); if (imageStream.get() && imageStream->size() > 0) { data.resize(imageStream->size()); imageStream->read(&data[0], data.size()); } } catch (std::exception &e) { LogError("SerializeTo: Failed to export Ogre texture " + Name().toStdString() + ":"); if (e.what()) OgreRenderer::OgreRenderingModule::LogError(e.what()); return false; } return true; }
Resource::DataStreamPtr ResourceManager::OpenAssetStream(const String& AssetName, const String& AssetGroup) { /// @todo This entire method is a bit of a hack. When the resource system gets refactored it should go through our archives or whatever equivalent. /// Since we currently have to put up with Ogre's system, we'll use it for now as a hack. NamedDataStreamIterator StreamIt = this->NamedDataStreams.find(AssetName); if( StreamIt != this->NamedDataStreams.end() ) return (*StreamIt).second; Ogre::DataStreamPtr OgreStream = this->OgreResource->openResource(AssetName,AssetGroup); Char8* AssetBuffer = new Char8[ OgreStream->size() ]; OgreStream->read( (void*)AssetBuffer, OgreStream->size() ); return this->CreateDataStream(AssetName,AssetBuffer,OgreStream->size()); }
//----------------------------------------------------------------------------------------- QPixmap HeightImageEditorCodec::onBeforeDisplay(Ogre::DataStreamPtr stream) { double file_len = stream->size() / 4; unsigned int map_size = sqrt(file_len); mBuffer = new unsigned char[map_size * map_size * sizeof(float)]; float *buf = (float *)mBuffer; stream->read(buf, map_size * map_size * 4); float max_h = -1000000.0f; float min_h = 1000000.0f; for(unsigned int i = 0; i < map_size * map_size; i++) { if(buf[i] > max_h) max_h = buf[i]; if(buf[i] < min_h) min_h = buf[i]; } float diff = max_h - min_h; if(diff > 0.0f) { unsigned char *colbuf = (unsigned char *)buf; int pos = 0; for(unsigned int i = 0; i < map_size * map_size; i++) { float tval = mapToRange(buf[i], min_h, max_h, 60, 360); HSVtoARGB(&colbuf[pos], tval, 1.0f, 1.0f); pos += 4; } } else memset(buf, 0xFF, map_size * map_size * 4); QImage image = QImage((unsigned char *)buf, map_size, map_size, QImage::Format_ARGB32); mPixmap = QPixmap(QPixmap::fromImage(image)); return mPixmap; }
//loader for ScriptSystem std::string OgreFileLoader(lua_State* pState, std::string strFile) { if(!Ogre::ResourceGroupManager::getSingleton().resourceExists(Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, strFile)) return std::string("file not found"); Ogre::DataStreamPtr ds = Ogre::ResourceGroupManager::getSingleton().openResource(strFile); char *buffer = ICE_NEW char[ds->size()]; ds->read(buffer, ds->size()); ds->close(); if(luaL_loadbuffer(pState, buffer, ds->size(), strFile.c_str()) || lua_pcall(pState, 0, 0, 0)) { ICE_DELETE buffer; return std::string(lua_tostring(pState, -1)); } ICE_DELETE buffer; return std::string(); }
bool LanguageManager::loadLanguage(const std::string & _file, const std::string & _group, bool _user) { if (!_group.empty()) { if (!helper::isFileExist(_file, _group)) { MYGUI_LOG(Error, "file '" << _file << "' not found in group'" << _group << "'"); return false; } Ogre::DataStreamPtr stream = Ogre::ResourceGroupManager::getSingletonPtr()->openResource(_file, _group); // проверяем на сигнатуру utf8 uint32 sign = 0; stream->read((void*)&sign, 3); if (sign != 0x00BFBBEF) { MYGUI_LOG(Error, "file '" << _file << "' is not UTF8 format"); return false; } _loadLanguage(stream, _user); return true; } std::ifstream stream(_file.c_str()); if (false == stream.is_open()) { MYGUI_LOG(Error, "error open file '" << _file << "'"); return false; } // проверяем на сигнатуру utf8 uint32 sign = 0; stream.read((char*)&sign, 3); if (sign != 0x00BFBBEF) { MYGUI_LOG(Error, "file '" << _file << "' is not UTF8 format"); stream.close(); return false; } _loadLanguage(stream, _user); stream.close(); return true; }
QByteArray *ResourceManager::read(const char *path, const char *group) { Ogre::String groupName = Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME; if (group) groupName = group; Ogre::DataStreamPtr dataStream = Ogre::ResourceGroupManager::getSingleton().openResource(path, groupName); int totalSize = dataStream->size(); QScopedPointer<QByteArray> result(new QByteArray(totalSize, Qt::Uninitialized)); int bytesRead = 0; char *buffer = result->data(); while (bytesRead < totalSize) { int read = dataStream->read(buffer, totalSize - bytesRead); buffer += read; bytesRead += read; } return result.take(); }
void FvFTDTerrainPageSerializerImpl::ReadHeightMap(Ogre::DataStreamPtr &spStream, FvTerrainPage *pkDest, FvUInt32 uiLodLevel) { FV_ASSERT(pkDest); FTDHeightMapHeader kHeader; spStream->read(&kHeader,sizeof(FTDHeightMapHeader)); pkDest->m_fMinHeight = kHeader.m_fMinHeight; pkDest->m_fMaxHeight = kHeader.m_fMaxHeight; pkDest->m_uiHeightLodLevel = uiLodLevel; pkDest->m_uiVisiableOffset = pkDest->m_uiHeightLodLevel > 0 ? 0 : FV_DEFAULT_VISIBLE_OFFSET; if (pkDest->m_fMaxHeight < pkDest->m_fMinHeight) std::swap(pkDest->m_fMinHeight, pkDest->m_fMaxHeight); if(kHeader.m_uiVersion == VERSION_PNG) pkDest->m_kHeights.load(spStream,"png"); else if(kHeader.m_uiVersion == VERSION_DDS) pkDest->m_kHeights.load(spStream,"dds"); FV_ASSERT(pkDest->m_kHeights.getWidth() == kHeader.m_uiWidth); FV_ASSERT(pkDest->m_kHeights.getHeight() == kHeader.m_uiHeight); }
void FvFTDTerrainPageSerializerImpl::ReadLodNormalMap(Ogre::DataStreamPtr &spStream, FvTerrainPage *pkDest) { FTDNormalMapHeader kHeader; spStream->read(&kHeader,sizeof(FTDNormalMapHeader)); if(kHeader.m_uiVersion == VERSION_PNG) { Ogre::Codec *pkCodec = 0; pkCodec = Ogre::Codec::getCodec("png"); if(pkCodec == NULL) return; Ogre::Codec::DecodeResult kRes = pkCodec->decode(spStream); Ogre::ImageCodec::ImageData *pkData = static_cast<Ogre::ImageCodec::ImageData*>(kRes.second.getPointer()); pkDest->m_spLodNormalMap = Ogre::TextureManager::getSingleton().loadRawData(pkDest->m_kLodNormalName, FvTerrainPage::TERRAIN_INERNAL_RESOURCE_GROUP, Ogre::DataStreamPtr(kRes.first), Ogre::ushort(pkData->width), Ogre::ushort(pkData->height), Ogre::PF_BYTE_LA); } }
uint16_t read_le16() { uint8_t buffer[2]; if(inp->read(buffer, 2) != 2) return 0; return buffer[0] | (buffer[1]<<8); }
void MWState::StateManager::saveGame (const std::string& description, const Slot *slot) { try { ESM::SavedGame profile; MWBase::World& world = *MWBase::Environment::get().getWorld(); MWWorld::Ptr player = world.getPlayerPtr(); profile.mContentFiles = world.getContentFiles(); profile.mPlayerName = player.getClass().getName (player); profile.mPlayerLevel = player.getClass().getNpcStats (player).getLevel(); std::string classId = player.get<ESM::NPC>()->mBase->mClass; if (world.getStore().get<ESM::Class>().isDynamic(classId)) profile.mPlayerClassName = world.getStore().get<ESM::Class>().find(classId)->mName; else profile.mPlayerClassId = classId; profile.mPlayerCell = world.getCellName(); profile.mInGameTime.mGameHour = world.getTimeStamp().getHour(); profile.mInGameTime.mDay = world.getDay(); profile.mInGameTime.mMonth = world.getMonth(); profile.mInGameTime.mYear = world.getYear(); profile.mTimePlayed = mTimePlayed; profile.mDescription = description; int screenshotW = 259*2, screenshotH = 133*2; // *2 to get some nice antialiasing Ogre::Image screenshot; world.screenshot(screenshot, screenshotW, screenshotH); Ogre::DataStreamPtr encoded = screenshot.encode("jpg"); profile.mScreenshot.resize(encoded->size()); encoded->read(&profile.mScreenshot[0], encoded->size()); if (!slot) slot = getCurrentCharacter()->createSlot (profile); else slot = getCurrentCharacter()->updateSlot (slot, profile); boost::filesystem::ofstream stream (slot->mPath, std::ios::binary); ESM::ESMWriter writer; const std::vector<std::string>& current = MWBase::Environment::get().getWorld()->getContentFiles(); for (std::vector<std::string>::const_iterator iter (current.begin()); iter!=current.end(); ++iter) writer.addMaster (*iter, 0); // not using the size information anyway -> use value of 0 writer.setFormat (ESM::Header::CurrentFormat); int recordCount = 1 // saved game header +MWBase::Environment::get().getJournal()->countSavedGameRecords() +MWBase::Environment::get().getWorld()->countSavedGameRecords() +MWBase::Environment::get().getScriptManager()->getGlobalScripts().countSavedGameRecords() +MWBase::Environment::get().getDialogueManager()->countSavedGameRecords() +MWBase::Environment::get().getWindowManager()->countSavedGameRecords(); writer.setRecordCount (recordCount); writer.save (stream); Loading::Listener& listener = *MWBase::Environment::get().getWindowManager()->getLoadingScreen(); listener.setProgressRange(recordCount); listener.setLabel("#{sNotifyMessage4}"); Loading::ScopedLoad load(&listener); writer.startRecord (ESM::REC_SAVE); slot->mProfile.save (writer); writer.endRecord (ESM::REC_SAVE); listener.increaseProgress(); MWBase::Environment::get().getJournal()->write (writer, listener); MWBase::Environment::get().getDialogueManager()->write (writer, listener); MWBase::Environment::get().getWorld()->write (writer, listener); MWBase::Environment::get().getScriptManager()->getGlobalScripts().write (writer, listener); MWBase::Environment::get().getWindowManager()->write(writer, listener); // Ensure we have written the number of records that was estimated if (writer.getRecordCount() != recordCount+1) // 1 extra for TES3 record std::cerr << "Warning: number of written savegame records does not match. Estimated: " << recordCount+1 << ", written: " << writer.getRecordCount() << std::endl; writer.close(); if (stream.fail()) throw std::runtime_error("Write operation failed"); Settings::Manager::setString ("character", "Saves", slot->mPath.parent_path().filename().string()); } catch (const std::exception& e) { std::stringstream error; error << "Failed to save game: " << e.what(); std::cerr << error.str() << std::endl; std::vector<std::string> buttons; buttons.push_back("#{sOk}"); MWBase::Environment::get().getWindowManager()->messageBox(error.str(), buttons); // If no file was written, clean up the slot if (slot && !boost::filesystem::exists(slot->mPath)) getCurrentCharacter()->deleteSlot(slot); } }
//--------------------------------------------------------------------- void BackgroundFileSerializer::readObject( Ogre::DataStreamPtr &stream, SpriteData &pDest ) { readObject( stream, pDest.dst ); readShorts( stream, pDest.unknown_04, 2 ); readObject( stream, pDest.src ); readObject( stream, pDest.src2 ); readShort( stream, pDest.width ); readShort( stream, pDest.height ); uint16 size; // width and height are sometimes incorrect in the file if ( m_layer_index < 2 ) { size = 16; } else if ( m_layer_index < BackgroundFile::LAYER_COUNT) { size = 32; } else { OGRE_EXCEPT(Ogre::Exception::ERR_INVALIDPARAMS ,"m_layer_index not set correctly" ,"BackgroundFileSerializer::readObject" ); } pDest.width = pDest.height = size; readShort( stream, pDest.palette_page ); readShort( stream, pDest.depth ); // Force depth values switch ( m_layer_index ) { case 0: pDest.depth = 4095; break; case 2: pDest.depth = 4096; break; case 3: pDest.depth = 0; break; } uint8 animation[2]; stream->read( animation, sizeof( animation ) ); pDest.animation_id = animation[0]; pDest.animation_frame = animation[1]; uint8 has_blending[2]; stream->read( has_blending, sizeof( has_blending ) ); pDest.has_blending[0] = has_blending[0] > 0; pDest.has_blending[1] = has_blending[1] > 0; readShort( stream, pDest.blending ); readShort( stream, pDest.data_page ); readShort( stream, pDest.data_page2 ); // when data_page2 != 0, it must be used instead of data_page (not for the first layer) if ( m_layer_index > 0 && pDest.data_page2 ) { pDest.src = pDest.src2; pDest.data_page = pDest.data_page2; } readShort( stream, pDest.colour_depth ); readObject( stream, pDest.src_big ); pDest.src_big /= src_big_SCALE; stream->skip( 2 * 2 ); // 2 * uint16 unused }
uint32_t read_le32() { uint8_t buffer[4]; if(inp->read(buffer, 4) != 4) return 0; return buffer[0] | (buffer[1]<<8) | (buffer[2]<<16) | (buffer[3]<<24); }
int FFmpeg_Decoder::readPacket(void *user_data, uint8_t *buf, int buf_size) { Ogre::DataStreamPtr stream = static_cast<FFmpeg_Decoder*>(user_data)->mDataStream; return stream->read(buf, buf_size); }
void DotSceneLoader::processTerrainPage(rapidxml::xml_node<>* XMLNode) { Ogre::String name = getAttrib(XMLNode, "name"); int pageX = Ogre::StringConverter::parseInt(XMLNode->first_attribute("pageX")->value()); int pageY = Ogre::StringConverter::parseInt(XMLNode->first_attribute("pageY")->value()); Ogre::Real worldSize = getAttribReal(XMLNode, "worldSize"); int mapSize = Ogre::StringConverter::parseInt(XMLNode->first_attribute("mapSize")->value()); bool colourmapEnabled = getAttribBool(XMLNode, "colourmapEnabled"); int colourmapTexturesize = Ogre::StringConverter::parseInt(XMLNode->first_attribute("colourmapTexturesize")->value()); int layerCount = Ogre::StringConverter::parseInt(XMLNode->first_attribute("layerCount")->value()); Ogre::String filename = mTerrainGroup->generateFilename(pageX, pageY); if (Ogre::ResourceGroupManager::getSingleton().resourceExists(mTerrainGroup->getResourceGroup(), filename)) { mTerrainGroup->defineTerrain(pageX, pageY); } else { rapidxml::xml_node<>* pElement; pElement = XMLNode->first_node("position"); if(pElement) mTerrainPosition = parseVector3(pElement); Ogre::DataStreamPtr stream = Ogre::ResourceGroupManager::getSingleton().openResource(name + Ogre::String(".ohm"), "General" ); size_t size = stream.get()->size(); if(size != mapSize * mapSize * 4) { OGRE_EXCEPT( Ogre::Exception::ERR_INTERNAL_ERROR, "Size of stream does not match terrainsize!", "TerrainPage" ); } float* buffer = OGRE_ALLOC_T(float, size, Ogre::MEMCATEGORY_GEOMETRY); stream->read(buffer, size); Ogre::Terrain::ImportData& imp = mTerrainGroup->getDefaultImportSettings(); imp.terrainSize = mapSize; imp.worldSize = worldSize; imp.inputFloat = buffer; imp.inputImage = 0; imp.deleteInputData = true; imp.minBatchSize = 33; imp.maxBatchSize = 65; imp.layerList.resize(layerCount); int count = 0; // Process layers (*) rapidxml::xml_node<>* pTerrainLayer; rapidxml::xml_node<>* pTerrainTextures; rapidxml::xml_node<>* pTerrainTexture; pElement = XMLNode->first_node("layers"); while(pElement) { pTerrainLayer = pElement->first_node("layer"); while(pTerrainLayer) { int worldSize = Ogre::StringConverter::parseInt(pTerrainLayer->first_attribute("worldSize")->value()); pTerrainTextures = pTerrainLayer->first_node("textures"); pTerrainTexture = pTerrainTextures->first_node("texture"); while(pTerrainTexture) { imp.layerList[count].textureNames.push_back(getAttrib(pTerrainTexture,"name","")); imp.layerList[count].worldSize = (Ogre::Real)worldSize; pTerrainTexture = pTerrainTexture->next_sibling("texture"); } count++; // do stuff pTerrainLayer = pTerrainLayer->next_sibling("layer"); } pElement = pElement->next_sibling("layers"); } mTerrainGroup->defineTerrain(pageX, pageY, &imp); } }
bool MapLoader::loadMapFormFile(std::string mapname) { int mapsize; Terrain* terrain = Terrain::getSingletonPtr(); DataLibrary* datalibrary = DataLibrary::getSingletonPtr(); std::string path = ".\\..\\Media\\Map\\" + mapname; //ticpp::Document *doc = new ticpp::Document(); rapidxml::xml_document<> doc; //doc.LoadFile(path,TIXML_ENCODING_UTF8); Ogre::DataStreamPtr stream = Ogre::ResourceGroupManager::getSingleton().openResource(mapname, "Data", true); char* s=new char[stream->size()+1]; stream->read(s,stream->size()); s[stream->size()]='\0'; doc.parse<0>(s); std::string str1; //载入地图名字,介绍和脚本名 //ticpp::Element *element = doc.FirstChildElement("MapName"); rapidxml::xml_node<> * element = doc.first_node("MapName"); //element->GetText(&str1); str1 = element->value(); datalibrary->setData("GameData/BattleData/MapData/MapName", StringTable::getSingleton().getString(str1)); //delete element; //element = doc.FirstChildElement("MapScript"); element = doc.first_node("MapScript"); //element->GetText(&str1); str1 = element->value(); datalibrary->setData("GameData/BattleData/MapData/MapScript", str1); //delete element; element = doc.first_node("MapMini"); //element->GetText(&str1); if (element!=NULL) { str1 = element->value(); } else { str1="MiniMap1.png"; } datalibrary->setData("GameData/BattleData/MapData/MapMini", str1); //element = doc.FirstChildElement("MapInfo"); element = doc.first_node("MapInfo"); //element->GetText(&str1); str1 = element->value(); datalibrary->setData("GameData/BattleData/MapData/MapInfo",str1); //delete element; //element = doc.FirstChildElement("MapLoadBG"); element = doc.first_node("MapLoadBG"); //element->GetText(&str1); str1 = element->value(); datalibrary->setData("GameData/BattleData/MapData/MapLoadBG",str1); //delete element; //载入地图地形信息 //element = doc.FirstChildElement("MapSize"); element = doc.first_node("MapSize"); //element->GetText(&mapsize); mapsize = Ogre::StringConverter::parseUnsignedInt(element->value()); MapDataManager::getSingleton().mMapSize = mapsize; datalibrary->setData("GameData/BattleData/MapData/MapSize", mapsize); //delete element; //element= doc.FirstChildElement("MapGround"); element = doc.first_node("MapGround"); //ticpp::Iterator<ticpp::Element> child; rapidxml::xml_node<> *child = element->first_node(); std::string datapath; //for(child = child.begin(element); child != child.end(); child++) for(; child; child =child->next_sibling()) { std::string layer,type,texture; //child->GetValue(&layer); layer = child->name(); //child->GetAttribute("Type",&type); rapidxml::xml_attribute<> *attr = child->first_attribute("Type"); type = attr->value(); //child->GetAttribute("Texture",&texture); attr = child->first_attribute("Texture"); texture = attr->value(); datapath = str(boost::format("GameData/BattleData/MapData/Ground/%1%")%layer); datalibrary->setData(datapath, type); datapath = str(boost::format("GameData/BattleData/MapData/Ground/%1%Tex")%layer); datalibrary->setData(datapath, texture); } //delete element; //element = doc.FirstChildElement("MapData"); element = doc.first_node("MapData"); //element->GetText(&str1); str1 = element->value(); for(int y = 0; y < mapsize; y++) { for(int x = 0; x < mapsize; x++) { int index = y * mapsize + x; char datapathtemp[64]; sprintf_s(datapathtemp, 64, "GameData/BattleData/MapData/Map/M%d", MapDataManager::getSingleton().getGridId(x, y)); std::string datapath = datapathtemp; if(str1[index * 2] == 'l') { bool iscliff = false; for(int i = y - 1; i < y + 2; i ++) { for(int j = x - 1; j < x + 2; j++) { int u = (i<0)?0:i; u = (u >= mapsize)?mapsize-1:u; int v = (j<0)?0:j; v = (v >= mapsize)?mapsize-1:v; int tempindex = u * mapsize + v; if(str1[tempindex * 2] == 'h' ) { iscliff = true; } } } if(iscliff) datalibrary->setData(datapath + "/TerrainType", Cliff); else datalibrary->setData(datapath + "/TerrainType", LowGround); } else if(str1[index * 2] == 'w') { datalibrary->setData(datapath + "/TerrainType", Water); } else if(str1[index * 2] == 'h') { datalibrary->setData(datapath + "/TerrainType", HighGround); } else if(str1[index * 2] == 'r') { datalibrary->setData(datapath + "/TerrainType", Ramp); } if(str1[index * 2+1] == 'g') { datalibrary->setData(datapath + "/GroundType", GreenLand); } else if(str1[index * 2+1] == 'd') { datalibrary->setData(datapath + "/GroundType", Desert); } else if(str1[index * 2+1] == 'w') { datalibrary->setData(datapath + "/GroundType", Swamp); } else if(str1[index * 2+1] == 's') { datalibrary->setData(datapath + "/GroundType", Snow); } } } //delete element; //element = doc.FirstChildElement("MapObject"); element = doc.first_node("MapObject"); //for(child = child.begin(element); child != child.end(); child++) for(child = element->first_node(); child; child =child->next_sibling()) { std::string objname; //child->GetValue(&objname); objname = child->name(); datapath = std::string("GameData/BattleData/MapData/MapObjModleInfo/") + objname; int objx,objy, objdir; std::string meshname,objtype; //child->GetAttribute("GridX",&objx); rapidxml::xml_attribute<> *attr = child->first_attribute("GridX"); objx = Ogre::StringConverter::parseInt(attr->value()); //child->GetAttribute("GridY",&objy); attr = child->first_attribute("GridY"); objy = Ogre::StringConverter::parseInt(attr->value()); //child->GetAttribute("Mesh",&meshname); attr=child->first_attribute("Mesh"); meshname = attr->value(); //child->GetAttribute("Type",&objtype); attr=child->first_attribute("Type"); objtype = attr->value(); attr=child->first_attribute("Direction"); objdir = Ogre::StringConverter::parseInt(attr->value()); datalibrary->setData(datapath + "/GridX", objx); datalibrary->setData(datapath + "/GridY", objy); datalibrary->setData(datapath + "/Mesh", meshname); datalibrary->setData(datapath + "/Direction", objdir); //物品类型脚本 std::string mapobjscript("none"); datalibrary->getData(str(boost::format("StaticData/MapObjType/%1%/Script")%objtype), mapobjscript); datapath = std::string("GameData/BattleData/MapData/Map/M") + Ogre::StringConverter::toString(MapDataManager::getSingleton().getGridId(objx, objy)) + std::string("/MapObjType"); if(mapobjscript != "none") { MapObjScriptInfo scriptinfo; scriptinfo.x = objx; scriptinfo.y = objy; scriptinfo.script = mapobjscript; scriptinfo.path = datapath + "/ScriptContext"; mMapObjScriptInfo.push(scriptinfo); } datalibrary->setData(datapath, objtype); datalibrary->setData(datapath + "/MapObjModuleId", objname); } //delete element; //element = doc.FirstChildElement("MapEffect"); element = doc.first_node("MapEffect"); //for(child = child.begin(element); child != child.end(); child++) for(child = element->first_node(); child; child =child->next_sibling()) { std::string particlename; //child->GetValue(&particlename); particlename = child->name(); datapath = std::string("GameData/BattleData/MapData/MapParticleInfo/") + particlename; int particlex,particley; std::string name; //child->GetAttribute("GridX",&particlex); rapidxml::xml_attribute<> *attr = child->first_attribute("GridX"); particlex = Ogre::StringConverter::parseInt(attr->value()); //child->GetAttribute("GridY",&particley); attr = child->first_attribute("GridY"); particley = Ogre::StringConverter::parseInt(attr->value()); //child->GetAttribute("Type",&name); attr = child->first_attribute("Type"); name = attr->value(); datalibrary->setData(datapath + "/GridX", particlex); datalibrary->setData(datapath + "/GridY", particley); datalibrary->setData(datapath + "/Type", name); } terrain->createTerrain(); //delete element; //载入区域信息 //element = doc.FirstChildElement("MapArea"); element = doc.first_node("MapArea"); //for(child = child.begin(element); child != child.end(); child++) for(child = element->first_node(); child; child =child->next_sibling()) { std::string areaname; //child->GetValue(&areaname); areaname = child->name(); datapath = std::string("GameData/BattleData/MapData/Area/") + areaname; Area area(datapath + "/CoordList"); std::vector<Crood> croodVec; //ticpp::Iterator<ticpp::Element> childchild; rapidxml::xml_node<> *childchild = child->first_node(); //for(childchild = childchild.begin(child.Get()); childchild != childchild.end(); childchild++) for(; childchild; childchild=childchild->next_sibling()) { std::string coordname; //childchild->GetValue(&coordname); coordname = childchild->name(); int x; int y; //childchild->GetAttribute("X",&x); rapidxml::xml_attribute<> *attr = childchild->first_attribute("X"); x = Ogre::StringConverter::parseInt(attr->value()); //childchild->GetAttribute("Y",&y); attr = childchild->first_attribute("Y"); y = Ogre::StringConverter::parseInt(attr->value()); croodVec.push_back(Crood(x, y)); } area.setCroodVec(croodVec); MapDataManager::getSingleton().mMapArea.insert(std::make_pair(areaname, area)); } //delete element; //载入队伍信息 //element = doc.FirstChildElement("MapTeam"); element = doc.first_node("MapTeam"); for(int n = 2; n < 5; n++) { std::string name = std::string("Team") + Ogre::StringConverter::toString(n); std::string factionid; //ticpp::Element* subelement = element->FirstChildElement(name); child = element->first_node(name.c_str()); //subelement->GetAttribute("TeamFaction",&factionid); rapidxml::xml_attribute<> *attr = child->first_attribute("TeamFaction"); factionid = attr->value(); datalibrary->setData(std::string("GameData/BattleData/Team/")+ name+ "/FactionId", factionid); if(factionid != "none") { //subelement->GetAttribute("TeamType",&factionid); attr = child->first_attribute("TeamType"); factionid = attr->value(); datalibrary->setData(std::string("GameData/BattleData/Team/")+ name+ "/Relation", factionid); } //delete subelement; } std::string playerfactionid; datalibrary->getData("GameData/StoryData/Faction",playerfactionid); datalibrary->setData("GameData/BattleData/Team/Team1/FactionId",playerfactionid); datalibrary->setData("GameData/BattleData/Team/Team1/Relation","player"); //delete element; //载入部队信息 //element = doc.FirstChildElement("MapSquad"); element = doc.first_node("MapSquad"); MapSquadInfo mapsquadinfo; //for(child = child.begin(element); child != child.end(); child++) for(child = element->first_node(); child;child = child->next_sibling()) { std::string teamid; //child->GetValue(&teamid); teamid = child->name(); if(teamid == "Team1") mapsquadinfo.team = 1; else if(teamid == "Team2") mapsquadinfo.team = 2; else if(teamid == "Team3") mapsquadinfo.team = 3; else mapsquadinfo.team = 4; datapath = std::string("GameData/BattleData/SquadList"); //ticpp::Iterator<ticpp::Element> childchild; rapidxml::xml_node<> *childchild = child->first_node(); //for(childchild = childchild.begin(child.Get()); childchild != childchild.end(); childchild++) for(; childchild; childchild =childchild->next_sibling()) { // std::string squadid; // std::string squadtype; //childchild->GetValue(&mapsquadinfo.squadId); mapsquadinfo.squadId = childchild->name(); // int x; // int y; // Direction d; // int unitnum; // int morale; //childchild->GetAttribute("Type",&mapsquadinfo.squadTempId); rapidxml::xml_attribute<> *attr = childchild->first_attribute("Type"); mapsquadinfo.squadTempId = attr->value(); //childchild->GetAttribute("GridX",&mapsquadinfo.x); attr = childchild->first_attribute("GridX"); mapsquadinfo.x = Ogre::StringConverter::parseInt(attr->value()); //childchild->GetAttribute("GridY",&mapsquadinfo.y); attr = childchild->first_attribute("GridY"); mapsquadinfo.y = Ogre::StringConverter::parseInt(attr->value()); //childchild->GetAttribute("UnitNum",&mapsquadinfo.unitNum); attr = childchild->first_attribute("UnitNum"); mapsquadinfo.unitNum = Ogre::StringConverter::parseInt(attr->value()); //childchild->GetAttribute("Direction",&mapsquadinfo.dir); attr = childchild->first_attribute("Direction"); mapsquadinfo.dir = Ogre::StringConverter::parseInt(attr->value()); mMapSquadInfo.push(mapsquadinfo); // AVGSquadManager::getSingleton().addSquad(squadid,squadtype, datapath); // int type; // Formation f; // datalibrary->getData(datapath + std::string("/") + squadid + std::string("/Type"), type ); // if(type == SQUAD_NORMAL) // f = Line; // else // f = Loose; // datalibrary->setData(datapath + std::string("/") + squadid + std::string("/GridX"), x, true ); // datalibrary->setData(datapath + std::string("/") + squadid + std::string("/GridY"), y, true ); // datalibrary->setData(datapath + std::string("/") + squadid + std::string("/UnitNumber"), unitnum, true ); // datalibrary->setData(datapath + std::string("/") + squadid + std::string("/Direction"), d, true ); // datalibrary->setData(datapath + std::string("/") + squadid + std::string("/Formation"), f, true ); // datalibrary->setData(datapath + std::string("/") + squadid + std::string("/TeamId"), teamid, true ); // datalibrary->setData(datapath + std::string("/") + squadid + std::string("/CreateType"), MapSquad, true ); // datalibrary->setData(datapath + std::string("/") + squadid + std::string("/ActionPoint"), 0.0f, true ); // datalibrary->setData(datapath + std::string("/") + squadid + std::string("/Morale"), morale, true ); } } //delete element; delete []s; return true; }