void AArch64A57FPLoadBalancing:: scanInstruction(MachineInstr *MI, unsigned Idx, std::map<unsigned, Chain*> &ActiveChains, std::set<std::unique_ptr<Chain>> &AllChains) { // Inspect "MI", updating ActiveChains and AllChains. if (isMul(MI)) { for (auto &I : MI->uses()) maybeKillChain(I, Idx, ActiveChains); for (auto &I : MI->defs()) maybeKillChain(I, Idx, ActiveChains); // Create a new chain. Multiplies don't require forwarding so can go on any // unit. unsigned DestReg = MI->getOperand(0).getReg(); DEBUG(dbgs() << "New chain started for register " << TRI->getName(DestReg) << " at " << *MI); auto G = llvm::make_unique<Chain>(MI, Idx, getColor(DestReg)); ActiveChains[DestReg] = G.get(); AllChains.insert(std::move(G)); } else if (isMla(MI)) { // It is beneficial to keep MLAs on the same functional unit as their // accumulator operand. unsigned DestReg = MI->getOperand(0).getReg(); unsigned AccumReg = MI->getOperand(3).getReg(); maybeKillChain(MI->getOperand(1), Idx, ActiveChains); maybeKillChain(MI->getOperand(2), Idx, ActiveChains); if (DestReg != AccumReg) maybeKillChain(MI->getOperand(0), Idx, ActiveChains); if (ActiveChains.find(AccumReg) != ActiveChains.end()) { DEBUG(dbgs() << "Chain found for accumulator register " << TRI->getName(AccumReg) << " in MI " << *MI); // For simplicity we only chain together sequences of MULs/MLAs where the // accumulator register is killed on each instruction. This means we don't // need to track other uses of the registers we want to rewrite. // // FIXME: We could extend to handle the non-kill cases for more coverage. if (MI->getOperand(3).isKill()) { // Add to chain. DEBUG(dbgs() << "Instruction was successfully added to chain.\n"); ActiveChains[AccumReg]->add(MI, Idx, getColor(DestReg)); // Handle cases where the destination is not the same as the accumulator. if (DestReg != AccumReg) { ActiveChains[DestReg] = ActiveChains[AccumReg]; ActiveChains.erase(AccumReg); } return; } DEBUG(dbgs() << "Cannot add to chain because accumulator operand wasn't " << "marked <kill>!\n"); maybeKillChain(MI->getOperand(3), Idx, ActiveChains); } DEBUG(dbgs() << "Creating new chain for dest register " << TRI->getName(DestReg) << "\n"); auto G = llvm::make_unique<Chain>(MI, Idx, getColor(DestReg)); ActiveChains[DestReg] = G.get(); AllChains.insert(std::move(G)); } else { // Non-MUL or MLA instruction. Invalidate any chain in the uses or defs // lists. for (auto &I : MI->uses()) maybeKillChain(I, Idx, ActiveChains); for (auto &I : MI->defs()) maybeKillChain(I, Idx, ActiveChains); } }
/// Implements Base::load_from_xml() void Joint::load_from_xml(XMLTreeConstPtr node, std::map<std::string, BasePtr>& id_map) { std::map<std::string, BasePtr>::const_iterator id_iter; // *********************************************************************** // don't verify that the node is correct, b/c Joint will // be subclassed // *********************************************************************** // load the parent data Visualizable::load_from_xml(node, id_map); // read the lower limits, if given const XMLAttrib* lolimit_attr = node->get_attrib("lower-limits"); if (lolimit_attr) lolimit_attr->get_vector_value(lolimit); // read the upper limits, if given const XMLAttrib* hilimit_attr = node->get_attrib("upper-limits"); if (hilimit_attr) hilimit_attr->get_vector_value(hilimit); // read the maximum actuator force, if given const XMLAttrib* maxforce_attr = node->get_attrib("max-forces"); if (maxforce_attr) maxforce_attr->get_vector_value(maxforce); // read the joint positions, if given const XMLAttrib* q_attr = node->get_attrib("q"); if (q_attr) q_attr->get_vector_value(q); else q.set_zero(num_dof()); // read the joint velocities, if given const XMLAttrib* qd_attr = node->get_attrib("qd"); if (qd_attr) qd_attr->get_vector_value(qd); // read the joint positions, if given const XMLAttrib* q_init_attr = node->get_attrib("q-tare"); if (q_init_attr) { _determine_q_tare = false; q_init_attr->get_vector_value(_q_tare); } else _determine_q_tare = true; // read the Coulomb friction coefficient, if given const XMLAttrib* fc_attr = node->get_attrib("coulomb-friction-coeff"); if (fc_attr) mu_fc = fc_attr->get_real_value(); // read the viscous friction coefficient, if given const XMLAttrib* fv_attr = node->get_attrib("viscous-friction-coeff"); if (fv_attr) mu_fv = fv_attr->get_real_value(); // read the restitution coefficient, if given const XMLAttrib* resti_attr = node->get_attrib("restitution-coeff"); if (resti_attr) limit_restitution = resti_attr->get_real_value(); // read the articulated body, if given const XMLAttrib* ab_attr = node->get_attrib("articulated-body-id"); if (ab_attr) { // get the ID const std::string& ID = ab_attr->get_string_value(); // look for the ID -- only warn if it is not found if ((id_iter = id_map.find(ID)) == id_map.end()) { #ifdef _DEBUG_XML_ std::cout << "Joint::load_from_xml() warning - "; std::cout << "articulated body" << std::endl << " '" << ID << "' not "; std::cout << "found" << std::endl << " ** This warning could result "; std::cout << "from joints being constructed before articulated bodies "; std::cout << std::endl << " and may not be serious..." << std::endl; std::cout << " offending node: " << std::endl << *node; #endif } else set_articulated_body(boost::dynamic_pointer_cast<RCArticulatedBody>(id_iter->second)); } // read the inboard link id, if given const XMLAttrib* inboard_attr = node->get_attrib("inboard-link-id"); if (inboard_attr) { // get the ID of the inboard link const std::string& id = inboard_attr->get_string_value(); // complain if the link not found but don't treat it as an error-- there // are circular dependencies if ((id_iter = id_map.find(id)) == id_map.end()) { #ifdef _DEBUG_XML_ std::cout << "Joint::load_from_xml() warning - link "; std::cout << id << " not found" << std::endl; std::cout << " ** This warning could result from joints being "; std::cout << " constructed before links" << std::endl << " and may "; std::cout << "not be serious" << std::endl; std::cout << " offending node: " << std::endl << *node; #endif } else { RigidBodyPtr inboard(boost::dynamic_pointer_cast<RigidBody>(id_iter->second)); set_inboard_link(inboard); } } // read the outboard link id, if given const XMLAttrib* outboard_attr = node->get_attrib("outboard-link-id"); if (outboard_attr) { // get the ID of the outboard link const std::string& id = outboard_attr->get_string_value(); // complain if the link not found but don't treat it as an error-- there // are circular dependencies if ((id_iter = id_map.find(id)) == id_map.end()) { #ifdef _DEBUG_XML_ std::cout << "Joint::load_from_xml() warning - link "; std::cout << id << " not found" << std::endl; std::cout << " ** This warning could result from joints being "; std::cout << " constructed before links" << std::endl << " and may "; std::cout << "not be serious" << std::endl; std::cout << " offending node: " << std::endl << *node; #endif } else { RigidBodyPtr outboard(boost::dynamic_pointer_cast<RigidBody>(id_iter->second)); set_outboard_link(outboard); } } // get the global position of the joint, if possible const XMLAttrib* pos_attr = node->get_attrib("global-position"); if (pos_attr) { // get the position of the joint Vector3 position; pos_attr->get_vector_value(position); // make sure that both inboard and outboard links have been set if (!get_inboard_link() || !get_outboard_link()) { std::cerr << "Joint::load_from_xml() - global position"; std::cerr << " specified w/o " << std::endl << " inboard and/or"; std::cerr << " outboard links set!" << std::endl; return; } // get the inboard and outboard links RigidBodyPtr inboard(get_inboard_link()); RigidBodyPtr outboard(get_outboard_link()); // get the transforms for the two bodies const Matrix4& Ti = inboard->get_transform(); const Matrix4& To = outboard->get_transform(); // determine the vector from the inboard link to the joint (link coords) Vector3 inboard_to_joint = Ti.inverse_mult_point(position); // determine the vector from the joint to the outboard link (link coords) Vector3 joint_to_outboard_lf = -To.inverse_mult_point(position); // NOTE: the calculation immediately below assumes that the induced // transform (i.e., the transform that the joint applies) is initally // identity // compute the vector from the joint to the outboard link in joint frame Vector3 joint_to_outboard_jf = (Ti.inverse_transform() * To).get_translation() - inboard_to_joint; // add/replace this as an inner joint inboard->add_outer_joint(outboard, get_this(), inboard_to_joint); outboard->add_inner_joint(inboard, get_this(), joint_to_outboard_jf, joint_to_outboard_lf); } // get the spatial axis in link coordinates; note that this must be done // after the link IDs are set const XMLAttrib* sa_link_attr = node->get_attrib("spatial-axis-link"); if (sa_link_attr) { SMatrix6N si; sa_link_attr->get_matrix_value(si); if (si.columns() != num_dof()) throw std::runtime_error("Incorrect spatial matrix size reading XML attribute spatial-axis-link"); _si = si; } }
int main(int argc, char **argv) { // GLUT initialization glutInit(&argc, argv); glutInitDisplayMode(GLUT_DEPTH|GLUT_DOUBLE|GLUT_RGBA|GLUT_MULTISAMPLE); glutInitContextVersion (3, 3); glutInitContextFlags (GLUT_COMPATIBILITY_PROFILE ); glutInitWindowPosition(100,100); glutInitWindowSize(320,320); glutCreateWindow("Lighthouse3D - Assimp Demo"); // Callback Registration glutDisplayFunc(renderScene); glutReshapeFunc(changeSize); glutIdleFunc(renderScene); // Mouse and Keyboard Callbacks glutKeyboardFunc(processKeys); glutMouseFunc(processMouseButtons); glutMotionFunc(processMouseMotion); glutMouseWheelFunc ( mouseWheel ) ; // Init GLEW //glewExperimental = GL_TRUE; glewInit(); if (glewIsSupported("GL_VERSION_3_3")) printf("Ready for OpenGL 3.3\n"); else { printf("OpenGL 3.3 not supported\n"); return(1); } // Init the app (load model and textures) and OpenGL if (!init()) printf("Could not Load the Model\n"); printf ("Vendor: %s\n", glGetString (GL_VENDOR)); printf ("Renderer: %s\n", glGetString (GL_RENDERER)); printf ("Version: %s\n", glGetString (GL_VERSION)); printf ("GLSL: %s\n", glGetString (GL_SHADING_LANGUAGE_VERSION)); // return from main loop glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS); // GLUT main loop glutMainLoop(); // cleaning up textureIdMap.clear(); // clear myMeshes stuff for (unsigned int i = 0; i < myMeshes.size(); ++i) { glDeleteVertexArrays(1,&(myMeshes[i].vao)); glDeleteTextures(1,&(myMeshes[i].texIndex)); glDeleteBuffers(1,&(myMeshes[i].uniformBlockIndex)); } // delete buffers glDeleteBuffers(1,&matricesUniBuffer); return(0); }
namespace se { /// TCP Stream id class - serves as the key in the streams map class Stream_id { public: /// constructor Stream_id() { } /// constructor taking source and destination adresses Stream_id( in6addr_t &src_ip, in6addr_t &dst_ip, unsigned short src_port, unsigned short dst_port) { m_src_ip = src_ip; m_dst_ip = dst_ip; m_src_port = src_port; m_dst_port = dst_port; } /// < comparison operator for the std::map bool operator < (const Stream_id &rhs) const { return memcmp(this,&rhs,sizeof(Stream_id)) < 0; } private: in6addr_t m_src_ip, m_dst_ip; unsigned short m_src_port,m_dst_port; }; /// TCP data segment container /** Data_segment contains the data found in a single tcp packet * Data_segment are inerted into a list in the Stream class */ class Data_segment { public: /// Constructor taking a memory block with packet content Data_segment( unsigned char *data, unsigned int len) { m_datasize = len; m_data = new unsigned char[len]; for (unsigned int i=0; i<len; i++) { m_data[i]=data[i]; } } /// Copy constructor Data_segment(const Data_segment &other) { m_datasize = other.m_datasize; m_data = new unsigned char[m_datasize]; for (unsigned int i=0; i<m_datasize; i++) { m_data[i]=other.m_data[i]; } } /// Destructor ~Data_segment() { delete []m_data; } /// size of the data unsigned int m_datasize; /// pointer to the data unsigned char *m_data; }; int g_count = 0; /// TCP Stream class /** The Stream class has an Stream_id and a list of Data_segemnts that make up * a tcp data stream. * The Streams are organized into a global map ( g_tcp_streams ) indexed by a Stream_id */ class Stream { public: /// Constructor Stream() { m_ser = g_count++; m_content = false; m_nseq = false; m_seq = 0; } /// add a datasegment to the stream /** If the segment has the expected sequence number * the segment will be added to the list */ void add( bool syn,unsigned int seq, Data_segment &s ) { m_content=true; if (!m_segments.size()||syn) m_seq=seq; if (m_seq==seq) { m_content = true; if ( (s.m_datasize > 0 && s.m_datasize <= 65535) ) { m_segments.push_back(s); m_seq=seq+s.m_datasize; } } } /// checka if there's any content in the stream bool has_content() { return m_content; } /// Erase (and free) all segments and reset state void erase() { m_content = false; m_nseq = false; m_segments.clear(); } /// return the streams data size int get_size() { int size = 0; for (std::list<Data_segment>::iterator it = m_segments.begin(); it != m_segments.end(); it ++) { size += it->m_datasize; } return size; } /// debug functionality to dump a streams content void dump() { int start=2; for (std::list<Data_segment>::iterator it = m_segments.begin(); it != m_segments.end(); it ++) { for (unsigned int i=start; i< it->m_datasize; i++) { printf("%02x",it->m_data[i]); } start = 0; } printf("\n"); } /// returns the data in the stream /** The returned data is located in a static buffer shared by all streams * the data is valid until the next call to get_buffer() */ unsigned char *get_buffer() { int p=0; for (std::list<Data_segment>::iterator it = m_segments.begin(); it != m_segments.end(); it ++) { for (unsigned int i=0; i< it->m_datasize; i++) { m_buffer[p++]=it->m_data[i]; if (p>=0xffff) return m_buffer; } } return m_buffer; } private: unsigned int m_seq; int m_ser; bool m_content; bool m_nseq; std::list<Data_segment> m_segments; static unsigned char m_buffer[0x10000]; }; unsigned char Stream::m_buffer[0x10000]; std::map<Stream_id,Stream> g_tcp_streams; /// assemble_tcp builds datastreams out of tcp packets /** TCP packets are inserted into streams. When the streams are closed * the contained data is returned as a pointer the data * it is up to the caller to free() the memory returned. */ unsigned char * assemble_tcp ( Payload &payload, in6addr_t *src_ip, in6addr_t *dst_ip, unsigned short src_port, unsigned short dst_port, unsigned int *rest, unsigned int seq, unsigned char *data, int len, char syn, char fin, char rst, char ack) { Stream_id id ( *src_ip, *dst_ip, src_port, dst_port ); Stream &str = g_tcp_streams[id]; bool data_avail = false; if (!str.has_content()) { Data_segment seg( data, len); str.add( syn,seq, seg); } else { if (rst == 1) { str.erase(); } else if (syn == 1) { str.erase(); Data_segment seg( data, len); str.add( syn,seq, seg); } else { Data_segment seg( data, len); str.add( syn,seq, seg); } } data = 0; if (str.has_content() ) { int size = str.get_size(); unsigned char *buffer = str.get_buffer(); int dns_size = (int(buffer[0])<<8) | buffer[1]; data_avail = (fin == 1) && (rst == 0); if (data_avail || dns_size+2==size) { *rest = size; if (*rest > 0xffff) *rest = 0xffff; data = (unsigned char*)payload.alloc(*rest); memcpy( data, buffer, *rest ); str.erase(); g_tcp_streams.erase(id); } } return data; } }
bool ModLoad(uint Base, uint Size, const char* FullPath) { // // Handle a new module being loaded // // TODO: Do loaded modules always require a path? if(!Base || !Size || !FullPath) return false; MODINFO info; // Copy the module path in the struct strcpy_s(info.path, FullPath); // Break the module path into a directory and file name char dir[MAX_PATH] = ""; char file[MAX_MODULE_SIZE] = ""; strcpy_s(dir, FullPath); _strlwr(dir); char* fileStart = strrchr(dir, '\\'); if(fileStart) { strcpy_s(file, fileStart + 1); *fileStart = '\0'; } //calculate module hash from full file name info.hash = ModHashFromName(file); // Copy the extension into the module struct { char* extensionPos = strrchr(file, '.'); if(extensionPos) { strcpy_s(info.extension, extensionPos); extensionPos[0] = '\0'; } } // Copy the name to the module struct strcpy_s(info.name, file); // Module base address/size info.base = Base; info.size = Size; // Process module sections info.sections.clear(); WString wszFullPath = StringUtils::Utf8ToUtf16(FullPath); if(StaticFileLoadW(wszFullPath.c_str(), UE_ACCESS_READ, false, &info.Handle, &info.FileMapSize, &info.MapHandle, &info.FileMapVA)) { // Get the entry point info.entry = GetPE32DataFromMappedFile(info.FileMapVA, 0, UE_OEP) + info.base; // Enumerate all PE sections int sectionCount = (int)GetPE32DataFromMappedFile(info.FileMapVA, 0, UE_SECTIONNUMBER); for(int i = 0; i < sectionCount; i++) { MODSECTIONINFO curSection; curSection.addr = GetPE32DataFromMappedFile(info.FileMapVA, i, UE_SECTIONVIRTUALOFFSET) + info.base; curSection.size = GetPE32DataFromMappedFile(info.FileMapVA, i, UE_SECTIONVIRTUALSIZE); const char* sectionName = (const char*)GetPE32DataFromMappedFile(info.FileMapVA, i, UE_SECTIONNAME); // Escape section name when needed strcpy_s(curSection.name, StringUtils::Escape(sectionName).c_str()); // Add entry to the vector info.sections.push_back(curSection); } } // Add module to list EXCLUSIVE_ACQUIRE(LockModules); modinfo.insert(std::make_pair(Range(Base, Base + Size - 1), info)); EXCLUSIVE_RELEASE(); SymUpdateModuleList(); return true; }
void deleteAtrac(int atracID) { if (atracMap.find(atracID) != atracMap.end()) { delete atracMap[atracID]; atracMap.erase(atracID); } }
//------------------------------------------------------------------------ //------------------------------------------------------------------------ SmartPointer<Texture> Texture::open(std::string filename,bool bUseCacheIfPossible,bool bCacheInMemory) { if (!filename.length()) { Log::printf("Texture::open cannot open texture because filename is empty\n"); return SmartPointer<Texture>(); } //use cache? if (bUseCacheIfPossible) { if (textures_in_cache.find(Utils::ToLower(filename))!=textures_in_cache.end()) { //Log::printf("Opened texture file %s from cache (already in memory)\n",Filename.c_str()); return textures_in_cache[Utils::ToLower(filename)]; } } //opening from disk juce::File jfile(juce::File::getCurrentWorkingDirectory().getChildFile(filename.c_str())); juce::String jext=jfile.getFileExtension().toLowerCase(); SmartPointer<Texture> ret; if (jext==".tga") { ret=readTga(filename); if (!ret) return ret; //failed } else { juce::Image jimg=juce::ImageFileFormat::loadFrom(jfile); if (!jimg.isValid()) { Log::printf("Texture::open cannot open texture file %s \n",filename.c_str()); return SmartPointer<Texture>(); } int width = jimg.getWidth(); int height = jimg.getHeight(); int bpp = jimg.getFormat()==juce::Image::ARGB? 32 : (jimg.getFormat()==juce::Image::RGB? 24 : (jimg.getFormat()==juce::Image::SingleChannel? 8:0)); if((width == 0) || (height == 0) || !(bpp==24 || bpp==32 || bpp==8)) { Log::printf("Texture::open failed to load the texture file %s (reason unsupported type bpp=%d width=%d height=%d\n",filename.c_str(),bpp,width,height); return SmartPointer<Texture>(); } ret=SmartPointer<Texture>(new Texture(width,height,bpp,0)); unsigned char* dst=ret->buffer; //Alpha if (bpp==8) { for (int Y=0;Y<height;Y++) { for (int X=0;X<width ;X++) { juce::Colour colour=jimg.getPixelAt(X,height-Y-1); //mirror y *dst++=colour.getAlpha(); }} } //RGB else if (bpp==24) { for (int Y=0;Y<height;Y++) { for (int X=0;X<width ;X++) { juce::Colour colour=jimg.getPixelAt(X,height-Y-1); //mirror y *dst++=colour.getRed (); *dst++=colour.getGreen(); *dst++=colour.getBlue (); }} } //RGBA else if (bpp==32) { for (int Y=0;Y<height;Y++) { for (int X=0;X<width ;X++) { juce::Colour colour=jimg.getPixelAt(X,height-Y-1); //mirror y *dst++=colour.getRed (); *dst++=colour.getGreen(); *dst++=colour.getBlue (); *dst++=colour.getAlpha(); }} } } Log::printf("image file %s loaded from disk width(%d) height(%d) bpp(%d)\n",filename.c_str(),ret->width,ret->height,ret->bpp); if (bCacheInMemory) textures_in_cache[Utils::ToLower(filename)]=ret; ret->filename=filename; return ret; }
Operaciones(){ operaciones.insert(std::make_pair("suma", new Sum<T, Func>())); };
void insertBack(std::string s, Func f){ operacionesConApuntadores.insert(std::make_pair(s,f)); };
virtual void OnUnload() override { extdata.clear(); }
virtual void OnDisable() override { extdata.clear(); }
namespace Mod_Pop_ECAttr_Extensions { /* maps ECAttr instances -> extra data instances */ std::map<CTFBot::EventChangeAttributes_t *, CTFBot::ExtraData> extdata; /* maps CTFBot instances -> their current ECAttr instance */ std::map<int, CTFBot::EventChangeAttributes_t *> ecattr_map; #if 0 /* maps CTFBot instances -> their current ECAttr name */ std::map<CHandle<CTFBot>, std::string> ecattr_map; #endif #if 0 const std::string& GetCurrentTFBotECAttrName(CTFBot *bot) { CHandle<CTFBot> handle = bot; auto it = ecattr_map.find(handle); if (it == ecattr_map.end()) { return "default"; } return *it; } #endif // ecattr_map: // clear in OnUnload and SetEnabled(false) // update every time CTFBot::OnEventChangeAttributes is called // const CTFBot::ExtraData& CTFBot::Ext() const { static CTFBot::ExtraData empty; auto it1 = ecattr_map.find(ENTINDEX(this)); if (it1 == ecattr_map.end()) { return empty; } auto ecattr = *it1; auto it2 = extdata.find(ecattr); if (it2 == extdata.end()) { return empty; } return *it2; } class CMod : public IMod { public: CMod() : IMod("Pop:ECAttr_Extensions") { } virtual void OnUnload() override { extdata.clear(); } virtual void OnDisable() override { extdata.clear(); } }; CMod s_Mod; ConVar cvar_enable("sig_pop_ecattr_extensions", "0", FCVAR_NOTIFY, "Mod: enable extended KV in EventChangeAttributes", [](IConVar *pConVar, const char *pOldValue, float flOldValue) { ConVarRef var(pConVar); s_Mod.Toggle(var.GetBool()); }); class CKVCond_ECAttr : public IKVCond { public: virtual bool operator()() override { return s_Mod.IsEnabled(); } }; CKVCond_ECAttr cond; }
int uthread_terminate(int tid) { blockTimer(); if(tid == 0)//if true: exits program { // terminate all threads: std::map<int, Thread*>::iterator threadIt; for (threadIt = gThreads.begin(); threadIt != gThreads.end(); ++threadIt) { Thread* tmp; switch(threadIt->second->getState() ) { case(READY) : gReady.remove(threadIt->second->getID() ); tmp = gThreads[threadIt->second->getID() ]; gThreads.erase(threadIt); delete tmp; break; case(RUNNING) : gThreads.erase(threadIt); // gRunning = NULL; break; case(BLOCKED) : gBlocked.erase(threadIt->second->getID() ); tmp = gThreads[threadIt->second->getID() ]; gThreads.erase(threadIt); delete tmp; break; default : break; } } delete gRunning; gRunning = NULL; resumeTimer(); exit(0); } if(gThreads.count(tid) == 0) //if true: thread doesn't exist { std::cerr<< TERMINATE_ERR << std::endl; resumeTimer(); return FAILURE; } if(gThreads[tid]->getState() == RUNNING)//if true: deletes thread + jumps to next thread { switchThreads(TERMINATED); } // if in ready or blocked: remove from lists (gReady/gBlocked + gThreads), and delete thread Thread* tmp = gThreads[tid]; if (tmp->getState() == READY ) { gReady.remove(tid); } if (tmp->getState() == BLOCKED) { gBlocked.erase(tid); } gThreads.erase(tid); gAvailableID.push(tid); delete tmp; resumeTimer(); return SUCCESS; }
int main() { { typedef std::pair<const int, double> V; V ar[] = { V(1, 1.5), V(2, 2.5), V(3, 3.5), V(4, 4.5), V(5, 5.5), V(7, 7.5), V(8, 8.5), }; std::map<int, double> m(ar, ar+sizeof(ar)/sizeof(ar[0])); assert(m.size() == 7); assert(m.at(1) == 1.5); m.at(1) = -1.5; assert(m.at(1) == -1.5); assert(m.at(2) == 2.5); assert(m.at(3) == 3.5); assert(m.at(4) == 4.5); assert(m.at(5) == 5.5); try { m.at(6); assert(false); } catch (std::out_of_range&) { } assert(m.at(7) == 7.5); assert(m.at(8) == 8.5); assert(m.size() == 7); } { typedef std::pair<const int, double> V; V ar[] = { V(1, 1.5), V(2, 2.5), V(3, 3.5), V(4, 4.5), V(5, 5.5), V(7, 7.5), V(8, 8.5), }; const std::map<int, double> m(ar, ar+sizeof(ar)/sizeof(ar[0])); assert(m.size() == 7); assert(m.at(1) == 1.5); assert(m.at(2) == 2.5); assert(m.at(3) == 3.5); assert(m.at(4) == 4.5); assert(m.at(5) == 5.5); try { m.at(6); assert(false); } catch (std::out_of_range&) { } assert(m.at(7) == 7.5); assert(m.at(8) == 8.5); assert(m.size() == 7); } }
//-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- void RigWellLogExtractor::populateReturnArrays(std::map<RigMDCellIdxEnterLeaveKey, HexIntersectionInfo > &uniqueIntersections) { // For same MD and same cell, remove enter/leave pairs, as they only touches the wellpath, and should not contribute. { std::map<RigMDCellIdxEnterLeaveKey, HexIntersectionInfo >::iterator it1 = uniqueIntersections.begin(); std::map<RigMDCellIdxEnterLeaveKey, HexIntersectionInfo >::iterator it2 = uniqueIntersections.begin(); std::vector<std::map<RigMDCellIdxEnterLeaveKey, HexIntersectionInfo >::iterator> iteratorsToIntersectonsToErase; while (it2 != uniqueIntersections.end()) { ++it2; if (it2 != uniqueIntersections.end()) { if (RigWellLogExtractionTools::isEqualDepth(it1->first.measuredDepth, it2->first.measuredDepth)) { if (it1->first.hexIndex == it2->first.hexIndex) { // Remove the two from the map, as they just are a touch of the cell surface CVF_TIGHT_ASSERT(!it1->first.isEnteringCell && it2->first.isEnteringCell); iteratorsToIntersectonsToErase.push_back(it1); iteratorsToIntersectonsToErase.push_back(it2); } } } ++it1; } // Erase all the intersections that is not needed for (size_t erItIdx = 0; erItIdx < iteratorsToIntersectonsToErase.size(); ++erItIdx) { uniqueIntersections.erase(iteratorsToIntersectonsToErase[erItIdx]); } } // Copy the map into a different sorting regime, with enter leave more significant than cell index std::map<RigMDEnterLeaveCellIdxKey, HexIntersectionInfo > sortedUniqueIntersections; { std::map<RigMDCellIdxEnterLeaveKey, HexIntersectionInfo >::iterator it = uniqueIntersections.begin(); while (it != uniqueIntersections.end()) { sortedUniqueIntersections.insert(std::make_pair(RigMDEnterLeaveCellIdxKey(it->first.measuredDepth, it->first.isEnteringCell, it->first.hexIndex), it->second)); ++it; } } // Add points for the endpoint of the wellpath, if it starts/ends inside a cell { // Add an intersection for the well startpoint that is inside the first cell std::map<RigMDEnterLeaveCellIdxKey, HexIntersectionInfo >::iterator it = sortedUniqueIntersections.begin(); if (it != sortedUniqueIntersections.end() && !it->first.isEnteringCell) // Leaving a cell as first intersection. Well starts inside a cell. { // Needs wellpath start point in front HexIntersectionInfo firstLeavingPoint = it->second; firstLeavingPoint.m_intersectionPoint = m_wellPath->m_wellPathPoints[0]; firstLeavingPoint.m_face = cvf::StructGridInterface::NO_FACE; firstLeavingPoint.m_isIntersectionEntering = true; sortedUniqueIntersections.insert(std::make_pair(RigMDEnterLeaveCellIdxKey(m_wellPath->m_measuredDepths[0], true, firstLeavingPoint.m_hexIndex), firstLeavingPoint)); } // Add an intersection for the well endpoint possibly inside the last cell. std::map<RigMDEnterLeaveCellIdxKey, HexIntersectionInfo >::reverse_iterator rit = sortedUniqueIntersections.rbegin(); if (rit != sortedUniqueIntersections.rend() && rit->first.isEnteringCell) // Entering a cell as last intersection. Well ends inside a cell. { // Needs wellpath end point at end HexIntersectionInfo lastEnterPoint = rit->second; lastEnterPoint.m_intersectionPoint = m_wellPath->m_wellPathPoints.back(); lastEnterPoint.m_isIntersectionEntering = false; lastEnterPoint.m_face = cvf::StructGridInterface::NO_FACE; sortedUniqueIntersections.insert(std::make_pair(RigMDEnterLeaveCellIdxKey(m_wellPath->m_measuredDepths.back(), false, lastEnterPoint.m_hexIndex), lastEnterPoint)); } } // Filter and store the intersections pairwise as cell enter-leave pairs // Discard points that does not have a match . { std::map<RigMDEnterLeaveCellIdxKey, HexIntersectionInfo >::iterator it1 = sortedUniqueIntersections.begin(); std::map<RigMDEnterLeaveCellIdxKey, HexIntersectionInfo >::iterator it2; while (it1 != sortedUniqueIntersections.end()) { it2 = it1; ++it2; if (it2 == sortedUniqueIntersections.end()) break; if (RigMDEnterLeaveCellIdxKey::isProperCellEnterLeavePair(it1->first, it2->first)) { appendIntersectionToArrays(it1->first.measuredDepth, it1->second); ++it1; appendIntersectionToArrays(it1->first.measuredDepth, it1->second); ++it1; } else { // If we haven't a proper pair, try our best to recover these variants: // 1-2 3 4 5 6 7 8 9 10 11-12 // +---+ // +---+ // +---+ std::map<RigMDEnterLeaveCellIdxKey, HexIntersectionInfo >::iterator it11 = it1; std::map<RigMDEnterLeaveCellIdxKey, HexIntersectionInfo >::iterator it21 = it2; // Check if we have overlapping cells (typically at a fault) ++it21; if (it21 != sortedUniqueIntersections.end() && RigMDEnterLeaveCellIdxKey::isProperCellEnterLeavePair(it11->first, it21->first)) { // Found 3 to 5 connection appendIntersectionToArrays(it11->first.measuredDepth, it11->second); appendIntersectionToArrays(it21->first.measuredDepth, it21->second); ++it11; ++it21; if (it21 != sortedUniqueIntersections.end() && RigMDEnterLeaveCellIdxKey::isProperCellEnterLeavePair(it11->first, it21->first)) { // Found a 4 to 6 connection appendIntersectionToArrays(it11->first.measuredDepth, it11->second); appendIntersectionToArrays(it21->first.measuredDepth, it21->second); it1 = it21; ++it1; continue; } else { RiaLogging::warning(QString("Well Log Extraction : ") + QString::fromStdString(m_wellCaseErrorMsgName) + (" Discards a point at MD: ") + QString::number((double)(it1->first.measuredDepth))); // Found that 8 to 10 is not connected, after finding 7 to 9 it1 = it21; // Discard 8 by Jumping to 10 continue; } } else { RiaLogging::warning(QString("Well Log Extraction : ") + QString::fromStdString(m_wellCaseErrorMsgName) + (" Discards a point at MD: ") + QString::number((double)(it1->first.measuredDepth))); // Found that 10 to 11 is not connected, and not 10 to 12 either ++it1; // Discard 10 and jump to 11 and hope that recovers us continue; } } } } }
void OBJWriter::write(const std::shared_ptr<gameplay::Model>& model, const std::string& baseName, const std::map<loader::TextureLayoutProxy::TextureKey, std::shared_ptr<gameplay::Material>>& mtlMap1, const std::map<loader::TextureLayoutProxy::TextureKey, std::shared_ptr<gameplay::Material>>& mtlMap2, const glm::vec3& ambientColor) const { Expects(model != nullptr); auto fullPath = m_basePath / baseName; Assimp::Exporter exporter; std::string formatIdentifier; for(size_t i = 0; i < exporter.GetExportFormatCount(); ++i) { auto descr = exporter.GetExportFormatDescription(i); BOOST_ASSERT(descr != nullptr); std::string exporterExtension = std::string(".") + descr->fileExtension; if(exporterExtension == fullPath.extension().string()) { formatIdentifier = descr->id; break; } } if(formatIdentifier.empty()) { BOOST_LOG_TRIVIAL(error) << "Failed to find an exporter for the supplied file extension"; BOOST_LOG_TRIVIAL(info) << "Here's the list of registered exporters"; for(size_t i = 0; i < exporter.GetExportFormatCount(); ++i) { auto descr = exporter.GetExportFormatDescription(i); BOOST_ASSERT(descr != nullptr); BOOST_LOG_TRIVIAL(info) << descr->description << ", extension `" << descr->fileExtension << "`, id `" << descr->id << "`"; } BOOST_THROW_EXCEPTION(std::runtime_error("Failed to find an exporter for the supplied file extension")); } std::unique_ptr<aiScene> scene = std::make_unique<aiScene>(); BOOST_ASSERT(scene->mRootNode == nullptr); scene->mRootNode = new aiNode(); { size_t totalPartCount = 0; for( const auto& mesh : model->getMeshes() ) { totalPartCount += mesh->getPartCount(); } scene->mNumMaterials = totalPartCount; scene->mMaterials = new aiMaterial*[totalPartCount]; std::fill_n(scene->mMaterials, totalPartCount, nullptr); scene->mNumMeshes = totalPartCount; scene->mMeshes = new aiMesh*[totalPartCount]; std::fill_n(scene->mMeshes, totalPartCount, nullptr); scene->mRootNode->mNumMeshes = totalPartCount; scene->mRootNode->mMeshes = new unsigned int[totalPartCount]; for( size_t i = 0; i < totalPartCount; ++i ) scene->mRootNode->mMeshes[i] = i; } for( size_t mi = 0, globalPartIndex = 0; mi < model->getMeshes().size(); ++mi ) { BOOST_ASSERT(mi < scene->mNumMeshes); const auto& mesh = model->getMeshes()[mi]; for( size_t pi = 0; pi < mesh->getPartCount(); ++pi , ++globalPartIndex ) { BOOST_ASSERT(globalPartIndex < scene->mNumMaterials); const std::shared_ptr<gameplay::MeshPart>& part = mesh->getPart(pi); scene->mMeshes[globalPartIndex] = new aiMesh(); aiMesh* outMesh = scene->mMeshes[globalPartIndex]; allocateElementMemory(mesh, outMesh); copyVertexData(mesh, outMesh); BOOST_ASSERT(part->getPrimitiveType() == gameplay::Mesh::PrimitiveType::TRIANGLES && part->getIndexCount() % 3 == 0); outMesh->mMaterialIndex = globalPartIndex; scene->mMaterials[globalPartIndex] = new aiMaterial(); scene->mMaterials[globalPartIndex]->AddProperty(new aiColor4D(ambientColor.r, ambientColor.g, ambientColor.b, 1), 1, AI_MATKEY_COLOR_AMBIENT); { // try to find the texture for our material using Entry = decltype(*mtlMap1.begin()); auto finder = [&part](const Entry& entry) { return entry.second == part->getMaterial(); }; auto texIt = std::find_if(mtlMap1.begin(), mtlMap1.end(), finder); bool found = false; if( texIt != mtlMap1.end() ) { scene->mMaterials[globalPartIndex]->AddProperty(new aiString(makeTextureName(texIt->first.tileAndFlag & TextureIndexMask) + ".png"), AI_MATKEY_TEXTURE_DIFFUSE(0)); found = true; } if( !found ) { texIt = std::find_if(mtlMap2.begin(), mtlMap2.end(), finder); if( texIt != mtlMap2.end() ) { scene->mMaterials[globalPartIndex]->AddProperty(new aiString(makeTextureName(texIt->first.tileAndFlag & TextureIndexMask) + ".png"), AI_MATKEY_TEXTURE_DIFFUSE(0)); } } } outMesh->mNumFaces = part->getIndexCount() / 3; outMesh->mFaces = new aiFace[outMesh->mNumFaces]; switch( part->getIndexFormat() ) { case gameplay::Mesh::INDEX8: copyIndices<uint8_t>(part, outMesh); break; case gameplay::Mesh::INDEX16: copyIndices<uint16_t>(part, outMesh); break; case gameplay::Mesh::INDEX32: copyIndices<uint32_t>(part, outMesh); break; default: break; } } } exporter.Export(scene.get(), formatIdentifier.c_str(), fullPath.string(), aiProcess_JoinIdenticalVertices | aiProcess_ValidateDataStructure | aiProcess_FlipUVs); }
Atrac *getAtrac(int atracID) { if (atracMap.find(atracID) == atracMap.end()) { return NULL; } return atracMap[atracID]; }
void UpdateAI(const uint32 diff) { if (!UpdateVictim()) { if (checkTimer < diff) { if (phase != EVENT_NULL && phase != EVENT_FIGHT) { bool found = false; for (std::map<uint64, uint8>::iterator it = prisoners.begin(); it != prisoners.end(); it++) { if (it->second == phase) { if (Creature *pPrisoner = me->GetCreature(it->first)) { if (pPrisoner->isAlive()) { found = true; break; } } } } if (!found) DoAction(uint8(phase) +1); } checkTimer = 2000; } else checkTimer -= diff; return; } if (AcidSpray_Timer < diff) { AddSpellToCast(me->getVictim(),SPELL_SLIME_SPRAY); AcidSpray_Timer = urand(4000, 12000); } else AcidSpray_Timer -=diff; if (PoisonBolt_Timer < diff) { AddSpellToCast(me->getVictim(), SPELL_POISON_BOLT); PoisonBolt_Timer = urand(4000, 12000);; } else PoisonBolt_Timer -=diff; if (PoisonSpawn_Timer < diff) { AddSpellToCast(me, SPELL_POISON_CLOUD); PoisonSpawn_Timer = 20000; } else PoisonSpawn_Timer -=diff; CastNextSpellIfAnyAndReady(); DoMeleeAttackIfReady(); }
//------------------------------------------------------------------------ //------------------------------------------------------------------------ void Texture::flushCache() { textures_in_cache.clear(); }
void mutation_branch::reset_all() { mutations_category.clear(); mutation_data.clear(); }
/** TCP packets are inserted into streams. When the streams are closed * the contained data is returned as a pointer the data * it is up to the caller to free() the memory returned. */ unsigned char * assemble_tcp ( Payload &payload, in6addr_t *src_ip, in6addr_t *dst_ip, unsigned short src_port, unsigned short dst_port, unsigned int *rest, unsigned int seq, unsigned char *data, int len, char syn, char fin, char rst, char ack) { Stream_id id ( *src_ip, *dst_ip, src_port, dst_port ); Stream &str = g_tcp_streams[id]; bool data_avail = false; if (!str.has_content()) { Data_segment seg( data, len); str.add( syn,seq, seg); } else { if (rst == 1) { str.erase(); } else if (syn == 1) { str.erase(); Data_segment seg( data, len); str.add( syn,seq, seg); } else { Data_segment seg( data, len); str.add( syn,seq, seg); } } data = 0; if (str.has_content() ) { int size = str.get_size(); unsigned char *buffer = str.get_buffer(); int dns_size = (int(buffer[0])<<8) | buffer[1]; data_avail = (fin == 1) && (rst == 0); if (data_avail || dns_size+2==size) { *rest = size; if (*rest > 0xffff) *rest = 0xffff; data = (unsigned char*)payload.alloc(*rest); memcpy( data, buffer, *rest ); str.erase(); g_tcp_streams.erase(id); } } return data; }
void PluginUtils::setPluginJavaData(PluginProtocol* pKeyObj, PluginJavaData* pData) { erasePluginJavaData(pKeyObj); s_PluginObjMap.insert(std::pair<PluginProtocol*, PluginJavaData*>(pKeyObj, pData)); s_JObjPluginMap.insert(std::pair<std::string, PluginProtocol*>(pData->jclassName, pKeyObj)); }
/* Function that returns the ID of the most dangerous neighboring plane and its ZEM. */ sim::threatContainer sim::findGreatestThreat(PlaneObject &plane1, std::map<int, PlaneObject> &planes) { /* Set reference for origin (Northwest corner of the course)*/ sim::coordinate origin; origin.latitude = 32.606573; origin.longitude = -85.490356; origin.altitude = 400; /* Set preliminary plane to avoid as non-existent and most dangerous ZEM as negative */ int planeToAvoid = -1; int iPlaneToAvoid = -1; double mostDangerousZEM = -1.0; double iMostDangerousZEM = -1.0; /* Set the preliminary time-to-go high */ double minimumTimeToGo = MINIMUM_TIME_TO_GO; double iMinimumTimeToGo = 3.5; /* Declare second plane and ID variable */ PlaneObject plane2; int ID; /* Make a position vector representation of the current plane */ double magnitude2, direction2; double magnitude = findDistance(origin.latitude, origin.longitude, plane1.getCurrentLoc().latitude, plane1.getCurrentLoc().longitude); double direction = findAngle(origin.latitude, origin.longitude, plane1.getCurrentLoc().latitude, plane1.getCurrentLoc().longitude); sim::mathVector p1(magnitude,direction); /* Make a heading vector representation of the current plane */ sim::mathVector d1(1.0,toCartesian(plane1.getCurrentBearing())); /* Declare variables needed for this loop */ sim::mathVector pDiff, dDiff; double timeToGo, zeroEffortMiss, distanceBetween, timeToDest, bearingDiff; std::map<int,sim::PlaneObject>::iterator it; for (it=planes.begin() ; it!= planes.end(); it++) { /* Unpacking plane to check */ ID = (*it).first; plane2 = (*it).second; /* If it's not in the Check Zone, check the other plane */ distanceBetween = plane1.findDistance(plane2); if (distanceBetween > CHECK_ZONE || plane1.getID() == ID) continue; /* Making a position vector representation of plane2 */ magnitude2 = findDistance(origin.latitude, origin.longitude, plane2.getCurrentLoc().latitude, plane2.getCurrentLoc().longitude); direction2 = findAngle(origin.latitude, origin.longitude, plane2.getCurrentLoc().latitude, plane2.getCurrentLoc().longitude); sim::mathVector p2(magnitude2,direction2); /* Make a heading vector representation of the other plane */ sim::mathVector d2(1.0,toCartesian(plane2.getCurrentBearing())); /* Compute time-to-go */ pDiff = p1-p2; dDiff = d1-d2; timeToGo = -1.0*pDiff.dotProduct(dDiff)/(MPS_SPEED*dDiff.dotProduct(dDiff)); /* Compute Zero Effort Miss */ zeroEffortMiss = sqrt(fabs(pDiff.dotProduct(pDiff) + 2.0*(MPS_SPEED*timeToGo)*pDiff.dotProduct(dDiff) + pow(MPS_SPEED*timeToGo,2.0)*dDiff.dotProduct(dDiff))); if( zeroEffortMiss > DANGER_ZEM || (timeToGo > minimumTimeToGo && timeToGo > iMinimumTimeToGo) || timeToGo < 0 ) continue; timeToDest = plane1.findDistance(plane1.getDestination().latitude, plane1.getDestination().longitude) / MPS_SPEED; /* If you're close to your destination and the other plane isn't much of a threat, then don't avoid it */ if ( timeToDest < 5.0 && zeroEffortMiss > 3.0*MPS_SPEED ) continue; /* If you're likely to zigzag, don't avoid the other plane */ bearingDiff = fabs(plane1.getCurrentBearing() - planes[ID].getCurrentBearing()); if ( plane1.findDistance(planes[ID]) > 3.5*MPS_SPEED && bearingDiff < CHATTERING_ANGLE) continue; /* Second Threshold, to prevent planes from flying into others when trying to avoid less imminent collisions */ if ( zeroEffortMiss <= SECOND_THRESHOLD && timeToGo <= iMinimumTimeToGo ) { iPlaneToAvoid = ID; iMostDangerousZEM = zeroEffortMiss; iMinimumTimeToGo = timeToGo; continue; } planeToAvoid = ID; mostDangerousZEM = zeroEffortMiss; minimumTimeToGo = timeToGo; } sim::threatContainer greatestThreat; if (iPlaneToAvoid > -1) { greatestThreat.planeID = iPlaneToAvoid; greatestThreat.ZEM = iMostDangerousZEM; greatestThreat.timeToGo = iMinimumTimeToGo; } else { greatestThreat.planeID = planeToAvoid; greatestThreat.ZEM = mostDangerousZEM; greatestThreat.timeToGo = minimumTimeToGo; } return greatestThreat; }
namespace cocos2d { namespace plugin { #define JAVAVM cocos2d::PluginJniHelper::getJavaVM() void PluginUtils::initPluginWrapper(android_app* app) { PluginJniMethodInfo t; if (! PluginJniHelper::getStaticMethodInfo(t , "org/cocos2dx/plugin/PluginWrapper" , "initFromNativeActivity" , "(Landroid/app/Activity;)V")) { outputLog("PluginUtils", "Failed to init context of plugin"); return; } t.env->CallStaticVoidMethod(t.classID, t.methodID, app->activity->clazz); t.env->DeleteLocalRef(t.classID); } jobject PluginUtils::createJavaMapObject(std::map<std::string, std::string>* paramMap) { JNIEnv* env = getEnv(); jclass class_Hashtable = env->FindClass("java/util/Hashtable"); jmethodID construct_method = env->GetMethodID( class_Hashtable, "<init>","()V"); jobject obj_Map = env->NewObject( class_Hashtable, construct_method, ""); if (paramMap != NULL) { jmethodID add_method= env->GetMethodID( class_Hashtable,"put","(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); for (std::map<std::string, std::string>::const_iterator it = paramMap->begin(); it != paramMap->end(); ++it) { env->CallObjectMethod(obj_Map, add_method, env->NewStringUTF(it->first.c_str()), env->NewStringUTF(it->second.c_str())); } } env->DeleteLocalRef(class_Hashtable); return obj_Map; } void PluginUtils::initJavaPlugin(PluginProtocol* pPlugin, jobject jObj, const char* className) { cocos2d::plugin::PluginJavaData* pUserData = new cocos2d::plugin::PluginJavaData(); pUserData->jobj = PluginUtils::getEnv()->NewGlobalRef(jObj); pUserData->jclassName = className; cocos2d::plugin::PluginUtils::setPluginJavaData(pPlugin, pUserData); } JNIEnv* PluginUtils::getEnv() { bool bRet = false; JNIEnv* env = NULL; do { if (JAVAVM->GetEnv((void**)&env, JNI_VERSION_1_4) != JNI_OK) { outputLog("PluginUtils", "Failed to get the environment using GetEnv()"); break; } if (JAVAVM->AttachCurrentThread(&env, 0) < 0) { outputLog("PluginUtils", "Failed to get the environment using AttachCurrentThread()"); break; } bRet = true; } while (0); if (!bRet) { env = NULL; } return env; } std::map<PluginProtocol*, PluginJavaData*> s_PluginObjMap; std::map<std::string, PluginProtocol*> s_JObjPluginMap; typedef std::map<PluginProtocol*, PluginJavaData*>::iterator ObjMapIter; typedef std::map<std::string, PluginProtocol*>::iterator JObjPluginMapIter; PluginJavaData* PluginUtils::getPluginJavaData(PluginProtocol* pKeyObj) { PluginJavaData* ret = NULL; ObjMapIter it = s_PluginObjMap.find(pKeyObj); if (it != s_PluginObjMap.end()) { ret = it->second; } return ret; } PluginProtocol* PluginUtils::getPluginPtr(std::string className) { PluginProtocol* ret = NULL; JObjPluginMapIter it = s_JObjPluginMap.find(className); if (it != s_JObjPluginMap.end()) { ret = it->second; } return ret; } void PluginUtils::setPluginJavaData(PluginProtocol* pKeyObj, PluginJavaData* pData) { erasePluginJavaData(pKeyObj); s_PluginObjMap.insert(std::pair<PluginProtocol*, PluginJavaData*>(pKeyObj, pData)); s_JObjPluginMap.insert(std::pair<std::string, PluginProtocol*>(pData->jclassName, pKeyObj)); } void PluginUtils::erasePluginJavaData(PluginProtocol* pKeyObj) { ObjMapIter it = s_PluginObjMap.find(pKeyObj); if (it != s_PluginObjMap.end()) { PluginJavaData* pData = it->second; if (pData != NULL) { jobject jobj = pData->jobj; JObjPluginMapIter pluginIt = s_JObjPluginMap.find(pData->jclassName); if (pluginIt != s_JObjPluginMap.end()) { s_JObjPluginMap.erase(pluginIt); } JNIEnv* pEnv = getEnv(); outputLog("PluginUtils", "Delete global reference."); pEnv->DeleteGlobalRef(jobj); delete pData; } s_PluginObjMap.erase(it); } } void PluginUtils::outputLog(const char* logTag, const char* pFormat, ...) { char buf[MAX_LOG_LEN + 1]; va_list args; va_start(args, pFormat); vsnprintf(buf, MAX_LOG_LEN, pFormat, args); va_end(args); __android_log_print(ANDROID_LOG_DEBUG, logTag, "%s", buf); } jobject PluginUtils::getJObjFromParam(PluginParam* param) { if (NULL == param) { return NULL; } jobject obj = NULL; PluginJniMethodInfo t; JNIEnv* env = PluginUtils::getEnv(); switch(param->getCurrentType()) { case PluginParam::kParamTypeInt: if (PluginJniHelper::getStaticMethodInfo(t, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;")) { obj = t.env->CallStaticObjectMethod(t.classID, t.methodID, param->getIntValue()); } break; case PluginParam::kParamTypeFloat: if (PluginJniHelper::getStaticMethodInfo(t, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;")) { obj = t.env->CallStaticObjectMethod(t.classID, t.methodID, param->getFloatValue()); } break; case PluginParam::kParamTypeBool: if (PluginJniHelper::getStaticMethodInfo(t, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;")) { obj = t.env->CallStaticObjectMethod(t.classID, t.methodID, param->getBoolValue()); } break; case PluginParam::kParamTypeString: obj = env->NewStringUTF(param->getStringValue()); break; case PluginParam::kParamTypeStringMap: { jclass cls = env->FindClass("org/json/JSONObject"); jmethodID mid = env->GetMethodID(cls,"<init>","()V"); obj = env->NewObject(cls,mid); std::map<std::string, std::string>::iterator it; std::map<std::string, std::string> mapParam = param->getStrMapValue(); for (it = mapParam.begin(); it != mapParam.end(); it++) { PluginJniMethodInfo tInfo; if (PluginJniHelper::getMethodInfo(tInfo, "org/json/JSONObject", "put", "(Ljava/lang/String;Ljava/lang/Object;)Lorg/json/JSONObject;")) { jstring strKey = tInfo.env->NewStringUTF(it->first.c_str()); jstring strValue = tInfo.env->NewStringUTF(it->second.c_str()); tInfo.env->CallObjectMethod(obj, tInfo.methodID, strKey, strValue); tInfo.env->DeleteLocalRef(tInfo.classID); tInfo.env->DeleteLocalRef(strKey); tInfo.env->DeleteLocalRef(strValue); } } } break; case PluginParam::kParamTypeMap: { jclass cls = env->FindClass("org/json/JSONObject"); jmethodID mid = env->GetMethodID(cls,"<init>","()V"); obj = env->NewObject(cls,mid); std::map<std::string, PluginParam*>::iterator it; std::map<std::string, PluginParam*> mapParam = param->getMapValue(); for (it = mapParam.begin(); it != mapParam.end(); it++) { PluginJniMethodInfo tInfo; if (PluginJniHelper::getMethodInfo(tInfo, "org/json/JSONObject", "put", "(Ljava/lang/String;Ljava/lang/Object;)Lorg/json/JSONObject;")) { jstring strKey = tInfo.env->NewStringUTF(it->first.c_str()); jobject objValue = PluginUtils::getJObjFromParam(it->second); tInfo.env->CallObjectMethod(obj, tInfo.methodID, strKey, objValue); tInfo.env->DeleteLocalRef(tInfo.classID); tInfo.env->DeleteLocalRef(strKey); PluginUtils::getEnv()->DeleteLocalRef(objValue); } } } break; default: break; } return obj; } }}// namespace cocos2d { namespace plugin {
void delegate_runner::create_process() { char path[MAX_PATH + 1]; if (GetFullPathNameA(program_to_run.c_str(), MAX_PATH, path, NULL)) { program_to_run = path; } options.push_argument_front(program_to_run); if (options.use_cmd) { options.push_argument_front("--cmd"); } options.use_cmd = true; const std::map< restriction_kind_t, std::string > cmd_units = { { restriction_user_time_limit, "ms" }, { restriction_memory_limit, "B" }, { restriction_processor_time_limit, "us" }, { restriction_security_limit, "" }, { restriction_write_limit, "B" }, { restriction_load_ratio, "" }, { restriction_idle_time_limit, "us" }, { restriction_processes_count_limit, "" } }; const std::map< restriction_kind_t, std::string > cmd_arg = { { restriction_user_time_limit, "tl" }, { restriction_memory_limit, "ml" }, { restriction_processor_time_limit, "d" }, { restriction_security_limit, "s" }, { restriction_write_limit, "wl" }, { restriction_load_ratio, "lr" }, { restriction_idle_time_limit, "y" }, { restriction_processes_count_limit, "only-process" } }; for (int i = 0; i < restriction_max; ++i) { if (restrictions.restrictions[i] != restriction_no_limit) { std::string argument = "-" + cmd_arg.find((restriction_kind_t)i)->second; argument += " " + std::to_string(restrictions.restrictions[i]); argument += cmd_units.find((restriction_kind_t)i)->second; options.push_argument_front(argument); } } auto process_pipes = [](options_class& options, const std::vector<std::string>& vals, const std::string& prefix) { for (auto i = vals.cbegin(); i != vals.cend(); ++i) { options.push_argument_front(prefix + *i); } }; process_pipes(options, options.stderror, "--err="); process_pipes(options, options.stdoutput, "--out="); process_pipes(options, options.stdinput, "--in="); std::string working_directory = options.working_directory; if (working_directory.length() == 0) { char dir[MAX_PATH + 1]; GetCurrentDirectoryA(MAX_PATH, dir); working_directory = dir; } options.push_argument_front("-wd \"" + working_directory + "\""); if (options.hide_report) { options.push_argument_front("-hr 1"); } for (auto i = options.environmentVars.cbegin(); i != options.environmentVars.cend(); ++i) { options.push_argument_front("-D " + i->first + "=" + i->second); } if (options.json) { options.push_argument_front("--json"); } options.push_argument_front("-env " + options.environmentMode); std::string shared_memory_name = "mem" + options.session.hash(); options.push_argument_front("--shared-memory=" + shared_memory_name); CreateFileMappingA( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, options_class::SHARED_MEMORY_BUF_SIZE, shared_memory_name.c_str() ); options.shared_memory = shared_memory_name; options.push_argument_front("--delegated:1"); runner::create_process(); }
void genControlInfo(int* oid, size_t oid_size, QueryData& results, const std::map<std::string, std::string>& config) { Row r; if (oid_size == 0) { return; } r["oid"] = stringFromMIB(oid, oid_size); // Request the description (the canonical name) for the MIB. char response[CTL_MAX_VALUE] = {0}; size_t response_size = CTL_MAX_VALUE; int request[CTL_MAXNAME + 2] = {0, CTL_DEBUG_DESCRIPTION}; memcpy(request + 2, oid, oid_size * sizeof(int)); if (sysctl(request, oid_size + 2, response, &response_size, 0, 0) != 0) { return; } r["name"] = std::string(response); if (oid[0] > 0 && oid[0] < static_cast<int>(kControlNames.size())) { r["subsystem"] = kControlNames[oid[0]]; } // Now request structure type. response_size = CTL_MAX_VALUE; request[1] = CTL_DEBUG_TYPE; if (sysctl(request, oid_size + 2, response, &response_size, 0, 0) != 0) { // Cannot request MIB type (int, string, struct, etc). return; } size_t oid_type = 0; if (response_size > 0) { oid_type = ((size_t)response[0] & CTLTYPE); if ((oid_type == 0 || oid_type == CTLTYPE_INT) && response_size > 4) { // For whatever reason, macOS defines fewer CTLTYPE's than BSD, and // sometimes uses the format character instead of (or in addition to) // the CTLTYPE to specify the type. Here we detect a few such cases and // map them to CTLTYPE's. // TODO: Both CTLTYPE_INT and CTLTYPE_QUAD can be specified as unsigned // using a similar method. char type_char = response[4]; switch (type_char) { case 'I': oid_type = CTLTYPE_INT; break; case 'L': if (sizeof(long) == sizeof(long long)) { oid_type = CTLTYPE_QUAD; } else if (sizeof(long) == sizeof(int)) { oid_type = CTLTYPE_INT; } break; case 'S': oid_type = CTLTYPE_STRUCT; break; case 'Q': oid_type = CTLTYPE_QUAD; break; // Otherwise leave the type as it was; we have no additional knowledge } } if (oid_type < kControlTypes.size()) { r["type"] = kControlTypes[oid_type]; } } // Finally request MIB value. if (oid_type > CTLTYPE_NODE && oid_type < CTLTYPE_OPAQUE) { size_t value_size = 0; sysctl(oid, oid_size, 0, &value_size, 0, 0); if (value_size > CTL_MAX_VALUE) { // If the value size is larger than the max value, limit. value_size = CTL_MAX_VALUE; } sysctl(oid, oid_size, response, &value_size, 0, 0); if (oid_type == CTLTYPE_INT) { unsigned int value; memcpy(&value, response, sizeof(int)); r["current_value"] = INTEGER(value); } else if (oid_type == CTLTYPE_STRING) { r["current_value"] = std::string(response); } else if (oid_type == CTLTYPE_QUAD) { unsigned long long value; memcpy(&value, response, sizeof(unsigned long long)); r["current_value"] = INTEGER(value); } } // If this MIB was set using sysctl.conf add the value. if (config.count(r.at("name")) > 0) { r["config_value"] = config.at(r["name"]); } results.push_back(r); }
inline void Symbol::InferExecutorArrays( const Context &context, std::vector<NDArray> *arg_arrays, std::vector<NDArray> *grad_arrays, std::vector<OpReqType> *grad_reqs, std::vector<NDArray> *aux_arrays, const std::map<std::string, NDArray> &args_map, const std::map<std::string, NDArray> &arg_grad_store, const std::map<std::string, OpReqType> &grad_req_type, const std::map<std::string, NDArray> &aux_map) const { const auto arg_name_list = ListArguments(); std::vector<std::vector<mx_uint> > in_shapes, aux_shapes, out_shapes; std::map<std::string, std::vector<mx_uint> > arg_shapes; for (const auto &arg_name : arg_name_list) { auto iter = args_map.find(arg_name); if (iter != args_map.end()) { arg_shapes[arg_name] = iter->second.GetShape(); } } InferShape(arg_shapes, &in_shapes, &aux_shapes, &out_shapes); for (size_t i = 0; i < in_shapes.size(); ++i) { const auto &shape = in_shapes[i]; const auto &arg_name = arg_name_list[i]; auto iter_arg = args_map.find(arg_name); if (iter_arg != args_map.end()) { arg_arrays->push_back(iter_arg->second); } else { arg_arrays->push_back(NDArray(shape, context, false)); NDArray::SampleGaussian(0, 1, &arg_arrays->back()); } auto iter_grad = arg_grad_store.find(arg_name); if (iter_grad != arg_grad_store.end()) { grad_arrays->push_back(iter_grad->second); } else { grad_arrays->push_back(NDArray(shape, context, false)); } auto iter_req = grad_req_type.find(arg_name); if (iter_req != grad_req_type.end()) { grad_reqs->push_back(iter_req->second); } else if (arg_name.rfind("data") == arg_name.length() - 4 || arg_name.rfind("label") == arg_name.length() - 5) { grad_reqs->push_back(OpReqType::kNullOp); } else { grad_reqs->push_back(OpReqType::kWriteTo); } } const auto aux_name_list = ListAuxiliaryStates(); for (size_t i = 0; i < aux_shapes.size(); ++i) { const auto &shape = aux_shapes[i]; const auto &aux_name = aux_name_list[i]; auto iter_aux = aux_map.find(aux_name); if (iter_aux != aux_map.end()) { aux_arrays->push_back(iter_aux->second); } else { aux_arrays->push_back(NDArray(shape, context, false)); NDArray::SampleGaussian(0, 1, &aux_arrays->back()); } } }
namespace Platform { #ifdef OLYMPIA_LINUX_USE_MMAP static std::map<void*, int> s_blockSizes; #endif void initializeMemoryManagement() { return; } unsigned pageSize() { #if defined(OLYMPIA_LINUX) || defined(OLYMPIA_MAC) return sysconf(_SC_PAGE_SIZE); #elif defined(OLYMPIA_WINDOWS) SYSTEM_INFO system_info; GetSystemInfo(&system_info); return system_info.dwPageSize; #endif } void* allocateJSBlock(unsigned size) { // See: JavaScriptCore/runtime/Collector.cpp OLYMPIA_ASSERT(size == BLOCK_SIZE); #if defined(OLYMPIA_LINUX) //|| defined(OLYMPIA_MAC) #if ENABLE(JSC_MULTIPLE_THREADS) #error Need to initialize pagesize safely. #endif static size_t pagesize = pageSize(); size_t extra = 0; if (BLOCK_SIZE > pagesize) extra = BLOCK_SIZE - pagesize; void* mmapResult = mmap(NULL, BLOCK_SIZE + extra, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); uintptr_t address = reinterpret_cast<uintptr_t>(mmapResult); size_t adjust = 0; if ((address & BLOCK_OFFSET_MASK) != 0) adjust = BLOCK_SIZE - (address & BLOCK_OFFSET_MASK); if (adjust > 0) munmap(reinterpret_cast<char*>(address), adjust); if (adjust < extra) munmap(reinterpret_cast<char*>(address + adjust + BLOCK_SIZE), extra - adjust); address += adjust; return reinterpret_cast<void*>(address); #elif defined(OLYMPIA_WINDOWS) #if COMPILER(MINGW) && !COMPILER(MINGW64) void* address = __mingw_aligned_malloc(BLOCK_SIZE, BLOCK_SIZE); #else void* address = _aligned_malloc(BLOCK_SIZE, BLOCK_SIZE); #endif memset(address, 0, BLOCK_SIZE); return address; #elif defined(OLYMPIA_MAC) vm_address_t address = 0; vm_map(current_task(), &address, BLOCK_SIZE, BLOCK_OFFSET_MASK, VM_FLAGS_ANYWHERE | VM_TAG_FOR_COLLECTOR_MEMORY, MEMORY_OBJECT_NULL, 0, FALSE, VM_PROT_DEFAULT, VM_PROT_DEFAULT, VM_INHERIT_DEFAULT); return reinterpret_cast<void*>(address); #endif } void freeJSBlock(void* address) { #if defined(OLYMPIA_LINUX)// || defined(OLYMPIA_MAC) munmap(reinterpret_cast<char*>(address), BLOCK_SIZE); #elif defined(OLYMPIA_WINDOWS) #if COMPILER(MINGW) && !COMPILER(MINGW64) __mingw_aligned_free(block); #else _aligned_free(address); #endif #elif defined(OLYMPIA_MAC) vm_deallocate(current_task(), reinterpret_cast<vm_address_t>(address), BLOCK_SIZE); #endif } void* reserveVirtualMemory(size_t& totalBytes) { #ifdef OLYMPIA_LINUX #ifdef OLYMPIA_LINUX_USE_MMAP void* p = mmap(0, totalBytes, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0); if (p != MAP_FAILED) s_blockSizes[p] = totalBytes; return p; #else return malloc(totalBytes); #endif #elif defined(OLYMPIA_WINDOWS) return VirtualAlloc(0, totalBytes, MEM_RESERVE, PAGE_READWRITE); #elif defined(OLYMPIA_MAC) return malloc(totalBytes); #else OLYMPIA_CRASH(); #endif } void releaseVirtualMemory(void* address) { #ifdef OLYMPIA_LINUX #ifdef OLYMPIA_LINUX_USE_MMAP munmap(address, s_blockSizes[address]); s_blockSizes.erase(address); #else free(address); #endif #elif defined(OLYMPIA_WINDOWS) VirtualFree(address, 0, MEM_RELEASE); #elif defined(OLYMPIA_MAC) return free(address); #else OLYMPIA_CRASH(); #endif } void* commitVirtualMemory(void* address, unsigned totalBytes) { #ifdef OLYMPIA_LINUX #if defined(OLYMPIA_LINUX_USE_MMAP) && defined(__USE_BSD) if (!madvise(address, totalBytes, MADV_WILLNEED)) return NULL; #else return address; #endif #elif defined(OLYMPIA_WINDOWS) return VirtualAlloc(address, totalBytes, MEM_COMMIT, PAGE_READWRITE); #elif defined(OLYMPIA_MAC) return address; #else OLYMPIA_CRASH(); #endif } void decommitVirtualMemory(void* address, unsigned totalBytes) { #if defined(OLYMPIA_LINUX_USE_MMAP) && defined(__USE_BSD) madvise(address, totalBytes, MADV_DONTNEED); #endif return; } } // namespace Platform
int LoadGLTextures(const aiScene* scene) { ILboolean success; /* initialization of DevIL */ ilInit(); /* scan scene's materials for textures */ for (unsigned int m=0; m<scene->mNumMaterials; ++m) { int texIndex = 0; aiString path; // filename aiReturn texFound = scene->mMaterials[m]->GetTexture(aiTextureType_DIFFUSE, texIndex, &path); while (texFound == AI_SUCCESS) { //fill map with textures, OpenGL image ids set to 0 textureIdMap[path.data] = 0; // more textures? texIndex++; texFound = scene->mMaterials[m]->GetTexture(aiTextureType_DIFFUSE, texIndex, &path); } } int numTextures = textureIdMap.size(); /* create and fill array with DevIL texture ids */ ILuint* imageIds = new ILuint[numTextures]; ilGenImages(numTextures, imageIds); /* create and fill array with GL texture ids */ GLuint* textureIds = new GLuint[numTextures]; glGenTextures(numTextures, textureIds); /* Texture name generation */ /* get iterator */ std::map<std::string, GLuint>::iterator itr = textureIdMap.begin(); int i=0; for (; itr != textureIdMap.end(); ++i, ++itr) { //save IL image ID std::string filename = (*itr).first; // get filename (*itr).second = textureIds[i]; // save texture id for filename in map ilBindImage(imageIds[i]); /* Binding of DevIL image name */ ilEnable(IL_ORIGIN_SET); ilOriginFunc(IL_ORIGIN_LOWER_LEFT); success = ilLoadImage((ILstring)filename.c_str()); if (success) { /* Convert image to RGBA */ ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE); /* Create and load textures to OpenGL */ glBindTexture(GL_TEXTURE_2D, textureIds[i]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ilGetInteger(IL_IMAGE_WIDTH), ilGetInteger(IL_IMAGE_HEIGHT), 0, GL_RGBA, GL_UNSIGNED_BYTE, ilGetData()); } else printf("Couldn't load Image: %s\n", filename.c_str()); } /* Because we have already copied image data into texture data we can release memory used by image. */ ilDeleteImages(numTextures, imageIds); //Cleanup delete [] imageIds; delete [] textureIds; //return success; return true; }
void WriteContinuousDelayFile::write_cir(std::map<std::string, CIR> cirs, std::map<std::string, double> reference_delays, CIR_number_t CIRnum) { if (cirs.size() != nof_links) { stringstream msg; msg << "error: Number of provided CIRs (" << cirs.size() << ") does not match number of links in file (" << nof_links << ")."; throw runtime_error(msg.str()); } if (reference_delays.size() != nof_links) { stringstream msg; msg << "error: Number of provided reference delays (" << reference_delays.size() << ") does not match number of links in file (" << nof_links << ")."; throw logic_error(msg.str()); } for (std::map<std::string, CIR>::iterator it = cirs.begin(); it != cirs.end(); ++it) { const string link_name = it->first; // write reference delay: append_reference_delay(link_groups[link_name], reference_delays[link_name]); // write CIR: vector<CDX::impulse_t> impulses = it->second; stringstream dsName; dsName << CIRnum; H5::CompType cp_cmplx(sizeof(hdf5_impulse_t)); cp_cmplx.insertMember("type", HOFFSET(hdf5_impulse_t, type), H5::PredType::NATIVE_INT16); cp_cmplx.insertMember("delays", HOFFSET(hdf5_impulse_t, delays), H5::PredType::NATIVE_DOUBLE); cp_cmplx.insertMember("real", HOFFSET(hdf5_impulse_t, real), H5::PredType::NATIVE_DOUBLE); cp_cmplx.insertMember("imag", HOFFSET(hdf5_impulse_t, imag), H5::PredType::NATIVE_DOUBLE); hdf5_impulse_t wdata[impulses.size()]; const size_t RANK = 1; hsize_t dimsf3[RANK]; // dataset dimensions dimsf3[0] = impulses.size(); H5::DataSpace dspace3(RANK, dimsf3); H5::DataSet dset3 = group_cirs[link_name]->createDataSet( dsName.str().c_str(), cp_cmplx, dspace3); for (size_t i = 0; i < impulses.size(); i++) { wdata[i].type = impulses.at(i).type; wdata[i].delays = impulses.at(i).delay; wdata[i].real = impulses.at(i).amplitude.real(); wdata[i].imag = impulses.at(i).amplitude.imag(); } dset3.write(wdata, cp_cmplx); } }