Пример #1
0
int main()
{
	WriteVersion();

#ifdef __FreeBSD__
	_malloc_options = "A";
#endif

	CConfig Config;
	CNetPoller poller;
	CDBManager DBManager; 
	CClientManager ClientManager;
	PlayerHB player_hb;
	CGuildManager GuildManager;
	CPrivManager PrivManager;
	CMoneyLog MoneyLog;
	ItemAwardManager ItemAwardManager;
	marriage::CManager MarriageManager;
	CMonarch Monarch;
	CBlockCountry	BlockCountry;
	CItemIDRangeManager ItemIDRangeManager;
#ifdef __AUCTION__
	AuctionManager auctionManager;
#endif
	if (!Start())
		return 1;

	GuildManager.Initialize();
	MarriageManager.Initialize();
	BlockCountry.Load();
	ItemIDRangeManager.Build();
#ifdef __AUCTION__
	AuctionManager::instance().Initialize();
#endif
	sys_log(0, "Metin2DBCacheServer Start\n");

	CClientManager::instance().MainLoop();

	signal_timer_disable();

	DBManager.Quit();
	int iCount;

	while (1)
	{
		iCount = 0;

		iCount += CDBManager::instance().CountReturnQuery(SQL_PLAYER);
		iCount += CDBManager::instance().CountAsyncQuery(SQL_PLAYER);

		if (iCount == 0)
			break;

		usleep(1000);
		sys_log(0, "WAITING_QUERY_COUNT %d", iCount);
	}

	return 1;
}
Пример #2
0
int EXRFile::OpenOutputFile(const char* i_fileName)
{
	m_file = fopen(i_fileName, "wb");
	
	if (!m_file)
	{
		return IMF_ERROR_ERROR;
	}
	
	m_channelList = new ChannelList(*m_header->GetChannelList());
	m_channelList->Sort();
	
	m_header->GetAttribute("dataWindow", "box2i", (char*)&m_dataWindow[0]);
	m_header->GetAttribute("compression", "compression", (char*)&m_compression);
	
	int width = m_dataWindow[2] - m_dataWindow[0] + 1;
	size_t datasize = m_channelList->GetPixelSize() * width;
	if (m_compression == IMF_ZIP_COMPRESSION)
	{
		m_scanline_block =
			new ScanLineZipBlock(
				m_file,
				datasize,
				m_dataWindow[1]);
	}
	else
	{
		m_scanline_block =
			new ScanLineBlock(
				m_file,
				datasize,
				m_dataWindow[1]);
	}

	int height = m_dataWindow[3] - m_dataWindow[1] + 1;

	m_blocks =  height / m_scanline_block->NumLinesInBlock();
	m_blocks += height % m_scanline_block->NumLinesInBlock() > 0;

	m_offset_table = new uint64_t [m_blocks];
	m_offset_table_counter = 0;
	
	WriteMagic();
	WriteVersion();
	WriteHeader();
	WriteZerroOffsets();

	return IMF_ERROR_NOERROR;
}
Пример #3
0
/**
\fn	void InitVersion ()

\brief	Initialises the version system. 

\author	Paril
\date	25/05/2010
**/
void InitVersion ()
{
#if (VERSION_CHECKING != VC_NONE)
	ServerPrint ("Checking for new version...\n");

	if (!CFile::Exists(VERSION_PATH))
	{
		ServerPrint ("Version file non-existant, writing... ");
		WriteVersion ();
		ServerPrint ("done\n");
	}
	else
		VerifyVersionFile ();
	
	CheckNewVersion ();
#endif
}
Пример #4
0
void VerifyVersionFile ()
{
	CFileBuffer Buffer (VERSION_PATH, true);
	CParser Parser (Buffer.GetBuffer<char> (), PSP_COMMENT_LINE);

	String prefix;
	Parser.ParseToken (PSF_ALLOW_NEWLINES, prefix);

	uint8 minor;
	uint16 major;
	uint32 build;
	Parser.ParseDataType<uint16> (PSF_ALLOW_NEWLINES, &major, 1);
	Parser.ParseDataType<uint8> (PSF_ALLOW_NEWLINES, &minor, 1);
	Parser.ParseDataType<uint32> (PSF_ALLOW_NEWLINES, &build, 1);

	if (CompareVersion (prefix.CString(), major, minor, build))
	{
		ServerPrint ("Version file out of date; updating...\n");
		WriteVersion ();
	}
}
Пример #5
0
        void TensorBoardFileWriter::Init()
        {
            time_t time = std::time(0);
            std::wstring filePath = GetNewFilePath(m_dir, time);

            msra::files::make_intermediate_dirs(filePath);

            m_file = fopenOrDie(ToString(filePath), "wb");
            m_fileName = filePath;

            // Write the first record with the current version, and flush
            // right away so the file contents will be easily determined.
            WriteVersion(time);

            if (m_model)
            {
                WriteModel();
            }

            Flush();
        }
Пример #6
0
/**
 *
 *  @author OLiver
 */
bool Savegame::Save(BinaryFile& file)
{
    // Versionszeug schreiben
    WriteVersion(file, 8, SAVE_SIGNATURE, SAVE_VERSION);

    // Timestamp der Aufzeichnung
    unser_time_t tmpTime = libendian::ConvertEndianess<false>::fromNative(save_time);
    file.WriteRawData(&tmpTime, 8);

    // Mapname
    file.WriteShortString(map_name);

    // Anzahl Spieler
    file.WriteUnsignedChar(GetPlayerCount());

    // Größe der Spielerdaten (später ausfüllen)
    unsigned players_size = 0;
    unsigned players_pos = file.Tell();
    file.WriteUnsignedInt(players_size);

    // Spielerdaten
    WritePlayerData(file);

    // Wieder zurückspringen und Größe des Spielerblocks eintragen
    unsigned new_pos = file.Tell();
    file.Seek(players_pos, SEEK_SET);
    file.WriteUnsignedInt(new_pos - players_pos - 4);
    file.Seek(new_pos, SEEK_SET);

    // GGS
    WriteGGS(file);

    // Start-GF
    file.WriteUnsignedInt(start_gf);

    // Serialisiertes Spielzeug reinschreiben
    sgd.WriteToFile(file);

    return true;
}
Пример #7
0
void MeshSaverImplv1_0::Save(OutputStreamPtr& out,
		AssetSaver& saver) {

	try {
		MeshTemplate* mesh = static_cast<MeshTemplate*>(
					saver.GetRequestPtr()->GetStreamedObject());

		WriteVersion(out);

		ChunkOutputStream stream(out);
		WriteMeshHeader(mesh, stream);
		WriteBoundsInfo(mesh->GetBounds(), stream);
		MeshBuffer* buffer = mesh->GetSharedMeshBuffer();
		MaterialTemplatePtr material = mesh->GetSharedMaterial();
		if (buffer) {
			WriteVertexData(buffer, stream);
			WriteIndexData(buffer, stream);
		}

		if (material) {
			WriteMaterialData(material, stream);
		}

		uint32 numPrim = mesh->GetNumPrimitiveGroups();
		for (uint32 i = 0; i < numPrim; ++i) {
			OutputSerializer& ser = stream.BeginChunk(MCID_SUBMESH_DATA);
			WriteSubMeshData(mesh, mesh->GetPrimitive(i), stream);
			stream.EndChunk();
		}
	} catch (const GracefulErrorExcept& e) {
		saver.GetRequestPtr()->SetCompleted(false);
		NEX_THROW(e);
	}

	saver.GetRequestPtr()->SetCompleted(true);
}
Пример #8
0
int main(int argc, char **argv)
{
#ifdef DEBUG_ALLOC
	DebugAllocator::StaticSetUp();
#endif

	ilInit(); // DevIL Initialize

	WriteVersion();
	
	SECTREE_MANAGER	sectree_manager;
	CHARACTER_MANAGER	char_manager;
	ITEM_MANAGER	item_manager;
	CShopManager	shop_manager;
	CMobManager		mob_manager;
	CMotionManager	motion_manager;
	CPartyManager	party_manager;
	CSkillManager	skill_manager;
	CPVPManager		pvp_manager;
	LZOManager		lzo_manager;
	DBManager		db_manager;
	AccountDB 		account_db;

	LogManager		log_manager;
	MessengerManager	messenger_manager;
	P2P_MANAGER		p2p_manager;
	CGuildManager	guild_manager;
	CGuildMarkManager mark_manager;
	CDungeonManager	dungeon_manager;
	CRefineManager	refine_manager;
	CBanwordManager	banword_manager;
	CPrivManager	priv_manager;
	CWarMapManager	war_map_manager;
	building::CManager	building_manager;
	CTargetManager	target_manager;
	marriage::CManager	marriage_manager;
	marriage::WeddingManager wedding_manager;
	CItemAddonManager	item_addon_manager;
	CArenaManager arena_manager;
	COXEventManager OXEvent_manager;
	CMonarch		Monarch;
	CHorseNameManager horsename_manager;

	DESC_MANAGER	desc_manager;

	TrafficProfiler	trafficProfiler;
	CTableBySkill SkillPowerByLevel;
	CPolymorphUtils polymorph_utils;
	CProfiler		profiler;
	CBattleArena	ba;
	SpamManager		spam_mgr;
	CThreeWayWar	threeway_war;
	CDragonLairManager	dl_manager;

	CSpeedServerManager SSManager;
	DSManager dsManager;

#ifdef __AUCTION__
	AuctionManager auctionManager;
#endif

	if (!start(argc, argv)) {
		CleanUpForEarlyExit();
		return 0;
	}

	quest::CQuestManager quest_manager;

	if (!quest_manager.Initialize()) {
		CleanUpForEarlyExit();
		return 0;
	}

	MessengerManager::instance().Initialize();
	CGuildManager::instance().Initialize();
	fishing::Initialize();
	OXEvent_manager.Initialize();
	if (speed_server)
		CSpeedServerManager::instance().Initialize();

	Cube_init();
	Blend_Item_init();
	ani_init();
	PanamaLoad();

	if ( g_bTrafficProfileOn )
		TrafficProfiler::instance().Initialize( TRAFFIC_PROFILE_FLUSH_CYCLE, "ProfileLog" );

	// Client PackageCrypt

	//TODO : make it config
	const std::string strPackageCryptInfoDir = "package/";
	if( !desc_manager.LoadClientPackageCryptInfo( strPackageCryptInfoDir.c_str() ) )
	{
		sys_err("Failed to Load ClientPackageCryptInfo File(%s)", strPackageCryptInfoDir.c_str());	
	}

#if defined (__FreeBSD__) && defined(__FILEMONITOR__)
	PFN_FileChangeListener pPackageNotifyFunc =  &(DESC_MANAGER::NotifyClientPackageFileChanged);
	//FileMonitorFreeBSD::Instance().AddWatch( strPackageCryptInfoName, pPackageNotifyFunc );
#endif

	while (idle());

	sys_log(0, "<shutdown> Starting...");
	g_bShutdown = true;
	g_bNoMoreClient = true;

	if (g_bAuthServer)
	{
		int iLimit = DBManager::instance().CountQuery() / 50;
		int i = 0;

		do
		{
			DWORD dwCount = DBManager::instance().CountQuery();
			sys_log(0, "Queries %u", dwCount);

			if (dwCount == 0)
				break;

			usleep(500000);

			if (++i >= iLimit)
				if (dwCount == DBManager::instance().CountQuery())
					break;
		} while (1);
	}

	sys_log(0, "<shutdown> Destroying CArenaManager...");
	arena_manager.Destroy();
	sys_log(0, "<shutdown> Destroying COXEventManager...");
	OXEvent_manager.Destroy();

	sys_log(0, "<shutdown> Disabling signal timer...");
	signal_timer_disable();

	sys_log(0, "<shutdown> Shutting down CHARACTER_MANAGER...");
	char_manager.GracefulShutdown();
	sys_log(0, "<shutdown> Shutting down ITEM_MANAGER...");
	item_manager.GracefulShutdown();

	sys_log(0, "<shutdown> Flushing db_clientdesc...");
	db_clientdesc->FlushOutput();
	sys_log(0, "<shutdown> Flushing p2p_manager...");
	p2p_manager.FlushOutput();

	sys_log(0, "<shutdown> Destroying CShopManager...");
	shop_manager.Destroy();
	sys_log(0, "<shutdown> Destroying CHARACTER_MANAGER...");
	char_manager.Destroy();
	sys_log(0, "<shutdown> Destroying ITEM_MANAGER...");
	item_manager.Destroy();
	sys_log(0, "<shutdown> Destroying DESC_MANAGER...");
	desc_manager.Destroy();
	sys_log(0, "<shutdown> Destroying quest::CQuestManager...");
	quest_manager.Destroy();
	sys_log(0, "<shutdown> Destroying building::CManager...");
	building_manager.Destroy();

	sys_log(0, "<shutdown> Flushing TrafficProfiler...");
	trafficProfiler.Flush();

	destroy();

#ifdef DEBUG_ALLOC
	DebugAllocator::StaticTearDown();
#endif

	return 1;
}
Пример #9
0
/**
 *
 *  @author OLiver
 */
bool Replay::WriteHeader(const std::string& filename)
{
	// Datei öffnen
	if(!file.Open(filename.c_str(),OFM_WRITE))
		return false;

	Replay::filename = filename;

	// Versionszeug schreiben
	WriteVersion(file,6,REPLAY_SIGNATURE,REPLAY_VERSION);
	// Timestamp der Aufzeichnung (TODO: Little/Big Endian unterscheidung)
	file.WriteRawData(&save_time,8);
	/// NWF-Länge
	file.WriteUnsignedShort(nwf_length);
	/// Zufallsgeneratorinitialisierung
	file.WriteUnsignedInt(random_init);
	/// Pathfinding-Results hier drin?
	file.WriteUnsignedChar(pathfinding_results ? 1 : 0);

	// Position merken für End-GF
	last_gf_file_pos = file.Tell();

	/// End-GF (erstmal nur 0, wird dann im Spiel immer geupdatet)
	file.WriteUnsignedInt(last_gf);
	// Anzahl Spieler
	file.WriteUnsignedChar(player_count);
	// Spielerdaten
	WritePlayerData(file);
	// GGS
	WriteGGS(file);

	// Map-Type
	file.WriteUnsignedShort(static_cast<unsigned short>(map_type));

	switch(map_type)
	{
	default:
		break;
	case MAPTYPE_OLDMAP:
		{
			// Map-Daten
			file.WriteUnsignedInt(map_length);
			file.WriteUnsignedInt(map_zip_length);
			file.WriteRawData(map_data,map_zip_length);
		} break;
	case MAPTYPE_SAVEGAME:
		{
			// Savegame speichern
			if(!savegame->Save(file))
				return false;
		} break;
	}

	// Mapname
	file.WriteShortString(map_name);

	// bei ungerader 4er position aufrunden
	//while(file.Tell() % 4)
	//	file.WriteSignedChar(0);

	// Alles sofort reinschreiben
	file.Flush();
	
	gf_file_pos  = 0;

	// Create File for pathfinding results
	if(pathfinding_results)
		pf_file.Open((filename + "_res").c_str(),OFM_WRITE);

	return true;
}
Пример #10
0
CDB::CDB(const char* pszFile, const char* pszMode, bool fTxn) : pdb(NULL)
{
    int ret;
    if (pszFile == NULL)
        return;

    bool fCreate = strchr(pszMode, 'c');
    bool fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
    unsigned int nFlags = DB_THREAD;
    if (fCreate)
        nFlags |= DB_CREATE;
    else if (fReadOnly)
        nFlags |= DB_RDONLY;
    if (!fReadOnly || fTxn)
        nFlags |= DB_AUTO_COMMIT;

    CRITICAL_BLOCK(cs_db)
    {
        if (!fDbEnvInit)
        {
            string strAppDir = GetAppDir();
            string strLogDir = strAppDir + "\\database";
            _mkdir(strLogDir.c_str());
            printf("dbenv.open strAppDir=%s\n", strAppDir.c_str());

            dbenv.set_lg_dir(strLogDir.c_str());
            dbenv.set_lg_max(10000000);
            dbenv.set_lk_max_locks(10000);
            dbenv.set_lk_max_objects(10000);
            dbenv.set_errfile(fopen("db.log", "a")); /// debug
            ///dbenv.log_set_config(DB_LOG_AUTO_REMOVE, 1); /// causes corruption
            ret = dbenv.open(strAppDir.c_str(),
                             DB_CREATE     |
                             DB_INIT_LOCK  |
                             DB_INIT_LOG   |
                             DB_INIT_MPOOL |
                             DB_INIT_TXN   |
                             DB_THREAD     |
                             DB_PRIVATE    |
                             DB_RECOVER,
                             0);
            if (ret > 0)
                throw runtime_error(strprintf("CDB() : error %d opening database environment\n", ret));
            fDbEnvInit = true;
        }

        strFile = pszFile;
        ++mapFileUseCount[strFile];
    }

    pdb = new Db(&dbenv, 0);

    ret = pdb->open(NULL,      // Txn pointer
                    pszFile,   // Filename
                    "main",    // Logical db name
                    DB_BTREE,  // Database type
                    nFlags,    // Flags
                    0);

    if (ret > 0)
    {
        delete pdb;
        pdb = NULL;
        CRITICAL_BLOCK(cs_db)
            --mapFileUseCount[strFile];
        strFile = "";
        throw runtime_error(strprintf("CDB() : can't open database file %s, error %d\n", pszFile, ret));
    }

    if (fCreate && !Exists(string("version")))
        WriteVersion(VERSION);

    RandAddSeed();
}
Пример #11
0
PictSelection::PictSelection (istream& from, State* state) : (nil) {
    ReadPictGS(from, state);
    ReadChildren(from, state);
    valid = from.good();
}

// ReadChildren loops determining which kind of Selection follows and
// creating it until it reads "end" which means all of the children
// have been created.

void PictSelection::ReadChildren (istream& from, State* state) {
    while (from.good()) {
	Skip(from);
	Selection* child = nil;
	from >> buf;
	if (strcmp(buf, "BSpl") == 0) {
	    child = new BSplineSelection(from, state);
	} else if (strcmp(buf, "Circ") == 0) {
	    child = new	CircleSelection(from, state);
	} else if (strcmp(buf, "CBSpl") == 0) {
	    child = new	ClosedBSplineSelection(from, state);
	} else if (strcmp(buf, "Elli") == 0) {
	    child = new	EllipseSelection(from, state);
	} else if (strcmp(buf, "Line") == 0) {
	    child = new	LineSelection(from, state);
	} else if (strcmp(buf, "MLine") == 0) {
	    child = new	MultiLineSelection(from, state);
	} else if (strcmp(buf, "Pict") == 0) {
	    child = new	PictSelection(from, state);
	} else if (strcmp(buf, "Poly") == 0) {
	    child = new	PolygonSelection(from, state);
	} else if (strcmp(buf, "Rect") == 0) {
	    child = new	RectSelection(from, state);
	} else if (strcmp(buf, "Text") == 0) {
	    child = new	TextSelection(from, state);
	} else if (strcmp(buf, "eop") == 0) {
	    break;
	} else {
	    fprintf(stderr, "unknown Selection %s, skipping\n", buf);
	    continue;
	}
	if (from.good()) {
	    Append(child);
	} else {
	    delete child;
	}
    }
}

// WritePicture writes the picture's data and Postscript code to print
// it wrapped in Postscript comments that minimally conform to version
// 1.0 of Adobe Systems's structuring conventions for Postscript.  The
// picture must remove itself from its parent if it has a parent to
// prevent the parent's transformation from affecting the picture's
// calculation of its bounding box.

void PictSelection::WritePicture (ostream& to, boolean verbose) {
    Picture* parent = (Picture*) Parent();
    if (parent != nil) {
	parent->SetCurrent(this);
	parent->Remove(this);
    }

    ScaleToPostscriptCoords();
    if (verbose) {
	WriteComments(to);
	WritePrologue(to);
	WriteVersion(to);
	WriteGridSpacing(to);
	WriteDrawing(to);
	WriteTrailer(to);
    } else {
	WriteVersion(to);
	WriteGridSpacing(to);
	WriteDrawing(to);
    }
    ScaleToScreenCoords();

    if (parent != nil) {
	parent->InsertBeforeCur(this);
    }
}
Пример #12
0
BerkeleyBatch::BerkeleyBatch(BerkeleyDatabase& database, const char* pszMode, bool fFlushOnCloseIn) : pdb(nullptr), activeTxn(nullptr)
{
    fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
    fFlushOnClose = fFlushOnCloseIn;
    env = database.env;
    if (database.IsDummy()) {
        return;
    }
    const std::string &strFilename = database.strFile;

    bool fCreate = strchr(pszMode, 'c') != nullptr;
    unsigned int nFlags = DB_THREAD;
    if (fCreate)
        nFlags |= DB_CREATE;

    {
        LOCK(cs_db);
        if (!env->Open(false /* retry */))
            throw std::runtime_error("BerkeleyBatch: Failed to open database environment.");

        pdb = env->mapDb[strFilename];
        if (pdb == nullptr) {
            int ret;
            std::unique_ptr<Db> pdb_temp = MakeUnique<Db>(env->dbenv.get(), 0);

            bool fMockDb = env->IsMock();
            if (fMockDb) {
                DbMpoolFile* mpf = pdb_temp->get_mpf();
                ret = mpf->set_flags(DB_MPOOL_NOFILE, 1);
                if (ret != 0) {
                    throw std::runtime_error(strprintf("BerkeleyBatch: Failed to configure for no temp file backing for database %s", strFilename));
                }
            }

            ret = pdb_temp->open(nullptr,                             // Txn pointer
                            fMockDb ? nullptr : strFilename.c_str(),  // Filename
                            fMockDb ? strFilename.c_str() : "main",   // Logical db name
                            DB_BTREE,                                 // Database type
                            nFlags,                                   // Flags
                            0);

            if (ret != 0) {
                throw std::runtime_error(strprintf("BerkeleyBatch: Error %d, can't open database %s", ret, strFilename));
            }

            // Call CheckUniqueFileid on the containing BDB environment to
            // avoid BDB data consistency bugs that happen when different data
            // files in the same environment have the same fileid.
            //
            // Also call CheckUniqueFileid on all the other g_dbenvs to prevent
            // bitcoin from opening the same data file through another
            // environment when the file is referenced through equivalent but
            // not obviously identical symlinked or hard linked or bind mounted
            // paths. In the future a more relaxed check for equal inode and
            // device ids could be done instead, which would allow opening
            // different backup copies of a wallet at the same time. Maybe even
            // more ideally, an exclusive lock for accessing the database could
            // be implemented, so no equality checks are needed at all. (Newer
            // versions of BDB have an set_lk_exclusive method for this
            // purpose, but the older version we use does not.)
            for (const auto& env : g_dbenvs) {
                CheckUniqueFileid(env.second, strFilename, *pdb_temp, this->env->m_fileids[strFilename]);
            }

            pdb = pdb_temp.release();
            env->mapDb[strFilename] = pdb;

            if (fCreate && !Exists(std::string("version"))) {
                bool fTmp = fReadOnly;
                fReadOnly = false;
                WriteVersion(CLIENT_VERSION);
                fReadOnly = fTmp;
            }
        }
        ++env->mapFileUseCount[strFilename];
        strFile = strFilename;
    }
}
Пример #13
0
int EXRFile::OpenOutputFile(const char* i_fileName)
{
	m_file = fopen(i_fileName, "wb");
	
	if (!m_file)
	{
		return IMF_ERROR_ERROR;
	}
	
	m_channelList = new ChannelList(*m_header->GetChannelList());
	m_channelList->Sort();
	
	m_header->GetAttribute("dataWindow", "box2i", (char*)&m_dataWindow[0]);
	m_header->GetAttribute("compression", "compression", (char*)&m_compression);

	/* TODO: Get and use length of the attribute */
	char type[256];
	const char* deepscanline = "deepscanline";
	m_header->GetAttribute("type", "string", type);
	if (strncmp(type, deepscanline, strlen(deepscanline)) == 0)
	{
		m_dataType = IMF_DEEPSCANLINE;
	}
	else
	{
		m_dataType = IMF_SCANLINEIMAGE;
	}

	int width = m_dataWindow[2] - m_dataWindow[0] + 1;
	size_t datasize = m_channelList->GetPixelSize() * width;

	if( m_dataType == IMF_DEEPSCANLINE )
	{
		if (m_compression == IMF_ZIPS_COMPRESSION)
		{
			m_scanline_block =
				new ScanLineDeepZipSBlock(
						m_file,
						width * sizeof(m_fb_sampleCount[0]),
						m_channelList->GetPixelSize(),
						m_dataWindow[1]);
		}
		else
		{
			m_scanline_block =
				new ScanLineDeepBlock(
						m_file,
						width * sizeof(m_fb_sampleCount[0]),
						m_channelList->GetPixelSize(),
						m_dataWindow[1]);
		}
	}
	else
	switch( m_compression )
	{
		case IMF_ZIP_COMPRESSION:
			m_scanline_block =
				new ScanLineZipBlock(
					m_file,
					datasize,
					m_dataWindow[1],
					ScanLineZipBlock::kDefaultBlockSize);
			break;
		case IMF_ZIPS_COMPRESSION:
			m_scanline_block =
				new ScanLineZipBlock(
					m_file,
					datasize,
					m_dataWindow[1],
					1);
			break;
		default:
			m_scanline_block =
				new ScanLineBlock(
					m_file,
					datasize,
					m_dataWindow[1]);
	}

	int height = m_dataWindow[3] - m_dataWindow[1] + 1;

	m_blocks =  height / m_scanline_block->NumLinesInBlock();
	m_blocks += height % m_scanline_block->NumLinesInBlock() > 0;

	m_offset_table = new uint64_t [m_blocks];
	// Initialize table to 0, so that valgrind doesn't complain about writing it out to file before we initialize it
	for( int i = 0; i < m_blocks; i++ ) m_offset_table[i] = 0;
	m_offset_table_counter = 0;
	
	WriteMagic();
	WriteVersion();
	WriteHeader();
	WriteZerroOffsets();

	return IMF_ERROR_NOERROR;
}
Пример #14
0
Файл: db.cpp Проект: AltJ/ECCoin
CDB::CDB(const std::string &strFilename, const char *pszMode, bool fFlushOnCloseIn) : pdb(NULL), activeTxn(NULL)
{
    int ret;
    fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
    fFlushOnClose = fFlushOnCloseIn;
    if (strFilename.empty())
        return;

    bool fCreate = strchr(pszMode, 'c') != NULL;
    unsigned int nFlags = DB_THREAD;
    if (fCreate)
        nFlags |= DB_CREATE;

    {
        LOCK(bitdb.cs_db);
        if (!bitdb.Open(GetDataDir()))
            throw std::runtime_error("CDB: Failed to open database environment.");

        strFile = strFilename;
        ++bitdb.mapFileUseCount[strFile];
        pdb = bitdb.mapDb[strFile];
        if (pdb == NULL)
        {
            pdb = new Db(bitdb.dbenv, 0);

            bool fMockDb = bitdb.IsMock();
            if (fMockDb)
            {
                DbMpoolFile *mpf = pdb->get_mpf();
                ret = mpf->set_flags(DB_MPOOL_NOFILE, 1);
                if (ret != 0)
                    throw std::runtime_error(
                        strprintf("CDB: Failed to configure for no temp file backing for database %s", strFile));
            }

            ret = pdb->open(NULL, // Txn pointer
                fMockDb ? NULL : strFile.c_str(), // Filename
                fMockDb ? strFile.c_str() : "main", // Logical db name
                DB_BTREE, // Database type
                nFlags, // Flags
                0);

            if (ret != 0)
            {
                delete pdb;
                pdb = NULL;
                --bitdb.mapFileUseCount[strFile];
                strFile = "";
                throw std::runtime_error(strprintf("CDB: Error %d, can't open database %s", ret, strFile));
            }

            if (fCreate && !Exists(std::string("version")))
            {
                bool fTmp = fReadOnly;
                fReadOnly = false;
                WriteVersion(CLIENT_VERSION);
                fReadOnly = fTmp;
            }

            bitdb.mapDb[strFile] = pdb;
        }
    }
}
Пример #15
0
CDB::CDB(const char* pszFile, const char* pszMode) : pdb(NULL)
{
    int ret;
    if (pszFile == NULL)
        return;

    fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
    bool fCreate = strchr(pszMode, 'c');
    unsigned int nFlags = DB_THREAD;
    if (fCreate)
        nFlags |= DB_CREATE;

    CRITICAL_BLOCK(cs_db)
    {
        if (!fDbEnvInit)
        {
            if (fShutdown)
                return;
            string strDataDir = GetDataDir();
            string strLogDir = strDataDir + "/database";
            filesystem::create_directory(strLogDir.c_str());
            string strErrorFile = strDataDir + "/db.log";
            printf("dbenv.open strLogDir=%s strErrorFile=%s\n", strLogDir.c_str(), strErrorFile.c_str());

            dbenv.set_lg_dir(strLogDir.c_str());
            dbenv.set_lg_max(10000000);
#if !(TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)
            dbenv.set_lk_max_locks(10000);
            dbenv.set_lk_max_objects(10000);
#endif
            dbenv.set_errfile(fopen(strErrorFile.c_str(), "a")); /// debug
            dbenv.set_flags(DB_AUTO_COMMIT, 1);
            ret = dbenv.open(strDataDir.c_str(),
                             DB_CREATE     |
#if !(TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)
                             DB_INIT_LOCK  |
#endif
                             DB_INIT_LOG   |
                             DB_INIT_MPOOL |
                             DB_INIT_TXN   |
                             DB_THREAD     |
                             DB_RECOVER,
                             S_IRUSR | S_IWUSR);
            if (ret > 0)
                throw runtime_error(strprintf("CDB() : error %d opening database environment", ret));
            fDbEnvInit = true;
        }

        strFile = pszFile;
        ++mapFileUseCount[strFile];
        pdb = mapDb[strFile];
        if (pdb == NULL)
        {
            pdb = new Db(&dbenv, 0);

            ret = pdb->open(NULL,      // Txn pointer
                            pszFile,   // Filename
                            "main",    // Logical db name
                            DB_BTREE,  // Database type
                            nFlags,    // Flags
                            0);

            if (ret > 0)
            {
                delete pdb;
                pdb = NULL;
                CRITICAL_BLOCK(cs_db)
                    --mapFileUseCount[strFile];
                strFile = "";
                throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
            }

            if (fCreate && !Exists(string("version")))
            {
                bool fTmp = fReadOnly;
                fReadOnly = false;
                WriteVersion(VERSION);
                fReadOnly = fTmp;
            }

            mapDb[strFile] = pdb;
        }
    }
}
Пример #16
0
CDB::CDB(const char* pszFile, const char* pszMode) : pdb(NULL)
{
    int ret;
    if (pszFile == NULL)
        return;

    fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
    bool fCreate = strchr(pszMode, 'c');
    unsigned int nFlags = DB_THREAD;
    if (fCreate)
        nFlags |= DB_CREATE;

    CRITICAL_BLOCK(cs_db)
    {
        if (!dbLock)
        {
            if (fShutdown)
                return;
            string strDataDir = GetDataDir();
            string strLogDir = strDataDir + "/database";
            filesystem::create_directory(strLogDir.c_str());
            string strErrorFile = strDataDir + "/db.log";
            printf("dbenv.open strLogDir=%s strErrorFile=%s\n", strLogDir.c_str(), strErrorFile.c_str());

            // if strErrorFile exists and is locked, exception: another Bitcoin must
            // be using this DataDir:
            if (boost::filesystem::exists(strErrorFile))
            {
                dbLock = new boost::interprocess::file_lock(strErrorFile.c_str());
                bool locked = dbLock->try_lock();
                if (!locked)
                    throw runtime_error(_("Cannot lock db.log, is bitcoin already running?\n"));
            }

            dbenv.set_lg_dir(strLogDir.c_str());
            dbenv.set_lg_max(10000000);
            dbenv.set_lk_max_locks(10000);
            dbenv.set_lk_max_objects(10000);
            dbenv.set_errfile(fopen(strErrorFile.c_str(), "a")); /// debug
            dbenv.set_flags(DB_AUTO_COMMIT, 1);
            ret = dbenv.open(strDataDir.c_str(),
                             DB_CREATE     |
                             DB_INIT_LOCK  |
                             DB_INIT_LOG   |
                             DB_INIT_MPOOL |
                             DB_INIT_TXN   |
                             DB_THREAD     |
                             DB_PRIVATE    |
                             DB_RECOVER,
                             S_IRUSR | S_IWUSR);
            if (ret > 0)
                throw runtime_error(strprintf("CDB() : error %d opening database environment\n", ret));

            if (!dbLock)
            {
                dbLock = new boost::interprocess::file_lock(strErrorFile.c_str());
                dbLock->lock();
            }
        }

        strFile = pszFile;
        ++mapFileUseCount[strFile];
        pdb = mapDb[strFile];
        if (pdb == NULL)
        {
            pdb = new Db(&dbenv, 0);

            ret = pdb->open(NULL,      // Txn pointer
                            pszFile,   // Filename
                            "main",    // Logical db name
                            DB_BTREE,  // Database type
                            nFlags,    // Flags
                            0);

            if (ret > 0)
            {
                delete pdb;
                pdb = NULL;
                CRITICAL_BLOCK(cs_db)
                    --mapFileUseCount[strFile];
                strFile = "";
                throw runtime_error(strprintf("CDB() : can't open database file %s, error %d\n", pszFile, ret));
            }

            if (fCreate && !Exists(string("version")))
            {
                bool fTmp = fReadOnly;
                fReadOnly = false;
                WriteVersion(VERSION);
                fReadOnly = fTmp;
            }

            mapDb[strFile] = pdb;
        }
    }
}
Пример #17
0
// ----- M A I N ---------------------------------------------------------------
int main(int argc, char** argv) {
  SetWorldSilent(true); // No STDOUT output from cpptraj routines.
  std::string topname, crdname, title, bres, pqr, sybyltype, writeconect;
  std::string aatm(" pdbatom"), ter_opt(" terbyres"), box(" sg \"P 1\"");
  TrajectoryFile::TrajFormatType fmt = TrajectoryFile::PDBFILE;
  bool ctr_origin = false;
  bool useExtendedInfo = false;
  int res_offset = 0;
  int debug = 0;
  int numSoloArgs = 0;
  for (int i = 1; i < argc; ++i) {
    std::string arg( argv[i] );
    if (arg == "-p" && i+1 != argc && topname.empty()) // Topology
      topname = std::string( argv[++i] );
    else if (arg == "-c" && i+1 != argc && crdname.empty()) // Coords
      crdname = std::string( argv[++i] );
    else if (arg == "-tit" && i+1 != argc && title.empty()) // Title
      title = " title " + std::string( argv[++i] );
    else if (arg == "-offset" && i+1 != argc) // Residue # offset
      res_offset = convertToInteger( argv[++i] );
    else if ((arg == "-d" || arg == "--debug") && i+1 != argc) // Debug level
      debug = convertToInteger( argv[++i] );
    else if (arg == "-h" || arg == "--help") { // Help
      Help(argv[0], true);
      return 0;
    } else if (arg == "-v" || arg == "--version") { // Version info
      WriteVersion();
      return 0;
    } else if (arg == "-aatm") // Amber atom names, include extra pts
      aatm.assign(" include_ep");
    else if (arg == "-sybyl") // Amber atom types to SYBYL
      sybyltype.assign(" sybyltype");
    else if (arg == "-conect") // Write CONECT records from bond info
      writeconect.assign(" conect");
    else if (arg == "-ep") // PDB atom names, include extra pts
      aatm.append(" include_ep");
    else if (arg == "-bres") // PDB residue names
      bres.assign(" pdbres");
    else if (arg == "-ext") // Use extended PDB info from Topology
      useExtendedInfo = true;
    else if (arg == "-ctr")  // Center on origin
      ctr_origin = true;
    else if (arg == "-noter") // No TER cards
      ter_opt.assign(" noter");
    else if (arg == "-nobox") // No CRYST1 record
      box.assign(" nobox");
    else if (arg == "-pqr") { // Charge/Radii in occ/bfactor cols
      pqr.assign(" dumpq");
      ++numSoloArgs;
    } else if (arg == "-mol2") { // output as mol2
      fmt = TrajectoryFile::MOL2FILE;
      ++numSoloArgs;
    } else if (Unsupported(arg)) {
      mprinterr("Error: Option '%s' is not yet supported.\n\n", arg.c_str());
      return 1;
    } else {
      mprinterr("Error: Unrecognized option '%s'\n", arg.c_str());
      Help(argv[0], false);
      return 1;
    }
  }
  if (debug > 0) WriteVersion();
  // Check command line for errors.
  if (topname.empty()) topname.assign("prmtop");
  if (debug > 0 && crdname.empty())
    mprinterr("| Reading Amber restart from STDIN\n");
  if (numSoloArgs > 1) {
    mprinterr("Error: Only one alternate output format option may be specified (found %i)\n",
              numSoloArgs);
    Help(argv[0], true);
    return 1;
  }
  if (!sybyltype.empty() && fmt != TrajectoryFile::MOL2FILE) {
    mprinterr("Warning: -sybyl is only valid for MOL2 file output.\n");
    sybyltype.clear();
  }
  if (debug > 0) {
    mprinterr("Warning: debug is %i; debug info will be written to STDOUT.\n", debug);
    SetWorldSilent(false);
  }
  // Topology
  ParmFile pfile;
  Topology parm;
  if (pfile.ReadTopology(parm, topname, debug)) {
    if (topname == "prmtop") Help(argv[0], false);
    return 1;
  }
  if (!useExtendedInfo)
    parm.ResetPDBinfo();
  if (res_offset != 0)
    for (int r = 0; r < parm.Nres(); r++)
      parm.SetRes(r).SetOriginalNum( parm.Res(r).OriginalResNum() + res_offset );
  ArgList trajArgs;
  // Input coords
  Frame TrajFrame;
  CoordinateInfo cInfo;
  if (!crdname.empty()) {
    Trajin_Single trajin;
    if (trajin.SetupTrajRead(crdname, trajArgs, &parm)) return 1;
    cInfo = trajin.TrajCoordInfo();
    TrajFrame.SetupFrameV(parm.Atoms(), cInfo);
    trajin.BeginTraj();
    if (trajin.ReadTrajFrame(0, TrajFrame)) return 1;
    trajin.EndTraj();
  } else {
    // Assume Amber restart from STDIN
    // Check that input is from a redirect.
    if ( isatty(fileno(stdin)) ) {
      mprinterr("Error: No coordinates specified with '-c' and no STDIN '<'.\n");
      return 1;
    }
    Traj_AmberRestart restartIn;
    restartIn.SetDebug( debug );
    //restartIn.processReadArgs( trajArgs );
    int total_frames = restartIn.setupTrajin("", &parm);
    if (total_frames < 1) return 1;
    cInfo = restartIn.CoordInfo();
    TrajFrame.SetupFrameV(parm.Atoms(), cInfo);
    if (restartIn.openTrajin()) return 1;
    if (restartIn.readFrame(0, TrajFrame)) return 1;
    restartIn.closeTraj();
  }
  if (ctr_origin) 
    TrajFrame.CenterOnOrigin(false);
  // Output coords
  Trajout_Single trajout;
  trajArgs.SetList( aatm + bres + pqr + title + ter_opt + box + sybyltype + writeconect, " " );
  if ( trajout.PrepareStdoutTrajWrite(trajArgs, &parm, cInfo, 1, fmt) ) return 1;
  trajout.WriteSingle(0, TrajFrame);
  trajout.EndTraj();
  return 0;
}