///////////////////////////////////////////////////////////////////////////// // WMIReferenceProvider::referenceNames // // /////////////////////////////////////////////////////////////////////////// Array<CIMObjectPath> WMIReferenceProvider::referenceNames( const String& nameSpace, const String& userName, const String& password, const CIMObjectPath& objectName, const String& resultClass, const String& role) { Array<CIMObject> objects; Array<CIMObjectPath> objectNames; PEG_METHOD_ENTER(TRC_WMIPROVIDER,"WMIReferenceProvider::referenceNames()"); // create an empty property list to save time... Array<CIMName> propNames; CIMPropertyList propertyList(propNames); // now get the objects objects = references( nameSpace, userName, password, objectName, resultClass, role, false, false, propertyList); // now get the names from the object Uint32 size = objects.size(); Uint32 i; //check if namespace is remote CIMNamespaceName oNamespace(nameSpace); String strNamespace = oNamespace.getString(); String strNamespaceLower = strNamespace; strNamespaceLower.toLower(); String strRemotePrefix = ""; if (strNamespaceLower.subString(0, 4) != "root") { Uint32 uiPos = strNamespaceLower.find("root"); if (uiPos == PEG_NOT_FOUND) throw CIMException(CIM_ERR_FAILED); strRemotePrefix = strNamespace.subString(0, uiPos); } for (i=0; i<size; i++) { CIMObjectPath oObjectPath = objects[i].getPath(); if (strRemotePrefix != "") { strNamespace = strRemotePrefix; oNamespace = strNamespace.append(oObjectPath.getNameSpace().getString()); oObjectPath.setNameSpace(oNamespace); } objectNames.append(oObjectPath); } PEG_METHOD_EXIT(); return objectNames; }
void snmpDeliverTrap_emanate::deliverTrap( const String& trapOid, const String& securityName, const String& targetHost, const Uint16& targetHostFormat, const String& otherTargetHostFormat, const Uint32& portNumber, const Uint16& snmpVersion, const String& engineID, const Array<String>& vbOids, const Array<String>& vbTypes, const Array<String>& vbValues) { VarBind* vbhead = NULL; VarBind* vb = NULL; VarBind* vblast = NULL; OID* object = NULL; // Translate a string into an OID OID* sendtrapOid = MakeOIDFromDot(trapOid.getCString()); if (sendtrapOid == NULL) { throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( _MSG_INVALID_KEY, _MSG_INVALID_TRAPOID)); } // Destination : convert targetHost into Transport CString trap_dest = targetHost.getCString(); TransportInfo global_ti; global_ti.type = SR_IP_TRANSPORT; switch (targetHostFormat) { case _HOST_NAME: { char* ipAddr = _getIPAddress(trap_dest); if (ipAddr == NULL) { throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( _MSG_DESTINATION_NOT_FOUND_KEY, _MSG_DESTINATION_NOT_FOUND)); } global_ti.t_ipAddr = inet_addr(trap_dest); break; } case _IPV4_ADDRESS: { global_ti.t_ipAddr = inet_addr(trap_dest); break; } default: { throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_NOT_SUPPORTED, MessageLoaderParms( _MSG_TARGETHOSTFORMAT_NOT_SUPPORTED_KEY, _MSG_TARGETHOSTFORMAT_NOT_SUPPORTED)); break; } } global_ti.t_ipPort = htons((unsigned short)portNumber); // Community Name, default is public CString _community; if (securityName.size() == 0) { String community; community.assign("public"); _community = community.getCString(); } else { _community = securityName.getCString(); } OctetString* community_name = MakeOctetStringFromText(_community); if (community_name == NULL) { throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( _MSG_INVALID_SECURITY_NAME_KEY, _MSG_INVALID_SECURITY_NAME)); } // getting IP address of the host CString hostname = System::getHostName().getCString(); char* IP_string = _getIPAddress(hostname); // formatting agent(host) address into OctetString format OctetString* agent_addr; SR_INT32 s1, s2, s3, s4; SR_UINT32 ipaddr; // pull out each of the 4 octet values from IP address sscanf(IP_string,"%d.%d.%d.%d", &s1, &s2, &s3, &s4); // validate the values for s1, s2, s3, and s4 to make sure values are // between 0 and 255 if (!_isValidOctet(s1) || !_isValidOctet(s2) || !_isValidOctet(s3) || !_isValidOctet(s4)) { throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( _MSG_INVALID_OCTET_VALUE_KEY, _MSG_INVALID_OCTET_VALUE)); } // create an empty 4 length OctetString agent_addr = MakeOctetString(NULL,4); if (agent_addr == NULL) { throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( _MSG_CREATE_OCTET_FAILED_KEY, _MSG_CREATE_OCTET_FAILED)); } // fill in values for OctetString agent_addr->octet_ptr[0] = (unsigned char)s1; agent_addr->octet_ptr[1] = (unsigned char)s2; agent_addr->octet_ptr[2] = (unsigned char)s3; agent_addr->octet_ptr[3] = (unsigned char)s4; // specTrap from trapOid. SR_INT32 genTrap = 0; SR_INT32 specTrap = 0; OID* enterpriseOid ; Array<String> standard_traps; standard_traps.append(String("1.3.6.1.6.3.1.1.5.1")); standard_traps.append(String("1.3.6.1.6.3.1.1.5.2")); standard_traps.append(String("1.3.6.1.6.3.1.1.5.3")); standard_traps.append(String("1.3.6.1.6.3.1.1.5.4")); standard_traps.append(String("1.3.6.1.6.3.1.1.5.5")); standard_traps.append(String("1.3.6.1.6.3.1.1.5.6")); Array<String> oids; String tmpoid = trapOid; while(tmpoid.find(".") != PEG_NOT_FOUND) { oids.append(tmpoid.subString(0, tmpoid.find("."))); tmpoid = tmpoid.subString(tmpoid.find(".") + 1); } oids.append(tmpoid); String ent; if (Contains(standard_traps, trapOid)) { // // if the trapOid is one of the standard traps, // then the SNMPV1 enterprise parameter must be set // to the value of the trapOid, the generic-trap // parameter must be set to one of (0 - 5), and the // specific-trap parameter must be set to 0 // enterpriseOid = sendtrapOid; // the generic trap is last sub-identifier of the // trapOid minus 1 genTrap = atoi(oids[oids.size() - 1].getCString()) - 1; specTrap = 0; } else { // // if the trapOid is not one of the standard traps: // then 1) the generic-trap parameter must be set to 6, // 2) if the next-to-last sub-identifier of the // trapOid is zero, then the SNMPV1 enterprise // parameter is the trapOid with the last 2 // sub-identifiers removed, otherwise, the // SNMPV1 enterprise parameter is the trapOid // with the last sub-identifier removed; // 3) the SNMPv1 specific-trap parameter is the last // sub-identifier of the trapOid; // genTrap = 6; specTrap = atoi(oids[oids.size()-1].getCString()); ent = oids[0]; for (Uint8 i = 1; i < oids.size()-2; i++) { ent = ent + "." + oids[i]; } if (oids[oids.size()-2] != "0") { ent = ent + "." + oids[oids.size()-2]; } enterpriseOid = MakeOIDFromDot(ent.getCString()); if (enterpriseOid == NULL) { throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( _MSG_INVALID_ENTERPRISEOID_KEY, _MSG_INVALID_ENTERPRISEOID)); } } // creates VarBind for (Uint32 i = 0; i < vbOids.size(); i++) { CString _vbOid = vbOids[i].getCString(); CString _vbValue = vbValues[i].getCString(); if ((object = MakeOIDFromDot(_vbOid)) == NULL) { throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( _MSG_INVALID_PROPERTYOID_KEY, _MSG_INVALID_PROPERTYOID)); } if (String::equalNoCase(vbTypes[i], "OctetString")) { OctetString* value; value = CloneOctetString(MakeOctetStringFromText(_vbValue)); if (value == NULL) { throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( _MSG_INVALID_PROPERTYVALUE_KEY, _MSG_INVALID_PROPERTYVALUE)); } if ((vb = MakeVarBindWithValue( object, (OID*) NULL, OCTET_PRIM_TYPE, value)) == NULL) { throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( _MSG_MAKE_VARBIND_FAILED_FOR_OCTET_PRIM_TYPE_KEY, _MSG_MAKE_VARBIND_FAILED_FOR_OCTET_PRIM_TYPE)); } } else if (String::equalNoCase(vbTypes[i], "OID")) { void* value = MakeOIDFromDot(_vbValue); if (value == NULL) { throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( _MSG_INVALID_PROPERTYVALUE_KEY, _MSG_INVALID_PROPERTYVALUE)); } if ((vb = MakeVarBindWithValue( object, (OID*) NULL, OBJECT_ID_TYPE, value)) == NULL) { throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( _MSG_MAKE_VARBIND_FAILED_FOR_OBJECT_ID_TYPE_KEY, _MSG_MAKE_VARBIND_FAILED_FOR_OBJECT_ID_TYPE)); } } else { int vbvalue = atoi(_vbValue); void* value = &vbvalue; if (value == NULL) { throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( _MSG_INVALID_PROPERTYVALUE_KEY, _MSG_INVALID_PROPERTYVALUE)); } if ((vb = MakeVarBindWithValue( object, (OID*) NULL, INTEGER_TYPE, value)) == NULL) { throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( _MSG_MAKE_VARBIND_FAILED_FOR_INTEGER_TYPE_KEY, _MSG_MAKE_VARBIND_FAILED_FOR_INTEGER_TYPE)); } } if (i == 0) { vbhead = vb; vblast = vb; } else { vblast->next_var = vb; vblast = vblast->next_var; } } vblast->next_var = NULL; // Now send the trap switch (snmpVersion) { case _SNMPv1_TRAP: { SendNotificationToDestSMIv1Params( 1, // notifyType - TRAP genTrap, // genTrap specTrap, // specTrap enterpriseOid, // enterprise agent_addr, // agent_addr vbhead, // vb NULL, // contextName 1, // retryCount 1, // timeout community_name, // securityName, SR_SECURITY_LEVEL_NOAUTH, // securityLevel SR_SECURITY_MODEL_V1, // securityModel &global_ti, // Transport Info 0); // cfg_chk break; } case _SNMPv2C_TRAP: { SendNotificationToDestSMIv2Params( (SR_INT32)SNMPv2_TRAP_TYPE, // notifyType - NOTIFICATION sendtrapOid, // snmpTrapOID agent_addr, // agent_addr vbhead, // vb NULL, // contextName 1, // retryCount 100, // timeout community_name, // securityName or community SR_SECURITY_LEVEL_NOAUTH, // securityLevel SR_SECURITY_MODEL_V2C, // securityModel &global_ti, // TransportInfo 0); // cfg_chk break; } default: { throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_NOT_SUPPORTED, MessageLoaderParms( _MSG_VERSION_NOT_SUPPORTED_KEY, _MSG_VERSION_NOT_SUPPORTED)); break; } } // Free OID built by calls MakeOIDFromDot() FreeOID(sendtrapOid); FreeOID(enterpriseOid); FreeOID(object); // Free the data structures allocated and built by calls // MakeOctetString() and MakeOctetStringFrom Text() FreeOctetString(community_name); FreeOctetString(agent_addr); // Free the VarBind data structures allocated and built // by calls MakeVarBindWithValue() FreeVarBindList(vbhead); FreeVarBindList(vb); FreeVarBindList(vblast); }
Variant f_dns_get_record(const String& hostname, int type /* = -1 */, VRefParam authns /* = null */, VRefParam addtl /* = null */) { IOStatusHelper io("dns_get_record", hostname.data(), type); if (type < 0) type = PHP_DNS_ALL; if (type & ~PHP_DNS_ALL && type != PHP_DNS_ANY) { raise_warning("Type '%d' not supported", type); return false; } /* Initialize the return array */ Array ret; authns = Array::Create(); addtl = Array::Create(); unsigned char *cp = NULL, *end = NULL; int qd, an, ns = 0, ar = 0; querybuf answer; /* - We emulate an or'ed type mask by querying type by type. * (Steps 0 - NUMTYPES-1 ) * If additional info is wanted we check again with DNS_T_ANY * (step NUMTYPES / NUMTYPES+1 ) * store_results is used to skip storing the results retrieved in step * NUMTYPES+1 when results were already fetched. * - In case of PHP_DNS_ANY we use the directly fetch DNS_T_ANY. * (step NUMTYPES+1 ) */ bool first_query = true; bool store_results = true; for (int t = (type == PHP_DNS_ANY ? (PHP_DNS_NUM_TYPES + 1) : 0); t < PHP_DNS_NUM_TYPES + 2 || first_query; t++) { first_query = false; int type_to_fetch; switch (t) { case 0: type_to_fetch = type & PHP_DNS_A ? DNS_T_A : 0; break; case 1: type_to_fetch = type & PHP_DNS_NS ? DNS_T_NS : 0; break; case 2: type_to_fetch = type & PHP_DNS_CNAME ? DNS_T_CNAME : 0; break; case 3: type_to_fetch = type & PHP_DNS_SOA ? DNS_T_SOA : 0; break; case 4: type_to_fetch = type & PHP_DNS_PTR ? DNS_T_PTR : 0; break; case 5: type_to_fetch = type & PHP_DNS_HINFO ? DNS_T_HINFO : 0; break; case 6: type_to_fetch = type & PHP_DNS_MX ? DNS_T_MX : 0; break; case 7: type_to_fetch = type & PHP_DNS_TXT ? DNS_T_TXT : 0; break; case 8: type_to_fetch = type & PHP_DNS_AAAA ? DNS_T_AAAA : 0; break; case 9: type_to_fetch = type & PHP_DNS_SRV ? DNS_T_SRV : 0; break; case 10: type_to_fetch = type & PHP_DNS_NAPTR ? DNS_T_NAPTR : 0; break; case 11: type_to_fetch = type & PHP_DNS_A6 ? DNS_T_A6 : 0; break; case PHP_DNS_NUM_TYPES: store_results = false; continue; default: case (PHP_DNS_NUM_TYPES + 1): type_to_fetch = DNS_T_ANY; break; } if (!type_to_fetch) continue; struct __res_state *res; res = ResolverInit::s_res.get()->getResolver(); if (res == NULL) { return false; } int n = res_nsearch(res, hostname.data(), C_IN, type_to_fetch, answer.qb2, sizeof answer); if (n < 0) { res_nclose(res); php_dns_free_res(res); continue; } HEADER *hp; cp = answer.qb2 + HFIXEDSZ; end = answer.qb2 + n; hp = (HEADER *)&answer; qd = ntohs(hp->qdcount); an = ntohs(hp->ancount); ns = ntohs(hp->nscount); ar = ntohs(hp->arcount); /* Skip QD entries, they're only used by dn_expand later on */ while (qd-- > 0) { n = dn_skipname(cp, end); if (n < 0) { raise_warning("Unable to parse DNS data received"); res_nclose(res); php_dns_free_res(res); return false; } cp += n + QFIXEDSZ; } /* YAY! Our real answers! */ while (an-- && cp && cp < end) { Array retval; cp = php_parserr(cp, &answer, type_to_fetch, store_results, retval); if (!retval.empty() && store_results) { ret.append(retval); } } res_nclose(res); php_dns_free_res(res); } /* List of Authoritative Name Servers */ while (ns-- > 0 && cp && cp < end) { Array retval; cp = php_parserr(cp, &answer, DNS_T_ANY, true, retval); if (!retval.empty()) { authns.append(retval); } } /* Additional records associated with authoritative name servers */ while (ar-- > 0 && cp && cp < end) { Array retval; cp = php_parserr(cp, &answer, DNS_T_ANY, true, retval); if (!retval.empty()) { addtl.append(retval); } } return ret; }
//================================================================= bool TileAssembler::readRawFile(std::string& pModelFilename, ModelPosition& pModelPosition, AABSPTree<SubModel *> *pMainTree) { std::string filename = iSrcDir; if(filename.length() >0) filename.append("/"); filename.append(pModelFilename); FILE *rf = fopen(filename.c_str(), "rb"); if(!rf) { // depending on the extractor version, the data could be located in the root dir std::string baseModelFilename = pModelFilename.substr((pModelFilename.find_first_of("/")+1),pModelFilename.length()); filename = iSrcDir; if(filename.length() >0) filename.append("/"); filename.append(baseModelFilename); rf = fopen(filename.c_str(), "rb"); } if(!rf) { printf("ERROR: Can't open model file in form: %s",pModelFilename.c_str()); printf("... or form: %s",filename.c_str() ); return false; } char ident[8]; int trianglecount =0; #ifdef _ASSEMBLER_DEBUG int startgroup = 0; //2; int endgroup = INT_MAX; //2; fprintf(::g_df,"-------------------------------------------------\n"); fprintf(::g_df,"%s\n", pModelFilename.c_str()); fprintf(::g_df,"-------------------------------------------------\n"); #else int startgroup = 0; int endgroup = INT_MAX; #endif // temporary use defines to simplify read/check code (close file and return at fail) #define READ_OR_RETURN(V,S) if(fread((V), (S), 1, rf) != 1) { \ fclose(rf); return(false); } #define CMP_OR_RETURN(V,S) if(strcmp((V),(S)) != 0) { \ fclose(rf); return(false); } READ_OR_RETURN(&ident, 8); if(strcmp(ident, "VMAP001") == 0) { // OK, do nothing } else if(strcmp(ident, "VMAP002") == 0) { // we have to read one int. This is needed during the export and we have to skip it here int tempNVectors; READ_OR_RETURN(&tempNVectors, sizeof(int)); } else { // wrong version fclose(rf); return(false); } G3D::uint32 groups; char blockId[5]; blockId[4] = 0; int blocksize; READ_OR_RETURN(&groups, sizeof(G3D::uint32)); for(int g=0;g<(int)groups;g++) { // group MUST NOT have more then 65536 indexes !! Array will have a problem with that !! (strange ...) Array<int> tempIndexArray; Array<Vector3> tempVertexArray; AABSPTree<Triangle> *gtree = new AABSPTree<Triangle>(); // add free gtree at fail #undef READ_OR_RETURN #undef CMP_OR_RETURN #define READ_OR_RETURN(V,S) if(fread((V), (S), 1, rf) != 1) { \ fclose(rf); delete gtree; return(false); } #define CMP_OR_RETURN(V,S) if(strcmp((V),(S)) != 0) { \ fclose(rf); delete gtree; return(false); } G3D::uint32 flags; READ_OR_RETURN(&flags, sizeof(G3D::uint32)); G3D::uint32 branches; READ_OR_RETURN(&blockId, 4); CMP_OR_RETURN(blockId, "GRP "); READ_OR_RETURN(&blocksize, sizeof(int)); READ_OR_RETURN(&branches, sizeof(G3D::uint32)); for(int b=0;b<(int)branches; b++) { G3D::uint32 indexes; // indexes for each branch (not used jet) READ_OR_RETURN(&indexes, sizeof(G3D::uint32)); } // ---- indexes READ_OR_RETURN(&blockId, 4); CMP_OR_RETURN(blockId, "INDX"); READ_OR_RETURN(&blocksize, sizeof(int)); unsigned int nindexes; READ_OR_RETURN(&nindexes, sizeof(G3D::uint32)); if(nindexes >0) { unsigned short *indexarray = new unsigned short[nindexes*sizeof(unsigned short)]; READ_OR_RETURN(indexarray, nindexes*sizeof(unsigned short)); for(int i=0;i<(int)nindexes; i++) { unsigned short val = indexarray[i]; tempIndexArray.append(val); } delete[] indexarray; } // ---- vectors READ_OR_RETURN(&blockId, 4); CMP_OR_RETURN(blockId, "VERT"); READ_OR_RETURN(&blocksize, sizeof(int)); unsigned int nvectors; READ_OR_RETURN(&nvectors, sizeof(int)); float *vectorarray = 0; // add vectorarray free #undef READ_OR_RETURN #undef CMP_OR_RETURN #define READ_OR_RETURN(V,S) if(fread((V), (S), 1, rf) != 1) { \ fclose(rf); delete gtree; delete[] vectorarray; return(false); } #define CMP_OR_RETURN(V,S) if(strcmp((V),(S)) != 0) { \ fclose(rf); delete gtree; delete[] vectorarray; return(false); } if(nvectors >0) { vectorarray = new float[nvectors*sizeof(float)*3]; READ_OR_RETURN(vectorarray, nvectors*sizeof(float)*3); } // ----- liquit if(flags & 1) { // we have liquit -> not handled yet ... skip READ_OR_RETURN(&blockId, 4); CMP_OR_RETURN(blockId, "LIQU"); READ_OR_RETURN(&blocksize, sizeof(int)); fseek(rf, blocksize, SEEK_CUR); } for(unsigned int i=0, indexNo=0; indexNo<nvectors; indexNo++) { Vector3 v = Vector3(vectorarray[i+2], vectorarray[i+1], vectorarray[i+0]); i+=3; v = pModelPosition.transform(v); float swapy = v.y; v.y = v.x; v.x = swapy; tempVertexArray.append(v); } // ---- calculate triangles int rest = nindexes%3; if(rest != 0) { nindexes -= rest; } for(unsigned int i=0;i<(nindexes);) { Triangle t = Triangle(tempVertexArray[tempIndexArray[i+2]], tempVertexArray[tempIndexArray[i+1]], tempVertexArray[tempIndexArray[i+0]] ); i+=3; ++trianglecount; if(g>= startgroup && g <= endgroup) { gtree->insert(t); } } // drop of temporary use defines #undef READ_OR_RETURN #undef CMP_OR_RETURN if(vectorarray != 0) { delete vectorarray; } if(gtree->size() >0) { gtree->balance(); SubModel *sm = new SubModel(gtree); #ifdef _ASSEMBLER_DEBUG if(::g_df) fprintf(::g_df,"group trianglies: %d, Tris: %d, Nodes: %d, gtree.triangles: %d\n", g, sm->getNTriangles(), sm->getNNodes(), gtree->memberTable.size()); if(sm->getNTriangles() != gtree->memberTable.size()) { if(::g_df) fprintf(::g_df,"ERROR !!!! group trianglies: %d, Tris: %d, Nodes: %d, gtree.triangles: %d\n", g, sm->getNTriangles(), sm->getNNodes(), gtree->memberTable.size()); } #endif sm->setBasePosition(pModelPosition.iPos); pMainTree->insert(sm); } delete gtree; } fclose(rf); return true; }
void TextOutput::wordWrapIndentAppend(const std::string& str) { // TODO: keep track of the last space character we saw so we don't // have to always search. if ((option.wordWrap == Settings::WRAP_NONE) || (currentColumn + (int)str.size() <= option.numColumns)) { // No word-wrapping is needed // Add one character at a time. // TODO: optimize for strings without newlines to add multiple // characters. for (uint32 i = 0; i < str.size(); ++i) { indentAppend(str[i]); } return; } // Number of columns to wrap against int cols = option.numColumns - indentSpaces; // Copy forward until we exceed the column size, // and then back up and try to insert newlines as needed. for (uint32 i = 0; i < str.size(); ++i) { indentAppend(str[i]); if ((str[i] == '\r') && (i + 1 < str.size()) && (str[i + 1] == '\n')) { // \r\n, we need to hit the \n to enter word wrapping. ++i; indentAppend(str[i]); } if (currentColumn >= cols) { debugAssertM(str[i] != '\n' && str[i] != '\r', "Should never enter word-wrapping on a newline character"); // True when we're allowed to treat a space as a space. bool unquotedSpace = option.allowWordWrapInsideDoubleQuotes || ! inDQuote; // Cases: // // 1. Currently in a series of spaces that ends with a newline // strip all spaces and let the newline // flow through. // // 2. Currently in a series of spaces that does not end with a newline // strip all spaces and replace them with single newline // // 3. Not in a series of spaces // search backwards for a space, then execute case 2. // Index of most recent space uint32 lastSpace = data.size() - 1; // How far back we had to look for a space uint32 k = 0; uint32 maxLookBackward = currentColumn - indentSpaces; // Search backwards (from current character), looking for a space. while ((k < maxLookBackward) && (lastSpace > 0) && (! ((data[lastSpace] == ' ') && unquotedSpace))) { --lastSpace; ++k; if ((data[lastSpace] == '\"') && !option.allowWordWrapInsideDoubleQuotes) { unquotedSpace = ! unquotedSpace; } } if (k == maxLookBackward) { // We couldn't find a series of spaces if (option.wordWrap == Settings::WRAP_ALWAYS) { // Strip the last character we wrote, force a newline, // and replace the last character; data.pop(); writeNewline(); indentAppend(str[i]); } else { // Must be Settings::WRAP_WITHOUT_BREAKING // // Don't write the newline; we'll come back to // the word wrap code after writing another character } } else { // We found a series of spaces. If they continue // to the new string, strip spaces off both. Otherwise // strip spaces from data only and insert a newline. // Find the start of the spaces. firstSpace is the index of the // first non-space, looking backwards from lastSpace. uint32 firstSpace = lastSpace; while ((k < maxLookBackward) && (firstSpace > 0) && (data[firstSpace] == ' ')) { --firstSpace; ++k; } if (k == maxLookBackward) { ++firstSpace; } if (lastSpace == (uint32)data.size() - 1) { // Spaces continued up to the new string data.resize(firstSpace + 1); writeNewline(); // Delete the spaces from the new string while ((i < str.size() - 1) && (str[i + 1] == ' ')) { ++i; } } else { // Spaces were somewhere in the middle of the old string. // replace them with a newline. // Copy over the characters that should be saved Array<char> temp; for (uint32 j = lastSpace + 1; j < (uint32)data.size(); ++j) { char c = data[j]; if (c == '\"') { // Undo changes to quoting (they will be re-done // when we paste these characters back on). inDQuote = !inDQuote; } temp.append(c); } // Remove those characters and replace with a newline. data.resize(firstSpace + 1); writeNewline(); // Write them back for (uint32 j = 0; j < (uint32)temp.size(); ++j) { indentAppend(temp[j]); } // We are now free to continue adding from the // new string, which may or may not begin with spaces. } // if spaces included new string } // if hit indent } // if line exceeded } // iterate over str }
Array<CIMInstance> RUEpProvider::_NextHopRouteInstances() { PEG_METHOD_ENTER(TRC_PROVIDERAGENT, "RUEpProvider::_NextHopRouteInstances()"); Array<CIMInstance> _retInstances; NextHopRouteList _nhrl; InterfaceList _ifl; for (Uint16 i = 0; i<_nhrl.size(); i++) { NextHopIPRoute _nhipr = _nhrl.getRoute(i); if (_nhipr.isRouteLocal()) { CIMInstance instance(CLASS_CIM_NEXT_HOP_ROUTE); String _destAddr, _destMask, _instanceID; Uint16 _addrType; Uint8 _prefLength; if (!_nhipr.getInstanceID(_instanceID)) { throw CIMOperationFailedException( "Can't determine InstanceID in: " + String("RUEpProvider::_NextHopRouteInstances()")); } instance.addProperty(CIMProperty( PROPERTY_INSTANCE_ID, _instanceID)); if (!_nhipr.getDestinationAddress(_destAddr)) { throw CIMOperationFailedException( "Can't determine destination address in: " + String("RUEpProvider::_NextHopRouteInstances()")); } instance.addProperty(CIMProperty( PROPERTY_DESTINATION_ADDRESS, _destAddr)); if (_nhipr.getAddressType(_addrType)) { instance.addProperty(CIMProperty( PROPERTY_ADDRESS_TYPE, _addrType)); if (_addrType == 1) // IPv4 address. { if (!_nhipr.getDestinationMask(_destMask)) { throw CIMOperationFailedException( "Can't determine destination mask in: " + String("RUEpProvider::_NextHopRouteInstances()")); } instance.addProperty(CIMProperty( PROPERTY_DESTINATION_MASK, _destMask)); } else { if (_addrType == 2) // IPv6 address. { if (!_nhipr.getPrefixLength(_prefLength)) { throw CIMOperationFailedException( "Can't determine prefix length for route in: " + String("RUEpProvider::_NextHopRouteInstances()")); } instance.addProperty(CIMProperty( PROPERTY_PREFIX_LENGTH, _prefLength)); } } } else { throw CIMOperationFailedException( "Can't determine address type in: " + String("RUEpProvider::_NextHopRouteInstances()")); } // Build CIMObjectPath from keybindings Array<CIMKeyBinding> keyBindings; keyBindings.append( CIMKeyBinding( PROPERTY_INSTANCE_ID, _instanceID, CIMKeyBinding::STRING)); CIMObjectPath path( String::EMPTY, CIMNamespaceName(), CLASS_CIM_NEXT_HOP_ROUTE, keyBindings); instance.setPath(path); _nhrInstances.append(instance); _retInstances.append(instance); } } // Loop over next hop routes. PEG_METHOD_EXIT(); return _retInstances; }
static void _testInstances(void) { // Simple test: instance with a few string properties { WsmInstance inst("testClass"); WsmValue val_1("value_1"); WsmValue val_2("value_2"); inst.addProperty(WsmProperty("property_1", val_1)); inst.addProperty(WsmProperty("property_2", val_2)); _checkInstance(inst, "Instances with string properties do not compare"); } // Test string array properties { WsmInstance inst("testClass"); Array<String> stra; for (int i = 0; i < 5; i++) { char buf[20]; sprintf(buf, "prop_1 value: %d", i); stra.append(buf); } WsmValue val1(stra); inst.addProperty(WsmProperty("property_1", val1)); stra.clear(); for (int i = 0; i < 10; i++) { char buf[20]; sprintf(buf, "prop_2 value: %d", i); stra.append(buf); } WsmValue val2(stra); inst.addProperty(WsmProperty("property_2", val2)); _checkInstance(inst, "Instances with string array properties do not compare"); } // Test EPR properties { WsmInstance inst("testClass"); WsmEndpointReference epr; epr.address = "http://www.acme.com:5988/wsman"; epr.resourceUri = "TestURI"; epr.selectorSet->selectors. append(WsmSelector("sel_1 name", "sel_1 value")); epr.selectorSet->selectors. append(WsmSelector("sel_2 name", "sel_2 value")); WsmValue val(epr); inst.addProperty(WsmProperty("property_1", val)); _checkInstance(inst, "Instances with EPR properties do not compare"); } // Test EPR array properties { WsmInstance inst("testClass"); Array<WsmEndpointReference> epra; for (int i = 0; i < 5; i++) { char buf[50]; WsmEndpointReference epr; sprintf(buf, "http://www.acme.com_%d:5988/wsman", i); epr.address = buf; sprintf(buf, "TestURI_%d", i); epr.resourceUri = buf; sprintf(buf, "selector value %d", i); epr.selectorSet->selectors. append(WsmSelector("sel_name", buf)); epra.append(epr); } WsmValue val(epra); inst.addProperty(WsmProperty("property_1", val)); _checkInstance(inst, "Instances with EPR array properties do not compare"); } // Test recursive EPR properties { WsmInstance inst("testClass"); WsmEndpointReference epr1; epr1.address = "http://www.acme.com_1:5988/wsman"; epr1.resourceUri = "TestURI_1"; epr1.selectorSet->selectors. append(WsmSelector("sel_0 name", "sel_1 value")); epr1.selectorSet->selectors. append(WsmSelector("sel_1 name", "sel_2 value")); WsmEndpointReference epr2; epr2.address = "http://www.acme.com_2:5988/wsman"; epr2.resourceUri = "TestURI_2"; epr2.selectorSet->selectors.append(WsmSelector("sel_2 name", epr1)); WsmEndpointReference epr3; epr3.address = "http://www.acme.com_3:5988/wsman"; epr3.resourceUri = "TestURI_3"; epr3.selectorSet->selectors.append(WsmSelector("sel_3 name", epr2)); WsmEndpointReference epr; epr.address = "http://www.acme.com:5988/wsman"; epr.resourceUri = "TestURI"; epr.selectorSet->selectors.append(WsmSelector("sel name", epr3)); WsmValue val(epr); inst.addProperty(WsmProperty("property_1", val)); _checkInstance(inst, "Instances with recursive EPR properties do not compare"); } // Test embedded instance properties { WsmInstance inst1("testClass_1"); WsmValue val_1("value_1"); WsmValue val_2("value_2"); inst1.addProperty(WsmProperty("property_1", val_1)); inst1.addProperty(WsmProperty("property_2", val_2)); WsmInstance inst("testClass"); WsmValue val_3(inst1); inst.addProperty(WsmProperty("property_3", val_3)); _checkInstance(inst, "Instances with instance properties do not compare"); } // Test arrays of embedded instances { WsmInstance inst("testClass"); Array<WsmInstance> insta; for (int i = 0; i < 5; i++) { char buf[20]; sprintf(buf, "testClass_%d", i); WsmInstance inst1(buf); sprintf(buf, "value_%d", i); WsmValue val(buf); sprintf(buf, "property_%d", i); inst1.addProperty(WsmProperty(buf, val)); insta.append(inst1); } WsmValue val(insta); inst.addProperty(WsmProperty("prop_array", val)); _checkInstance(inst, "Instances with instance array properties do not compare"); } // Test recursive embedded instances { WsmInstance inst1("testClass_1"); WsmValue val_0("value_0"); WsmValue val_1("value_1"); inst1.addProperty(WsmProperty("property_0", val_0)); inst1.addProperty(WsmProperty("property_1", val_1)); WsmInstance inst2("testClass_2"); WsmValue val_2(inst1); inst2.addProperty(WsmProperty("property_2", val_2)); WsmInstance inst3("testClass_3"); WsmValue val_3(inst2); inst3.addProperty(WsmProperty("property_3", val_3)); WsmInstance inst("testClass"); WsmValue val(inst3); inst.addProperty(WsmProperty("property", val)); _checkInstance(inst, "Instances with recursive instance properties do not compare"); } }
Array FrameInjection::GetBacktrace(bool skip /* = false */, bool withSelf /* = false */, bool withThis /* = true */) { Array bt = Array::Create(); FrameInjection *t = ThreadInfo::s_threadInfo->m_top; if (skip && t) { t = t->m_prev; } // This is used by onError with extended exceptions if (withSelf && t) { String filename = t->getFileName(); // If the top frame is not an extension function, // add it to the trace if (filename != "") { Array frame = Array::Create(); frame.set(s_file, filename, true); frame.set(s_line, t->m_line, true); bt.append(frame); } } while (t && (RuntimeOption::InjectedStackTraceLimit < 0 || bt.size() < RuntimeOption::InjectedStackTraceLimit)) { Array frame = Array::Create(); if (t->m_prev) { String file = t->m_prev->getFileName(); if (!file.empty() && t->m_prev->m_line) { frame.set(s_file, file, true); frame.set(s_line, t->m_prev->m_line, true); } } else if (t->m_flags & PseudoMain) { // Stop at top, don't include top file break; } if (t->m_flags & PseudoMain) { frame.set(s_function, "include", true); frame.set(s_args, Array::Create(t->getFileName()), true); } else { const char *c = strstr(t->m_name, "::"); if (c) { frame.set(s_function, String(c + 2), true); frame.set(s_class, t->getClassName()->copy(), true); if (ObjectData *obj = t->getObjectV()) { if (withThis) { frame.set(s_object, Object(obj), true); } frame.set(s_type, "->", true); } else { frame.set(s_type, "::", true); } } else { frame.set(s_function, t->m_name, true); } Array args = t->getArgs(); if (!args.isNull()) { frame.set(s_args, args, true); } else { frame.set(s_args, Array::Create(), true); } } bt.append(frame); t = t->m_prev; } return bt; }
Object* System::vm_find_object(STATE, GCToken gct, Array* arg, Object* callable, CallFrame* calling_environment) { ObjectMemory::GCInhibit inhibitor(state->memory()); // Support an aux mode, where callable is an array and we just append // objects to it rather than #call it. Array* ary = try_as<Array>(callable); if(!ary) ary = nil<Array>(); Array* args = Array::create(state, 1); int total = 0; QueryCondition* condition = create_condition(state, arg); if(!condition) return Fixnum::from(0); Object* ret = cNil; // Special case for looking for an immediate if(Object* obj = condition->immediate()) { if(Symbol* sym = try_as<Symbol>(obj)) { // Check whether this is actually a valid symbol, not // some random non existing symbol. if(!state->shared().symbols.lookup_string(state, sym)) { delete condition; std::ostringstream msg; msg << "Invalid symbol 0x" << std::hex << reinterpret_cast<uintptr_t>(sym); Exception::range_error(state, msg.str().c_str()); return 0; } } if(!ary->nil_p()) { ary->append(state, obj); } else { args->set(state, 0, obj); ret = callable->send(state, calling_environment, G(sym_call), args, cNil, false); } delete condition; if(!ret) return 0; return Fixnum::from(1); } OnStack<2> os(state, ary, args); state->set_call_frame(calling_environment); ObjectWalker walker(state->memory()); GCData gc_data(state->vm()); { StopTheWorld stw(state, gct, calling_environment); // Seed it with the root objects. walker.seed(gc_data); } Object* obj = walker.next(); while(obj) { if(condition->perform(state, obj)) { total++; if(!ary->nil_p()) { ary->append(state, obj); } else { // We call back into Ruby land here, so that might trigger a GC // This ensures we mark all the locations of the current search // queue for the walker, so we update these object references // properly. Object** stack_buf = walker.stack_buf(); size_t stack_size = walker.stack_size(); Object** variable_buffer[stack_size]; for(size_t i = 0; i < stack_size; ++i) { variable_buffer[i] = &stack_buf[i]; } VariableRootBuffer vrb(state->vm()->current_root_buffers(), variable_buffer, stack_size); args->set(state, 0, obj); ret = callable->send(state, calling_environment, G(sym_call), args, cNil, false); if(!ret) break; } } obj = walker.next(); } delete condition; if(!ret) return 0; return Integer::from(state, total); }
void _xml_characterDataHandler(void *userData, const XML_Char *s, int len) { XmlParser *parser = (XmlParser *)userData; if (parser) { Variant retval; Array args = Array::Create(); if (parser->characterDataHandler.toBoolean()) { args.append(parser); args.append(_xml_xmlchar_zval(s, len, parser->target_encoding)); xml_call_handler(parser, parser->characterDataHandler, args); } if (!parser->data.isNull()) { int i; int doprint = 0; String decoded_value; int decoded_len; decoded_value = xml_utf8_decode(s,len, parser->target_encoding); decoded_len = decoded_value.size(); for (i = 0; i < decoded_len; i++) { switch (decoded_value[i]) { case ' ': case '\t': case '\n': default: doprint = 1; break; } if (doprint) { break; } } if (doprint || (! parser->skipwhite)) { if (parser->lastwasopen) { String myval; // check if value exists, if yes append to that if (parser->ctag.toArrRef().exists(s_value)) { myval = parser->ctag.toArray().rvalAt(s_value).toString(); myval += decoded_value; parser->ctag.toArrRef().set(s_value, myval); } else { parser->ctag.toArrRef().set( s_value, decoded_value ); } } else { Array tag; String myval; String mytype; auto curtag = parser->data.toArrRef().pop(); SCOPE_EXIT { try { parser->data.toArrRef().append(curtag); } catch (...) {} }; if (curtag.toArrRef().exists(s_type)) { mytype = curtag.toArrRef().rvalAt(s_type).toString(); if (!strcmp(mytype.data(), "cdata") && curtag.toArrRef().exists(s_value)) { myval = curtag.toArrRef().rvalAt(s_value).toString(); myval += decoded_value; curtag.toArrRef().set(s_value, myval); return; } } if (parser->level <= XML_MAXLEVEL) { tag = Array::Create(); _xml_add_to_info(parser, parser->ltags[parser->level-1] + parser->toffset); tag.set(s_tag, String(parser->ltags[parser->level-1] + parser->toffset, CopyString)); tag.set(s_value, decoded_value); tag.set(s_type, s_cdata); tag.set(s_level, parser->level); parser->data.toArrRef().append(tag); } else if (parser->level == (XML_MAXLEVEL + 1)) { raise_warning("Maximum depth exceeded - Results truncated"); } } } } }
// l10n - note: ignoring indication language void snmpIndicationHandler::handleIndication( const OperationContext& context, const String nameSpace, CIMInstance& indication, CIMInstance& handler, CIMInstance& subscription, ContentLanguages & contentLanguages) { Array<String> propOIDs; Array<String> propTYPEs; Array<String> propVALUEs; CIMProperty prop; CIMQualifier trapQualifier; Uint32 qualifierPos; String propValue; String mapstr1; String mapstr2; PEG_METHOD_ENTER (TRC_IND_HANDLER, "snmpIndicationHandler::handleIndication"); try { CIMClass indicationClass = _repository->getClass( nameSpace, indication.getClassName(), false, true, false, CIMPropertyList()); Uint32 propertyCount = indication.getPropertyCount(); for (Uint32 i=0; i < propertyCount; i++) { prop = indication.getProperty(i); if (!prop.isUninitialized()) { CIMName propName = prop.getName(); Uint32 propPos = indicationClass.findProperty(propName); if (propPos != PEG_NOT_FOUND) { CIMProperty trapProp = indicationClass.getProperty(propPos); qualifierPos = trapProp.findQualifier(CIMName ("MappingStrings")); if (qualifierPos != PEG_NOT_FOUND) { trapQualifier = trapProp.getQualifier(qualifierPos); mapstr1.clear(); mapstr1 = trapQualifier.getValue().toString(); if ((mapstr1.find("OID.IETF") != PEG_NOT_FOUND) && (mapstr1.find("DataType.IETF") != PEG_NOT_FOUND)) { if (mapstr1.subString(0, 8) == "OID.IETF") { mapstr1 = mapstr1.subString(mapstr1.find("SNMP.")+5); if (mapstr1.find("|") != PEG_NOT_FOUND) { mapstr2.clear(); mapstr2 = mapstr1.subString(0, mapstr1.find("DataType.IETF")-1); propOIDs.append(mapstr2); propValue.clear(); propValue = prop.getValue().toString(); propVALUEs.append(propValue); mapstr2 = mapstr1.subString(mapstr1.find("|")+2); mapstr2 = mapstr2.subString(0, mapstr2.size()-1); propTYPEs.append(mapstr2); } } } } } } } // Collected complete data in arrays and ready to send the trap. // trap destination and SNMP type are defined in handlerInstance // and passing this instance as it is to deliverTrap() call #ifdef HPUX_EMANATE static snmpDeliverTrap_emanate emanateTrap; #else static snmpDeliverTrap_stub emanateTrap; #endif Uint32 targetHostPos = handler.findProperty(CIMName ("TargetHost")); Uint32 targetHostFormatPos = handler.findProperty(CIMName ("TargetHostFormat")); Uint32 otherTargetHostFormatPos = handler.findProperty(CIMName ( "OtherTargetHostFormat")); Uint32 portNumberPos = handler.findProperty(CIMName ("PortNumber")); Uint32 snmpVersionPos = handler.findProperty(CIMName ("SNMPVersion")); Uint32 securityNamePos = handler.findProperty(CIMName ("SNMPSecurityName")); Uint32 engineIDPos = handler.findProperty(CIMName ("SNMPEngineID")); if ((targetHostPos != PEG_NOT_FOUND) && (targetHostFormatPos != PEG_NOT_FOUND) && (snmpVersionPos != PEG_NOT_FOUND) && (indicationClass.findQualifier(CIMName ("MappingStrings")) != PEG_NOT_FOUND)) { // properties from the handler instance String targetHost; String otherTargetHostFormat = String(); String securityName = String(); String engineID = String(); Uint16 targetHostFormat = 0; Uint16 snmpVersion = 0; Uint32 portNumber; String trapOid; // // Get snmpTrapOid from context // try { SnmpTrapOidContainer trapContainer = context.get (SnmpTrapOidContainer::NAME); trapOid = trapContainer.getSnmpTrapOid(); } catch (Exception& e) { // get trapOid from indication Class Uint32 pos = indicationClass.findQualifier(CIMName ("MappingStrings")); if (pos != PEG_NOT_FOUND) { trapOid = indicationClass.getQualifier(pos).getValue().toString(); trapOid = trapOid.subString(11, PEG_NOT_FOUND); if ((String::compare(trapOid, "SNMP.", 5)) == 0) { trapOid = trapOid.subString(5, (trapOid.size()-6)); } else { PEG_TRACE_STRING(TRC_IND_HANDLER, Tracer::LEVEL4, "Invalid MappingStrings Value " + trapOid); PEG_METHOD_EXIT(); // l10n // throw PEGASUS_CIM_EXCEPTION(CIM_ERR_FAILED, "Invalid MappingStrings Value"); throw PEGASUS_CIM_EXCEPTION_L (CIM_ERR_FAILED, MessageLoaderParms("Handler.snmpIndicationHandler.snmpIndicationHandler.INVALID_MS_VALUE", "Invalid MappingStrings Value")); } } else { PEG_TRACE_STRING(TRC_IND_HANDLER, Tracer::LEVEL4, "Qualifier MappingStrings can not be found."); PEG_METHOD_EXIT(); //L10N_ TODO DONE //throw PEGASUS_CIM_EXCEPTION(CIM_ERR_FAILED, "Qualifier MappingStrings can not be found"); MessageLoaderParms parms("Handler.snmpIndicationHandler.snmpIndicationHandler.QUALIFIER_MAPPINGS_NOT_FOUND", "Qualifier MappingStrings can not be found"); throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, parms); } } handler.getProperty(targetHostPos).getValue().get(targetHost); handler.getProperty(targetHostFormatPos).getValue().get(targetHostFormat); if (otherTargetHostFormatPos != PEG_NOT_FOUND) { handler.getProperty(otherTargetHostFormatPos).getValue().get (otherTargetHostFormat); } if (portNumberPos != PEG_NOT_FOUND) { handler.getProperty(portNumberPos).getValue().get(portNumber); } else { // default port portNumber = SNMP_TRAP_DEFAULT_PORT; } handler.getProperty(snmpVersionPos).getValue().get(snmpVersion); if (securityNamePos != PEG_NOT_FOUND) { handler.getProperty(securityNamePos).getValue().get(securityName); } if (engineIDPos != PEG_NOT_FOUND) { handler.getProperty(engineIDPos).getValue().get(engineID); } emanateTrap.deliverTrap( trapOid, securityName, targetHost, targetHostFormat, otherTargetHostFormat, portNumber, snmpVersion, engineID, propOIDs, propTYPEs, propVALUEs); } else { PEG_TRACE_STRING(TRC_IND_HANDLER, Tracer::LEVEL4, "Invalid IndicationHandlerSNMPMapper instance."); PEG_METHOD_EXIT(); // l10n // throw PEGASUS_CIM_EXCEPTION(CIM_ERR_FAILED, // "Invalid IndicationHandlerSNMPMapper instance"); throw PEGASUS_CIM_EXCEPTION_L (CIM_ERR_FAILED, MessageLoaderParms("Handler.snmpIndicationHandler.snmpIndicationHandler.INVALID_SNMP_INSTANCE", "Invalid IndicationHandlerSNMPMapper instance")); } } catch (CIMException & c) { PEG_TRACE_STRING(TRC_IND_HANDLER, Tracer::LEVEL4, c.getMessage()); PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION (CIM_ERR_FAILED, c.getMessage()); } catch (Exception& e) { PEG_TRACE_STRING(TRC_IND_HANDLER, Tracer::LEVEL4, e.getMessage()); PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION (CIM_ERR_FAILED, e.getMessage()); } catch (...) { PEG_TRACE_STRING(TRC_IND_HANDLER, Tracer::LEVEL4, "Failed to deliver trap."); PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION_L (CIM_ERR_FAILED, MessageLoaderParms("Handler.snmpIndicationHandler.snmpIndicationHandler.FAILED_TO_DELIVER_TRAP", "Failed to deliver trap.")); } }
Array VoxelMesher::build(const VoxelBuffer &buffer, unsigned int channel, Vector3i min, Vector3i max) { uint64_t time_before = OS::get_singleton()->get_ticks_usec(); ERR_FAIL_COND_V(_library.is_null(), Array()); ERR_FAIL_COND_V(channel >= VoxelBuffer::MAX_CHANNELS, Array()); const VoxelLibrary &library = **_library; for (unsigned int i = 0; i < MAX_MATERIALS; ++i) { Arrays &a = _arrays[i]; a.positions.clear(); a.normals.clear(); a.uvs.clear(); a.colors.clear(); a.indices.clear(); } float baked_occlusion_darkness; if (_bake_occlusion) baked_occlusion_darkness = _baked_occlusion_darkness / 3.0; // The technique is Culled faces. // Could be improved with greedy meshing: https://0fps.net/2012/06/30/meshing-in-a-minecraft-game/ // However I don't feel it's worth it yet: // - Not so much gain for organic worlds with lots of texture variations // - Works well with cubes but not with any shape // - Slower // => Could be implemented in a separate class? // Data must be padded, hence the off-by-one Vector3i::sort_min_max(min, max); const Vector3i pad(1, 1, 1); min.clamp_to(pad, max); max.clamp_to(min, buffer.get_size() - pad); int index_offset = 0; // Iterate 3D padded data to extract voxel faces. // This is the most intensive job in this class, so all required data should be as fit as possible. // The buffer we receive MUST be dense (i.e not compressed, and channels allocated). // That means we can use raw pointers to voxel data inside instead of using the higher-level getters, // and then save a lot of time. uint8_t *type_buffer = buffer.get_channel_raw(Voxel::CHANNEL_TYPE); // _ // | \ // /\ \\ // / /|\\\ // | |\ \\\ // | \_\ \\| // | | ) // \ | | // \ / CRASH_COND(type_buffer == NULL); //CRASH_COND(memarr_len(type_buffer) != buffer.get_volume() * sizeof(uint8_t)); // Build lookup tables so to speed up voxel access. // These are values to add to an address in order to get given neighbor. int row_size = buffer.get_size().y; int deck_size = buffer.get_size().x * row_size; int side_neighbor_lut[Cube::SIDE_COUNT]; side_neighbor_lut[Cube::SIDE_LEFT] = row_size; side_neighbor_lut[Cube::SIDE_RIGHT] = -row_size; side_neighbor_lut[Cube::SIDE_BACK] = -deck_size; side_neighbor_lut[Cube::SIDE_FRONT] = deck_size; side_neighbor_lut[Cube::SIDE_BOTTOM] = -1; side_neighbor_lut[Cube::SIDE_TOP] = 1; int edge_neighbor_lut[Cube::EDGE_COUNT]; edge_neighbor_lut[Cube::EDGE_BOTTOM_BACK] = side_neighbor_lut[Cube::SIDE_BOTTOM] + side_neighbor_lut[Cube::SIDE_BACK]; edge_neighbor_lut[Cube::EDGE_BOTTOM_FRONT] = side_neighbor_lut[Cube::SIDE_BOTTOM] + side_neighbor_lut[Cube::SIDE_FRONT]; edge_neighbor_lut[Cube::EDGE_BOTTOM_LEFT] = side_neighbor_lut[Cube::SIDE_BOTTOM] + side_neighbor_lut[Cube::SIDE_LEFT]; edge_neighbor_lut[Cube::EDGE_BOTTOM_RIGHT] = side_neighbor_lut[Cube::SIDE_BOTTOM] + side_neighbor_lut[Cube::SIDE_RIGHT]; edge_neighbor_lut[Cube::EDGE_BACK_LEFT] = side_neighbor_lut[Cube::SIDE_BACK] + side_neighbor_lut[Cube::SIDE_LEFT]; edge_neighbor_lut[Cube::EDGE_BACK_RIGHT] = side_neighbor_lut[Cube::SIDE_BACK] + side_neighbor_lut[Cube::SIDE_RIGHT]; edge_neighbor_lut[Cube::EDGE_FRONT_LEFT] = side_neighbor_lut[Cube::SIDE_FRONT] + side_neighbor_lut[Cube::SIDE_LEFT]; edge_neighbor_lut[Cube::EDGE_FRONT_RIGHT] = side_neighbor_lut[Cube::SIDE_FRONT] + side_neighbor_lut[Cube::SIDE_RIGHT]; edge_neighbor_lut[Cube::EDGE_TOP_BACK] = side_neighbor_lut[Cube::SIDE_TOP] + side_neighbor_lut[Cube::SIDE_BACK]; edge_neighbor_lut[Cube::EDGE_TOP_FRONT] = side_neighbor_lut[Cube::SIDE_TOP] + side_neighbor_lut[Cube::SIDE_FRONT]; edge_neighbor_lut[Cube::EDGE_TOP_LEFT] = side_neighbor_lut[Cube::SIDE_TOP] + side_neighbor_lut[Cube::SIDE_LEFT]; edge_neighbor_lut[Cube::EDGE_TOP_RIGHT] = side_neighbor_lut[Cube::SIDE_TOP] + side_neighbor_lut[Cube::SIDE_RIGHT]; int corner_neighbor_lut[Cube::CORNER_COUNT]; corner_neighbor_lut[Cube::CORNER_BOTTOM_BACK_LEFT] = side_neighbor_lut[Cube::SIDE_BOTTOM] + side_neighbor_lut[Cube::SIDE_BACK] + side_neighbor_lut[Cube::SIDE_LEFT]; corner_neighbor_lut[Cube::CORNER_BOTTOM_BACK_RIGHT] = side_neighbor_lut[Cube::SIDE_BOTTOM] + side_neighbor_lut[Cube::SIDE_BACK] + side_neighbor_lut[Cube::SIDE_RIGHT]; corner_neighbor_lut[Cube::CORNER_BOTTOM_FRONT_RIGHT] = side_neighbor_lut[Cube::SIDE_BOTTOM] + side_neighbor_lut[Cube::SIDE_FRONT] + side_neighbor_lut[Cube::SIDE_RIGHT]; corner_neighbor_lut[Cube::CORNER_BOTTOM_FRONT_LEFT] = side_neighbor_lut[Cube::SIDE_BOTTOM] + side_neighbor_lut[Cube::SIDE_FRONT] + side_neighbor_lut[Cube::SIDE_LEFT]; corner_neighbor_lut[Cube::CORNER_TOP_BACK_LEFT] = side_neighbor_lut[Cube::SIDE_TOP] + side_neighbor_lut[Cube::SIDE_BACK] + side_neighbor_lut[Cube::SIDE_LEFT]; corner_neighbor_lut[Cube::CORNER_TOP_BACK_RIGHT] = side_neighbor_lut[Cube::SIDE_TOP] + side_neighbor_lut[Cube::SIDE_BACK] + side_neighbor_lut[Cube::SIDE_RIGHT]; corner_neighbor_lut[Cube::CORNER_TOP_FRONT_RIGHT] = side_neighbor_lut[Cube::SIDE_TOP] + side_neighbor_lut[Cube::SIDE_FRONT] + side_neighbor_lut[Cube::SIDE_RIGHT]; corner_neighbor_lut[Cube::CORNER_TOP_FRONT_LEFT] = side_neighbor_lut[Cube::SIDE_TOP] + side_neighbor_lut[Cube::SIDE_FRONT] + side_neighbor_lut[Cube::SIDE_LEFT]; uint64_t time_prep = OS::get_singleton()->get_ticks_usec() - time_before; time_before = OS::get_singleton()->get_ticks_usec(); for (unsigned int z = min.z; z < max.z; ++z) { for (unsigned int x = min.x; x < max.x; ++x) { for (unsigned int y = min.y; y < max.y; ++y) { // min and max are chosen such that you can visit 1 neighbor away from the current voxel without size check // TODO In this intensive routine, there is a way to make voxel access fastest by getting a pointer to the channel, // and using offset lookup to get neighbors rather than going through get_voxel validations int voxel_index = y + x * row_size + z * deck_size; int voxel_id = type_buffer[voxel_index]; if (voxel_id != 0 && library.has_voxel(voxel_id)) { const Voxel &voxel = library.get_voxel_const(voxel_id); Arrays &arrays = _arrays[voxel.get_material_id()]; // Hybrid approach: extract cube faces and decimate those that aren't visible, // and still allow voxels to have geometry that is not a cube // Sides for (unsigned int side = 0; side < Cube::SIDE_COUNT; ++side) { const PoolVector<Vector3> &positions = voxel.get_model_side_positions(side); int vertex_count = positions.size(); if (vertex_count != 0) { int neighbor_voxel_id = type_buffer[voxel_index + side_neighbor_lut[side]]; // TODO Better face visibility test if (is_face_visible(library, voxel, neighbor_voxel_id)) { // The face is visible int shaded_corner[8] = { 0 }; if (_bake_occlusion) { // Combinatory solution for https://0fps.net/2013/07/03/ambient-occlusion-for-minecraft-like-worlds/ for (unsigned int j = 0; j < 4; ++j) { unsigned int edge = Cube::g_side_edges[side][j]; int edge_neighbor_id = type_buffer[voxel_index + edge_neighbor_lut[edge]]; if (!is_transparent(library, edge_neighbor_id)) { shaded_corner[Cube::g_edge_corners[edge][0]] += 1; shaded_corner[Cube::g_edge_corners[edge][1]] += 1; } } for (unsigned int j = 0; j < 4; ++j) { unsigned int corner = Cube::g_side_corners[side][j]; if (shaded_corner[corner] == 2) { shaded_corner[corner] = 3; } else { int corner_neigbor_id = type_buffer[voxel_index + corner_neighbor_lut[corner]]; if (!is_transparent(library, corner_neigbor_id)) { shaded_corner[corner] += 1; } } } } PoolVector<Vector3>::Read rv = positions.read(); PoolVector<Vector2>::Read rt = voxel.get_model_side_uv(side).read(); // Subtracting 1 because the data is padded Vector3 pos(x - 1, y - 1, z - 1); // Append vertices of the faces in one go, don't use push_back { int append_index = arrays.positions.size(); arrays.positions.resize(arrays.positions.size() + vertex_count); Vector3 *w = arrays.positions.ptrw() + append_index; for (unsigned int i = 0; i < vertex_count; ++i) { w[i] = rv[i] + pos; } } { int append_index = arrays.uvs.size(); arrays.uvs.resize(arrays.uvs.size() + vertex_count); memcpy(arrays.uvs.ptrw() + append_index, rt.ptr(), vertex_count * sizeof(Vector2)); } { int append_index = arrays.normals.size(); arrays.normals.resize(arrays.normals.size() + vertex_count); Vector3 *w = arrays.normals.ptrw() + append_index; for (unsigned int i = 0; i < vertex_count; ++i) { w[i] = Cube::g_side_normals[side].to_vec3(); } } if (_bake_occlusion) { // Use color array int append_index = arrays.colors.size(); arrays.colors.resize(arrays.colors.size() + vertex_count); Color *w = arrays.colors.ptrw() + append_index; for (unsigned int i = 0; i < vertex_count; ++i) { Vector3 v = rv[i]; // General purpose occlusion colouring. // TODO Optimize for cubes // TODO Fix occlusion inconsistency caused by triangles orientation? Not sure if worth it float shade = 0; for (unsigned int j = 0; j < 4; ++j) { unsigned int corner = Cube::g_side_corners[side][j]; if (shaded_corner[corner]) { float s = baked_occlusion_darkness * static_cast<float>(shaded_corner[corner]); float k = 1.0 - Cube::g_corner_position[corner].distance_to(v); if (k < 0.0) k = 0.0; s *= k; if (s > shade) shade = s; } } float gs = 1.0 - shade; w[i] = Color(gs, gs, gs); } } const PoolVector<int> &side_indices = voxel.get_model_side_indices(side); PoolVector<int>::Read ri = side_indices.read(); unsigned int index_count = side_indices.size(); { int i = arrays.indices.size(); arrays.indices.resize(arrays.indices.size() + index_count); int *w = arrays.indices.ptrw(); for(unsigned int j = 0; j < index_count; ++j) { w[i++] = index_offset + ri[j]; } } index_offset += vertex_count; } } } // Inside if (voxel.get_model_positions().size() != 0) { // TODO Get rid of push_backs const PoolVector<Vector3> &vertices = voxel.get_model_positions(); int vertex_count = vertices.size(); PoolVector<Vector3>::Read rv = vertices.read(); PoolVector<Vector3>::Read rn = voxel.get_model_normals().read(); PoolVector<Vector2>::Read rt = voxel.get_model_uv().read(); Vector3 pos(x - 1, y - 1, z - 1); for (unsigned int i = 0; i < vertex_count; ++i) { arrays.normals.push_back(rn[i]); arrays.uvs.push_back(rt[i]); arrays.positions.push_back(rv[i] + pos); } if(_bake_occlusion) { // TODO handle ambient occlusion on inner parts arrays.colors.push_back(Color(1,1,1)); } const PoolVector<int> &indices = voxel.get_model_indices(); PoolVector<int>::Read ri = indices.read(); unsigned int index_count = indices.size(); for(unsigned int i = 0; i < index_count; ++i) { arrays.indices.push_back(index_offset + ri[i]); } index_offset += vertex_count; } } } } } uint64_t time_meshing = OS::get_singleton()->get_ticks_usec() - time_before; time_before = OS::get_singleton()->get_ticks_usec(); // Commit mesh // print_line(String("Made mesh v: ") + String::num(_arrays[0].positions.size()) // + String(", i: ") + String::num(_arrays[0].indices.size())); Array surfaces; // TODO We could return a single byte array and use Mesh::add_surface down the line? for (int i = 0; i < MAX_MATERIALS; ++i) { const Arrays &arrays = _arrays[i]; if (arrays.positions.size() != 0) { /*print_line("Arrays:"); for(int i = 0; i < arrays.positions.size(); ++i) print_line(String(" P {0}").format(varray(arrays.positions[i]))); for(int i = 0; i < arrays.normals.size(); ++i) print_line(String(" N {0}").format(varray(arrays.normals[i]))); for(int i = 0; i < arrays.uvs.size(); ++i) print_line(String(" UV {0}").format(varray(arrays.uvs[i])));*/ Array mesh_arrays; mesh_arrays.resize(Mesh::ARRAY_MAX); { PoolVector<Vector3> positions; PoolVector<Vector2> uvs; PoolVector<Vector3> normals; PoolVector<Color> colors; PoolVector<int> indices; raw_copy_to(positions, arrays.positions); raw_copy_to(uvs, arrays.uvs); raw_copy_to(normals, arrays.normals); raw_copy_to(colors, arrays.colors); raw_copy_to(indices, arrays.indices); mesh_arrays[Mesh::ARRAY_VERTEX] = positions; mesh_arrays[Mesh::ARRAY_TEX_UV] = uvs; mesh_arrays[Mesh::ARRAY_NORMAL] = normals; mesh_arrays[Mesh::ARRAY_COLOR] = colors; mesh_arrays[Mesh::ARRAY_INDEX] = indices; } surfaces.append(mesh_arrays); } } uint64_t time_commit = OS::get_singleton()->get_ticks_usec() - time_before; //print_line(String("P: {0}, M: {1}, C: {2}").format(varray(time_prep, time_meshing, time_commit))); return surfaces; }
void LifecycleIndicationProvider::createInstance( const OperationContext & context, const CIMObjectPath & instanceReference, const CIMInstance & instanceObject, ObjectPathResponseHandler & handler) { // cout << "LifecycleIndicationProvider::createInstance()" << endl; // Validate the class name if(!instanceObject.getClassName().equal( "Sample_LifecycleIndicationProviderClass")) { throw CIMNotSupportedException( instanceObject.getClassName().getString()); } // Find the key property Uint32 idIndex = instanceObject.findProperty("uniqueId"); if(idIndex == PEG_NOT_FOUND) { throw CIMInvalidParameterException("Missing key value"); } CIMInstance cimInstance = instanceObject.clone(); // Create the new instance name CIMValue idValue = instanceObject.getProperty(idIndex).getValue(); Array<CIMKeyBinding> keys; keys.append(CIMKeyBinding("uniqueId", idValue)); CIMObjectPath instanceName = CIMObjectPath( String(), CIMNamespaceName(), instanceObject.getClassName(), keys); cimInstance.setPath(instanceName); // Determine whether this instance already exists for(Uint32 i = 0, n = _instances.size(); i < n; i++) { if(instanceName == _instances[i].getPath()) { throw CIMObjectAlreadyExistsException(instanceName.toString()); } } // begin processing the request handler.processing(); // add the new instance to the array _instances.append(cimInstance); // deliver the new instance name handler.deliver(instanceName); // complete processing the request handler.complete(); // If there is at least one subscription active for the lifecycle indication // InstCreation_for_Sample_LifecycleIndicationProviderClass, then generate // that indication here, embedding the newly-created instance as // the SourceInstance property. See LifecycleIndicationProviderR.mof. if (_lifecycle_indications_enabled) { CIMInstance indicationInstance( CIMName( "InstCreation_for_Sample_LifecycleIndicationProviderClass")); CIMObjectPath path; path.setNameSpace("root/SampleProvider"); path.setClassName( "InstCreation_for_Sample_LifecycleIndicationProviderClass"); indicationInstance.setPath(path); char buffer[32]; sprintf(buffer, "%d", _nextUID++); indicationInstance.addProperty (CIMProperty ("IndicationIdentifier",String(buffer))); CIMDateTime currentDateTime = CIMDateTime::getCurrentDateTime (); indicationInstance.addProperty (CIMProperty ("IndicationTime", currentDateTime)); indicationInstance.addProperty (CIMProperty ("SourceInstance",CIMObject(cimInstance))); _indication_handler->deliver (indicationInstance); // cout << "LifecycleIndicationProvider::createInstance() sent " // "InstCreation_for_Sample_LifecycleIndicationProviderClass" // << endl; } }
// Pack trap information into the PDU void snmpDeliverTrap_netsnmp::_packTrapInfoIntoPdu( const String& trapOid, snmp_pdu* snmpPdu) { PEG_METHOD_ENTER(TRC_IND_HANDLER, "snmpDeliverTrap_netsnmp::_packTrapInfoIntoPdu"); oid enterpriseOid[MAX_OID_LEN]; size_t enterpriseOidLength; Array<String> standard_traps; standard_traps.append(String("1.3.6.1.6.3.1.1.5.1")); standard_traps.append(String("1.3.6.1.6.3.1.1.5.2")); standard_traps.append(String("1.3.6.1.6.3.1.1.5.3")); standard_traps.append(String("1.3.6.1.6.3.1.1.5.4")); standard_traps.append(String("1.3.6.1.6.3.1.1.5.5")); standard_traps.append(String("1.3.6.1.6.3.1.1.5.6")); Array<const char*> oidSubIdentifiers; CString trapOidCStr = trapOid.getCString(); char* trapOidCopy = strdup(trapOidCStr); char* numericEntOid = (char*) malloc(strlen(trapOidCStr)); try { #if !defined(PEGASUS_OS_TYPE_WINDOWS) && !defined(PEGASUS_OS_ZOS) char* last; for (const char* p = strtok_r(trapOidCopy, ".", &last); p; p=strtok_r(NULL, ".", &last)) #else for (const char* p = strtok(trapOidCopy, "."); p; p=strtok(NULL, ".")) #endif { oidSubIdentifiers.append(p); } long genTrap = 0; long specTrap = 0; enterpriseOidLength = MAX_OID_LEN; if (Contains(standard_traps, trapOid)) { // // if the trapOid is one of the standard traps, // then the SNMPV1 enterprise parameter must be set // to the value of the trapOid, the generic-trap // parameter must be set to one of (0 - 5), and the // specific-trap parameter must be set to 0 // // Convert trapOid from numeric form to a list of subidentifiers if (read_objid((const char*)trapOidCStr, enterpriseOid, &enterpriseOidLength) == 0) { // Failed to parse trapOid PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms(_MSG_READ_OBJID_FAILED_KEY, _MSG_READ_OBJID_FAILED, trapOid)); } // the generic trap is last sub-identifier of the // trapOid minus 1 snmpPdu->trap_type = atoi(oidSubIdentifiers[oidSubIdentifiers.size() - 1]) - 1; snmpPdu->specific_type = 0; } else { // // if the trapOid is not one of the standard traps: // then 1) the generic-trap parameter must be set to 6, // 2) if the next-to-last sub-identifier of the // trapOid is zero, then the SNMPV1 enterprise // parameter is the trapOid with the last 2 // sub-identifiers removed, otherwise, the // SNMPV1 enterprise parameter is the trapOid // with the last sub-identifier removed; // 3) the SNMPv1 specific-trap parameter is the last // sub-identifier of the trapOid; // snmpPdu->trap_type = 6; snmpPdu->specific_type = atoi(oidSubIdentifiers[oidSubIdentifiers.size()-1]); strcpy(numericEntOid, oidSubIdentifiers[0]); for (Uint32 i = 1; i < oidSubIdentifiers.size()-2; i++) { strcat(numericEntOid, "."); strcat(numericEntOid, oidSubIdentifiers[i]); } if (strcmp(oidSubIdentifiers[oidSubIdentifiers.size()-2], "0") != 0) { strcat(numericEntOid, "."); strcat(numericEntOid, oidSubIdentifiers[oidSubIdentifiers.size()-2]); } // Convert ent from numeric form to a list of subidentifiers if (read_objid(numericEntOid, enterpriseOid, &enterpriseOidLength) == 0) { // Failed to parse numericEntOid PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms(_MSG_READ_ENTOID_FAILED_KEY, _MSG_READ_ENTOID_FAILED, String(numericEntOid))); } } snmpPdu->enterprise = (oid*) malloc(enterpriseOidLength * sizeof(oid)); memcpy(snmpPdu->enterprise, enterpriseOid, enterpriseOidLength * sizeof(oid)); snmpPdu->enterprise_length = enterpriseOidLength; } catch (...) { free(trapOidCopy); free(numericEntOid); PEG_METHOD_EXIT(); throw; } free(trapOidCopy); free(numericEntOid); PEG_METHOD_EXIT(); }
void convertMidiFile(MidiFile& midifile, Array<Array<double> >& matlab) { midifile.absoluteTime(); midifile.joinTracks(); Array<double> event(7); event.allowGrowth(0); Array<double> ontimes(128); Array<int> onvelocities(128); int i; for (i=0; i<128; i++) { ontimes[i] = -1.0; onvelocities[i] = -1; } double offtime = 0.0; int key = 0; int vel = 0; int command = 0; if (verboseQ) { cout << "-1\ttpq\t" << midifile.getTicksPerQuarterNote() << endl; } for (i=0; i<midifile.getNumEvents(0); i++) { event.setAll(unused); command = midifile.getEvent(0, i).data[0] & 0xf0; if (command == 0xf0) { command = midifile.getEvent(0, i).data[0]; } if (command == 0x90 && midifile.getEvent(0, i).data[2] != 0) { // store note-on velocity and time key = midifile.getEvent(0, i).data[1]; vel = midifile.getEvent(0, i).data[2]; ontimes[key] = getTime(midifile.getEvent(0, i).time, tempo, midifile.getTicksPerQuarterNote()); onvelocities[key] = vel; } else if (command == 0x90 || command == 0x80) { // note off command write to output key = midifile.getEvent(0, i).data[1]; offtime = getTime(midifile.getEvent(0, i).time, tempo, midifile.getTicksPerQuarterNote()); legend_opcode[OP_NOTE/1000] = 1; if (verboseQ) { cout << ontimes[key] << "\tnote" << "\tdur=" << offtime - ontimes[key] << "\tpch=" << key << "\tvel=" << onvelocities[key] << "\tch=" << (midifile.getEvent(0, i).data[0] & 0x0f) << "\ttrack=" << midifile.getEvent(0, i).track << endl; } else { event[0] = ontimes[key]; event[1] = OP_NOTE; event[2] = offtime - ontimes[key]; event[3] = key; event[4] = onvelocities[key]; event[5] = (midifile.getEvent(0, i).data[0] & 0x0f); event[6] = midifile.getEvent(0, i).track; } } else if (command == 0xb0) { legend_controller[midifile.getEvent(0,i).data[1]] = 1; legend_opcode[OP_CONTROL/1000] = 1; if (verboseQ) { cout << getTime(midifile.getEvent(0,i).time, tempo, midifile.getTicksPerQuarterNote()) << "\tcontrol" << "\ttype=" << (int)midifile.getEvent(0, i).data[1] << "\tval=" << (int)midifile.getEvent(0, i).data[2] << "\tch=" << (midifile.getEvent(0, i).data[0] & 0x0f) << "\ttrack=" << midifile.getEvent(0, i).track << "\n"; } else { event[0] = getTime(midifile.getEvent(0,i).time, tempo, midifile.getTicksPerQuarterNote()); event[1] = OP_CONTROL; event[2] = (int)midifile.getEvent(0,i).data[1]; event[3] = (int)midifile.getEvent(0,i).data[2]; event[5] = (midifile.getEvent(0, i).data[0] & 0x0f); event[6] = midifile.getEvent(0, i).track; } } else if (command == 0xc0) { legend_instr[midifile.getEvent(0,i).data[1]] = 1; legend_opcode[OP_INSTR/1000] = 1; if (verboseQ) { cout << getTime(midifile.getEvent(0,i).time, tempo, midifile.getTicksPerQuarterNote()) << "\tinstr" << "\tname=" << GMinstrument[midifile.getEvent(0,i).data[1]] << "\tnum=" << (int)midifile.getEvent(0, i).data[1] << "\tch=" << (midifile.getEvent(0, i).data[0] & 0x0f) << "\ttrack=" << midifile.getEvent(0, i).track << "\n"; } else { event[0] = getTime(midifile.getEvent(0,i).time, tempo, midifile.getTicksPerQuarterNote()); event[1] = OP_INSTR; event[2] = (int)midifile.getEvent(0, i).data[1]; event[5] = (midifile.getEvent(0, i).data[0] & 0x0f); event[6] = midifile.getEvent(0, i).track; } } else if (command == 0xff) { if (verboseQ) { cout << getTime(midifile.getEvent(0,i).time, tempo, midifile.getTicksPerQuarterNote()) << "\t"; } else { event[0] = getTime(midifile.getEvent(0,i).time, tempo, midifile.getTicksPerQuarterNote()); } processMetaEvent(midifile, i, event); if (verboseQ) { cout << "\n"; } } // check for tempo indication if (midifile.getEvent(0, i).data[0] == 0xff && midifile.getEvent(0, i).data[1] == 0x51) { setTempo(midifile, i, tempo); } if (event[1] != unused) { matlab.append(event); } } }
void App::onGraphics (RenderDevice *rd, Array< SurfaceRef > &posed3D, Array< Surface2DRef > &posed2D) { rd->setColorClearValue(Color3::white()); rd->clear(); doFunStuff(); rd->push2D(); int w = rd->width(); int h = rd->height(); /////////////////////////////////////// // Left panel # define LABEL(str) p.y += titleFont->draw2D(rd, str, p - Vector2((float)w * 0.0075f, 0), s * 2, Color3::white() * 0.4f).y # define PRINT(str) p.y += reportFont->draw2D(rd, str, p, s, Color3::black()).y int x0 = int(w * 0.015f); // Cursor position Vector2 p(x0, h * 0.02f); // Font size float s = w * 0.013; LABEL("Shaders"); PRINT(std::string("Combiners: ") + combineShader); PRINT(std::string("Assembly: ") + asmShader); PRINT(std::string("GLSL: ") + glslShader); p.y += s * 2; LABEL("Extensions"); PRINT(std::string("FSAA: ") + ((GLCaps::supports("WGL_ARB_multisample") || GLCaps::supports("GL_ARB_multisample")) ? "Yes" : "No")); PRINT(std::string("Two-sided Stencil: ") + ((GLCaps::supports_two_sided_stencil() ? "Yes" : "No"))); PRINT(std::string("Stencil Wrap: ") + (GLCaps::supports("GL_EXT_stencil_wrap") ? "Yes" : "No")); PRINT(std::string("Texture Compression: ") + (GLCaps::supports("GL_EXT_texture_compression_s3tc") ? "Yes" : "No")); PRINT(std::string("Shadow Maps: ") + (GLCaps::supports("GL_ARB_shadow") ? "Yes" : "No")); PRINT(std::string("Frame Buffer Object: ") + (GLCaps::supports("GL_EXT_framebuffer_object") ? "Yes" : "No")); PRINT(std::string("Vertex Arrays: ") + (GLCaps::supports_GL_ARB_vertex_buffer_object() ? "Yes" : "No")); /////////////////////////////////////// // Right Panel x0 = int(w * 0.6f); // Cursor position p = Vector2(x0, h * 0.02f); // Graphics Card LABEL("Graphics Card"); rd->setTexture(0, cardLogo); Draw::rect2D(Rect2D::xywh(p.x - s * 6, p.y, s * 5, s * 5), rd); rd->setTexture(0, NULL); PRINT(GLCaps::vendor().c_str()); PRINT(GLCaps::renderer().c_str()); PRINT(format("Driver Version %s", GLCaps::driverVersion().c_str())); # ifdef G3D_WIN32 PRINT(format("%d MB Video RAM", DXCaps::videoMemorySize() / (1024 * 1024))); { uint32 ver = DXCaps::version(); PRINT(format("DirectX %d.%d", ver/100, ver%100)); } # endif p.y += s * 2; // Processor LABEL("Processor"); rd->setTexture(0, chipLogo); Draw::rect2D(Rect2D::xywh(p.x - s * 6, p.y, s * 5, s * 5), rd); rd->setTexture(0, NULL); PRINT(System::cpuVendor().c_str()); PRINT(System::cpuArchitecture().c_str()); Array<std::string> features; if (System::has3DNow()) { features.append("3DNow"); } if (System::hasMMX()) { features.append("MMX"); } if (System::hasSSE()) { features.append("SSE"); } if (System::hasSSE2()) { features.append("SSE2"); } if (chipSpeed != "") { PRINT(chipSpeed + " " + stringJoin(features, '/')); } else { PRINT(stringJoin(features, '/')); } p.y += s * 2; // Operating System LABEL("OS"); rd->setTexture(0, osLogo); Draw::rect2D(Rect2D::xywh(p.x - s * 6, p.y - s * 2, s * 5, s * 5), rd); rd->setTexture(0, NULL); if (beginsWith(System::operatingSystem(), "Windows 5.0")) { PRINT("Windows 2000"); } else if (beginsWith(System::operatingSystem(), "Windows 5.1")) { PRINT("Windows XP"); } PRINT(System::operatingSystem().c_str()); p.y += s * 3; x0 = int(w - s * 10); titleFont->draw2D(rd, "Features", p - Vector2(w * 0.0075f, 0), s * 2, Color3::white() * 0.4f); p.y += reportFont->draw2D(rd, format("f%d", featureRating), Vector2(x0, p.y), s*2, Color3::red() * 0.5).y; drawBar(rd, featureRating, p); // Designed to put NV40 at 50 performanceRating = log(rd->stats().frameRate) * 15.0f; p.y += s * 4; performanceButton = Rect2D::xywh(p, titleFont->draw2D(rd, "Speed", p - Vector2(w * 0.0075f, 0), s * 2, Color3::white() * 0.4f)); { float spd = iRound(performanceRating * 10) / 10.0f; p.y += reportFont->draw2D(rd, format("%5.1f", spd), Vector2(x0 - s*2, p.y), s*2, Color3::red() * 0.5).y; } drawBar(rd, (int)min(performanceRating, 100.0f), p); p.y += s * 4; titleFont->draw2D(rd, "Quality", p - Vector2(w * 0.0075f, 0), s * 2, Color3::white() * 0.4f); p.y += reportFont->draw2D(rd, quality(bugCount), Vector2(x0, p.y), s*2, Color3::red() * 0.5f).y; drawBar(rd, iClamp(100 - bugCount * 10, 0, 100), p); # undef PRINT p.y = h - 50; # define PRINT(str) p.y += reportFont->draw2D(rd, str, p, 8, Color3::black()).y; PRINT("These ratings are based on the performance of G3D apps."); PRINT("They may not be representative of overall 3D performance."); PRINT("Speed is based on both processor and graphics card. Upgrading"); PRINT("your graphics driver may improve Quality and Features."); # undef PRINT # undef LABEL switch (popup) { case NONE: break; case PERFORMANCE: { // Draw the popup box Rect2D box = drawPopup("Performance Details"); p.x = box.x0() + 10; p.y = box.y0() + 30; Vector2 spacing(box.width() / 6.5, 0); std::string str; float factor = 3 * vertexPerformance.numTris / 1e6; # define PRINT(cap, val) \ reportFont->draw2D(rd, cap, p, s, Color3::black());\ reportFont->draw2D(rd, (vertexPerformance.val[0] > 0) ? \ format("%5.1f", vertexPerformance.val[0]) : \ std::string("X"), p + spacing * 3, s, Color3::red() * 0.5, Color4::clear(), GFont::XALIGN_RIGHT);\ reportFont->draw2D(rd, (vertexPerformance.val[0] > 0) ? \ format("%5.1f", factor * vertexPerformance.val[0]) : \ std::string("X"), p + spacing * 4, s, Color3::red() * 0.5, Color4::clear(), GFont::XALIGN_RIGHT);\ reportFont->draw2D(rd, (vertexPerformance.val[1] > 0) ? \ format("%5.1f", vertexPerformance.val[1]) : \ std::string("X"), p + spacing * 5, s, Color3::red() * 0.5, Color4::clear(), GFont::XALIGN_RIGHT);\ p.y += reportFont->draw2D(rd, (vertexPerformance.val[1] > 0) ? \ format("%5.1f", factor * vertexPerformance.val[1]) : \ std::string("X"), p + spacing * 6, s, Color3::red() * 0.5, Color4::clear(), GFont::XALIGN_RIGHT).y; reportFont->draw2D(rd, "Incoherent", p + spacing * 3.5, s, Color3::black(), Color4::clear(), GFont::XALIGN_RIGHT); p.y += reportFont->draw2D(rd, "Coherent", p + spacing * 5.5, s, Color3::black(), Color4::clear(), GFont::XALIGN_RIGHT).y; reportFont->draw2D(rd, "FPS*", p + spacing * 3, s, Color3::black(), Color4::clear(), GFont::XALIGN_RIGHT); reportFont->draw2D(rd, "MVerts/s", p + spacing * 4, s, Color3::black(), Color4::clear(), GFont::XALIGN_RIGHT); reportFont->draw2D(rd, "FPS*", p + spacing * 5, s, Color3::black(), Color4::clear(), GFont::XALIGN_RIGHT).y; p.y += reportFont->draw2D(rd, "MVerts/s", p + spacing * 6, s, Color3::black(), Color4::clear(), GFont::XALIGN_RIGHT).y; PRINT("glBegin/glEnd", beginEndFPS); PRINT("glDrawElements", drawElementsRAMFPS); PRINT(" + VBO", drawElementsVBOFPS); PRINT(" + uint16", drawElementsVBO16FPS); PRINT(" + gl interleave", drawElementsVBOIFPS); PRINT(" + manual interleave", drawElementsVBOIMFPS); PRINT(" (without shading)", drawElementsVBOPeakFPS); reportFont->draw2D(rd, "glDrawArrays", p, s, Color3::black()); reportFont->draw2D(rd, (vertexPerformance.drawArraysVBOPeakFPS > 0) ? \ format("%5.1f", vertexPerformance.drawArraysVBOPeakFPS) : \ std::string("X"), p + spacing * 5, s, Color3::red() * 0.5, Color4::clear(), GFont::XALIGN_RIGHT);\ p.y += reportFont->draw2D(rd, (vertexPerformance.drawArraysVBOPeakFPS > 0) ? \ format("%5.1f", factor * vertexPerformance.drawArraysVBOPeakFPS) : \ std::string("X"), p + spacing * 6, s, Color3::red() * 0.5, Color4::clear(), GFont::XALIGN_RIGHT).y; # undef PRINT p.y += s; p.y += reportFont->draw2D(rd, format("* FPS at %d k polys/frame.", iRound(vertexPerformance.numTris / 1000.0)), p + Vector2(20, 0), s, Color3::black()).y; } } rd->pop2D(); }
void RUEpProvider::_createAssociationInstances( Array<CIMInstance> nhrInst, Array<CIMInstance> ipifInst) { PEG_METHOD_ENTER(TRC_PROVIDERAGENT, "RUEpProvider::_createAssociationInstances()"); Uint16 nhrInstSize = nhrInst.size(); Uint16 ipifInstSize = ipifInst.size(); for (Uint16 i = 0; i < nhrInstSize; i++) // Routes loop. { CIMInstance _nhrInstRet, _ipifInstRet; CIMInstance _nhrInst = nhrInst[i]; CIMProperty _ipifAddress; CIMProperty _ipifSubnetMask_PrefixLength; CIMProperty _ipifProtocolIFType; CIMProperty _nhrInstanceID = _nhrInst.getProperty( _nhrInst.findProperty(PROPERTY_INSTANCE_ID)); CIMProperty _nhrAddrType; CIMProperty _nhrDestMask_PrefixLength; for (Uint16 j = 0; j<ipifInstSize; j++) // Interfaces loop. { CIMInstance _ipifInst = ipifInst[j]; _ipifProtocolIFType = _ipifInst.getProperty( _ipifInst.findProperty(PROPERTY_PROTOCOL_IF_TYPE)); Uint16 _pift; CIMValue _piftCIMValue = _ipifProtocolIFType.getValue(); if ((_piftCIMValue.getType() == CIMTYPE_UINT16) && (!_piftCIMValue.isNull ())) { _piftCIMValue.get(_pift); } else { throw CIMOperationFailedException( "Can't determine CIMValue::TYPE of ProtocolIFType:" + String(cimTypeToString(_piftCIMValue.getType()))); } if (_pift == 4096) // IPv4 address. { _ipifAddress = _ipifInst.getProperty( _ipifInst.findProperty( PROPERTY_IPV4ADDRESS)); _ipifSubnetMask_PrefixLength = _ipifInst.getProperty( _ipifInst.findProperty( PROPERTY_SUBNET_MASK)); } else { if (_pift == 4097) // IPv6 address. { _ipifAddress = _ipifInst.getProperty( _ipifInst.findProperty( PROPERTY_IPV6ADDRESS)); _ipifSubnetMask_PrefixLength = _ipifInst.getProperty( _ipifInst.findProperty( PROPERTY_IPV6ADDRESS)); } else { char buffer[22]; Uint32 sz; String _piftStr = Uint16ToString(buffer, _pift, sz); throw CIMOperationFailedException( "ProtocolIFType == " + _piftStr ); } } // In this implementation, we choose InstanceID to be // equal DestinationAddress. So, if Address of interface // and InstanceID of route doesn't match, check if SubnetMask // of interface and DestinationMask route does. if (!_nhrInstanceID.getValue().equal(_ipifAddress.getValue())) { _nhrAddrType = _nhrInst.getProperty( _nhrInst.findProperty( PROPERTY_ADDRESS_TYPE)); Uint16 _addrt; CIMValue _nhratCIMValue = _nhrAddrType.getValue(); if ((_nhratCIMValue.getType() == CIMTYPE_UINT16) && (!_nhratCIMValue.isNull())) { _nhratCIMValue.get(_addrt); } else { throw CIMOperationFailedException( "Can't determine CIMValue::TYPE of AddressType: " + String(cimTypeToString(_piftCIMValue.getType()))); } if (_addrt == 1) // IPv4 address. { _nhrDestMask_PrefixLength = _nhrInst.getProperty( _nhrInst.findProperty( PROPERTY_DESTINATION_MASK)); } else { if (_addrt == 2) // IPv6 address. { _nhrDestMask_PrefixLength = _nhrInst.getProperty( _nhrInst.findProperty( PROPERTY_PREFIX_LENGTH)); } else { char buffer[22]; Uint32 sz; String _addrtStr = Uint16ToString(buffer, _addrt, sz); throw CIMOperationFailedException( "Unknown AddressType = " + _addrtStr); } } // If SubnetMask of interface and DestinationMask route // doesn't match, these instances are unrelated. So, // proceed to the next pair. if (!_nhrDestMask_PrefixLength.getValue().equal( _ipifSubnetMask_PrefixLength.getValue())) { continue; } } // Build the CIMObjectPath from the instances matching CIMObjectPath _ipifObj = _ipifInst.getPath(); CIMObjectPath _nhrObj = _nhrInst.getPath(); CIMInstance assocInst(CLASS_PG_ROUTE_USES_ENDPOINT); assocInst.addProperty( CIMProperty( CIMName("Antecedent"), _ipifObj, 0, CLASS_CIM_PROTOCOL_ENDPOINT)); assocInst.addProperty( CIMProperty( CIMName("Dependent"), _nhrObj, 0, CLASS_CIM_NEXT_HOP_ROUTE)); // Build CIMObjectPath from keybindings Array<CIMKeyBinding> keyBindings; CIMKeyBinding _ipifBinding( CIMName("Antecedent"), _ipifObj.toString(), CIMKeyBinding::REFERENCE); CIMKeyBinding _nhrBinding( CIMName("Dependent"), _nhrObj.toString(), CIMKeyBinding::REFERENCE); keyBindings.append (_ipifBinding); keyBindings.append (_nhrBinding); CIMObjectPath path( String::EMPTY, CIMNamespaceName(), CLASS_PG_ROUTE_USES_ENDPOINT, keyBindings); assocInst.setPath(path); _AssociationInstances.append(assocInst); break; } // Interfaces loop end. } // Routes loop end. PEG_METHOD_EXIT(); }
void MeshAlg::generateGrid( Array<Vector3>& vertex, Array<Vector2>& texCoord, Array<int>& index, int wCells, int hCells, const Vector2& textureScale, bool spaceCentered, bool twoSided, const CoordinateFrame& xform, const Image1::Ref& height) { vertex.fastClear(); texCoord.fastClear(); index.fastClear(); // Generate vertices for (int z = 0; z <= hCells; ++z) { for (int x = 0; x <= wCells; ++x) { Vector3 v(x / (float)wCells, 0, z / (float)hCells); Vector2 t = v.xz() * textureScale; texCoord.append(t); if (height.notNull()) { v.y = height->nearest(v.x * (height->width() - 1), v.z * (height->height() - 1)).value; } if (spaceCentered) { v -= Vector3(0.5f, 0, 0.5f); } v = xform.pointToWorldSpace(v); vertex.append(v); } } // Generate indices for (int z = 0; z < hCells; ++z) { for (int x = 0; x < wCells; ++x) { int A = x + z * (wCells + 1); int B = A + 1; int C = A + (wCells + 1); int D = C + 1; // A B // *-----* // | \ | // | \ | // *-----* // C D index.append(A, D, B); index.append(A, C, D); } } if (twoSided) { // The index array needs to have reversed winding for the bottom // and offset by the original number of vertices Array<int> ti = index; ti.reverse(); for (int i = 0; i < ti.size(); ++i) { ti[i] += vertex.size(); } index.append(ti); // Duplicate the arrays vertex.append(Array<Vector3>(vertex)); texCoord.append(Array<Vector2>(texCoord)); } }
Array<CIMInstance> RUEpProvider::_IPInterfaceInstances() { PEG_METHOD_ENTER(TRC_PROVIDERAGENT, "RUEpProvider::_IPInterfaceInstances()"); Array<CIMInstance> _retInstances; InterfaceList _ifl; for (Uint16 i = 0; i<_ifl.size(); i++) { CIMInstance instance(CLASS_CIM_PROTOCOL_ENDPOINT); IPInterface _ipif = _ifl.getInterface(i); String _addr, _subnetMask; Uint16 _protocolIFType; Uint8 _prefLength; if (_ipif.getProtocolIFType(_protocolIFType)) { instance.addProperty(CIMProperty( PROPERTY_PROTOCOL_IF_TYPE, _protocolIFType)); if (_protocolIFType == 4096) // IPv4 address. { if (!_ipif.getIPv4Address(_addr)) { throw CIMOperationFailedException( "Can't determine IPv4 address in: " + String("RUEpProvider::_IPInterfaceInstances()")); } instance.addProperty(CIMProperty(PROPERTY_IPV4ADDRESS, _addr)); if (!_ipif.getSubnetMask(_subnetMask)) { throw CIMOperationFailedException( "Can't determine subnet mask in: " + String("RUEpProvider::_IPInterfaceInstances()")); } instance.addProperty(CIMProperty( PROPERTY_SUBNET_MASK, _subnetMask)); } else { if (_protocolIFType == 4097) // IPv6 address. { if (!_ipif.getIPv6Address(_addr)) { throw CIMOperationFailedException( "Can't determine IPv6 address in: " + String("RUEpProvider::_IPInterfaceInstances()")); } instance.addProperty(CIMProperty( PROPERTY_IPV6ADDRESS, _addr)); if (!_ipif.getPrefixLength(_prefLength)) { throw CIMOperationFailedException( "Can't determine prefix length for interface in: " + String("RUEpProvider::_IPInterfaceInstances()")); } instance.addProperty(CIMProperty( PROPERTY_PREFIX_LENGTH, _prefLength)); } } } else { throw CIMOperationFailedException( "Can't determine instance protocol type in: " + String("RUEpProvider::_IPInterfaceInstances()")); } // Build CIMObjectPath from keybindings Array<CIMKeyBinding> keyBindings; keyBindings.append( CIMKeyBinding( PROPERTY_ADDRESS, _addr, CIMKeyBinding::STRING)); CIMObjectPath path( String::EMPTY, CIMNamespaceName(), CLASS_CIM_PROTOCOL_ENDPOINT, keyBindings); instance.setPath(path); _ipifInstances.append(instance); _retInstances.append(instance); } PEG_METHOD_EXIT(); return _retInstances; }
//========================================================================================================== // Main test driver can be used on any model so test cases should be very easy to add //========================================================================================================== void testMomentArmDefinitionForModel(const string &filename, const string &coordName, const string &muscleName, SimTK::Vec2 rom, double mass, string errorMessage) { using namespace SimTK; bool passesDefinition = true; bool passesDynamicConsistency = true; // Load OpenSim model Model osimModel(filename); osimModel.initSystem(); // Create the moment-arm solver to solve for moment-arms MomentArmSolver maSolver(osimModel); Coordinate &coord = (coordName != "") ? osimModel.updCoordinateSet().get(coordName) : osimModel.updCoordinateSet()[0]; // Consider one force, which is the muscle of interest Muscle &muscle = (muscleName != "") ? dynamic_cast<Muscle&>((osimModel.updMuscles().get(muscleName))) : dynamic_cast<Muscle&>(osimModel.updMuscles()[0]); if( mass >= 0.0){ for(int i=0; i<osimModel.updBodySet().getSize(); i++){ osimModel.updBodySet()[i].setMass(mass); Inertia inertia(mass); osimModel.updBodySet()[i].setInertia(inertia); } } SimTK::State &s = osimModel.initSystem(); Array<string> coupledCoordNames; for(int i=0; i<osimModel.getConstraintSet().getSize(); i++){ OpenSim::Constraint& aConstraint = osimModel.getConstraintSet().get(i); if(aConstraint.getConcreteClassName() == "CoordinateCouplerConstraint"){ CoordinateCouplerConstraint& coupler = dynamic_cast<CoordinateCouplerConstraint&>(aConstraint); Array<string> coordNames = coupler.getIndependentCoordinateNames(); coordNames.append(coupler.getDependentCoordinateName()); int ind = coordNames.findIndex(coord.getName()); if (ind > -1){ for(int j=0; j<coordNames.getSize(); j++){ if(j!=ind) coupledCoordNames.append(coordNames[j]); } } } } // Reset all speeds to zero s.updU() = 0; // Disable all forces for(int i=0; i<osimModel.updForceSet().getSize(); i++){ osimModel.updForceSet()[i].setDisabled(s, true); } // Also disable gravity osimModel.getGravityForce().disable(s); // Enable just muscle we are interested in. muscle.setDisabled(s, false); coord.setClamped(s, false); coord.setLocked(s, false); double q = rom[0]; int nsteps = 10; double dq = (rom[1]-rom[0])/nsteps; cout << "___________________________________________________________________________________" << endl; cout << "MA genforce/fm::dl/dtheta joint angle IDTorq :: EquiTorq MA::MA_dl/dtheta" << endl; cout << "===================================================================================" << endl; for(int i = 0; i <=nsteps; i++){ coord.setValue(s, q, true); double angle = coord.getValue(s); //cout << "muscle force: " << muscle.getForce(s) << endl; //double ma = muscle.computeMomentArm(s, coord); double ma = maSolver.solve(s, coord, muscle.getGeometryPath()); double ma_dldtheta = computeMomentArmFromDefinition(s, muscle.getGeometryPath(), coord); cout << "r's = " << ma << "::" << ma_dldtheta <<" at q = " << coord.getValue(s)*180/Pi; try { // Verify that the definition of the moment-arm is satisfied ASSERT_EQUAL(ma, ma_dldtheta, integ_accuracy); } catch (const OpenSim::Exception&) { passesDefinition = false; } // Verify that the moment-arm calculated is dynamically consistent with moment generated if (mass!=0 ) { muscle.overrideActuation(s, true); muscle.setOverrideActuation(s, 10); osimModel.getMultibodySystem().realize(s, Stage::Acceleration); double force = muscle.getActuation(s); // Get muscle's applied body forces const Vector_<SpatialVec>& appliedBodyForces = osimModel.getMultibodySystem().getRigidBodyForces(s, Stage::Dynamics); //appliedBodyForces.dump("Applied Body Force resulting from muscle"); // And any applied mobility (gen) forces due to gearing (moving path point) const Vector& appliedGenForce = osimModel.getMultibodySystem().getMobilityForces(s, Stage::Dynamics); // Get current system accelerations const Vector& knownUDots = s.getUDot(); //knownUDots.dump("Acceleration due to ECU muscle:"); // Convert body forces to equivalent mobility forces (joint torques) Vector equivalentGenForce(s.getNU(), 0.0); osimModel.getMultibodySystem().getMatterSubsystem().calcTreeEquivalentMobilityForces(s, appliedBodyForces, equivalentGenForce); if(s.getSystemStage() < SimTK::Stage::Dynamics) osimModel.getMultibodySystem().realize(s,SimTK::Stage::Dynamics); // include any directly applied gen force from the path (muscle) tension equivalentGenForce += appliedGenForce; // Determine the contribution of constraints (if any) to the effective torque Vector_<SimTK::SpatialVec> constraintForcesInParent; Vector constraintMobilityForces; // Get all forces applied to model by constraints osimModel.getMultibodySystem().getMatterSubsystem().calcConstraintForcesFromMultipliers(s, -s.getMultipliers(), constraintForcesInParent, constraintMobilityForces); // Perform inverse dynamics Vector ivdGenForces; osimModel.getMultibodySystem().getMatterSubsystem().calcResidualForceIgnoringConstraints(s, constraintMobilityForces, constraintForcesInParent, knownUDots, ivdGenForces); //constraintForcesInParent.dump("Constraint Body Forces"); //constraintMobilityForces.dump("Constraint Mobility Forces"); Vector W = computeGenForceScaling(osimModel, s, coord, coupledCoordNames); double equivalentMuscleTorque = ~W*equivalentGenForce; double equivalentIvdMuscleTorque = ~W*(ivdGenForces); //+constraintMobilityForces); cout << " Tau = " << equivalentIvdMuscleTorque <<"::" << equivalentMuscleTorque << " r*fm = " << ma*force <<"::" << ma_dldtheta*force << endl; try { // Resulting torque from ID (no constraints) + constraints = equivalent applied torque ASSERT_EQUAL(0.0, (equivalentIvdMuscleTorque-equivalentMuscleTorque)/equivalentIvdMuscleTorque, integ_accuracy); // verify that equivalent torque is in fact moment-arm*force ASSERT_EQUAL(0.0, (ma*force-equivalentMuscleTorque)/equivalentMuscleTorque, integ_accuracy); } catch (const OpenSim::Exception&) { passesDynamicConsistency = false; } } else { cout << endl; } // Increment the joint angle q += dq; } if(!passesDefinition) cout << "WARNING: Moment arm did not satisfy dL/dTheta equivalence." << endl; if(!passesDynamicConsistency) cout << "WARNING: Moment arm * force did not satisfy Torque equivalence." << endl; // Minimum requirement to pass is that calculated moment-arm satifies either // dL/dTheta definition or is at least dynamically consistent, in which dL/dTheta is not ASSERT(passesDefinition || passesDynamicConsistency, __FILE__, __LINE__, errorMessage); }
//================================================================= bool TileAssembler::convertWorld() { #ifdef _ASSEMBLER_DEBUG # ifdef _DEBUG ::g_df = fopen("../TileAssembler_debug.txt", "wb"); # else ::g_df = fopen("../TileAssembler_release.txt", "wb"); # endif #endif std::string fname = iSrcDir; fname.append("/"); fname.append("dir"); iCoordModelMapping->setModelNameFilterMethod(iFilterMethod); printf("Read coordinate mapping...\n"); if(!iCoordModelMapping->readCoordinateMapping(fname)) return false; Array<unsigned int> mapIds = iCoordModelMapping->getMaps(); if(mapIds.size() == 0) { printf("Fatal error: empty map list!\n"); return false; } for(int i=0; i<mapIds.size(); ++i) { unsigned int mapId = mapIds[i]; #ifdef _ASSEMBLER_DEBUG if(mapId == 0) // "Azeroth" just for debug { for(int x=28; x<29; ++x) //debug { for(int y=28; y<29; ++y) { #else // ignore DeeprunTram (369) it is too large for short vector and not important // ignore test (13), Test (29) , development (451) if(mapId != 369 && mapId != 13 && mapId != 29 && mapId != 451) { for(int x=0; x<66; ++x) { for(int y=0; y<66; ++y) { #endif Array<ModelContainer*> mc; std::string dirname; char buffer[100]; if(iCoordModelMapping->isWorldAreaMap(mapId) && x<65 && y<65) { sprintf(buffer, "%03u_%d_%d",mapId,y,x); // Let's flip x and y here dirname = std::string(buffer); printf("%s...\n",dirname.c_str()); } else { sprintf(buffer, "%03u",mapId); dirname = std::string(buffer); // prevent spam for small maps if(x==0 && y==0) printf("%s...\n",dirname.c_str()); } bool result = fillModelContainerArray(dirname, mapId, x, y, mc); emptyArray(mc); if(!result) return false; } } } } #ifdef _ASSEMBLER_DEBUG if(::g_df) fclose(::g_df); #endif return true; } //================================================================= bool TileAssembler::fillModelContainerArray(const std::string& pDirFileName, unsigned int pMapId, int pXPos, int pYPos, Array<ModelContainer*>& pMC) { ModelContainer* modelContainer; NameCollection nameCollection = iCoordModelMapping->getFilenamesForCoordinate(pMapId, pXPos, pYPos); if(nameCollection.size() == 0) return true; // no data... char dirfilename[500]; sprintf(dirfilename,"%s/%s.vmdir",iDestDir.c_str(),pDirFileName.c_str()); FILE *dirfile = fopen(dirfilename, "ab"); if(!dirfile) { printf("ERROR: Can't create file %s",dirfilename); return false; } char destnamebuffer[500]; char fullnamedestnamebuffer[500]; if(nameCollection.iMainFiles.size() >0) { sprintf(destnamebuffer,"%03u_%i_%i.vmap",pMapId, pYPos, pXPos); // flip it here too std::string checkDoubleStr = std::string(dirfilename); checkDoubleStr.append("##"); checkDoubleStr.append(std::string(destnamebuffer)); // Check, if same file already is in the same dir file if(!iCoordModelMapping->isAlreadyProcessedSingleFile(checkDoubleStr)) { iCoordModelMapping->addAlreadyProcessedSingleFile(checkDoubleStr); fprintf(dirfile, "%s\n",destnamebuffer); sprintf(fullnamedestnamebuffer,"%s/%s",iDestDir.c_str(),destnamebuffer); modelContainer = processNames(nameCollection.iMainFiles, fullnamedestnamebuffer); if(modelContainer) pMC.append(modelContainer); else printf("warning: (if) problems in processing data for %s\n",destnamebuffer); } } // process the large singe files int pos = 0; while(pos < nameCollection.iSingeFiles.size()) { std::string destFileName = iDestDir; destFileName.append("/"); std::string dirEntryName = getDirEntryNameFromModName(pMapId,nameCollection.iSingeFiles[pos]); std::string checkDoubleStr = std::string(dirfilename); checkDoubleStr.append("##"); checkDoubleStr.append(nameCollection.iSingeFiles[pos]); // Check, if same file already is in the same dir file if(!iCoordModelMapping->isAlreadyProcessedSingleFile(checkDoubleStr)) { iCoordModelMapping->addAlreadyProcessedSingleFile(checkDoubleStr); fprintf(dirfile, "%s\n",dirEntryName.c_str()); destFileName.append(dirEntryName); Array<std::string> positionarray; positionarray.append(nameCollection.iSingeFiles[pos]); if(!iCoordModelMapping->isAlreadyProcessedSingleFile(nameCollection.iSingeFiles[pos])) { modelContainer = processNames(positionarray, destFileName.c_str()); iCoordModelMapping->addAlreadyProcessedSingleFile(nameCollection.iSingeFiles[pos]); if(modelContainer) pMC.append(modelContainer); else printf("warning: (while) problems in processing data for %s\n",destFileName.c_str()); } } ++pos; } fclose(dirfile); return true; } //================================================================= void removeEntriesFromTree(AABSPTree<SubModel *>* pTree) { Array<SubModel *> submodelArray; pTree->getMembers(submodelArray); int no = submodelArray.size(); while(no > 0) { --no; delete submodelArray[no]; } } //================================================================= ModelContainer* TileAssembler::processNames(const Array<std::string>& pPositions, const char* pDestFileName) { ModelContainer *modelContainer = 0; Vector3 basepos = Vector3(0,0,0); AABSPTree<SubModel *>* mainTree = new AABSPTree<SubModel *>(); int pos = 0; bool result = true; while(result && (pos < pPositions.size())) { std::string modelPosString = pPositions[pos]; std::string modelFileName = getModNameFromModPosName(modelPosString); if(!fillModelIntoTree(mainTree, basepos, modelPosString, modelFileName)) { result = false; break; } ++pos; } if(result && mainTree->size() > 0) { mainTree->balance(); modelContainer = new ModelContainer(mainTree); modelContainer->writeFile(pDestFileName); } removeEntriesFromTree(mainTree); delete mainTree; return(modelContainer); }
// This function takes an array of arrays, each of which is of the // form array($dbh, ...). The only thing that matters in the inner // arrays is the first element being a MySQL instance. It then // procedes to block for up to 'timeout' seconds, waiting for the // first actionable descriptor(s), which it then returns in the form // of the original arrays passed in. The intention is the caller // would include other information they care about in the tail of the // array so they can decide how to act on the // potentially-now-queryable descriptors. // // This function is a poor shadow of how the async library can be // used; for more complex cases, we'd use libevent and share our event // loop with other IO operations such as memcache ops, thrift calls, // etc. That said, this function is reasonably efficient for most use // cases. Variant f_mysql_async_wait_actionable(const Variant& items, double timeout) { size_t count = items.toArray().size(); if (count == 0 || timeout < 0) { return Array::Create(); } struct pollfd* fds = (struct pollfd*)calloc(count, sizeof(struct pollfd)); SCOPE_EXIT { free(fds); }; // Walk our input, determine what kind of poll() operation is // necessary for the descriptor in question, and put an entry into // fds. int nfds = 0; for (ArrayIter iter(items.toArray()); iter; ++iter) { Array entry = iter.second().toArray(); if (entry.size() < 1) { raise_warning("element %d did not have at least one entry", nfds); return Array::Create(); } MySQL* mySQL = entry.rvalAt(0).toResource().getTyped<MySQL>(); MYSQL* conn = mySQL->get(); if (conn->async_op_status == ASYNC_OP_UNSET) { raise_warning("runtime/ext_mysql: no pending async operation in " "progress"); return Array::Create(); } pollfd* fd = &fds[nfds++]; fd->fd = mysql_get_file_descriptor(conn); if (conn->net.async_blocking_state == NET_NONBLOCKING_READ) { fd->events = POLLIN; } else { fd->events = POLLOUT; } fd->revents = 0; } // The poll itself; either the timeout is hit or one or more of the // input fd's is ready. int timeout_millis = static_cast<long>(timeout * 1000); int res = poll(fds, nfds, timeout_millis); if (res == -1) { raise_warning("unable to poll [%d]: %s", errno, folly::errnoStr(errno).c_str()); return Array::Create(); } // Now just find the ones that are ready, and copy the corresponding // arrays from our input array into our return value. Array ret = Array::Create(); nfds = 0; for (ArrayIter iter(items.toArray()); iter; ++iter) { Array entry = iter.second().toArray(); if (entry.size() < 1) { raise_warning("element %d did not have at least one entry", nfds); return Array::Create(); } MySQL* mySQL = entry.rvalAt(0).toResource().getTyped<MySQL>(); MYSQL* conn = mySQL->get(); pollfd* fd = &fds[nfds++]; if (fd->fd != mysql_get_file_descriptor(conn)) { raise_warning("poll returned events out of order wtf"); continue; } if (fd->revents != 0) { ret.append(iter.second()); } } return ret; }
const uint8* VideoOutput::convertFrame(const uint8* src, const ImageFormat* format, bool invertY) { m_temp.resize(m_settings.width * m_settings.height * ImageFormat::RGB8()->cpuBitsPerPixel / 8, false); // invert the frame if required or not already inverted const bool invertRequired = ((m_settings.codec == CODEC_ID_RAWVIDEO) && (m_settings.raw.invert != invertY)) || ((m_settings.codec != CODEC_ID_RAWVIDEO) && invertY); // go through an intermediate conversion if required const PixelFormat matchingPixelFormat = ConvertImageFormatToPixelFormat(format); Array<const void*> inputBuffers; inputBuffers.append(src); Array<void*> outputBuffers; outputBuffers.append(m_temp.getCArray()); const bool success = ImageFormat::convert(inputBuffers, m_settings.width, m_settings.height, format, 0, outputBuffers, ImageFormat::RGB8(), 0, invertRequired); if (! success) { throwException(success, "Unable to add frame due to unsupported conversion of formats."); } # ifndef G3D_NO_FFMPEG m_avInputFrame->format = matchingPixelFormat; if (PIX_FMT_RGB24 != m_avStream->codec->pix_fmt) { // finally convert to the format the encoder expects AVFrame* convFrame = avcodec_alloc_frame(); throwException(convFrame, "Unable to append frame because in " "VideoOutput, avcodec_alloc_frame returned NULL"); avpicture_fill(reinterpret_cast<AVPicture*>(convFrame), m_temp.getCArray(), matchingPixelFormat, m_settings.width, m_settings.height); // Create resize context since the parameters shouldn't change throughout the video SwsContext* resizeContext = sws_getContext(m_settings.width, m_settings.height, matchingPixelFormat, m_settings.width, m_settings.height, m_avStream->codec->pix_fmt, SWS_BILINEAR, NULL, NULL, NULL); debugAssert(resizeContext); sws_scale(resizeContext, convFrame->data, convFrame->linesize, 0, m_settings.height, m_avInputFrame->data, m_avInputFrame->linesize); av_free(convFrame); av_free(resizeContext); } else { // otherwise just setup the input frame without conversion avpicture_fill(reinterpret_cast<AVPicture*>(m_avInputFrame), m_temp.getCArray(), matchingPixelFormat, m_settings.width, m_settings.height); } # endif return m_temp.getCArray(); }
void testAdjacency() { printf("MeshAlg::computeAdjacency\n"); { // 2 // /| // / | // / | // /___| // 0 1 // // MeshAlg::Geometry geometry; Array<int> index; Array<MeshAlg::Face> faceArray; Array<MeshAlg::Edge> edgeArray; Array<MeshAlg::Vertex> vertexArray; geometry.vertexArray.append(Vector3(0,0,0)); geometry.vertexArray.append(Vector3(1,0,0)); geometry.vertexArray.append(Vector3(1,1,0)); index.append(0, 1, 2); MeshAlg::computeAdjacency( geometry.vertexArray, index, faceArray, edgeArray, vertexArray); debugAssert(faceArray.size() == 1); debugAssert(edgeArray.size() == 3); debugAssert(faceArray[0].containsVertex(0)); debugAssert(faceArray[0].containsVertex(1)); debugAssert(faceArray[0].containsVertex(2)); debugAssert(faceArray[0].containsEdge(0)); debugAssert(faceArray[0].containsEdge(1)); debugAssert(faceArray[0].containsEdge(2)); debugAssert(edgeArray[0].inFace(0)); debugAssert(edgeArray[1].inFace(0)); debugAssert(edgeArray[2].inFace(0)); MeshAlg::debugCheckConsistency(faceArray, edgeArray, vertexArray); // Severely weld, creating a degenerate face MeshAlg::weldAdjacency(geometry.vertexArray, faceArray, edgeArray, vertexArray, 1.1); MeshAlg::debugCheckConsistency(faceArray, edgeArray, vertexArray); debugAssert(! faceArray[0].containsVertex(0)); } { // // 0====1 // (degenerate face) // MeshAlg::Geometry geometry; Array<int> index; Array<MeshAlg::Face> faceArray; Array<MeshAlg::Edge> edgeArray; Array<MeshAlg::Vertex> vertexArray; geometry.vertexArray.append(Vector3(0,0,0)); geometry.vertexArray.append(Vector3(1,0,0)); index.append(0, 1, 0); MeshAlg::computeAdjacency( geometry.vertexArray, index, faceArray, edgeArray, vertexArray); debugAssert(faceArray.size() == 1); debugAssert(edgeArray.size() == 2); debugAssert(faceArray[0].containsVertex(0)); debugAssert(faceArray[0].containsVertex(1)); debugAssert(faceArray[0].containsEdge(0)); debugAssert(faceArray[0].containsEdge(1)); debugAssert(edgeArray[0].inFace(0)); debugAssert(edgeArray[1].inFace(0)); MeshAlg::debugCheckConsistency(faceArray, edgeArray, vertexArray); } { // 2 . // /|\ . // / | \ . // / | \ . // /___|___\ . // 0 1 3 // // MeshAlg::Geometry geometry; Array<int> index; Array<MeshAlg::Face> faceArray; Array<MeshAlg::Edge> edgeArray; Array<MeshAlg::Vertex> vertexArray; geometry.vertexArray.append(Vector3(0,0,0)); geometry.vertexArray.append(Vector3(1,0,0)); geometry.vertexArray.append(Vector3(1,1,0)); geometry.vertexArray.append(Vector3(2,0,0)); index.append(0, 1, 2); index.append(1, 3, 2); MeshAlg::computeAdjacency( geometry.vertexArray, index, faceArray, edgeArray, vertexArray); debugAssert(faceArray.size() == 2); debugAssert(edgeArray.size() == 5); debugAssert(vertexArray.size() == 4); debugAssert(faceArray[0].containsVertex(0)); debugAssert(faceArray[0].containsVertex(1)); debugAssert(faceArray[0].containsVertex(2)); debugAssert(faceArray[1].containsVertex(3)); debugAssert(faceArray[1].containsVertex(1)); debugAssert(faceArray[1].containsVertex(2)); // The non-boundary edge must be first debugAssert(! edgeArray[0].boundary()); debugAssert(edgeArray[1].boundary()); debugAssert(edgeArray[2].boundary()); debugAssert(edgeArray[3].boundary()); debugAssert(edgeArray[4].boundary()); MeshAlg::debugCheckConsistency(faceArray, edgeArray, vertexArray); MeshAlg::weldAdjacency(geometry.vertexArray, faceArray, edgeArray, vertexArray); MeshAlg::debugCheckConsistency(faceArray, edgeArray, vertexArray); debugAssert(faceArray.size() == 2); debugAssert(edgeArray.size() == 5); debugAssert(vertexArray.size() == 4); } { // Test Welding // 2 . // /|\ . // / | \ . // / | \ . // /___|___\ . // 0 1,4 3 // MeshAlg::Geometry geometry; Array<int> index; Array<MeshAlg::Face> faceArray; Array<MeshAlg::Edge> edgeArray; Array<MeshAlg::Vertex> vertexArray; geometry.vertexArray.append(Vector3(0,0,0)); geometry.vertexArray.append(Vector3(1,0,0)); geometry.vertexArray.append(Vector3(1,1,0)); geometry.vertexArray.append(Vector3(2,0,0)); geometry.vertexArray.append(Vector3(1,0,0)); index.append(0, 1, 2); index.append(2, 4, 3); MeshAlg::computeAdjacency( geometry.vertexArray, index, faceArray, edgeArray, vertexArray); debugAssert(faceArray.size() == 2); debugAssert(edgeArray.size() == 6); debugAssert(vertexArray.size() == 5); debugAssert(edgeArray[0].boundary()); debugAssert(edgeArray[1].boundary()); debugAssert(edgeArray[2].boundary()); debugAssert(edgeArray[3].boundary()); debugAssert(edgeArray[4].boundary()); debugAssert(edgeArray[5].boundary()); debugAssert(faceArray[0].containsVertex(0)); debugAssert(faceArray[0].containsVertex(1)); debugAssert(faceArray[0].containsVertex(2)); debugAssert(faceArray[1].containsVertex(2)); debugAssert(faceArray[1].containsVertex(3)); debugAssert(faceArray[1].containsVertex(4)); MeshAlg::debugCheckConsistency(faceArray, edgeArray, vertexArray); MeshAlg::weldAdjacency(geometry.vertexArray, faceArray, edgeArray, vertexArray); MeshAlg::debugCheckConsistency(faceArray, edgeArray, vertexArray); debugAssert(faceArray.size() == 2); debugAssert(edgeArray.size() == 5); debugAssert(vertexArray.size() == 5); debugAssert(! edgeArray[0].boundary()); debugAssert(edgeArray[1].boundary()); debugAssert(edgeArray[2].boundary()); debugAssert(edgeArray[3].boundary()); debugAssert(edgeArray[4].boundary()); } { // Test Welding // 2,5 // /|\ . // / | \ . // / | \ . // /___|___\ . // 0 1,4 3 // MeshAlg::Geometry geometry; Array<int> index; Array<MeshAlg::Face> faceArray; Array<MeshAlg::Edge> edgeArray; Array<MeshAlg::Vertex> vertexArray; geometry.vertexArray.append(Vector3(0,0,0)); geometry.vertexArray.append(Vector3(1,0,0)); geometry.vertexArray.append(Vector3(1,1,0)); geometry.vertexArray.append(Vector3(2,0,0)); geometry.vertexArray.append(Vector3(1,0,0)); geometry.vertexArray.append(Vector3(1,1,0)); index.append(0, 1, 2); index.append(5, 4, 3); MeshAlg::computeAdjacency( geometry.vertexArray, index, faceArray, edgeArray, vertexArray); debugAssert(faceArray.size() == 2); debugAssert(edgeArray.size() == 6); debugAssert(vertexArray.size() == 6); debugAssert(edgeArray[0].boundary()); debugAssert(edgeArray[1].boundary()); debugAssert(edgeArray[2].boundary()); debugAssert(edgeArray[3].boundary()); debugAssert(edgeArray[4].boundary()); debugAssert(edgeArray[5].boundary()); debugAssert(faceArray[0].containsVertex(0)); debugAssert(faceArray[0].containsVertex(1)); debugAssert(faceArray[0].containsVertex(2)); debugAssert(faceArray[1].containsVertex(5)); debugAssert(faceArray[1].containsVertex(3)); debugAssert(faceArray[1].containsVertex(4)); MeshAlg::debugCheckConsistency(faceArray, edgeArray, vertexArray); MeshAlg::weldAdjacency(geometry.vertexArray, faceArray, edgeArray, vertexArray); MeshAlg::debugCheckConsistency(faceArray, edgeArray, vertexArray); debugAssert(faceArray.size() == 2); debugAssert(edgeArray.size() == 5); debugAssert(vertexArray.size() == 6); debugAssert(! edgeArray[0].boundary()); debugAssert(edgeArray[1].boundary()); debugAssert(edgeArray[2].boundary()); debugAssert(edgeArray[3].boundary()); debugAssert(edgeArray[4].boundary()); } }
void test01() { NameSpaceManager nsm; _nameSpaceNames.append(CIMNamespaceName("aa")); _nameSpaceNames.append(CIMNamespaceName("aa/bb")); _nameSpaceNames.append(CIMNamespaceName("aa/bb/cc")); _nameSpaceNames.append(CIMNamespaceName("/lmnop/qrstuv")); _nameSpaceNames.append(CIMNamespaceName("root")); _nameSpaceNames.append(CIMNamespaceName("xx")); _nameSpaceNames.append(CIMNamespaceName("xx/yy")); for (Uint32 j = 0; j < _nameSpaceNames.size(); j++) { // NOTE: The "root" namespace is created by CIMRepository, which is not // used by this test program. So the "root" namespace is not expected // to be created automatically in this case. //if (!_nameSpaceNames[j].equal(CIMNamespaceName("root"))) { // Create a namespace nsm.createNameSpace(_nameSpaceNames[j], true, true, String::EMPTY); } } Array<CIMNamespaceName> nameSpaceNames; nsm.getNameSpaceNames(nameSpaceNames); if (verbose) nsm.print(cout); PEGASUS_TEST_ASSERT(nameSpaceNames.size() == NUM_NAMESPACE_NAMES); BubbleSort(nameSpaceNames); for (Uint32 i = 0; i < NUM_NAMESPACE_NAMES; i++) { PEGASUS_TEST_ASSERT(_nameSpaceNames[i] == nameSpaceNames[i]); PEGASUS_TEST_ASSERT(nsm.nameSpaceExists(nameSpaceNames[i])); } nsm.deleteNameSpace(CIMNamespaceName("lmnop/qrstuv")); nsm.getNameSpaceNames(nameSpaceNames); PEGASUS_TEST_ASSERT(nameSpaceNames.size() == NUM_NAMESPACE_NAMES - 1); // Create and delete a class to test these functions nsm.createClass(CIMNamespaceName("aa/bb"), "MySuperClass", CIMName()); nsm.createClass(CIMNamespaceName("aa/bb"), "MyClass", "MySuperClass"); PEGASUS_TEST_ASSERT( nsm.getSuperClassName(CIMNamespaceName("aa/bb"), "MySuperClass") == CIMName()); PEGASUS_TEST_ASSERT( nsm.getSuperClassName(CIMNamespaceName("aa/bb"), "MyClass") == "MySuperClass"); nsm.deleteClass(CIMNamespaceName("aa/bb"), "MyClass"); nsm.deleteClass(CIMNamespaceName("aa/bb"), "MySuperClass"); for (Uint32 j = 0; j < _nameSpaceNames.size(); j++) { if (!_nameSpaceNames[j].equal(CIMNamespaceName("root")) && !_nameSpaceNames[j].equal(CIMNamespaceName("lmnop/qrstuv"))) { nsm.deleteNameSpace(CIMNamespaceName(_nameSpaceNames[j])); } } nsm.getNameSpaceNames(nameSpaceNames); // Only the root namespace should be left. PEGASUS_TEST_ASSERT(nameSpaceNames.size() == 1); PEGASUS_TEST_ASSERT(nameSpaceNames[0].equal(CIMNamespaceName("root"))); // confirm we can delete root nsm.deleteNameSpace(nameSpaceNames[0]); nsm.getNameSpaceNames(nameSpaceNames); PEGASUS_TEST_ASSERT(nameSpaceNames.size() == 0); }
int main(int argc, char** argv) { try { GlobalMPISession session(&argc, &argv); // verbosity<SymbolicTransformation>() = 0; verbosity<Evaluator>() = 6; // verbosity<EvalVector>() = 6; verbosity<EvaluatableExpr>() = 6; Expr::showAllParens() = true; EvalVector::shadowOps() = true; Expr dx = new Derivative(0); Expr dy = new Derivative(1); Expr u = new UnknownFunctionStub("u"); Expr alpha = new UnknownParameter("alpha"); Expr alpha0 = new Parameter(3.14, "alpha0"); Expr beta = new UnknownParameter("beta"); Expr beta0 = new Parameter(2.72, "beta0"); Expr v = new TestFunctionStub("v"); Out::os() << "u=" << u << std::endl; Out::os() << "v=" << v << std::endl; Out::os() << "alpha=" << alpha << std::endl; Expr x = new CoordExpr(0); Expr y = new CoordExpr(1); Expr u0 = new DiscreteFunctionStub("u0"); Expr zero = new ZeroExpr(); Array<Expr> tests; tests.append(v*dx*(u*u - x*u) + dx*(v*alpha*u) + v*sin(alpha*u) + 2.0*v + v*exp(u*beta)); // tests.append(v*sin(alpha*u)); //tests.append(v*alpha*u); for (int i=0; i<tests.length(); i++) { RegionQuadCombo rqc(rcp(new CellFilterStub()), rcp(new QuadratureFamilyStub(1))); EvalContext context(rqc, makeSet(2), EvalContext::nextID()); context.setSetupVerbosity(5); testExpr(tests[i], Sundance::List(v), Sundance::List(u), Sundance::List(u0), Sundance::List(alpha, beta), Sundance::List(alpha0, beta0), context); } } catch(std::exception& e) { Out::println(e.what()); } }
/** * New sprintf implementation for PHP. * * Modifiers: * * " " pad integers with spaces * "-" left adjusted field * n field size * "."n precision (floats only) * "+" Always place a sign (+ or -) in front of a number * * Type specifiers: * * "%" literal "%", modifiers are ignored. * "b" integer argument is printed as binary * "c" integer argument is printed as a single character * "d" argument is an integer * "f" the argument is a float * "o" integer argument is printed as octal * "s" argument is a string * "x" integer argument is printed as lowercase hexadecimal * "X" integer argument is printed as uppercase hexadecimal */ char *string_printf(const char *format, int len, CArrRef args, int *outlen) { Array vargs = args; if (!vargs.isNull() && !vargs->isVectorData()) { vargs = Array::Create(); for (ArrayIter iter(args); iter; ++iter) { vargs.append(iter.second()); } } if (len == 0) { return strdup(""); } int size = 240; char *result = (char *)malloc(size); int outpos = 0; int argnum = 0, currarg = 1; for (int inpos = 0; inpos < len; ++inpos) { char ch = format[inpos]; int expprec = 0; if (ch != '%') { appendchar(&result, &outpos, &size, ch); continue; } if (format[inpos + 1] == '%') { appendchar(&result, &outpos, &size, '%'); inpos++; continue; } /* starting a new format specifier, reset variables */ int alignment = ALIGN_RIGHT; int adjusting = 0; char padding = ' '; int always_sign = 0; int width, precision; inpos++; /* skip the '%' */ ch = format[inpos]; if (isascii(ch) && !isalpha(ch)) { /* first look for argnum */ int temppos = inpos; while (isdigit((int)format[temppos])) temppos++; if (format[temppos] == '$') { argnum = getnumber(format, &inpos); if (argnum <= 0) { free(result); throw_invalid_argument("argnum: must be greater than zero"); return NULL; } inpos++; /* skip the '$' */ } else { argnum = currarg++; } /* after argnum comes modifiers */ for (;; inpos++) { ch = format[inpos]; if (ch == ' ' || ch == '0') { padding = ch; } else if (ch == '-') { alignment = ALIGN_LEFT; /* space padding, the default */ } else if (ch == '+') { always_sign = 1; } else if (ch == '\'') { padding = format[++inpos]; } else { break; } } ch = format[inpos]; /* after modifiers comes width */ if (isdigit(ch)) { if ((width = getnumber(format, &inpos)) < 0) { free(result); throw_invalid_argument("width: must be greater than zero " "and less than %d", INT_MAX); return NULL; } adjusting |= ADJ_WIDTH; } else { width = 0; } ch = format[inpos]; /* after width and argnum comes precision */ if (ch == '.') { ch = format[++inpos]; if (isdigit((int)ch)) { if ((precision = getnumber(format, &inpos)) < 0) { free(result); throw_invalid_argument("precision: must be greater than zero " "and less than %d", INT_MAX); return NULL; } ch = format[inpos]; adjusting |= ADJ_PRECISION; expprec = 1; } else { precision = 0; } } else { precision = 0; } } else { width = precision = 0; argnum = currarg++; } if (argnum > vargs.size()) { free(result); throw_invalid_argument("arguments: (too few)"); return NULL; } if (ch == 'l') { ch = format[++inpos]; } /* now we expect to find a type specifier */ Variant tmp = vargs[argnum-1]; switch (ch) { case 's': { String s = tmp.toString(); appendstring(&result, &outpos, &size, s, width, precision, padding, alignment, s.size(), 0, expprec, 0); break; } case 'd': appendint(&result, &outpos, &size, tmp.toInt64(), width, padding, alignment, always_sign); break; case 'u': appenduint(&result, &outpos, &size, tmp.toInt64(), width, padding, alignment); break; case 'g': case 'G': case 'e': case 'E': case 'f': case 'F': appenddouble(&result, &outpos, &size, tmp.toDouble(), width, padding, alignment, precision, adjusting, ch, always_sign); break; case 'c': appendchar(&result, &outpos, &size, tmp.toByte()); break; case 'o': append2n(&result, &outpos, &size, tmp.toInt64(), width, padding, alignment, 3, hexchars, expprec); break; case 'x': append2n(&result, &outpos, &size, tmp.toInt64(), width, padding, alignment, 4, hexchars, expprec); break; case 'X': append2n(&result, &outpos, &size, tmp.toInt64(), width, padding, alignment, 4, HEXCHARS, expprec); break; case 'b': append2n(&result, &outpos, &size, tmp.toInt64(), width, padding, alignment, 1, hexchars, expprec); break; case '%': appendchar(&result, &outpos, &size, '%'); break; default: break; } } /* possibly, we have to make sure we have room for the terminating null? */ result[outpos]=0; if (outlen) *outlen = outpos; return result; }
void DefaultInstanceProvider::_copySuperClasses( CIMClient & client, const String & nameSpace, const CIMClass & cimClass, Array<CIMClass> & superClasses) { // get the super class name CIMName superClassName = cimClass.getSuperClassName(); if (superClassName.isNull()) { Uint32 numSuperClasses = superClasses.size(); if (numSuperClasses == 0) { // No super class, just return return; } // copy the super classes for (Uint32 i = numSuperClasses; i > 0; i--) { // check to see if class already exists // CIMClass cimClass; try { cimClass = _repository->getClass(nameSpace, superClasses[i-1].getClassName()); } catch (Exception&) { // // Super class does not exist, create the super class // try { _repository->createClass( nameSpace, superClasses[i-1] ); } catch( Exception& ex ) { const String msg = "Create superClass failed. " + ex.getMessage(); throw CIMOperationFailedException( msg ); } } } return; } // get the super class CIMClass superClass; Boolean localOnly = false; Boolean includeQualifiers = true; Boolean includeClassOrigin = false; try { superClass = client.getClass(nameSpace, superClassName, localOnly, includeQualifiers, includeClassOrigin); // add superclass to array superClasses.append(superClass); } catch( Exception& ex ) { const String msg = "Get Super Class failed. " + ex.getMessage(); throw CIMOperationFailedException( msg ); } // recursive call. copy superclasses of this class _copySuperClasses( client, nameSpace, superClass, superClasses); }
std::string System::findDataFile (const std::string& full, bool errorIfNotFound) { // Places where specific files were most recently found. This is // used to cache seeking of common files. static Table<std::string, std::string> lastFound; // First check if the file exists as requested. This will go // through the FileSystemCache, so most calls do not touch disk. if (FileSystem::exists(full)) { return full; } // Now check where we previously found this file. std::string* last = lastFound.getPointer(full); if (last != NULL) { if (FileSystem::exists(*last)) { // Even if cwd has changed the file is still present. // We won't notice if it has been deleted, however. return *last; } else { // Remove this from the cache it is invalid lastFound.remove(full); } } // Places to look static Array<std::string> directoryArray; std::string initialAppDataDir(instance().m_appDataDir); const char* g3dPath = getenv("G3DDATA"); if (directoryArray.size() == 0) { // Initialize the directory array RealTime t0 = System::time(); Array<std::string> baseDirArray; baseDirArray.append(""); if (! initialAppDataDir.empty()) { baseDirArray.append(initialAppDataDir); } # ifdef G3D_WIN32 if (g3dPath == NULL) { // If running the demos under visual studio from the G3D.sln file, // this will locate the data directory. const char* paths[] = {"../data-files/", "../../data-files/", "../../../data-files/", NULL}; for (int i = 0; paths[i]; ++i) { if (FileSystem::exists(pathConcat(paths[i], "G3D-DATA-README.TXT"))) { g3dPath = paths[i]; break; } } } # endif if (g3dPath && (initialAppDataDir != g3dPath)) { baseDirArray.append(g3dPath); } static const std::string subdirs[] = {"font", "gui", "SuperShader", "cubemap", "icon", "material", "image", "md2", "md3", "ifs", "3ds", "sky", ""}; for (int j = 0; j < baseDirArray.size(); ++j) { std::string d = baseDirArray[j]; if ((d == "") || FileSystem::exists(d)) { directoryArray.append(d); for (int i = 0; ! subdirs[i].empty(); ++i) { const std::string& p = pathConcat(d, subdirs[i]); if (FileSystem::exists(p)) { directoryArray.append(p); } } } } logLazyPrintf("Initializing System::findDataFile took %fs\n", System::time() - t0); } for (int i = 0; i < directoryArray.size(); ++i) { const std::string& p = pathConcat(directoryArray[i], full); if (FileSystem::exists(p)) { lastFound.set(full, p); return p; } } if (errorIfNotFound) { // Generate an error message std::string locations; for (int i = 0; i < directoryArray.size(); ++i) { locations += "\'" + pathConcat(directoryArray[i], full) + "'\n"; } std::string msg = "Could not find '" + full + "'.\n\n"; msg += "cwd = \'" + FileSystem::currentDirectory() + "\'\n"; if (g3dPath) { msg += "G3DDATA = "; if (! FileSystem::exists(g3dPath)) { msg += "(illegal path!) "; } msg += std::string(g3dPath) + "\'\n"; } else { msg += "(G3DDATA environment variable is undefined)\n"; } msg += "GApp::Settings.dataDir = "; if (! FileSystem::exists(initialAppDataDir)) { msg += "(illegal path!) "; } msg += std::string(initialAppDataDir) + "\'\n"; msg += "\nLocations searched:\n" + locations; alwaysAssertM(false, msg); } // Not found return ""; }
void call_func() { try { // Connect. CIMClient client; client.connectLocal(); // // uint32 AssignSpares( // [IN(false), OUT] CIM_ConcreteJob REF Job, // [IN, OUT(false)] CIM_StoragePool REF InPool, // [Required, IN, OUT (false)] CIM_StorageExtent REF InExtents[], // [IN, OUT (false)] CIM_StorageRedundancySet REF RedundancySet); // // Build input arguments. Array<CIMParamValue> in; // InPool: CIMObjectPath InPool("CIM_StoragePool.InstanceID=\"1\""); in.append(CIMParamValue("InPool", InPool)); // InExtents: CIMObjectPath StorageExtent( "root/cimv2:MyStorageExtent." "CreationClassName=\"Aristos_DiskStorageExtent\"," "DeviceID=\"3:5000c500003ac807\"," "SystemCreationClassName=\"Aristos_ControllerSystem\"," "SystemName=\"500062E987654391\""); Array<CIMObjectPath> InExtents; InExtents.append(StorageExtent); InExtents.append(StorageExtent); InExtents.append(StorageExtent); in.append(CIMParamValue("InExtents", InExtents)); // RedundancySet: CIMObjectPath RedundancySet( "CIM_StorageRedundancySet.InstanceID=\"1\""); in.append(CIMParamValue("RedundancySet", RedundancySet)); // Invoke method. CIMObjectPath target("SNIA_SpareConfigurationService." "SystemCreationClassName=\"Mike\"," "SystemName=\"Mike\"," "CreationClassName=\"SNIA_SpareConfigurationService\""); Array<CIMParamValue> out; CIMValue value = client.invokeMethod( "root/cimv2", target, "AssignSpares", in, out); // Expect one output argument. assert(out.size() == 1); // Check return value. assert(value.getType() == CIMTYPE_UINT32); Uint32 return_value = 0; value.get(return_value); assert(return_value == 100); } catch(Exception& e) { cerr << "Error: " << e.getMessage() << endl; exit(1); } }