Exemple #1
0
const int GetTextureReference(String filename, GLint clampmode, GLint filtermode, bool optional)
{
	bool cached = false;
	TextureCacheEntry* currentCacheEntry = NULL;

	//check cache to see if it's loaded already
	std::map<String,TextureCacheEntry>::iterator it = theTextureCache.find(filename);

	// See if we already have it in the cache.
	if (it != theTextureCache.end())
	{
		//std::cout << "Found cached texture - " << filename.c_str() << std::endl;
		// If we found it and it's not dirty, bail out with the index.
		if (!it->second.dirty)
		{
			return it->second.textureIndex;
		}

		// We found it, but it's dirty.  We'll reload the texture below.
		cached = true;
		currentCacheEntry = &(it->second);
	}

	const char *texFile = filename.c_str();

	// get the image file type from FreeImage
	FREE_IMAGE_FORMAT fifmt = FreeImage_GetFileType(texFile, 0);

	if (fifmt == FIF_UNKNOWN)
	{
		fifmt = FreeImage_GetFIFFromFilename(texFile);
	}

	//actually load the image file
	FIBITMAP *dib = FreeImage_Load(fifmt, texFile, 0);

	if (dib != NULL)
	{
		GLuint texRef = 0;

		// Only generate an index if it's not cached.
		if (cached)
			texRef = currentCacheEntry->textureIndex;
		else
			glGenTextures(1, &texRef);

		glBindTexture(GL_TEXTURE_2D, texRef);

		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, clampmode);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, clampmode);

		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filtermode);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filtermode);

		GLenum format;
		int numComponents;

		if (FreeImage_IsTransparent(dib))
		{
			numComponents = 4;
			//NOTE: FreeImage loads in BGR[A] on little-endian and RGB[A] on big-endian
			//  doesn't matter since we're only using x86/Windows, but this would need to be
			//  ifdeffed if we wanted to support cross-platform stuffs. -- SJML
			format = GL_BGRA_EXT;
		}
		else
		{
			numComponents = 3;
			//NOTE: see above
			format = GL_BGR_EXT;
			dib = FreeImage_ConvertTo24Bits(dib); //want to ensure we don't have an alpha
		}

		BYTE* pixels = (BYTE*)FreeImage_GetBits(dib);

		gluBuild2DMipmaps(
			GL_TEXTURE_2D,
			numComponents,
			FreeImage_GetWidth(dib),
			FreeImage_GetHeight(dib),
			format,
			GL_UNSIGNED_BYTE,
			pixels
			);

		FreeImage_Unload(dib);

		//std::cout << "Loading - " << texFile << std::endl;

		// If it was cached, clear the dirty flag so we don't try and load it again.
		if (cached)
		{
			currentCacheEntry->dirty = false;
		}
		// If we're not cached, add a new entry.
		else 
		{
			TextureCacheEntry newEntry;
			newEntry.filename = filename;
			newEntry.clampMode = clampmode;
			newEntry.filterMode = filtermode;
			newEntry.textureIndex = texRef;
			newEntry.dirty = false;
			theTextureCache[filename] = newEntry;
		}

		return texRef;
	}
	else
	{
		if (!optional)
		{
			std::cout << "Failed to find - " << texFile << std::endl;
		}
		return -1;
	}
}
/*
 * The sim-side LLSD is in newsim/llagentinfo.cpp:forwardViewerStats.
 *
 * There's also a compatibility shim for the old fixed-format sim
 * stats in newsim/llagentinfo.cpp:processViewerStats.
 *
 * If you move stats around here, make the corresponding changes in
 * those locations, too.
 */
void send_stats()
{
	// IW 9/23/02 I elected not to move this into LLViewerStats
	// because it depends on too many viewer.cpp globals.
	// Someday we may want to merge all our stats into a central place
	// but that day is not today.

	// Only send stats if the agent is connected to a region.
	if (!gAgent.getRegion() || gNoRender)
	{
		return;
	}

	LLSD body;
	std::string url = gAgent.getRegion()->getCapability("ViewerStats");

	if (url.empty()) {
		llwarns << "Could not get ViewerStats capability" << llendl;
		return;
	}
	
	body["session_id"] = gAgentSessionID;
	
	LLSD &agent = body["agent"];
	
	time_t ltime;
	time(&ltime);
	F32 run_time = F32(LLFrameTimer::getElapsedSeconds());

	agent["start_time"] = S32(ltime - S32(run_time));

	// The first stat set must have a 0 run time if it doesn't actually
	// contain useful data in terms of FPS, etc.  We use half the
	// SEND_STATS_PERIOD seconds as the point at which these statistics become
	// valid.  Data warehouse uses a 0 value here to easily discard these
	// records with non-useful FPS values etc.
	if (run_time < (SEND_STATS_PERIOD / 2))
	{
		agent["run_time"] = 0.0f;
	}
	else
	{
		agent["run_time"] = run_time;
	}

	// send fps only for time app spends in foreground
	agent["fps"] = (F32)gForegroundFrameCount / gForegroundTime.getElapsedTimeF32();
	agent["version"] = gCurrentVersion;
	std::string language = LLUI::getLanguage();
	agent["language"] = language;
	
	agent["sim_fps"] = ((F32) gFrameCount - gSimFrames) /
		(F32) (gRenderStartTime.getElapsedTimeF32() - gSimLastTime);

	gSimLastTime = gRenderStartTime.getElapsedTimeF32();
	gSimFrames   = (F32) gFrameCount;

	agent["agents_in_view"] = LLVOAvatar::sNumVisibleAvatars;
	agent["ping"] = gAvgSimPing;
	agent["meters_traveled"] = gAgent.getDistanceTraveled();
	agent["regions_visited"] = gAgent.getRegionsVisited();
	agent["mem_use"] = LLMemory::getCurrentRSS() / 1024.0;

	LLSD &system = body["system"];
	
	system["ram"] = (S32) gSysMemory.getPhysicalMemoryKB();
	system["os"] = LLAppViewer::instance()->getOSInfo().getOSStringSimple();
	system["cpu"] = gSysCPU.getCPUString();
	unsigned char MACAddress[MAC_ADDRESS_BYTES];
	LLUUID::getNodeID(MACAddress);
	std::string macAddressString = llformat("%02x-%02x-%02x-%02x-%02x-%02x",
											MACAddress[0],MACAddress[1],MACAddress[2],
											MACAddress[3],MACAddress[4],MACAddress[5]);
	system["mac_address"] = macAddressString;
	system["serial_number"] = LLAppViewer::instance()->getSerialNumber();
	std::string gpu_desc = llformat(
		"%-6s Class %d ",
		gGLManager.mGLVendorShort.substr(0,6).c_str(),
		(S32)LLFeatureManager::getInstance()->getGPUClass())
		+ LLFeatureManager::getInstance()->getGPUString();

	system["gpu"] = gpu_desc;
	system["gpu_class"] = (S32)LLFeatureManager::getInstance()->getGPUClass();
	system["gpu_vendor"] = gGLManager.mGLVendorShort;
	system["gpu_version"] = gGLManager.mDriverVersionVendorString;

	LLSD &download = body["downloads"];

	download["world_kbytes"] = gTotalWorldBytes / 1024.0;
	download["object_kbytes"] = gTotalObjectBytes / 1024.0;
	download["texture_kbytes"] = gTotalTextureBytes / 1024.0;
	download["mesh_kbytes"] = LLMeshRepository::sBytesReceived/1024.0;

	LLSD &in = body["stats"]["net"]["in"];

	in["kbytes"] = gMessageSystem->mTotalBytesIn / 1024.0;
	in["packets"] = (S32) gMessageSystem->mPacketsIn;
	in["compressed_packets"] = (S32) gMessageSystem->mCompressedPacketsIn;
	in["savings"] = (gMessageSystem->mUncompressedBytesIn -
					 gMessageSystem->mCompressedBytesIn) / 1024.0;
	
	LLSD &out = body["stats"]["net"]["out"];
	
	out["kbytes"] = gMessageSystem->mTotalBytesOut / 1024.0;
	out["packets"] = (S32) gMessageSystem->mPacketsOut;
	out["compressed_packets"] = (S32) gMessageSystem->mCompressedPacketsOut;
	out["savings"] = (gMessageSystem->mUncompressedBytesOut -
					  gMessageSystem->mCompressedBytesOut) / 1024.0;

	LLSD &fail = body["stats"]["failures"];

	fail["send_packet"] = (S32) gMessageSystem->mSendPacketFailureCount;
	fail["dropped"] = (S32) gMessageSystem->mDroppedPackets;
	fail["resent"] = (S32) gMessageSystem->mResentPackets;
	fail["failed_resends"] = (S32) gMessageSystem->mFailedResendPackets;
	fail["off_circuit"] = (S32) gMessageSystem->mOffCircuitPackets;
	fail["invalid"] = (S32) gMessageSystem->mInvalidOnCircuitPackets;

	// Misc stats, two strings and two ints
	// These are not expecticed to persist across multiple releases
	// Comment any changes with your name and the expected release revision
	// If the current revision is recent, ping the previous author before overriding
	LLSD &misc = body["stats"]["misc"];

	// Screen size so the UI team can figure out how big the widgets
	// appear and use a "typical" size for end user tests.

	S32 window_width = gViewerWindow->getWindowWidthRaw();
	S32 window_height = gViewerWindow->getWindowHeightRaw();
	S32 window_size = (window_width * window_height) / 1024;
	misc["string_1"] = llformat("%d", window_size);
	if (gDebugTimers.find(0) != gDebugTimers.end() && gFrameTimeSeconds > 0)
	{
		misc["string_2"] = llformat("Texture Time: %.2f, Total Time: %.2f", gDebugTimers[0].getElapsedTimeF32(), gFrameTimeSeconds);
	}

// 	misc["int_1"] = LLSD::Integer(gSavedSettings.getU32("RenderQualityPerformance")); // Steve: 1.21
// 	misc["int_2"] = LLSD::Integer(gFrameStalls); // Steve: 1.21

	F32 unbaked_time = LLVOAvatar::sUnbakedTime * 1000.f / gFrameTimeSeconds;
	misc["int_1"] = LLSD::Integer(unbaked_time); // Steve: 1.22
	F32 grey_time = LLVOAvatar::sGreyTime * 1000.f / gFrameTimeSeconds;
	misc["int_2"] = LLSD::Integer(grey_time); // Steve: 1.22

	llinfos << "Misc Stats: int_1: " << misc["int_1"] << " int_2: " << misc["int_2"] << llendl;
	llinfos << "Misc Stats: string_1: " << misc["string_1"] << " string_2: " << misc["string_2"] << llendl;

	body["DisplayNamesEnabled"] = gSavedSettings.getS32("PhoenixNameSystem") > 0;
	body["DisplayNamesShowUsername"] = gSavedSettings.getS32("PhoenixNameSystem") == 1;
	
	body["MinimalSkin"] = false;
	
	LLViewerStats::getInstance()->addToMessage(body);
	LLHTTPClient::post(url, body, new ViewerStatsResponder());
}
Exemple #3
0
/*
 *  Patches an ASI Import Table for proper path translation
 */
void ThePlugin::ModuleInfo::PatchImports()
{
    // Converts a rva pointer to a actual pointer in the process space from this ASI
    auto rva_to_ptr = [this](long rva)
    { return auto_pointer((void*)((char*)(this->module) + rva)); };
    
    // Used to find translators lowerbound at a sorted list of translators by library name
    auto fn_compare_translator_with_lib_lb = [](path_translator_base* a, const char* b)
    {
        return strcmp(a->GetLibName(), b, false) < 0;
    };

    // Used to find translators upperbound at a sorted list of translators by library name
    auto fn_compare_translator_with_lib_ub = [](const char* a, path_translator_base* b)
    {
        return strcmp(a, b->GetLibName(), false) < 0;
    };

    // Used to find translators lowerbound by symbol name
    auto fn_compare_translator_with_symbol = [](path_translator_base* a, const char* b)
    {
        return strcmp(a->GetSymbol(), b) < 0;
    };
    
    static std::map<uintptr_t, std::string> iat_cache;
    
    // We need a list of pointers to some functions since some linkers (the Borland Linker)
    // doesn't produce a ILT
    if(iat_cache.empty())
    {
        for(auto& x : GetTranslators())
        {
            if(auto module = GetModuleHandleA(x->GetLibName()))
            {
                if(auto sym = GetProcAddress(module, x->GetSymbol()))
                    iat_cache[(uintptr_t)sym] = x->GetSymbol();
            }
        }
    }
    
    // Get list of singletoned translators
    auto& list = GetTranslators();
    
    // Setup pointers to headers in PE module
    IMAGE_THUNK_DATA32 *fname, *faddr;
    IMAGE_DOS_HEADER*  dos      = rva_to_ptr(0);
    IMAGE_NT_HEADERS*  nt       = rva_to_ptr(dos->e_lfanew);
    IMAGE_FILE_HEADER* pe       = &nt->FileHeader;
    IMAGE_OPTIONAL_HEADER* opt  = &nt->OptionalHeader;
    IMAGE_DATA_DIRECTORY* data  = &opt->DataDirectory[0];
    
    // Get address to import table
    if(data[IMAGE_DIRECTORY_ENTRY_IMPORT].Size == 0) return;
    IMAGE_IMPORT_DESCRIPTOR* imp = rva_to_ptr(data[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress);

    // Iterate on each imported library...
    for(auto* lib = imp; lib->Name != 0; ++lib)
    {
        // Get library name...
        const char* libname = rva_to_ptr(lib->Name);
        
        // Check out if we have any translator for this library...
        auto it_lib = std::lower_bound(list.begin(), list.end(), libname, fn_compare_translator_with_lib_lb);
        if((it_lib != list.end() && !strcmp((*it_lib)->GetLibName(), libname, false)) == false)
        {
            // ...we don't, get 'almost any library' lower bound
            it_lib = std::lower_bound(list.begin(), list.end(), "", fn_compare_translator_with_lib_lb);
        }
        
        // If we have a lower bound to start searching symbols from, get into symbols searching!
        if(it_lib != list.end())
        {
            // Find upper bound for this library
            auto it_lib_end = std::upper_bound(it_lib, list.end(),  (*it_lib)->GetLibName(), fn_compare_translator_with_lib_ub);

            // Get pointer to thunks aka function names and function address tables
            bool bHasILT = lib->OriginalFirstThunk != 0;
            fname = rva_to_ptr(lib->OriginalFirstThunk);
            faddr = rva_to_ptr(lib->FirstThunk);

            // Iterate on each name to see if we should patch it
            for(; faddr->u1.Function; ++fname, ++faddr)
            {
                const char* symbolName;
                
                if(bHasILT)
                {
                    // Is this just a ordinal import? Skip it, we don't have a symbol name!
                    if(fname->u1.Ordinal & IMAGE_ORDINAL_FLAG) continue;

                    // Get the symbol name
                    symbolName = (char*)(((IMAGE_IMPORT_BY_NAME*)(rva_to_ptr(fname->u1.AddressOfData)))->Name);
                }
                else
                {
                    auto sym = iat_cache.find(faddr->u1.Function);
                    if(sym == iat_cache.end()) continue;
                    symbolName = sym->second.c_str();
                }
                
                // Find arg translator from symbol...
                auto it_sym = std::lower_bound(it_lib, it_lib_end, symbolName, fn_compare_translator_with_symbol);
                if(it_sym != list.end() && !strcmp((*it_sym)->GetSymbol(), symbolName))
                {
                    // Add this translator and patch this import pointer into our translator...
                    (*this->translators.emplace(translators.end(), (*it_sym)->clone()))->Patch(&faddr->u1.Function);
                }
            }
        }
    }
}
Exemple #4
0
    void TerrainManager::initTerrainTextures(Terrain::ImportData* terrainData,
                                             int cellX, int cellY,
                                             int fromX, int fromY, int size,
                                             std::map<uint16_t, int>& indexes, size_t plugin)
    {
        // FIXME: In a multiple esm configuration, we have multiple palettes. Since this code
        //  crosses cell boundaries, we no longer have a unique terrain palette. Instead, we need
        //  to adopt the following code for a dynamic palette. And this is evil - the current design
        //  does not work well for this task...

        assert(terrainData != NULL && "Must have valid terrain data");
        assert(fromX >= 0 && fromY >= 0 &&
               "Can't get a terrain texture on terrain outside the current cell");
        assert(fromX+size <= ESM::Land::LAND_TEXTURE_SIZE &&
               fromY+size <= ESM::Land::LAND_TEXTURE_SIZE &&
               "Can't get a terrain texture on terrain outside the current cell");

        //this ensures that the ltex indexes are sorted (or retrived as sorted
        //which simplifies shading between cells).
        //
        //If we don't sort the ltex indexes, the splatting order may differ between
        //cells which may lead to inconsistent results when shading between cells
        int num = MWBase::Environment::get().getWorld()->getStore().get<ESM::LandTexture>().getSize(plugin);
        std::set<uint16_t> ltexIndexes;
        for ( int y = fromY - 1; y < fromY + size + 1; y++ )
        {
            for ( int x = fromX - 1; x < fromX + size + 1; x++ )
            {
                int idx = getLtexIndexAt(cellX, cellY, x, y);
                // This is a quick hack to prevent the program from trying to fetch textures
                //  from a neighboring cell, which might originate from a different plugin,
                //  and use a separate texture palette. Right now, we simply cast it to the
                //  default texture (i.e. 0).
                if (idx > num)
                  idx = 0;
                ltexIndexes.insert(idx);
            }
        }

        //there is one texture that we want to use as a base (i.e. it won't have
        //a blend map). This holds the ltex index of that base texture so that
        //we know not to include it in the output map
        int baseTexture = -1;
        for ( std::set<uint16_t>::iterator iter = ltexIndexes.begin();
              iter != ltexIndexes.end();
              ++iter )
        {
            uint16_t ltexIndex = *iter;
            //this is the base texture, so we can ignore this at present
            if ( ltexIndex == baseTexture )
            {
                continue;
            }

            const std::map<uint16_t, int>::const_iterator it = indexes.find(ltexIndex);

            if ( it == indexes.end() )
            {
                //NB: All vtex ids are +1 compared to the ltex ids

                const MWWorld::Store<ESM::LandTexture> &ltexStore =
                    MWBase::Environment::get().getWorld()->getStore().get<ESM::LandTexture>();

                // NOTE: using the quick hack above, we should no longer end up with textures indices
                //  that are out of bounds. However, I haven't updated the test to a multi-palette
                //  system yet. We probably need more work here, so we skip it for now.
                //assert( (int)ltexStore.getSize() >= (int)ltexIndex - 1 &&
                       //"LAND.VTEX must be within the bounds of the LTEX array");

                std::string texture;
                if ( ltexIndex == 0 )
                {
                    texture = "_land_default.dds";
                }
                else
                {
                    texture = ltexStore.search(ltexIndex-1, plugin)->mTexture;
                    //TODO this is needed due to MWs messed up texture handling
                    texture = texture.substr(0, texture.rfind(".")) + ".dds";
                }

                const size_t position = terrainData->layerList.size();
                terrainData->layerList.push_back(Terrain::LayerInstance());

                terrainData->layerList[position].worldSize = 256;
                terrainData->layerList[position].textureNames.push_back("textures\\" + texture);

                if ( baseTexture == -1 )
                {
                    baseTexture = ltexIndex;
                }
                else
                {
                    indexes[ltexIndex] = position;
                }
            }
        }
    }
Exemple #5
0
void Lexer::pull()
{
    _white = "";
    _text = "";

    char c;

    // skipping whitespace
    while (true)
    {
        _in.get(c);

        if (!_in)
        {
            _type = TOK_EOF;
            return;
        }
        if (whitespace.count(c))
        {
            _white += c;
            continue;
        }

        if (c != '\\')
            break;

        _white += c;
        _in.get(c);
        if (!_in || !whitespace.count(c))
            die("toplevel backslash not followed by whitespace");
        _white += c;
    }

    _text += c;
    auto it = operators.find(_text);
    if (it != operators.end())
    {
        while (true)
        {
            if (_in.get(c) && it->second.count(c))
            {
                _text += c;
                it = operators.find(_text);
                assert (it != operators.end());
                continue;
            }
            else
            {
                _in.unget();
                break;
            }
        }
        if (_text == "##" && !_macro_body)
        {
            die("'##' is only valid in a macro body");
        }
        if (_text == "#" && !_macro_body)
        {
            while ((_in.get(c)) && (c != '\n'))
            {
                if (c == '\\')
                {
                    _in.get(c);
                    if (!_in || !whitespace.count(c))
                        die("macro-level backslash not followed by whitespace");
                }
                _text += c;
            }
            // whatever?
            _in.unget();
            _type = TOK_PP;
            return;
        }
        if (_text == "//")
        {
            while ((_in.get(c)) && (c != '\n'))
            {
                if (c == '\\')
                {
                    _in.get(c);
                    if (!_in || !whitespace.count(c))
                        die("comment-level backslash not followed by whitespace");
                }
                _text += c;
            }
            // whatever!
            _in.unget();
            _type = TOK_SLC;
            return;
        }
        if (_text == "/*")
        {
            bool prev_star = false;
            while (true)
            {
                _in.get(c);
                if (!_in)
                    die("unclosed block comment");
                _text += c;
                prev_star = c == '*';
                if (prev_star && c == '/')
                    break;
            }
            _type = TOK_MLC;
            return;
        }
        _type = TOK_OP;
        return;
    }
    // not an operator or comment
    if (c == '"' || c == '\'')
    {
        char match = c;
        while (true)
        {
            _in.get(c);
            if (!_in)
                die("unclosed string/char literal");
            _text += c;
            if (c == match)
                break;
            if (c == '\\')
            {
                _in.get(c);
                if (!_in)
                    die("EOF after backslash in string/char literal");
                // we don't care if it's valid or not, just add it
                _text += c;
            }
        }
        _type = TOK_LIT;
        return;
    }
    if (digits.count(c))
    {
        std::set<char> *digs = &digits;
        if (c == '0')
        {
            if ((_in.get(c)) && (c == 'x' || c == 'X'))
            {
                digs = &higits;
                _text += c;
            }
            else
                _in.unget();
        }
        while ((_in.get(c)) && digs->count(c))
        {
            _text += c;
        }
        _in.unget();
        _type = TOK_LIT;
        return;
    }
    if (word_first.count(c))
    {
        while ((_in.get(c)) && word_rest.count(c))
            _text += c;
        _in.unget();
        _type = flavor(_text);
        return;
    }
    die("Unknown character");
}
Exemple #6
0
void halo_impl::unrender(std::set<map_location> invalidated_locations)
{
	if(preferences::show_haloes() == false || haloes.empty()) {
		return;
	}
	//assert(invalidated_haloes.empty());

	// Remove expired haloes
	std::map<int, effect>::iterator itor = haloes.begin();
	for(; itor != haloes.end(); ++itor ) {
		if(itor->second.expired()) {
			deleted_haloes.insert(itor->first);
		}
	}

	// Add the haloes marked for deletion to the invalidation set
	std::set<int>::const_iterator set_itor = deleted_haloes.begin();
	for(;set_itor != deleted_haloes.end(); ++set_itor) {
		invalidated_haloes.insert(*set_itor);
		haloes.find(*set_itor)->second.add_overlay_location(invalidated_locations);
	}

	// Test the multi-frame haloes whether they need an update
	for(set_itor = changing_haloes.begin();
			set_itor != changing_haloes.end(); ++set_itor) {
		if(haloes.find(*set_itor)->second.need_update()) {
			invalidated_haloes.insert(*set_itor);
			haloes.find(*set_itor)->second.add_overlay_location(invalidated_locations);
		}
	}

	// Find all halo's in a the invalidated area
	size_t halo_count;

	// Repeat until set of haloes in the invalidated area didn't change
	// (including none found) or all existing haloes are found.
	do {
		halo_count = invalidated_haloes.size();
		for(itor = haloes.begin(); itor != haloes.end(); ++itor) {
			// Test all haloes not yet in the set
			// which match one of the locations
			if(invalidated_haloes.find(itor->first) == invalidated_haloes.end() &&
					itor->second.on_location(invalidated_locations)) {

				// If found, add all locations which the halo invalidates,
				// and add it to the set
				itor->second.add_overlay_location(invalidated_locations);
				invalidated_haloes.insert(itor->first);
			}
		}
	} while (halo_count != invalidated_haloes.size() && halo_count != haloes.size());

	if(halo_count == 0) {
		return;
	}

	// Render the haloes:
	// iterate through all the haloes and invalidate if in set
	for(std::map<int, effect>::reverse_iterator ritor = haloes.rbegin(); ritor != haloes.rend(); ++ritor) {
		if(invalidated_haloes.find(ritor->first) != invalidated_haloes.end()) {
			ritor->second.unrender();
		}
	}

	// Really delete the haloes marked for deletion
	for(set_itor = deleted_haloes.begin(); set_itor != deleted_haloes.end(); ++set_itor) {
		// It can happen a deleted halo hasn't been rendered yet, invalidate them as well
		new_haloes.erase(*set_itor);

		changing_haloes.erase(*set_itor);
		invalidated_haloes.erase(*set_itor);
		haloes.erase(*set_itor);
	}

	deleted_haloes.clear();
}
Exemple #7
0
		ValidationItem::ValidationItem(String& configfile_section, std::map<String, DataItem*>& filenames_map, std::list<std::pair<double,double> >* item_positions, DataItemView* view)
			: DataItem(view)
		{
			result_color_ = QColor(205,225,205);
			type_ = -1;
			std::istringstream input;
			input.str(configfile_section);
			ValidationConfiguration conf = ConfigIO::readValidationConfiguration(&input);

			int no = conf.external_predictions.size();
			for(int i=0; i<no; i++)
			{
				String file_i = conf.external_predictions[i];
				std::map<String,DataItem*>::iterator it = filenames_map.find(file_i);
				if(it==filenames_map.end())
				{
					std::cout<<file_i<<" can not be found!!"<<std::endl;
					throw BALL::Exception::GeneralException(__FILE__,__LINE__,"ValidationItem reading error","PredictionItem of a nested cross validation fold could not be found!");
				}
				PredictionItem* pred_i = (PredictionItem*) it->second;
				addExternalFoldValidation(pred_i);
				
				if(i==0) // all folds of ONE validationItem for nested validation come from 
					// ONE PartitioningItem
				{
					Edge* edge = pred_i->dottedEdge();
					if(edge!=NULL)
					{
						if(edge->sourceNode()->inEdges().size()>0)
						{						
							DataItem* tmp = (*edge->sourceNode()->inEdges().begin())->sourceNode();
							if(tmp->type()==PartitioningItem::Type)
							{
								setPartitioner((PartitioningItem*)tmp);
							}
						}
					}
				}
			}
			
			
			// conf.data is not used since the inputItem connected to the modelItem is used for obtaining input data
			
			k_ = conf.k_folds;
			num_of_samples_ = conf.bootstrap_samples;
			num_of_runs_ = conf.no_of_permutation_tests;
			validation_statistic_ = conf.statistic;
			type_ = conf.val_type;
			
			std::map<String,DataItem*>::iterator it = filenames_map.find(conf.model);
			if(it==filenames_map.end())
			{
				throw BALL::Exception::GeneralException(__FILE__,__LINE__,"ValidationItem reading error","ModelItem for which the validation should be done can not be found!");
			}
			model_item_ = (ModelItem*) it->second;
			
			view_->data_scene->addItem(this);
			addToPipeline();
			if(item_positions!=0 && item_positions->size()>0)
			{
				std::pair<double,double> pos = item_positions->front();
				item_positions->pop_front();
				setPos(pos.first,pos.second);
			}
			
			Edge* edge = new Edge(model_item_, this);
			view_->data_scene->addItem(edge);

			setSavedAs(conf.output.c_str());
			
			/// if not defined in config-section explicitly, find type of validation to be done:
			if(type_==-1)
			{
				if(k_<2 && conf.external_predictions.size()>0) type_ = 5;
				else
				{
					if(k_<=0) type_ = 1;
					else if(num_of_samples_<=0) type_ = 2;
					else type_ = 3;
					if(num_of_runs_>0) type_ = 4;
				}
			}
			init();	
		}
/******************************************************************************
* Determines the the display particle colors.
******************************************************************************/
void ParticleDisplay::particleColors(std::vector<Color>& output, ParticlePropertyObject* colorProperty, ParticleTypeProperty* typeProperty, ParticlePropertyObject* selectionProperty)
{
	OVITO_ASSERT(colorProperty == nullptr || colorProperty->type() == ParticleProperty::ColorProperty);
	OVITO_ASSERT(typeProperty == nullptr || typeProperty->type() == ParticleProperty::ParticleTypeProperty);
	OVITO_ASSERT(selectionProperty == nullptr || selectionProperty->type() == ParticleProperty::SelectionProperty);

	Color defaultColor = defaultParticleColor();
	if(colorProperty) {
		// Take particle colors directly from the color property.
		OVITO_ASSERT(colorProperty->size() == output.size());
		std::copy(colorProperty->constDataColor(), colorProperty->constDataColor() + output.size(), output.begin());
	}
	else if(typeProperty) {
		// Assign colors based on particle types.
		OVITO_ASSERT(typeProperty->size() == output.size());
		// Generate a lookup map for particle type colors.
		const std::map<int,Color> colorMap = typeProperty->colorMap();
		std::array<Color,16> colorArray;
		// Check if all type IDs are within a small, non-negative range.
		// If yes, we can use an array lookup strategy. Otherwise we have to use a dictionary lookup strategy, which is slower.
		if(std::all_of(colorMap.begin(), colorMap.end(),
				[&colorArray](const std::map<int,Color>::value_type& i) { return i.first >= 0 && i.first < (int)colorArray.size(); })) {
			colorArray.fill(defaultColor);
			for(const auto& entry : colorMap)
				colorArray[entry.first] = entry.second;
			// Fill color array.
			const int* t = typeProperty->constDataInt();
			for(auto c = output.begin(); c != output.end(); ++c, ++t) {
				if(*t >= 0 && *t < (int)colorArray.size())
					*c = colorArray[*t];
				else
					*c = defaultColor;
			}
		}
		else {
			// Fill color array.
			const int* t = typeProperty->constDataInt();
			for(auto c = output.begin(); c != output.end(); ++c, ++t) {
				auto it = colorMap.find(*t);
				if(it != colorMap.end())
					*c = it->second;
				else
					*c = defaultColor;
			}
		}
	}
	else {
		// Assign a constant color to all particles.
		std::fill(output.begin(), output.end(), defaultColor);
	}

	// Highlight selected particles.
	if(selectionProperty) {
		OVITO_ASSERT(selectionProperty->size() == output.size());
		const Color selColor = selectionParticleColor();
		const int* t = selectionProperty->constDataInt();
		for(auto c = output.begin(); c != output.end(); ++c, ++t) {
			if(*t)
				*c = selColor;
		}
	}
}
/******************************************************************************
* Lets the display object render the data object.
******************************************************************************/
void ParticleDisplay::render(TimePoint time, DataObject* dataObject, const PipelineFlowState& flowState, SceneRenderer* renderer, ObjectNode* contextNode)
{
	// Get input data.
	ParticlePropertyObject* positionProperty = dynamic_object_cast<ParticlePropertyObject>(dataObject);
	ParticlePropertyObject* radiusProperty = ParticlePropertyObject::findInState(flowState, ParticleProperty::RadiusProperty);
	ParticlePropertyObject* colorProperty = ParticlePropertyObject::findInState(flowState, ParticleProperty::ColorProperty);
	ParticleTypeProperty* typeProperty = dynamic_object_cast<ParticleTypeProperty>(ParticlePropertyObject::findInState(flowState, ParticleProperty::ParticleTypeProperty));
	ParticlePropertyObject* selectionProperty = renderer->isInteractive() ? ParticlePropertyObject::findInState(flowState, ParticleProperty::SelectionProperty) : nullptr;
	ParticlePropertyObject* transparencyProperty = ParticlePropertyObject::findInState(flowState, ParticleProperty::TransparencyProperty);
	ParticlePropertyObject* shapeProperty = ParticlePropertyObject::findInState(flowState, ParticleProperty::AsphericalShapeProperty);
	if(shadingMode() != ParticlePrimitive::NormalShading)
		shapeProperty = nullptr;

	// Get number of particles.
	int particleCount = positionProperty ? (int)positionProperty->size() : 0;

	// Do we have to re-create the geometry buffer from scratch?
	bool recreateBuffer = !_particleBuffer || !_particleBuffer->isValid(renderer);

	// If rendering quality is set to automatic, pick quality level based on number of particles.
	ParticlePrimitive::RenderingQuality renderQuality = effectiveRenderingQuality(renderer, positionProperty);

	// Determine effective particle shape.
	ParticlePrimitive::ParticleShape effectiveParticleShape = particleShape();
	if(effectiveParticleShape == ParticlePrimitive::SquareShape && shapeProperty != nullptr)
		effectiveParticleShape = ParticlePrimitive::BoxShape;
	else
		shapeProperty = nullptr;

	// Set shading mode and rendering quality.
	if(!recreateBuffer) {
		recreateBuffer |= !(_particleBuffer->setShadingMode(shadingMode()));
		recreateBuffer |= !(_particleBuffer->setRenderingQuality(renderQuality));
		recreateBuffer |= !(_particleBuffer->setParticleShape(effectiveParticleShape));
		recreateBuffer |= ((transparencyProperty != nullptr) != _particleBuffer->translucentParticles());
	}

	// Do we have to resize the render buffer?
	bool resizeBuffer = recreateBuffer || (_particleBuffer->particleCount() != particleCount);

	// Do we have to update the particle positions in the render buffer?
	bool updatePositions = _positionsCacheHelper.updateState(positionProperty)
			|| resizeBuffer;

	// Do we have to update the particle radii in the geometry buffer?
	bool updateRadii = _radiiCacheHelper.updateState(
			radiusProperty,
			typeProperty,
			defaultParticleRadius())
			|| resizeBuffer;

	// Do we have to update the particle colors in the geometry buffer?
	bool updateColors = _colorsCacheHelper.updateState(
			colorProperty,
			typeProperty,
			selectionProperty,
			transparencyProperty,
			positionProperty)
			|| resizeBuffer;

	// Do we have to update the particle shapes in the geometry buffer?
	bool updateShapes = _shapesCacheHelper.updateState(
			shapeProperty) || resizeBuffer;

	// Re-create the geometry buffer if necessary.
	if(recreateBuffer)
		_particleBuffer = renderer->createParticlePrimitive(shadingMode(), renderQuality, effectiveParticleShape, transparencyProperty != nullptr);

	// Re-size the geometry buffer if necessary.
	if(resizeBuffer)
		_particleBuffer->setSize(particleCount);

	// Update position buffer.
	if(updatePositions && positionProperty) {
		OVITO_ASSERT(positionProperty->size() == particleCount);
		_particleBuffer->setParticlePositions(positionProperty->constDataPoint3());
	}

	// Update radius buffer.
	if(updateRadii && particleCount) {
		if(radiusProperty) {
			// Take particle radii directly from the radius property.
			OVITO_ASSERT(radiusProperty->size() == particleCount);
			_particleBuffer->setParticleRadii(radiusProperty->constDataFloat());
		}
		else if(typeProperty) {
			// Assign radii based on particle types.
			OVITO_ASSERT(typeProperty->size() == particleCount);
			// Build a lookup map for particle type raii.
			const std::map<int,FloatType> radiusMap = typeProperty->radiusMap();
			// Skip the following loop if all per-type radii are zero. In this case, simply use the default radius for all particles.
			if(std::any_of(radiusMap.cbegin(), radiusMap.cend(), [](const std::pair<int,FloatType>& it) { return it.second != 0; })) {
				// Allocate memory buffer.
				std::vector<FloatType> particleRadii(particleCount, defaultParticleRadius());
				// Fill radius array.
				const int* t = typeProperty->constDataInt();
				for(auto c = particleRadii.begin(); c != particleRadii.end(); ++c, ++t) {
					auto it = radiusMap.find(*t);
					// Set particle radius only if the type's radius is non-zero.
					if(it != radiusMap.end() && it->second != 0)
						*c = it->second;
				}
				_particleBuffer->setParticleRadii(particleRadii.data());
			}
			else {
				// Assign a constant radius to all particles.
				_particleBuffer->setParticleRadius(defaultParticleRadius());
			}
		}
		else {
			// Assign a constant radius to all particles.
			_particleBuffer->setParticleRadius(defaultParticleRadius());
		}
	}

	// Update color buffer.
	if(updateColors && particleCount) {
		if(colorProperty && !selectionProperty && !transparencyProperty) {
			// Direct particle colors.
			OVITO_ASSERT(colorProperty->size() == particleCount);
			_particleBuffer->setParticleColors(colorProperty->constDataColor());
		}
		else {
			std::vector<Color> colors(particleCount);
			particleColors(colors, colorProperty, typeProperty, selectionProperty);
			if(!transparencyProperty) {
				_particleBuffer->setParticleColors(colors.data());
			}
			else {
				// Add alpha channel based on transparency particle property.
				std::vector<ColorA> colorsWithAlpha(particleCount);
				const FloatType* t = transparencyProperty->constDataFloat();
				auto c_in = colors.cbegin();
				for(auto c_out = colorsWithAlpha.begin(); c_out != colorsWithAlpha.end(); ++c_out, ++c_in, ++t) {
					c_out->r() = c_in->r();
					c_out->g() = c_in->g();
					c_out->b() = c_in->b();
					c_out->a() = FloatType(1) - (*t);
				}
				_particleBuffer->setParticleColors(colorsWithAlpha.data());
			}
		}
	}

	// Update shapes buffer.
	if(updateShapes && particleCount) {
		if(shapeProperty) {
			OVITO_ASSERT(shapeProperty->size() == particleCount);
			_particleBuffer->setParticleShapes(shapeProperty->constDataVector3());
		}
	}

	if(renderer->isPicking()) {
		OORef<ParticlePickInfo> pickInfo(new ParticlePickInfo(flowState));
		renderer->beginPickObject(contextNode, pickInfo);
	}

	_particleBuffer->render(renderer);

	if(renderer->isPicking()) {
		renderer->endPickObject();
	}
}
shared_ptr<mw::Component> mDriftingGratingStimulusFactory::createObject(std::map<std::string, std::string> parameters,
																	 mwComponentRegistry *reg) {
	
	const char *TAG = "tag";
	const char *FRAMES_PER_SECOND = "frames_per_second";
	const char *STATISTICS_REPORTING = "statistics_reporting";
	const char *ERROR_REPORTING = "error_reporting";	
	const char *X_SIZE = "x_size";
	const char *Y_SIZE = "y_size";
	const char *X_POSITION = "x_position";
	const char *Y_POSITION = "y_position";
	const char *ROTATION = "rotation";
	const char *DIRECTION = "direction";
	const char *STARTING_PHASE = "starting_phase";
	const char *FREQUENCY = "spatial_frequency";
	const char *SPEED = "speed";
	const char *GRATING_TYPE = "grating_type";
	const char *ALPHA_MULTIPLIER = "alpha_multiplier";
	const char *MASK = "mask";
	const char *GRATING_SAMPLE_RATE = "grating_sample_rate";
	
	REQUIRE_ATTRIBUTES(parameters, 
					   TAG,
					   FRAMES_PER_SECOND,
					   STATISTICS_REPORTING,
					   ERROR_REPORTING,
					   X_SIZE,
					   Y_SIZE,
					   X_POSITION,
					   Y_POSITION,
					   ROTATION,
					   DIRECTION,
					   FREQUENCY,
					   SPEED,
					   GRATING_TYPE,
					   MASK);
	
	std::string tagname(parameters.find(TAG)->second);
	shared_ptr<Variable> frames_per_second = reg->getVariable(parameters.find(FRAMES_PER_SECOND)->second);	
	shared_ptr<Variable> statistics_reporting = reg->getVariable(parameters.find(STATISTICS_REPORTING)->second);	
	shared_ptr<Variable> error_reporting = reg->getVariable(parameters.find(ERROR_REPORTING)->second);	
	shared_ptr<Variable> x_size = reg->getVariable(parameters.find(X_SIZE)->second);	
	shared_ptr<Variable> y_size = reg->getVariable(parameters.find(Y_SIZE)->second);	
	shared_ptr<Variable> x_position = reg->getVariable(parameters.find(X_POSITION)->second);	
	shared_ptr<Variable> y_position = reg->getVariable(parameters.find(Y_POSITION)->second);	
	shared_ptr<Variable> rotation = reg->getVariable(parameters.find(ROTATION)->second);	
	shared_ptr<Variable> alpha_multiplier = reg->getVariable(parameters[ALPHA_MULTIPLIER], "1");
	shared_ptr<Variable> direction_in_degrees = reg->getVariable(parameters.find(DIRECTION)->second);	
	shared_ptr<Variable> spatial_frequency = reg->getVariable(parameters.find(FREQUENCY)->second);	
	shared_ptr<Variable> speed = reg->getVariable(parameters.find(SPEED)->second);	
	shared_ptr<Variable> starting_phase = reg->getVariable(parameters[STARTING_PHASE], "0");	
	shared_ptr<Variable> grating_sample_rate = reg->getVariable(parameters[GRATING_SAMPLE_RATE], "32");	
	
	
	checkAttribute(frames_per_second, 
				   parameters.find("reference_id")->second, 
				   FRAMES_PER_SECOND, 
				   parameters[FRAMES_PER_SECOND]);
	checkAttribute(statistics_reporting, 
				   parameters.find("reference_id")->second, 
				   STATISTICS_REPORTING, 
				   parameters.find(STATISTICS_REPORTING)->second);
	checkAttribute(error_reporting, 
				   parameters.find("reference_id")->second, 
				   ERROR_REPORTING, 
				   parameters.find(ERROR_REPORTING)->second);
	checkAttribute(x_size, 
				   parameters.find("reference_id")->second,	
				   X_SIZE,	
				   parameters.find(X_SIZE)->second);                                                    
	checkAttribute(y_size, 
				   parameters.find("reference_id")->second,
				   Y_SIZE, 
				   parameters.find(Y_SIZE)->second);                                                    
	checkAttribute(x_position, 
				   parameters.find("reference_id")->second, 
				   X_POSITION, 
				   parameters.find(X_POSITION)->second);                                        
	checkAttribute(y_position, 
				   parameters.find("reference_id")->second,
				   Y_POSITION,
				   parameters.find(Y_POSITION)->second);                                        
	checkAttribute(rotation,
				   parameters.find("reference_id")->second, 
				   ROTATION, 
				   parameters.find(ROTATION)->second);                                              
	checkAttribute(alpha_multiplier,
				   parameters.find("reference_id")->second,
				   ALPHA_MULTIPLIER, 
				   parameters.find(ALPHA_MULTIPLIER)->second);                      
	checkAttribute(direction_in_degrees, 
				   parameters.find("reference_id")->second, 
				   DIRECTION, 
				   parameters.find(DIRECTION)->second);                                           
	checkAttribute(spatial_frequency,
				   parameters.find("reference_id")->second, 
				   FREQUENCY, 
				   parameters.find(FREQUENCY)->second);                                           
	checkAttribute(speed, 
				   parameters.find("reference_id")->second,
				   SPEED, 
				   parameters.find(SPEED)->second);                                                       
	checkAttribute(starting_phase,
				   parameters.find("reference_id")->second, 
				   STARTING_PHASE, 
				   parameters.find(STARTING_PHASE)->second);                            
	checkAttribute(grating_sample_rate,
				   parameters.find("reference_id")->second,
				   GRATING_SAMPLE_RATE, 
				   parameters.find(GRATING_SAMPLE_RATE)->second);                            
	
	
	
	shared_ptr <mGratingData> grating;
	if(parameters.find(GRATING_TYPE)->second == "sinusoid") {
		grating = shared_ptr<mSinusoidGratingData>(new mSinusoidGratingData(grating_sample_rate));
	} else if(parameters.find(GRATING_TYPE)->second == "square") {
		grating = shared_ptr<mSquareGratingData>(new mSquareGratingData(grating_sample_rate));
	} else if(parameters.find(GRATING_TYPE)->second == "triangle") {
		grating = shared_ptr<mTriangleGratingData>(new mTriangleGratingData(grating_sample_rate));
	} else if(parameters.find(GRATING_TYPE)->second == "sawtooth") {
		const char *INVERTED = "inverted";
		
		shared_ptr <Variable> inverted = reg->getVariable(parameters[INVERTED], "0");	
		checkAttribute(inverted,
					   parameters.find("reference_id")->second, 
					   INVERTED, 
					   parameters.find(INVERTED)->second);                                              
		grating = shared_ptr<mSawtoothGratingData>(new mSawtoothGratingData(grating_sample_rate,
																			inverted));
	} else {
		throw SimpleException("illegal grating type: " + parameters.find(GRATING_TYPE)->second);		
	}
	
	if(GlobalCurrentExperiment == 0) {
		throw SimpleException("no experiment currently defined");		
	}
	
	shared_ptr<StimulusDisplay> default_display = GlobalCurrentExperiment->getStimulusDisplay();
	if(default_display == 0) {
		throw SimpleException("no stimulusDisplay in current experiment");
	}
	
	shared_ptr <Scheduler> scheduler = Scheduler::instance();
	if(scheduler == 0) {
		throw SimpleException("no scheduler registered");		
	}
	
	shared_ptr <mMask> mask;
	shared_ptr <Variable> mask_size = shared_ptr<Variable>(new ConstantVariable(128L));
	if(parameters.find(MASK)->second == "rectangle") {
		mask = shared_ptr<mMask>(new mRectangleMask(mask_size));
	} else if(parameters.find(MASK)->second == "ellipse") {
		mask = shared_ptr<mMask>(new mEllipseMask(mask_size));
	} else if(parameters.find(MASK)->second == "gaussian") {
		const char *STD_DEV = "std_dev";
		const char *MEAN = "mean";
		
		//		REQUIRE_ATTRIBUTES(parameters, 
		//						   STD_DEV,
		//						   MEAN);
		
		shared_ptr <Variable> std_dev = reg->getVariable(parameters[STD_DEV], "1");	
		shared_ptr <Variable> mean = reg->getVariable(parameters[MEAN], "0");	
		checkAttribute(std_dev,
					   parameters.find("reference_id")->second, 
					   STD_DEV, 
					   parameters.find(STD_DEV)->second);                                              
		checkAttribute(mean,
					   parameters.find("reference_id")->second, 
					   MEAN, 
					   parameters.find(MEAN)->second);                                              
		
		mask = shared_ptr<mMask>(new mGaussianMask(mask_size,
													 mean,
													 std_dev));
	} else {
		throw SimpleException("illegal mask: " + parameters.find(MASK)->second);				
	}
	
	shared_ptr<mDriftingGratingStimulus> new_drifting_grating=shared_ptr<mDriftingGratingStimulus>(new mDriftingGratingStimulus(tagname, 
																																scheduler,
																																default_display,
																																frames_per_second,
																																statistics_reporting,
																																error_reporting,
																																x_position,
																																y_position,
																																x_size,
																																y_size,
																																rotation,
																																alpha_multiplier,
																																direction_in_degrees,
																																spatial_frequency,
																																speed,
																																starting_phase,
																																mask,
																																grating));
	
	
	new_drifting_grating->load(default_display.get());
	shared_ptr <StimulusNode> thisStimNode = shared_ptr<StimulusNode>(new StimulusNode(new_drifting_grating));
	reg->registerStimulusNode(tagname, thisStimNode);
	
	return new_drifting_grating;
}
inline size_t SharedVariablesDataRep::vc_lookup(unsigned short key) const
{
  std::map<unsigned short, size_t>::const_iterator cit
    = variablesComponents.find(key);
  return (cit == variablesComponents.end()) ? 0 : cit->second;
}
Exemple #12
0
bool RunScript(const std::vector<char>& data, std::vector<char>& result)
{
	result.clear();
	std::string text(data.begin(), data.end());

	std::cout << "Run script:" << std::endl << text << std::endl;

	std::vector<std::string> lines = string_split(text, '\n');
	if ( ! lines.empty())
	{
		std::string cmd = lines[0];
		std::map<std::string, std::string> params;
		for (size_t i = 1; i < lines.size(); ++i)
		{
			size_t pos = lines[i].find_first_of(':');
			if (pos != std::string::npos)
			{
				std::string name = lines[i].substr(0, pos);
				std::string value = lines[i].substr(pos + 1);
				if ( ! name.empty())
				{
					params[name] = value;
				}
				std::cout << "  param: " << name << " => " << value << std::endl;
			}
		}

		if (rules.find(cmd) == rules.end())
		{
			std::cerr << "Unknown command: '" << cmd << "'" << std::endl;
		}
		else
		{
			std::string command = rules[cmd];
			for (std::map<std::string, std::string>::iterator it = params.begin(); it != params.end(); ++it)
			{
				std::cout << " Replace " << it->first << " => " << it->second << std::endl;

				command = string_replace(command, "$(" + it->first + ")", it->second);
			}
			command = string_replace(command, "{", "\\{");
			command = string_replace(command, "}", "\\}");
			command = string_replace(command, "\"", "\\\"");
			command = string_replace(command, "$", "\\$");
			std::cout << "Call: " << rules[cmd] << std::endl;
			std::cout << "Run: " << command << std::endl;

			FILE* fp = popen(command.c_str(), "r");
			if ( ! fp)
			{
				std::cerr << "Run script failed!" << std::endl;
				std::string text = CreateJSON(1, "Can not run script!");
				result.insert(result.begin(), text.begin(), text.end());
			}
			else
			{
				std::string text = "";
				while ( ! feof(fp))
				{
					char buffer[1024];
					while (fgets(buffer, sizeof(buffer), fp))
					{
						text += buffer;
					}
				}
				fclose(fp);
				result.insert(result.end(), text.begin(), text.end());
			}
		}
	}
	return true;
}
Exemple #13
0
 inline bool Pass::val(const Var v) const {
   std::map<Var,bool>::const_iterator p = pa.find(v);
   if (p == pa.end())
     throw Error::not_in_domain();
   return p -> second;
 }
Exemple #14
0
 inline bool Pass::in_domain(const Var v) const {
   return pa.find(v) != pa.end();
 }
Exemple #15
0
 object &get(object::id_t id) {
     if(m_objects.count(id) == 0)
         throw std::runtime_error("Object does not exist in store");
     return m_objects.find(id)->second;
 }
Exemple #16
0
void GNMGraph::DijkstraShortestPathTree(GNMGFID nFID,
                                   const std::map<GNMGFID, GNMStdEdge> &mstEdges,
                                         std::map<GNMGFID, GNMGFID> &mnPathTree)
{
    // Initialize all vertexes in graph with infinity mark.
    double dfInfinity = std::numeric_limits<double>::infinity();

    std::map<GNMGFID, double> mMarks;
    std::map<GNMGFID, GNMStdVertex>::iterator itv;
    for (itv = m_mstVertices.begin(); itv != m_mstVertices.end(); ++itv)
    {
        mMarks[itv->first] = dfInfinity;
    }

    mMarks[nFID] = 0.0;
    mnPathTree[nFID] = -1;

    // Initialize all vertexes as unseen (there are no seen vertexes).
    std::set<GNMGFID> snSeen;

    // We use multimap to maintain the ascending order of costs and because
    // there can be different vertexes with the equal cost.
    std::multimap<double,GNMGFID> to_see;
    std::multimap<double,GNMGFID>::iterator it;
    to_see.insert(std::pair<double,GNMGFID>(0.0, nFID));
    LPGNMCONSTVECTOR panOutcomeEdgeId;

    size_t i;
    GNMGFID nCurrenVertId, nCurrentEdgeId, nTargetVertId;
    double dfCurrentEdgeCost, dfCurrentVertMark, dfNewVertexMark;
    std::map<GNMGFID, GNMStdEdge>::const_iterator ite;

    // Continue iterations while there are some vertexes to see.
    while (!to_see.empty())
    {
        // We must see vertexes with minimal costs at first.
        // In multimap the first cost is the minimal.
        it = to_see.begin();

        nCurrenVertId = it->second;
        dfCurrentVertMark = it->first;
        snSeen.insert(it->second);
        to_see.erase(it);

        // For all neighbours for the current vertex.
        panOutcomeEdgeId = GetOutEdges(nCurrenVertId);
        if(NULL == panOutcomeEdgeId)
            continue;

        for (i = 0; i < panOutcomeEdgeId->size(); ++i)
        {
            nCurrentEdgeId = panOutcomeEdgeId->operator[](i);

            ite = mstEdges.find(nCurrentEdgeId);
            if(ite == mstEdges.end() || ite->second.bIsBloked)
                continue;

            // We go in any edge from source to target so we take only
            // direct cost (even if an edge is bi-directed).
            dfCurrentEdgeCost = ite->second.dfDirCost;

            // While we see outcome edges of current vertex id we definitely
            // know that target vertex id will be target for current edge id.
            nTargetVertId = GetOppositVertex(nCurrentEdgeId, nCurrenVertId);

            // Calculate a new mark assuming the full path cost (mark of the
            // current vertex) to this vertex.
            dfNewVertexMark = dfCurrentVertMark + dfCurrentEdgeCost;

            // Update mark of the vertex if needed.
            if (snSeen.find(nTargetVertId) == snSeen.end() &&
                    dfNewVertexMark < mMarks[nTargetVertId] &&
                    !CheckVertexBlocked(nTargetVertId))
            {
                mMarks[nTargetVertId] = dfNewVertexMark;
                mnPathTree[nTargetVertId] = nCurrentEdgeId;

                // The vertex with minimal cost will be inserted to the
                // beginning.
                to_see.insert(std::pair<double,GNMGFID>(dfNewVertexMark,
                                                        nTargetVertId));
            }
        }
    }
}
Exemple #17
0
 void destroy(object::id_t id) {
     if(m_objects.count(id) == 0)
         throw std::runtime_error("Object does not exist in store");
     m_objects.erase(m_objects.find(id));
 }
Exemple #18
0
 void DataFlow::mergeFlow(Graph<NodeDesc>* f,const Graph<NodeDesc>* g, std::map<Node*,Node*>& mapping)
 {
   // mapping is g -> f
   NodeList queue = g->rootNodes();
   while (!queue.empty())
   {
     Node* n = queue.back();
     queue.pop_back();
     // check predecessors
     bool allSourcesMapped = true;
     for (LinkListCIt sIt=n->sources().begin();sIt!=n->sources().end();sIt++)
     {
       Link* sLink = *sIt;
       map<Node*,Node*>::iterator findIt=mapping.find(sLink->source);
       if (findIt==mapping.end())
       {
         allSourcesMapped = false;
         break;
       }
     }
     if (!allSourcesMapped)
     {
       // some sources miss. Ignore current node for now
       continue;
     }
     if (mapping.find(n)==mapping.end())
     {
       // merge node
       // all sources are merged, merge current node
       Node* mergedNode(NULL);
       // first check if identical node already exists in f
       NodeList candidates;
       if (n->sources().size()>0)
       {
         candidates = mapping.find(n->sources()[0]->source)->second->targetNodes();
       } else {
         candidates = f->rootNodes();
       }
       for (NodeListIt cIt=candidates.begin();cIt!=candidates.end();cIt++)
       {
         if ((**cIt==*n) && sources_match(n->sources(),(*cIt)->sources(),mapping))
         {
           // found identical node
           mergedNode = *cIt;
           break;
         }
       }
       if (mergedNode==NULL)
       {
         // no identical node found. Create node
         mergedNode = f->createNode(n->v);
         for (LinkListCIt sIt=n->sources().begin();sIt!=n->sources().end();sIt++)
         {
           f->link(mapping.find((*sIt)->source)->second,(*sIt)->sourceOutputPort, mergedNode, (*sIt)->targetInputPort);
         }
       }
       // register mapping
       mapping[n] = mergedNode;
     }
     // add target nodes to queue
     NodeList targets = n->targetNodes();
     queue.insert(queue.end(),targets.begin(),targets.end());
   }
   // merge names
   for (NameMapCIt gnIt=g->getNames().begin();gnIt!=g->getNames().end();gnIt++)
   {
     NameMapCIt fnIt = f->getNames().find(gnIt->first);
     if (fnIt!=f->getNames().end()) {
       // check nodes are merged
       if (mapping[gnIt->second]!=fnIt->second) {
         cerr << "ERROR: '" << gnIt->first << "' node exists in the two graphs and cannot be merged !" << endl;
       }
     } else {
       // add named node to f
       f->setNodeName(mapping[gnIt->second], gnIt->first);
     }
   }
 }
std::string convertDVBUTF8(const char *data, int len, int table, int tsidonid)
{
	int newtable = 0;
	bool twochar = false;
	if (!len)
		return "";

	int i=0, t=0;

	if ( tsidonid )
	{
		std::map<int, int>::iterator it =
			TransponderDefaultMapping.find(tsidonid);
		if ( it != TransponderDefaultMapping.end() )
			table = it->second;
		twochar = TransponderUseTwoCharMapping.find(tsidonid) != TransponderUseTwoCharMapping.end();
	}
//printf("table %d tsidonid %04x twochar %d : %20s\n", table, tsidonid, twochar, data);
	switch(data[0])
	{
		case 1 ... 12:
			newtable=data[i++]+4;
//			eDebug("(1..12)text encoded in ISO-8859-%d",table);
			break;
		case 0x10:
		{
//			eDebug("(0x10)text encoded in ISO-8859-%d",n);
			int n=(data[i+1]<<8)|(data[i+2]);
			i += 3;
			switch(n)
			{
				case 12: 
					{} //eDebug("unsup. ISO8859-12 enc.", n);
				default:
					newtable=n;
					break;
			}
			break;
		}
		case 0x11:
			{} //eDebug("unsup. Basic Multilingual Plane of ISO/IEC 10646-1 enc.");
			++i;
			break;
		case 0x12:
			++i;
			{} //eDebug("unsup. KSC 5601 enc.");
			break;
		case 0x13:
			++i;
			{} //eDebug("unsup. GB-2312-1980 enc.");
			break;
		case 0x14:
			++i;
			{} //eDebug("unsup. Big5 subset of ISO/IEC 10646-1 enc.");
			break;
		case 0x0:
		case 0xD ... 0xF:
		case 0x15 ... 0x1F:
			{} //eDebug("reserved %d", data[0]);
			++i;
			break;
	}
	if(!table)
		table = newtable;
//dprintf("recode:::: tsidonid %X table %d two-char %d len %d\n", tsidonid, table, twochar, len);
	unsigned char res[2048];
	while (i < len)
	{
		unsigned long code=0;

		if ( i+1 < len && twochar && (code=doVideoTexSuppl(data[i], data[i+1])) ) {
			i+=2;
//dprintf("recode:::: doVideoTexSuppl code %lX\n", code);
		}

		if (!code)
			code=recode(data[i++], table);
		if (!code)
			continue;
				// Unicode->UTF8 encoding
		if (code < 0x80) // identity ascii <-> utf8 mapping
			res[t++]=char(code);
		else if (/*(table == 5) &&*/ (code == 0x8A)) // I don't think this is related to table 5 --seife
			/* code for parsing text in OSD (event details etc) not support \n it seems,
 			   as result all text after \n is missed. let it be space for now --focus */
			res[t++]= 0x20;//'\n'; // 0x8a is vertical tab. Just use newline for now.
		else if (code < 0x800) // two byte mapping
		{
			res[t++]=(code>>6)|0xC0;
			res[t++]=(code&0x3F)|0x80;
		} else if (code < 0x10000) // three bytes mapping
bool findNuisancePre(std::string name){

	std::map<std::string, std::pair<double, double> >::iterator it=prevals_.find(name);
	if (it!=prevals_.end()) return true;
	else return false;
}
Exemple #21
0
 DamageType DamageTypes::getDamageType(std::string& name)
 {
   std::map<std::string, DamageType>::iterator i = damageTypeMap.find(name);
   if (i == damageTypeMap.end()) return DamageTypes::Unknown;
   return (*i).second;
 }
Exemple #22
0
OfferDataNSeq BackendProducer::createFromCommonFriend(int userId,
																		 									int commFriendLimit,
																		 									const std::map<int, int>& weights,
																		 									const MyUtil::IntSeq& applyList,
																		 									const MyUtil::IntSeq& friendList,
																		 									const MyUtil::IntSeq& blockList,
																		 									const MyUtil::IntSeq& commBlockList,
																		 									std::ostringstream& createLog,
																		 									std::ostringstream& createDetail)
{
	struct timeval tvStart, tvComm;
	gettimeofday( &tvStart, NULL );

	OfferDataNSeq res;
	com::xiaonei::service::CommonFriendSeq commonFriends;
	com::xiaonei::service::CommonFriendSeq tmpCommon;
  
//  commonFriends = OfferFriendsUtil::calCommonFriend(userId, applyList, friendList, blockList, commBlockList, commFriendLimit);
	commonFriends = OfferFriendsUtil::calFoFCommonFriend(userId, applyList, friendList, blockList, commBlockList, commFriendLimit);
	MCE_INFO("[BackendProducer] create CommonFriend userId:" << userId 
			<< " offer new FoF CommonFriend  size:" << commonFriends.size());
  if(commonFriends.size() < commFriendLimit) {
	  tmpCommon = OfferFriendsUtil::calCommonFriend(userId, applyList
        , friendList, blockList, commBlockList, commFriendLimit - commonFriends.size());
    commonFriends.insert(commonFriends.end(), tmpCommon.begin(), tmpCommon.end());
  }
	MCE_INFO("[BackendProducer] create CommonFriend userId:" << userId 
			<< " offer old CommonFriend  size:" << tmpCommon.size());

	vector<int> commonIdSeq;
	for (vector<com::xiaonei::service::CommonFriend>::const_iterator iter = commonFriends.begin(); 
			iter != commonFriends.end(); ++iter) {
		commonIdSeq.push_back(iter->userId);
	}

	Int2IntMap commonIdMap = OfferFriendsUtil::getFriendCountBatch(commonIdSeq);  //何必呢??
	int base_weight = 0;
	std::map<int, int>::const_iterator weiIt = weights.find(BaseTypeCommonFriend);
	if (weiIt != weights.end()) {
		base_weight = weiIt->second;
	}

	createDetail << " comms_";
	for (vector<com::xiaonei::service::CommonFriend>::const_iterator commonIt = commonFriends.begin(); 
			commonIt != commonFriends.end(); ++commonIt) {
		Int2IntMap::const_iterator fIt = commonIdMap.find(commonIt->userId);
		short ffSize;   //这个干嘛了??
		if (fIt == commonIdMap.end()) {
			ffSize = 1;
			continue;
		}
		ffSize = (short)fIt->second;
		OfferDataN commFriend;
		commFriend.userId = commonIt->userId;
		short sameElementSize = (short)commonIt->shares.size();
		commFriend.weight = base_weight;

		commFriend.sign = ((int)0) | (((int)1) << BaseTraitCommonFriend);
		res.push_back(commFriend);
		createDetail << commFriend.userId << "_";
	}

	gettimeofday( &tvComm, NULL );
	double linCommStart = ((double)tvStart.tv_sec*1000000 + (double)tvStart.tv_usec);
	double linCommEnd = ((double)tvComm.tv_sec*1000000 + (double)tvComm.tv_usec);
	double linCommTime = linCommEnd - linCommStart;
	linCommTime = linCommTime/1000000;
	createLog	<< " commonFriends(" << commonFriends.size() << ")(" << linCommTime << "s)";
	return res;
}
Exemple #23
0
    void TerrainManager::initTerrainBlendMaps(Terrain* terrain,
                                              int cellX, int cellY,
                                              int fromX, int fromY, int size,
                                              const std::map<uint16_t, int>& indexes)
    {
        assert(terrain != NULL && "Must have valid terrain");
        assert(fromX >= 0 && fromY >= 0 &&
               "Can't get a terrain texture on terrain outside the current cell");
        assert(fromX+size <= ESM::Land::LAND_TEXTURE_SIZE &&
               fromY+size <= ESM::Land::LAND_TEXTURE_SIZE &&
               "Can't get a terrain texture on terrain outside the current cell");

        //size must be a power of 2 as we do divisions with a power of 2 number
        //that need to result in an integer for correct splatting
        assert( (size & (size - 1)) == 0 && "Size must be a power of 2");

        const int blendMapSize = terrain->getLayerBlendMapSize();
        const int splatSize    = blendMapSize / size;

        //zero out every map
        std::map<uint16_t, int>::const_iterator iter;
        for ( iter = indexes.begin(); iter != indexes.end(); ++iter )
        {
            float* pBlend = terrain->getLayerBlendMap(iter->second)
                                   ->getBlendPointer();
            memset(pBlend, 0, sizeof(float) * blendMapSize * blendMapSize);
        }

        //covert the ltex data into a set of blend maps
        for ( int texY = fromY - 1; texY < fromY + size + 1; texY++ )
        {
            for ( int texX = fromX - 1; texX < fromX + size + 1; texX++ )
            {
                const uint16_t ltexIndex = getLtexIndexAt(cellX, cellY, texX, texY);

                //check if it is the base texture (which isn't in the map) and
                //if it is don't bother altering the blend map for it
                if ( indexes.find(ltexIndex) == indexes.end() )
                {
                    continue;
                }

                //while texX is the splat index relative to the entire cell,
                //relX is relative to the current segment we are splatting
                const int relX = texX - fromX;
                const int relY = texY - fromY;

                const int layerIndex = indexes.find(ltexIndex)->second;

                float* const pBlend = terrain->getLayerBlendMap(layerIndex)
                                             ->getBlendPointer();

                for ( int y = -1; y < splatSize + 1; y++ )
                {
                    for ( int x = -1; x < splatSize + 1; x++ )
                    {

                        //Note: Y is reversed
                        const int splatY = blendMapSize - 1 - relY * splatSize - y;
                        const int splatX = relX * splatSize + x;

                        if ( splatX >= 0 && splatX < blendMapSize &&
                             splatY >= 0 && splatY < blendMapSize )
                        {
                            const int index = (splatY)*blendMapSize + splatX;

                            if ( y >= 0 && y < splatSize &&
                                 x >= 0 && x < splatSize )
                            {
                                pBlend[index] = 1;
                            }
                            else
                            {
                                //this provides a transition shading but also
                                //rounds off the corners slightly
                                pBlend[index] = std::min(1.0f, pBlend[index] + 0.5f);
                            }
                        }

                    }
                }
            }
        }

        for ( int i = 1; i < terrain->getLayerCount(); i++ )
        {
             TerrainLayerBlendMap* blend = terrain->getLayerBlendMap(i);
             blend->dirty();
             blend->update();
        }

    }
Exemple #24
0
std::map<int, OfferDataNSeq> BackendProducer::createFromSameInfoFriendForHighSchool(int userId,
																																		 								int infoLimit,
																																		 								const std::map<int,int>& weights,
																																		 								const MyUtil::IntSeq& applyList,
																																		 								const MyUtil::IntSeq& friendList,
																																		 								const MyUtil::IntSeq& blockList,
																																		 								const MyUtil::IntSeq& commBlockList,
																																		 								std::ostringstream& createLog,
																																		 								std::ostringstream& createDetail)
{
	MCE_INFO("[BackendProducer] createFromSameInfoFriendForHighSchool userId:" << userId << " infoLimit:" << infoLimit);
	struct timeval tvStart, tvInfo;
	gettimeofday( &tvStart, NULL );

	map<int, OfferDataNSeq> res;
	IntSeq filterList = friendList;
	filterList.push_back(userId);
	MCE_INFO("[BackendProducer] createFromSameInfoFriendForHighSchool filterList size:" << filterList.size());

  NetworkInfo sameInfoFriends = OfferFriendsUtil::getNetworkInfoWithHostageFromDB(userId, infoLimit, filterList);

	int base_weight = 0;
	map<int, int>::const_iterator weiIt = weights.find(BaseTypeSameInfoUniv);
	if (weiIt != weights.end()) {
		base_weight = weiIt->second;
		MCE_INFO("BaseTypeSameInfoUniv: " << base_weight);
	}

	int univCount = 0;
	createDetail << " univ_";
	pair<map<int, OfferDataNSeq>::iterator, bool> ins_univ_iter = res.insert(make_pair(BaseTypeSameInfoUniv, OfferDataNSeq()));

	for (ItemSeq::iterator iter = sameInfoFriends.univInfo.begin(); 
			iter != sameInfoFriends.univInfo.end(); ++iter) {   //添加大学资料匹配好友
		for(MyUtil::IntSeq::iterator it = iter->idSeq.begin(); 
				it != iter->idSeq.end(); ++it) {
			OfferDataN infoFriend;
			infoFriend.weight = base_weight;
			infoFriend.userId = *it;
			infoFriend.sign = ((int)0) | (((int)1)<<BaseTraitSameInfoUniv);
			ins_univ_iter.first->second.push_back(infoFriend);
			createDetail << infoFriend.userId << "_";
			++univCount;
		}
	}

	base_weight = 0;
	weiIt = weights.find(BaseTypeSameInfoHighSchool);
	if (weiIt != weights.end()) {
		base_weight = weiIt->second;
	}

	int highCount = 0;
	createDetail << " high_";
	pair<map<int, OfferDataNSeq>::iterator, bool> ins_high_iter = res.insert(make_pair(BaseTypeSameInfoHighSchool, OfferDataNSeq()));

	for (ItemSeq::iterator iter = sameInfoFriends.highschoolInfo.begin(); 
			iter != sameInfoFriends.highschoolInfo.end(); ++iter) {   //添加高中资料匹配好友
		for(MyUtil::IntSeq::iterator it=iter->idSeq.begin(); it!=iter->idSeq.end(); ++it) {
			OfferDataN infoFriend;
			infoFriend.weight = base_weight;
			infoFriend.userId = *it;
			infoFriend.sign = ((int)0) | (((int)1)<<BaseTraitSameInfoHighSchool);
			ins_high_iter.first->second.push_back(infoFriend);
			createDetail << infoFriend.userId << "_";
			++highCount;
		}
	}

	base_weight = 0;
	weiIt = weights.find(BaseTypeSameInfoJuniorSchool);
	if (weiIt!=weights.end()) {
		base_weight = weiIt->second;
	}
	int juCount = 0;
	createDetail << " juni_";
	pair<map<int, OfferDataNSeq>::iterator, bool> ins_junior_iter = res.insert(make_pair(BaseTypeSameInfoJuniorSchool, OfferDataNSeq()));

	for (ItemSeq::iterator iter = sameInfoFriends.juniorschoolInfo.begin(); 
			iter != sameInfoFriends.juniorschoolInfo.end(); ++iter) {  //添加初中资料匹配好友
		for(MyUtil::IntSeq::iterator it = iter->idSeq.begin(); 
				it != iter->idSeq.end(); ++it) {
			OfferDataN infoFriend;
			infoFriend.weight = base_weight;
			infoFriend.userId = *it;
			infoFriend.sign = ((int)0) | (((int)1)<<BaseTraitSameInfoJuniorSchool);
			ins_junior_iter.first->second.push_back(infoFriend);
			createDetail << infoFriend.userId << "_";
			++juCount;
		}
	}

	base_weight = 0;
	weiIt = weights.find(BaseTypeSameInfoElementarySchool);
	if (weiIt != weights.end()) {
		base_weight = weiIt->second;
	}

	int eleCount = 0;
	createDetail << " elem_";
	pair<map<int, OfferDataNSeq>::iterator, bool> ins_ele_iter = res.insert(make_pair(BaseTypeSameInfoElementarySchool, OfferDataNSeq()));
	for (ItemSeq::iterator iter = sameInfoFriends.elementaryschoolInfo.begin(); 
			iter != sameInfoFriends.elementaryschoolInfo.end(); ++iter) {  //添加小学资料匹配好友
		for (MyUtil::IntSeq::iterator it = iter->idSeq.begin(); 
				it!=iter->idSeq.end(); ++it) {
			OfferDataN infoFriend;
			infoFriend.weight = base_weight;
			infoFriend.userId = *it;

			infoFriend.sign = ((int)0) | (((int)1)<<BaseTraitSameInfoElementarySchool);
			ins_ele_iter.first->second.push_back(infoFriend);
			createDetail << infoFriend.userId << "_";
			++eleCount;
		}
	}

	/*中学推荐*/
  HighSchoolInfo highSchoolFriends = OfferFriendsUtil::getHighSchoolInfo(userId, infoLimit, filterList);
	base_weight = 0;
	weiIt = weights.find(BaseTypeAreaEnrollSame);
	if (weiIt != weights.end()) {
		base_weight = weiIt->second;
		MCE_INFO("BaseTypeAreaEnrollSame : " << base_weight);
	}

	int areaCount = 0;
	createDetail << " area_";
	pair<map<int, OfferDataNSeq>::iterator, bool> ins_area_iter = res.insert(make_pair(BaseTypeAreaEnrollSame, OfferDataNSeq()));
	for (RecommendItemSeq::iterator iter = highSchoolFriends.highschoolseq.begin(); 
			iter != highSchoolFriends.highschoolseq.end(); ++iter) {
		OfferDataN infoFriend;
		infoFriend.weight = base_weight;
		infoFriend.userId = iter->uid;

		infoFriend.sign = ((int)0) | (((int)1)<<BaseTraitAreaEnrollSame);
		ins_area_iter.first->second.push_back(infoFriend);
		createDetail << infoFriend.userId << "_";
		++areaCount;
	}
	for (RecommendItemSeq::iterator iter = highSchoolFriends.juniorschoolseq.begin(); 
			iter != highSchoolFriends.juniorschoolseq.end(); ++iter) {
		OfferDataN infoFriend;
		infoFriend.weight = base_weight;
		infoFriend.userId = iter->uid;

		infoFriend.sign = ((int)0) | (((int)1)<<BaseTraitAreaEnrollSame);
		ins_area_iter.first->second.push_back(infoFriend);
		createDetail << infoFriend.userId << "_";
		++areaCount;
	}
	for (RecommendItemSeq::iterator iter = highSchoolFriends.collegeseq.begin(); 
			iter != highSchoolFriends.collegeseq.end(); ++iter) {
		OfferDataN infoFriend;
		infoFriend.weight = base_weight;
		infoFriend.userId = iter->uid;

		infoFriend.sign = ((int)0) | (((int)1)<<BaseTraitAreaEnrollSame);
		ins_area_iter.first->second.push_back(infoFriend);
		createDetail << infoFriend.userId << "_";
		++areaCount;
	}

	gettimeofday(&tvInfo, NULL);
	double linInfoStart = ((double)tvStart.tv_sec*1000000 + (double)tvStart.tv_usec);	
	double linInfoEnd = ((double)tvInfo.tv_sec*1000000 + (double)tvInfo.tv_usec);
	double linInfoTime = linInfoEnd - linInfoStart;
	linInfoTime = linInfoTime/1000000;
	createLog	<< " sameInfoFriends("
			<< "(u" << sameInfoFriends.univInfo.size() << ":" << univCount << ")"
			<< "(h" << sameInfoFriends.highschoolInfo.size() << ":" << highCount << ")"
			<< "(j" << sameInfoFriends.juniorschoolInfo.size() << ":" << juCount << ")"
			<< "(e" << sameInfoFriends.elementaryschoolInfo.size() << ":" << eleCount << ")"
			<< "(a" << res[BaseTypeAreaEnrollSame].size() << ":" << areaCount << ")"
			<< "(" << linInfoTime << "s)";
	MCE_INFO("BackendUtil createlog << " << createLog.str());

	return res;
}
ndt::type ndt::detail::internal_substitute(const ndt::type &pattern, const std::map<std::string, ndt::type> &typevars,
                                           bool concrete) {
  // This function assumes that ``pattern`` is symbolic, so does not
  // have to check types that are always concrete
  switch (pattern.get_id()) {
#ifdef DYND_CUDA
  case cuda_device_id:
    return ndt::make_cuda_device(
        ndt::substitute(pattern.extended<base_memory_type>()->get_element_type(), typevars, concrete));
#endif
  case pointer_id:
    return ndt::make_type<ndt::pointer_type>(
        ndt::substitute(pattern.extended<pointer_type>()->get_target_type(), typevars, concrete));
  case fixed_dim_id:
    if (!pattern.extended<base_fixed_dim_type>()->is_sized()) {
      if (!concrete) {
        return ndt::make_fixed_dim_kind(
            ndt::substitute(pattern.extended<base_dim_type>()->get_element_type(), typevars, concrete));
      } else {
        throw invalid_argument("The dynd pattern type includes a symbolic "
                               "'fixed' dimension, which is not concrete as "
                               "requested");
      }
    } else {
      return ndt::make_fixed_dim(
          pattern.extended<fixed_dim_type>()->get_fixed_dim_size(),
          ndt::substitute(pattern.extended<fixed_dim_type>()->get_element_type(), typevars, concrete));
    }
  case var_dim_id:
    return ndt::make_type<ndt::var_dim_type>(
        ndt::substitute(pattern.extended<var_dim_type>()->get_element_type(), typevars, concrete));
  case struct_id:
    return ndt::make_type<ndt::struct_type>(
        pattern.extended<struct_type>()->get_field_names(),
        substitute_type_array(pattern.extended<tuple_type>()->get_field_types(), typevars, concrete));
  case tuple_id: {
    const std::vector<ndt::type> &element_tp =
        substitute_type_array(pattern.extended<tuple_type>()->get_field_types(), typevars, concrete);
    return ndt::make_type<ndt::tuple_type>(element_tp.size(), element_tp.data());
  }
  case option_id:
    return ndt::make_type<ndt::option_type>(
        ndt::substitute(pattern.extended<option_type>()->get_value_type(), typevars, concrete));
  case callable_id:
    return ndt::make_type<ndt::callable_type>(
        substitute(pattern.extended<callable_type>()->get_return_type(), typevars, concrete),
        substitute(pattern.extended<callable_type>()->get_pos_tuple(), typevars, concrete),
        substitute(pattern.extended<callable_type>()->get_kwd_struct(), typevars, concrete));
  case typevar_constructed_id: {
    map<std::string, ndt::type>::const_iterator it =
        typevars.find(pattern.extended<typevar_constructed_type>()->get_name());
    if (it->second.get_id() == void_id) {
      return substitute(pattern.extended<typevar_constructed_type>()->get_arg(), typevars, concrete);
    }
#ifdef DYND_CUDA
    if (it->second.get_id() == cuda_device_id) {
      return ndt::make_cuda_device(
          substitute(pattern.extended<typevar_constructed_type>()->get_arg(), typevars, concrete));
    }
#endif
  }
  case typevar_id: {
    map<std::string, ndt::type>::const_iterator it = typevars.find(pattern.extended<typevar_type>()->get_name());
    if (it != typevars.end()) {
      if (it->second.get_ndim() != 0) {
        stringstream ss;
        ss << "The substitution for dynd typevar " << pattern << ", " << it->second
           << ", is a dimension, expected a dtype";
        throw invalid_argument(ss.str());
      }
      if (!concrete || !it->second.is_symbolic()) {
        return it->second;
      } else {
        stringstream ss;
        ss << "The substitution for dynd typevar " << pattern << ", " << it->second << ", is not concrete as required";
        throw invalid_argument(ss.str());
      }
    } else {
      if (concrete) {
        stringstream ss;
        ss << "No substitution type for dynd type var " << pattern << " was available";
        throw invalid_argument(ss.str());
      } else {
        return pattern;
      }
    }
  }
  case typevar_dim_id: {
    map<std::string, ndt::type>::const_iterator it = typevars.find(pattern.extended<typevar_dim_type>()->get_name());
    if (it != typevars.end()) {
      if (it->second.get_ndim() == 0) {
        stringstream ss;
        ss << "The substitution for dynd typevar " << pattern << ", " << it->second
           << ", is a dtype, expected a dimension";
        throw invalid_argument(ss.str());
      }
      if (!concrete || !it->second.is_symbolic()) {
        switch (it->second.get_id()) {
        case fixed_dim_id:
          if (!it->second.extended<base_fixed_dim_type>()->is_sized()) {
            return ndt::make_fixed_dim_kind(
                ndt::substitute(pattern.extended<typevar_dim_type>()->get_element_type(), typevars, concrete));
          } else {
            return ndt::make_fixed_dim(
                it->second.extended<fixed_dim_type>()->get_fixed_dim_size(),
                ndt::substitute(pattern.extended<typevar_dim_type>()->get_element_type(), typevars, concrete));
          }
        case var_dim_id:
          return ndt::make_type<ndt::var_dim_type>(
              ndt::substitute(pattern.extended<typevar_dim_type>()->get_element_type(), typevars, concrete));
        default: {
          stringstream ss;
          ss << "The substitution for dynd typevar " << pattern << ", " << it->second
             << ", is not a substitutable dimension type";
          throw invalid_argument(ss.str());
        }
        }
      } else {
        stringstream ss;
        ss << "The substitution for dynd typevar " << pattern << ", " << it->second << ", is not concrete as required";
        throw invalid_argument(ss.str());
      }
    } else {
      if (concrete) {
        stringstream ss;
        ss << "No substitution type for dynd typevar " << pattern << " was available";
        throw invalid_argument(ss.str());
      } else {
        return ndt::make_type<ndt::typevar_dim_type>(
            pattern.extended<typevar_dim_type>()->get_name(),
            ndt::substitute(pattern.extended<typevar_dim_type>()->get_element_type(), typevars, concrete));
      }
    }
  }
  case pow_dimsym_id: {
    // Look up to the exponent typevar
    std::string exponent_name = pattern.extended<pow_dimsym_type>()->get_exponent();
    map<std::string, ndt::type>::const_iterator tv_type = typevars.find(exponent_name);
    intptr_t exponent = -1;
    if (tv_type != typevars.end()) {
      if (tv_type->second.get_id() == fixed_dim_id) {
        exponent = tv_type->second.extended<fixed_dim_type>()->get_fixed_dim_size();
      } else if (tv_type->second.get_id() == typevar_dim_id) {
        // If it's a typevar, substitute the new name in
        exponent_name = tv_type->second.extended<typevar_dim_type>()->get_name();
        if (concrete) {
          stringstream ss;
          ss << "The substitution for dynd typevar " << exponent_name << ", " << tv_type->second
             << ", is not concrete as required";
          throw invalid_argument(ss.str());
        }
      } else {
        stringstream ss;
        ss << "The substitution for dynd typevar " << exponent_name << ", " << tv_type->second
           << ", is not a fixed_dim integer as required";
        throw invalid_argument(ss.str());
      }
    }
    // If the exponent is zero, just substitute the rest of the type
    if (exponent == 0) {
      return ndt::substitute(pattern.extended<pow_dimsym_type>()->get_element_type(), typevars, concrete);
    }
    // Get the base type
    ndt::type base_tp = pattern.extended<pow_dimsym_type>()->get_base_type();
    if (base_tp.get_id() == typevar_dim_id) {
      map<std::string, ndt::type>::const_iterator btv_type =
          typevars.find(base_tp.extended<typevar_dim_type>()->get_name());
      if (btv_type == typevars.end()) {
        // We haven't seen this typevar yet, check if concrete
        // is required
        if (concrete) {
          stringstream ss;
          ss << "No substitution type for dynd typevar " << base_tp << " was available";
          throw invalid_argument(ss.str());
        }
      } else if (btv_type->second.get_ndim() > 0 && btv_type->second.get_id() != dim_fragment_id) {
        // Swap in for the base type
        base_tp = btv_type->second;
      } else {
        stringstream ss;
        ss << "The substitution for dynd typevar " << base_tp << ", " << btv_type->second
           << ", is not a substitutable dimension type";
        throw invalid_argument(ss.str());
      }
    }
    // Substitute the element type, then apply the exponent
    ndt::type result = ndt::substitute(pattern.extended<pow_dimsym_type>()->get_element_type(), typevars, concrete);
    if (exponent == 0) {
      return result;
    } else if (exponent < 0) {
      return ndt::make_type<ndt::pow_dimsym_type>(base_tp, exponent_name, result);
    } else {
      switch (base_tp.get_id()) {
      case fixed_dim_id: {
        if (!base_tp.extended<base_fixed_dim_type>()->is_sized()) {
          if (concrete) {
            stringstream ss;
            ss << "The base for a dimensional power type, 'Fixed ** " << exponent << "', is not concrete as required";
            throw invalid_argument(ss.str());
          }
          for (intptr_t i = 0; i < exponent; ++i) {
            result = ndt::make_fixed_dim_kind(result);
          }
          return result;
        } else {
          intptr_t dim_size = base_tp.extended<fixed_dim_type>()->get_fixed_dim_size();
          for (intptr_t i = 0; i < exponent; ++i) {
            result = ndt::make_fixed_dim(dim_size, result);
          }
          return result;
        }
      }
      case var_dim_id:
        for (intptr_t i = 0; i < exponent; ++i) {
          result = ndt::make_type<ndt::var_dim_type>(result);
        }
        return result;
      case typevar_dim_id: {
        const std::string &tvname = base_tp.extended<typevar_dim_type>()->get_name();
        for (intptr_t i = 0; i < exponent; ++i) {
          result = ndt::make_type<ndt::typevar_dim_type>(tvname, result);
        }
        return result;
      }
      default: {
        stringstream ss;
        ss << "Cannot substitute " << base_tp << " as the base of a dynd dimensional power type";
        throw invalid_argument(ss.str());
      }
      }
    }
  }
  case ellipsis_dim_id: {
    const std::string &name = pattern.extended<ellipsis_dim_type>()->get_name();
    if (!name.empty()) {
      map<std::string, ndt::type>::const_iterator it = typevars.find(pattern.extended<typevar_dim_type>()->get_name());
      if (it != typevars.end()) {
        if (it->second.get_id() == dim_fragment_id) {
          return it->second.extended<dim_fragment_type>()->apply_to_dtype(
              ndt::substitute(pattern.extended<ellipsis_dim_type>()->get_element_type(), typevars, concrete));
        } else {
          stringstream ss;
          ss << "The substitution for dynd typevar " << pattern << ", " << it->second
             << ", is not a dim fragment as required";
          throw invalid_argument(ss.str());
        }
      } else {
        if (concrete) {
          stringstream ss;
          ss << "No substitution type for dynd typevar " << pattern << " was available";
          throw invalid_argument(ss.str());
        } else {
          return ndt::make_ellipsis_dim(
              pattern.extended<ellipsis_dim_type>()->get_name(),
              ndt::substitute(pattern.extended<ellipsis_dim_type>()->get_element_type(), typevars, concrete));
        }
      }
    } else {
      throw invalid_argument("Cannot substitute into an unnamed ellipsis typevar");
    }
  }
  case any_kind_id: {
    if (concrete) {
      stringstream ss;
      ss << "The dynd type " << pattern << " is not concrete as required";
      throw invalid_argument(ss.str());
    } else {
      return pattern;
    }
  }
  case scalar_kind_id: {
    if (concrete) {
      stringstream ss;
      ss << "The dynd type " << pattern << " is not concrete as required";
      throw invalid_argument(ss.str());
    } else {
      return pattern;
    }
  }
  default:
    break;
  }

  stringstream ss;
  ss << "Unsupported dynd type \"" << pattern << "\" encountered for substituting typevars";
  throw invalid_argument(ss.str());
}
 bool TileCachedRecastMeshManager::updateTile(const ObjectId id, const btTransform& transform,
     const AreaType areaType, const TilePosition& tilePosition, std::map<TilePosition, CachedRecastMeshManager>& tiles)
 {
     const auto tile = tiles.find(tilePosition);
     return tile != tiles.end() && tile->second.updateObject(id, transform, areaType);
 }
void    GMLASXPathMatcher::SetDocumentMapURIToPrefix(
                        const std::map<CPLString,CPLString>& oMapURIToPrefix )
{
    m_aosReferenceXPaths.clear();

    // Split each reference XPath into its components
    for(size_t i = 0; i < m_aosReferenceXPathsUncompiled.size(); ++i )
    {
        const CPLString& osXPath( m_aosReferenceXPathsUncompiled[i] );

        std::vector<XPathComponent> oVector;

        size_t iPos = 0;
        bool bDirectChild = false;
        if( osXPath.size() >= 2 &&
            osXPath[0] == '/' && osXPath[1] == '/' )
        {
            iPos += 2;
        }
        else if( osXPath.size() >= 1 && osXPath[0] == '/' )
        {
            iPos += 1;
            bDirectChild = true;
        }

        while( iPos < osXPath.size() )
        {
            size_t iPosNextSlash = osXPath.find('/', iPos);

            if( iPos == iPosNextSlash )
            {
                bDirectChild = false;
                iPos ++;
                continue;
            }

            CPLString osCurNode;
            if( iPosNextSlash == std::string::npos )
                osCurNode.assign(osXPath, iPos, std::string::npos);
            else
                osCurNode.assign(osXPath, iPos, iPosNextSlash - iPos);

            // Translate the configuration prefix to the equivalent in
            // this current schema
            size_t iPosColumn = osCurNode.find(':');
            if( iPosColumn != std::string::npos )
            {
                bool bIsAttr = ( osCurNode[0] == '@' );
                CPLString osPrefix;
                CPLString osLocalname;
                osPrefix.assign(osCurNode,
                                bIsAttr ? 1 : 0,
                                iPosColumn - (bIsAttr ? 1 : 0));
                osLocalname.assign(osCurNode, iPosColumn+1,
                                std::string::npos);

                std::map<CPLString, CPLString>::const_iterator oIter =
                    m_oMapPrefixToURIReferenceXPaths.find(osPrefix);
                if( oIter != m_oMapPrefixToURIReferenceXPaths.end() )
                {
                    const CPLString& osURI( oIter->second );
                    oIter = oMapURIToPrefix.find( osURI );
                    if( oIter == oMapURIToPrefix.end() )
                        break;
                    osPrefix.assign(oIter->second);
                }

                osCurNode.clear();
                if( bIsAttr )
                    osCurNode.append(1, '@');
                osCurNode.append(osPrefix);
                osCurNode.append(1, ':');
                osCurNode.append(osLocalname);
            }

            XPathComponent comp;
            comp.m_osValue = osCurNode;
            comp.m_bDirectChild = bDirectChild;
            oVector.push_back(comp);

            if( iPosNextSlash == std::string::npos )
                iPos = osXPath.size();
            else
                iPos = iPosNextSlash + 1;

            bDirectChild = true;
        }

        if ( iPos < osXPath.size() )
            oVector.clear();
        m_aosReferenceXPaths.push_back(oVector);
    }
}
Exemple #28
0
void Block::setEditorData(std::map<std::string,std::string>& obj){
	//Iterator used to check if the map contains certain entries.
	map<string,string>::iterator it;

	//Check if the data contains the id block.
	it=obj.find("id");
	if(it!=obj.end()){
		//Set the id of the block.
		id=obj["id"];
	}

	//Block specific properties.
	switch(type){
	case TYPE_MOVING_BLOCK:
	case TYPE_MOVING_SHADOW_BLOCK:
	case TYPE_MOVING_SPIKES:
		{
			//Make sure that the editor data contains MovingPosCount.
			it=obj.find("MovingPosCount");
			if(it!=obj.end()){
				char s0[64];
				int m=atoi(obj["MovingPosCount"].c_str());
				movingPos.clear();
				for(int i=0;i<m;i++){
					SDL_Rect r={0,0,0,0};
					sprintf(s0+1,"%d",i);
					s0[0]='x';
					r.x=atoi(obj[s0].c_str());
					s0[0]='y';
					r.y=atoi(obj[s0].c_str());
					s0[0]='t';
					r.w=atoi(obj[s0].c_str());
					movingPos.push_back(r);
				}
			}

			//Check if the activated or disabled key is in the data.
			//NOTE: 'disabled' is obsolete in V0.5.
			it=obj.find("activated");
			if(it!=obj.end()){
				string s=it->second;
				editorFlags=0;
				if(!(s=="true" || atoi(s.c_str()))) editorFlags|=0x1;
				flags=flagsSave=editorFlags;
			}else{
				it=obj.find("disabled");
				if(it!=obj.end()){
					string s=it->second;
					editorFlags=0;
					if(s=="true" || atoi(s.c_str())) editorFlags|=0x1;
					flags=flagsSave=editorFlags;
				}
			}

			//Check if the loop key is in the data.
			it=obj.find("loop");
			if(it!=obj.end()){
				string s=obj["loop"];
				loop=false;
				if(s=="true" || atoi(s.c_str()))
					loop=true;
			}

		}
		break;
	case TYPE_CONVEYOR_BELT:
	case TYPE_SHADOW_CONVEYOR_BELT:
		{
			//Check if there's a speed key in the editor data.
			it=obj.find("speed");
			if(it!=obj.end()){
				editorSpeed=atoi(obj["speed"].c_str());
				speed=speedSave=editorSpeed;
			}

			//Check if the activated or disabled key is in the data.
			//NOTE: 'disabled' is obsolete in V0.5.
			it=obj.find("activated");
			if(it!=obj.end()){
				string s=it->second;
				editorFlags=0;
				if(!(s=="true" || atoi(s.c_str()))) editorFlags|=0x1;
				flags=flagsSave=editorFlags;
			}else{
				it=obj.find("disabled");
				if(it!=obj.end()){
					string s=it->second;
					editorFlags=0;
					if(s=="true" || atoi(s.c_str())) editorFlags|=0x1;
					flags=flagsSave=editorFlags;
				}
			}
		}
		break;
	case TYPE_PORTAL:
		{
			//Check if the automatic key is in the data.
			it=obj.find("automatic");
			if(it!=obj.end()){
				string s=obj["automatic"];
				editorFlags=0;
				if(s=="true" || atoi(s.c_str())) editorFlags|=0x1;
				flags=flagsSave=editorFlags;
			}

			//Check if the destination key is in the data.
			it=obj.find("destination");
			if(it!=obj.end()){
				destination=obj["destination"];
			}
		}
		break;
	case TYPE_BUTTON:
	case TYPE_SWITCH:
		{
			//Check if the behaviour key is in the data.
			it=obj.find("behaviour");
			if(it!=obj.end()){
				string s=obj["behaviour"];
				editorFlags=0;
				if(s=="on" || s==_("On")) editorFlags|=1;
				else if(s=="off" || s==_("Off")) editorFlags|=2;
				flags=flagsSave=editorFlags;
			}
		}
		break;
	case TYPE_NOTIFICATION_BLOCK:
		{
			//Check if the message key is in the data.
			it=obj.find("message");
			if(it!=obj.end()){
				message=obj["message"];
				//Change the characters '\n' to a real \n
				while(message.find("\\n")!=string::npos){
					message=message.replace(message.find("\\n"),2,"\n");
				}
			}
		}
		break;
	case TYPE_FRAGILE:
		{
			//Check if the status is in the data.
			it=obj.find("state");
			if(it!=obj.end()){
				editorFlags=atoi(obj["state"].c_str());
				flags=editorFlags;
				{
					const char* s=(flags==0)?"default":((flags==1)?"fragile1":((flags==2)?"fragile2":"fragile3"));
					appearance.changeState(s);
				}
			}
		}
	}
}
bool ChainParser::parseChain(XmlRpc::XmlRpcValue& chain_description, Tree tree, urdf::Model& robot_model,
                               std::map<std::string, unsigned int>& joint_name_to_index,
                               std::vector<std::string>& index_to_joint_name,
                               std::vector<double>& q_min, std::vector<double>& q_max) {
    ros::NodeHandle n("~");
    std::string ns = n.getNamespace();

    std::cout << chain_description << std::endl;

    if (chain_description.getType() != XmlRpc::XmlRpcValue::TypeStruct) {
        ROS_ERROR("Chain description should be a struct containing 'root' and 'tip'. (namespace: %s)", n.getNamespace().c_str());
        return false;
    }

    XmlRpc::XmlRpcValue& v_root_link = chain_description["root"];
    if (v_root_link.getType() != XmlRpc::XmlRpcValue::TypeString) {
        ROS_ERROR("Chain description for does not contain 'root'. (namespace: %s)", n.getNamespace().c_str());
        return false;
    }
    std::string root_link_name = (std::string)v_root_link;

    XmlRpc::XmlRpcValue& v_tip_link = chain_description["tip"];
    if (v_tip_link.getType() != XmlRpc::XmlRpcValue::TypeString) {
        ROS_ERROR("Chain description for does not contain 'tip'. (namespace: %s)", n.getNamespace().c_str());
        return false;
    }
    std::string tip_link_name = (std::string)v_tip_link;

    Chain* chain = new Chain();

    //if (!tree.kdl_tree.getChain(root_link_name, tip_link_name, chain->kdl_chain_)) {
    if (!tree.kdl_tree_.getChain("base", tip_link_name, chain->kdl_chain_)) {
        ROS_FATAL("Could not initialize chain object");
        return false;
    }

    for(unsigned int i = 0; i < chain->kdl_chain_.getNrOfSegments(); ++i) {
        const KDL::Segment& segment = chain->kdl_chain_.getSegment(i);
        const KDL::Joint& joint = segment.getJoint();

        if (joint.getType() != KDL::Joint::None)
        {
            //cout << "Segment: " << segment.getName() << endl;
            //cout << "Joint:   " << joint.getName() << endl;

            unsigned int full_joint_index = 0;

            std::map<std::string, unsigned int>::iterator it_joint = joint_name_to_index.find(joint.getName());

            if (it_joint == joint_name_to_index.end()) {
                // joint name is not yet in map, so give it a new fresh index and add it to the map
                full_joint_index = joint_name_to_index.size();

                //cout << "    new joint, gets index " << full_joint_index << endl;
                //cout << "    type: " << joint.getTypeName() << endl;

                joint_name_to_index[joint.getName()] = full_joint_index;
                index_to_joint_name.push_back(joint.getName());

                //cout << "    Lower limit: " << robot_model.getJoint(joint.getName())->limits->lower << endl;
                //cout << "    Upper limit: " << robot_model.getJoint(joint.getName())->limits->upper << endl;

                // determine joint limits from URDF
                q_min.push_back(robot_model.getJoint(joint.getName())->limits->lower);
                q_max.push_back(robot_model.getJoint(joint.getName())->limits->upper);

            } else {
                // joint name already in the map, so look-up its index
                full_joint_index = it_joint->second;

                //cout << "    existing joint, has index: " << full_joint_index << endl;
            }

        }

    }

    return true;
}
Exemple #30
0
void PoolObject::CheckEventLinkAndReport<GameObject>(uint32 poolId, int16 event_id, std::map<uint32, int16> const& /*creature2event*/, std::map<uint32, int16> const& go2event) const
{
    std::map<uint32, int16>::const_iterator itr = go2event.find(guid);
    if (itr == go2event.end() || itr->second != event_id)
        sLog.outErrorDb("Gameobject (GUID: %u) expected to be listed in `game_event_gameobject` for event %u as part pool %u", guid, event_id, poolId);
}