本文整理汇总了C++中std::map::find方法的典型用法代码示例。如果您正苦于以下问题:C++ map::find方法的具体用法?C++ map::find怎么用?C++ map::find使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类std::map
的用法示例。
在下文中一共展示了map::find方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: GetTextureReference
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;
//.........这里部分代码省略.........
示例2: send_stats
//.........这里部分代码省略.........
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());
}
示例3: strcmp
/*
* 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;
//.........这里部分代码省略.........
示例4: initTerrainTextures
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> <exStore =
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;
}
}
}
}
示例5: pull
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 == '*';
//.........这里部分代码省略.........
示例6: unrender
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();
}
示例7: if
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();
}
示例8: particleColors
/******************************************************************************
* 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;
}
}
}
示例9: render
/******************************************************************************
* 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) {
//.........这里部分代码省略.........
示例10: tagname
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,
//.........这里部分代码省略.........
示例11: vc_lookup
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;
}
示例12: RunScript
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;
}
示例13: val
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;
}
示例14: in_domain
inline bool Pass::in_domain(const Var v) const {
return pa.find(v) != pa.end();
}
示例15: runtime_error
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;
}