ParticleSystem* ParticleManager::getEmitter(const std::string& filename) { auto filepath = FileUtils::getInstance()->fullPathForFilename(filename); ValueMap dict; ParticleSystem* emitter; auto iter = _emitters.find(filepath); if (iter != _emitters.end()) { dict = iter->second; } else { dict = FileUtils::getInstance()->getValueMapFromFile(filepath); _emitters[filepath] = dict; } CCASSERT(!dict.empty(), "Particles: file not found"); if (filepath.find('/') != std::string::npos) { filepath = filepath.substr(0, filepath.rfind('/') + 1); emitter = ParticleSystemCustom::createWithDictionary(dict, filepath); } else { emitter = ParticleSystemCustom::createWithDictionary(dict, ""); } return emitter; }
void SpriteFrameCache::removeSpriteFramesFromFileContent(const std::string& plist_content) { ValueMap dict = FileUtils::getInstance()->getValueMapFromData(plist_content.data(), static_cast<int>(plist_content.size())); if (dict.empty()) { CCLOG("cocos2d:SpriteFrameCache:removeSpriteFramesFromFileContent: create dict by fail."); return; } removeSpriteFramesFromDictionary(dict); }
std::string CommonHelper::getLocalString(const char* key) { ValueMap dict; LanguageType lt= CCApplication::getInstance()->getCurrentLanguage(); switch (lt) { case LanguageType::CHINESE: dict = FileUtils::getInstance()->getValueMapFromFile("chinese.plist"); CCASSERT(!dict.empty(), "cannot create dictionary"); break; default: dict = FileUtils::getInstance()->getValueMapFromFile("english.plist"); CCASSERT(!dict.empty(), "cannot create dictionary"); break; } Value ret = dict[key]; return ret.asString(); }
/** Read an NSDictionary from a plist file and parse it automatically for animations */ void AnimationCache::addAnimationsWithFile(const std::string& plist) { CCASSERT( plist.size()>0, "Invalid texture file name"); std::string path = FileUtils::getInstance()->fullPathForFilename(plist); ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(path); CCASSERT( !dict.empty(), "CCAnimationCache: File could not be found"); addAnimationsWithDictionary(dict,plist); }
std::tuple<bool, std::string> TMXTilePropertyMgr::String(cocos2d::Point p, const std::string &property, const std::string layerName /*= "Meta"*/) { ValueMap valueMap = propertys(p, layerName); bool ret = false; std::string value; if (!valueMap.empty()) { value = valueMap[property].asString(); } return make_tuple(ret, value); }
bool TileMap::checkNodePassable(Vec2 tileCoord) { int tileGid = _collidable->getTileGIDAt(tileCoord); if (tileGid > 0) { ValueMap proMap = _tileMap->getPropertiesForGID(tileGid).asValueMap(); if (!proMap.empty()) { auto collision = proMap["Collidable"].asString(); if ("true" == collision) return false; } } return true; }
// // load file // void Configuration::loadConfigFile(const std::string& filename) { ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(filename); CCASSERT(!dict.empty(), "cannot create dictionary"); // search for metadata bool validMetadata = false; auto metadataIter = dict.find("metadata"); if (metadataIter != dict.cend() && metadataIter->second.getType() == Value::Type::MAP) { const auto& metadata = metadataIter->second.asValueMap(); auto formatIter = metadata.find("format"); if (formatIter != metadata.cend()) { int format = formatIter->second.asInt(); // Support format: 1 if (format == 1) { validMetadata = true; } } } if (! validMetadata) { CCLOG("Invalid config format for file: %s", filename.c_str()); return; } auto dataIter = dict.find("data"); if (dataIter == dict.cend() || dataIter->second.getType() != Value::Type::MAP) { CCLOG("Expected 'data' dict, but not found. Config file: %s", filename.c_str()); return; } // Add all keys in the existing dictionary const auto& dataMap = dataIter->second.asValueMap(); for (auto dataMapIter = dataMap.cbegin(); dataMapIter != dataMap.cend(); ++dataMapIter) { if (_valueDict.find(dataMapIter->first) == _valueDict.cend()) _valueDict[dataMapIter->first] = dataMapIter->second; else CCLOG("Key already present. Ignoring '%s'",dataMapIter->first.c_str()); } }
std::tuple<bool, bool> TMXTilePropertyMgr::Boolean(cocos2d::Point p, const std::string &property, const std::string layerName /*= "Meta"*/) { ValueMap valueMap = propertys(p, layerName); bool ret = false; bool value = false; if (!valueMap.empty()) { ret = true; value = valueMap[property].asBool(); } return std::make_tuple(ret, value); }
void writeStream(std::ostream &stream, int tabCount) { for(ValueMap::iterator vi = values.begin(); vi != values.end(); ++vi) { writeTabs(stream, tabCount); stream << (*vi).first << " = " << (*vi).second.first << std::endl; } for(GroupMap::iterator gi = groups.begin(); gi != groups.end(); ++gi) { if((gi != groups.begin()) || (!values.empty())) stream << std::endl; writeTabs(stream, tabCount); stream << (*gi).first << std::endl; writeTabs(stream, tabCount); stream << "{" << std::endl; (*gi).second->writeStream(stream, tabCount + 1), writeTabs(stream, tabCount); stream << "}" << std::endl; } if(!lines.empty() && ((!groups.empty() || !values.empty()))) stream << std::endl; for(LineList::iterator li = lines.begin(); li != lines.end(); ++li) { writeTabs(stream, tabCount); std::string &f = (*li); stream << (*li) << std::endl; } }
bool MultiPriceMatch::readFile(const char* fileName,const char* levelID) { bool bRet = false; string id = levelID; do{ CC_BREAK_IF(!FileUtils::getInstance()->isFileExist(fileName)); ValueMap root = FileUtils::getInstance()->getValueMapFromFile(fileName); CC_BREAK_IF(root.empty()); ValueVector pl = root["PRODUCT_LIST"].asValueVector(); CC_BREAK_IF(pl.empty()); int nSize = pl.size(); std::vector<int> levelNum_all; std::vector<int> levelNum; levelNum_all.clear(); levelNum.clear(); for(int i = 0; i < nSize; i++){ levelNum_all.push_back(i); } std::random_device rd1; std::mt19937 g1(rd1()); std::shuffle(std::begin(levelNum_all), std::end(levelNum_all), g1); for(int n=0; n< _TOTAL_PRODUCTS; ++n){ levelNum.push_back(levelNum_all[n]);// generate numbers } for (int i = 0; i < levelNum.size(); i++){ ValueMap pd = pl[levelNum[i]].asValueMap(); PRODUCT_INFO p; p.id = pd[PD_ID].asString().c_str(); p.name = pd[PD_NAME].asString().c_str(); p.image = pd[PD_IMAGE].asString().c_str(); p.price = pd[PD_PRICE].asString().c_str(); p.description = pd[PD_DESCRIPTION].asString().c_str(); p.sku = pd[PD_SKU].asString().c_str(); _product_list.push_back(p); } bRet = true; }while(0); return bRet; }
void Histogram::insertZeroBoundaryValues(float xMin, float xMax) { if (_valueMap.empty()) { if (xMin<xMax) { _valueMap[xMin] = 0.0; _valueMap[xMax] = 0.0; } return; } float interval = 1.0f; float min_gap_for_single_insertion = interval*1.5; float min_gap_for_double_insertion = interval*2.5; if (xMin<_valueMap.begin()->first) { _valueMap[xMin] = 0.0; } if (xMax>_valueMap.rbegin()->first) { _valueMap[xMax] = 0.0; } ValueMap::iterator itr = _valueMap.begin(); float previous_x = itr->first; for(; itr != _valueMap.end(); ++itr) { float current_x = itr->first; float gap = current_x-previous_x; if (gap>min_gap_for_double_insertion) { _valueMap[previous_x+interval] = 0.0f; _valueMap[current_x-interval] = 0.0f; } else if (gap>min_gap_for_single_insertion) { _valueMap[(previous_x+current_x)*0.5]=0.0f; } previous_x = current_x; } }
void SpriteFrameCache::removeSpriteFramesFromFile(const std::string& plist) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(plist); ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(fullPath); if (dict.empty()) { CCLOG("cocos2d:SpriteFrameCache:removeSpriteFramesFromFile: create dict by %s fail.",plist.c_str()); return; } removeSpriteFramesFromDictionary(dict); // remove it from the cache set<string>::iterator ret = _loadedFileNames->find(plist); if (ret != _loadedFileNames->end()) { _loadedFileNames->erase(ret); } }
void SpriteFrameCache::removeSpriteFramesFromFile(const std::string& plist) { std::string::size_type pos = plist.find(".md"); if (pos != std::string::npos) { auto module = TextureManager::getInstance()->getModule(plist); if (!module) { CCLOG("cocos2d:SpriteFrameCache:removeSpriteFramesFromFile: create moduleNames by %s fail.",plist.c_str()); return; } std::vector<std::string> keysToRemove; for (int i = 0; i < module->getModuleCount(); ++i) { std::string moduleName = module->getModuleName(i); if (_spriteFrames.at(moduleName)) { keysToRemove.push_back(moduleName); } } _spriteFrames.erase(keysToRemove); } else { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(plist); ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(fullPath); if (dict.empty()) { CCLOG("cocos2d:SpriteFrameCache:removeSpriteFramesFromFile: create dict by %s fail.",plist.c_str()); return; } removeSpriteFramesFromDictionary(dict); } // remove it from the cache set<string>::iterator ret = _loadedFileNames->find(plist); if (ret != _loadedFileNames->end()) { _loadedFileNames->erase(ret); } }
void FileUtils::loadFilenameLookupDictionaryFromFile(const std::string &filename) { const std::string fullPath = fullPathForFilename(filename); if (fullPath.length() > 0) { ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(fullPath); if (!dict.empty()) { ValueMap& metadata = dict["metadata"].asValueMap(); int version = metadata["version"].asInt(); if (version != 1) { CCLOG("cocos2d: ERROR: Invalid filenameLookup dictionary version: %d. Filename: %s", version, filename.c_str()); return; } setFilenameLookupDictionary( dict["filenames"].asValueMap()); } } }
ValueMap LWFResourceCache::loadParticle(const string &path, bool retain) { ParticleCache::iterator it = m_particleCache.find(path); if (it != m_particleCache.end()) { if (retain) ++it->second.first; return it->second.second; } string fullPath = FileUtils::getInstance()->fullPathForFilename(path.c_str()); ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(fullPath.c_str()); if (!dict.empty()) { m_particleCache[path] = make_pair(retain ? 1 : 0, dict); dict["path"] = Value(path); } return dict; }
bool ParticleSystem::initWithFile(const std::string& plistFile) { bool ret = false; _plistFile = FileUtils::getInstance()->fullPathForFilename(plistFile); ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(_plistFile.c_str()); CCASSERT( !dict.empty(), "Particles: file not found"); // XXX compute path from a path, should define a function somewhere to do it string listFilePath = plistFile; if (listFilePath.find('/') != string::npos) { listFilePath = listFilePath.substr(0, listFilePath.rfind('/') + 1); ret = this->initWithDictionary(dict, listFilePath.c_str()); } else { ret = this->initWithDictionary(dict, ""); } return ret; }
void UserDataMgr::loadFromDisk() { string fpath = FileUtils::getInstance()->getWritablePath(); ValueMap data = FileUtils::getInstance()->getValueMapFromFile(fpath+"user.txt"); if (data.empty()) { for (int i=udi_heart; i<udi_count; ++i) { m_val[i] = 0; } } else { for (int i=udi_heart; i<udi_count; ++i) { m_val[i] = data.at( to_string(i) ).asInt(); } } if (m_val[0] == 0) m_val[0] = 1; }
bool PEShapeCache::removeBodysWithFile(const std::string &plist) { ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(plist); CCASSERT(!dict.empty(), "Shape-file not found"); CCASSERT(dict.size() != 0, "plist file empty or not existing"); ValueMap &metadata = dict["metadata"].asValueMap(); int format = metadata["format"].asInt(); CCASSERT(format == 1, "format not supported!"); ValueMap &bodydict = dict.at("bodies").asValueMap(); for (auto iter = bodydict.cbegin(); iter != bodydict.cend(); ++iter) { std::string bodyName = iter->first; BodyDef *bd = bodyDefs.at(bodyName); if (bd != nullptr) { safeReleaseBodyDef(bd); bodyDefs.erase(bodyName); } } return true; }
void GB2ShapeCache::addShapesWithFile(const std::string &plist) { //const char *fullName = CCFileUtils::sharedFileUtils()->fullPathForFilename(plist.c_str()).c_str(); ValueMap dict = FileUtils::getInstance()->getValueMapFromFile((plist.c_str())); // not triggered - cocos2dx delivers empty dict if non was found //CCAssert(dict != NULL, "Shape-file not found"); CCAssert(!dict.empty(), "plist file empty or not existing"); ValueMap metadataDict = dict.at("metadata").asValueMap(); int format = metadataDict.at("format").asInt(); ptmRatio = metadataDict.at("ptm_ratio").asFloat(); log("ptmRatio = %f",ptmRatio); CCAssert(format == 1, "Format not supported"); ValueMap bodyDict = dict.at("bodies").asValueMap(); b2Vec2 vertices[b2_maxPolygonVertices]; std::string bodyName; ValueMap bodyData; //iterate body list for(auto dictElem : bodyDict) //CCDICT_FOREACH(bodyDict,dictElem ) { bodyData = dictElem.second.asValueMap(); bodyName = dictElem.first; BodyDef *bodyDef = new BodyDef(); bodyDef->anchorPoint = PointFromString(bodyData.at("anchorpoint").asString()); ValueVector fixtureList = bodyData.at("fixtures").asValueVector(); FixtureDef **nextFixtureDef = &(bodyDef->fixtures); //iterate fixture list //Ref *arrayElem; for(auto arrayElem : fixtureList) //CCARRAY_FOREACH(fixtureList, arrayElem) { b2FixtureDef basicData; ValueMap fixtureData = arrayElem.asValueMap(); basicData.filter.categoryBits = fixtureData.at("filter_categoryBits").asInt(); basicData.filter.maskBits = fixtureData.at("filter_maskBits").asInt(); basicData.filter.groupIndex = fixtureData.at("filter_groupIndex").asInt(); basicData.friction = fixtureData.at("friction").asFloat(); basicData.density = fixtureData.at("density").asFloat(); basicData.restitution = fixtureData.at("restitution").asFloat(); //CCLog("%s", static_cast<__String *>(fixtureData->objectForKey("id"))->getCString()); //basicData.userData = __String::create(static_cast<__String *>(fixtureData->objectForKey("id"))->getCString())->retain(); basicData.isSensor = fixtureData.at("isSensor").asBool(); // string cb = fixtureData.at("userdataCbValue").asString(); // int callbackData = 0; // if (cb != "") // callbackData =fixtureData.at("userdataCbValue").asInt(); std::string fixtureType = fixtureData.at("fixture_type").asString(); if (fixtureType == "POLYGON") { ValueVector polygonsArray = fixtureData.at("polygons").asValueVector(); //Ref *dicArrayElem; for(auto dicArrayElem : polygonsArray) //CCARRAY_FOREACH(polygonsArray, dicArrayElem) { FixtureDef *fix = new FixtureDef(); fix->fixture = basicData; // copy basic data // fix->callbackData = callbackData; b2PolygonShape *polyshape = new b2PolygonShape(); int vindex = 0; ValueVector polygonArray = dicArrayElem.asValueVector(); assert(polygonArray.capacity() <= b2_maxPolygonVertices); //Ref *piter; for(auto piter : polygonArray) //CCARRAY_FOREACH(polygonArray, piter) { string verStr = piter.asString(); Point offset = PointFromString(verStr); vertices[vindex].x = (offset.x / ptmRatio) ; vertices[vindex].y = (offset.y / ptmRatio) ; vindex++; } polyshape->Set(vertices, vindex); fix->fixture.shape = polyshape; // create a list *nextFixtureDef = fix; nextFixtureDef = &(fix->next); } } else if (fixtureType == "CIRCLE") { FixtureDef *fix = new FixtureDef(); fix->fixture = basicData; // copy basic data // fix->callbackData = callbackData; ValueMap circleData = fixtureData.at("circle").asValueMap(); b2CircleShape *circleShape = new b2CircleShape(); circleShape->m_radius = circleData.at("radius").asFloat() / ptmRatio; Point p = PointFromString(circleData.at("position").asString()); circleShape->m_p = b2Vec2(p.x / ptmRatio, p.y / ptmRatio); fix->fixture.shape = circleShape; // create a list *nextFixtureDef = fix; nextFixtureDef = &(fix->next); } else { CCAssert(0, "Unknown fixtureType"); } } // add the body element to the hash shapeObjects[bodyName] = bodyDef; } }
osg::Node* Histogram::createGraphicalRepresentation() { if (_valueMap.empty()) return 0; osg::ref_ptr<osg::MatrixTransform> transform = new osg::MatrixTransform; float xMin = _valueMap.begin()->first; float xMax = _valueMap.rbegin()->first; float depth = 0.0f; float yMax = 0.0f; // find yMax for(ValueMap::iterator itr = _valueMap.begin(); itr != _valueMap.end(); ++itr) { float y = itr->second; if (y>yMax) yMax = y; } float xScale = 1.0f/(xMax-xMin); float yScale = 1.0f/yMax; { osg::ref_ptr<osg::Geode> geode = new osg::Geode; transform->addChild(geode.get()); osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry; geode->addDrawable(geometry.get()); geode->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF); geode->getOrCreateStateSet()->setMode(GL_BLEND, osg::StateAttribute::ON); osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array; geometry->setVertexArray(vertices.get()); osg::ref_ptr<osg::Vec4Array> colours = new osg::Vec4Array; geometry->setColorArray(colours.get(), osg::Array::BIND_PER_PRIMITIVE_SET); colours->push_back(osg::Vec4(1.0,1.0,1.0,1.0)); colours->push_back(osg::Vec4(1.0,1.0,1.0,1.0)); colours->push_back(osg::Vec4(1.0,1.0,1.0,0.1)); unsigned numColumnsRequired = _valueMap.size(); vertices->reserve(numColumnsRequired*3); for(ValueMap::iterator itr = _valueMap.begin(); itr != _valueMap.end(); ++itr) { float x = itr->first; float y = itr->second; vertices->push_back(osg::Vec3(x*xScale, 0.0f, depth)); vertices->push_back(osg::Vec3(x*xScale, y*yScale, depth)); vertices->push_back(osg::Vec3(x*xScale, yMax*yScale, depth)); } osg::ref_ptr<osg::DrawElementsUShort> background_primitives = new osg::DrawElementsUShort(GL_TRIANGLE_STRIP); osg::ref_ptr<osg::DrawElementsUShort> historgram_primitives = new osg::DrawElementsUShort(GL_TRIANGLE_STRIP); osg::ref_ptr<osg::DrawElementsUShort> outline_primitives = new osg::DrawElementsUShort(GL_LINE_STRIP); for(unsigned int i=0; i<numColumnsRequired; ++i) { int iv = i*3; background_primitives->push_back(iv+2); background_primitives->push_back(iv+1); historgram_primitives->push_back(iv+1); historgram_primitives->push_back(iv+0); outline_primitives->push_back(iv+1); } geometry->addPrimitiveSet(outline_primitives.get()); geometry->addPrimitiveSet(historgram_primitives.get()); geometry->addPrimitiveSet(background_primitives.get()); } //transform->setMatrix(osg::Matrix::scale(xScale/(maxX-minY), yScale/(yMax), 1.0f)); transform->setMatrix(osg::Matrix::scale(2.0,1.0,1.0)*osg::Matrix::rotate(osg::DegreesToRadians(90.0), osg::Vec3d(1.0,0.0,0.0))); return transform.release(); }
// // load file // void Configuration::loadConfigFile(const std::string& filename) { ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(filename); CCASSERT(!dict.empty(), "cannot create dictionary"); // search for metadata bool validMetadata = false; auto metadataIter = dict.find("metadata"); if (metadataIter != dict.cend() && metadataIter->second.getType() == Value::Type::MAP) { const auto& metadata = metadataIter->second.asValueMap(); auto formatIter = metadata.find("format"); if (formatIter != metadata.cend()) { int format = formatIter->second.asInt(); // Support format: 1 if (format == 1) { validMetadata = true; } } } if (! validMetadata) { CCLOG("Invalid config format for file: %s", filename.c_str()); return; } auto dataIter = dict.find("data"); if (dataIter == dict.cend() || dataIter->second.getType() != Value::Type::MAP) { CCLOG("Expected 'data' dict, but not found. Config file: %s", filename.c_str()); return; } // Add all keys in the existing dictionary const auto& dataMap = dataIter->second.asValueMap(); for (const auto& dataMapIter : dataMap) { if (_valueDict.find(dataMapIter.first) == _valueDict.cend()) _valueDict[dataMapIter.first] = dataMapIter.second; else CCLOG("Key already present. Ignoring '%s'",dataMapIter.first.c_str()); } //light info std::string name = "cocos2d.x.3d.max_dir_light_in_shader"; if (_valueDict.find(name) != _valueDict.end()) _maxDirLightInShader = _valueDict[name].asInt(); else _valueDict[name] = Value(_maxDirLightInShader); name = "cocos2d.x.3d.max_point_light_in_shader"; if (_valueDict.find(name) != _valueDict.end()) _maxPointLightInShader = _valueDict[name].asInt(); else _valueDict[name] = Value(_maxPointLightInShader); name = "cocos2d.x.3d.max_spot_light_in_shader"; if (_valueDict.find(name) != _valueDict.end()) _maxSpotLightInShader = _valueDict[name].asInt(); else _valueDict[name] = Value(_maxSpotLightInShader); name = "cocos2d.x.3d.animate_quality"; if (_valueDict.find(name) != _valueDict.end()) _animate3DQuality = (Animate3DQuality)_valueDict[name].asInt(); else _valueDict[name] = Value((int)_animate3DQuality); Director::getInstance()->getEventDispatcher()->dispatchEvent(_loadedEvent); }
void startElement(void *ctx, const char *name, const char **atts) { CC_UNUSED_PARAM(ctx); CC_UNUSED_PARAM(atts); const std::string sName(name); if( sName == "dict" ) { if(_resultType == SAX_RESULT_DICT && _rootDict.empty()) { _curDict = &_rootDict; } _state = SAX_DICT; SAXState preState = SAX_NONE; if (! _stateStack.empty()) { preState = _stateStack.top(); } if (SAX_ARRAY == preState) { // add a new dictionary into the array _curArray->push_back(Value(ValueMap())); _curDict = &(_curArray->rbegin())->asValueMap(); } else if (SAX_DICT == preState) { // add a new dictionary into the pre dictionary CCASSERT(! _dictStack.empty(), "The state is wrong!"); ValueMap* preDict = _dictStack.top(); (*preDict)[_curKey] = Value(ValueMap()); _curDict = &(*preDict)[_curKey].asValueMap(); } // record the dict state _stateStack.push(_state); _dictStack.push(_curDict); } else if(sName == "key") { _state = SAX_KEY; } else if(sName == "integer") { _state = SAX_INT; } else if(sName == "real") { _state = SAX_REAL; } else if(sName == "string") { _state = SAX_STRING; } else if (sName == "array") { _state = SAX_ARRAY; if (_resultType == SAX_RESULT_ARRAY && _rootArray.empty()) { _curArray = &_rootArray; } SAXState preState = SAX_NONE; if (! _stateStack.empty()) { preState = _stateStack.top(); } if (preState == SAX_DICT) { (*_curDict)[_curKey] = Value(ValueVector()); _curArray = &(*_curDict)[_curKey].asValueVector(); } else if (preState == SAX_ARRAY) { CCASSERT(! _arrayStack.empty(), "The state is wrong!"); ValueVector* preArray = _arrayStack.top(); preArray->push_back(Value(ValueVector())); _curArray = &(_curArray->rbegin())->asValueVector(); } // record the array state _stateStack.push(_state); _arrayStack.push(_curArray); } else { _state = SAX_NONE; } }
void PEShapeCache::addBodysWithFile(const std::string &plist) { ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(plist); CCASSERT(!dict.empty(), "Shape-file not found"); CCASSERT(dict.size() != 0, "plist file empty or not existing"); ValueMap &metadata = dict["metadata"].asValueMap(); int format = metadata["format"].asInt(); CCASSERT(format == 1, "format not supported!"); ValueMap &bodydict = dict.at("bodies").asValueMap(); for (auto iter = bodydict.cbegin(); iter != bodydict.cend(); ++iter) { const ValueMap &bodyData = iter->second.asValueMap(); std::string bodyName = iter->first; BodyDef *bodyDef = new BodyDef(); bodyDefs.insert(bodyName, bodyDef); bodyDef->anchorPoint = PointFromString(bodyData.at("anchorpoint").asString()); const ValueVector &fixtureList = bodyData.at("fixtures").asValueVector(); float totalMass = 0.0f; float totalBodyMomentum = 0.0f; for (auto &fixtureitem : fixtureList) { FixtureData *fd = new FixtureData(); bodyDef->fixtures.pushBack(fd); auto &fixturedata = fixtureitem.asValueMap(); fd->friction = fixturedata.at("friction").asFloat(); fd->elasticity = fixturedata.at("elasticity").asFloat(); fd->mass = fixturedata.at("mass").asFloat(); fd->surfaceVelocity = PointFromString(fixturedata.at("surface_velocity").asString()); fd->layers = fixturedata.at("layers").asInt(); fd->group = fixturedata.at("group").asInt(); fd->collisionType = fixturedata.at("collision_type").asInt(); fd->isSensor = fixturedata.at("isSensor").asBool(); std::string fixtureType = "POLYGON"; // fixturedata.at("fixture_type").asString(); float totalArea = 0.0f; totalMass += fd->mass; if (strcmp("POLYGON", fixtureType.c_str()) == 0) { const ValueVector &polygonsArray = fixturedata.at("polygons").asValueVector(); fd->fixtureType = SHAPE_POLYGON; for (auto &polygonitem : polygonsArray) { Polygon *poly = new Polygon(); fd->polygons.pushBack(poly); auto &polygonArray = polygonitem.asValueVector(); poly->numVertices = polygonArray.size(); Point *vertices = poly->vertices = new Point[poly->numVertices]; int vindex = 0; for (auto &pointString : polygonArray) { Point offsex = PointFromString(pointString.asString()); vertices[vindex].x = offsex.x; vertices[vindex].y = offsex.y; vindex++; } poly->area = area(vertices, poly->numVertices); totalArea += poly->area; } } else if (strcmp("CIRCLE", fixtureType.c_str()) == 0) { fd->fixtureType = SHAPE_CIRCLE; const ValueMap &circleData = fixturedata.at("circle").asValueMap(); fd->radius = circleData.at("radius").asFloat(); fd->center = PointFromString(circleData.at("position").asString()); totalArea += 3.1415927 * fd->radius * fd->radius; } else { // unknown type assert(0); } fd->area = totalArea; // update sub polygon's masses and momentum cpFloat totalFixtureMomentum = 0.0f; if (totalArea) { if (fd->fixtureType == SHAPE_CIRCLE) { totalFixtureMomentum += cpMomentForCircle(PhysicsHelper::float2cpfloat(fd->mass), PhysicsHelper::float2cpfloat(fd->radius), PhysicsHelper::float2cpfloat(fd->radius), PhysicsHelper::point2cpv(fd->center)); } else { for (auto *p : fd->polygons) { // update mass p->mass = (p->area * fd->mass) / fd->area; cpVect *cpvs = new cpVect[p->numVertices]; // calculate momentum p->momentum = cpMomentForPoly(PhysicsHelper::float2cpfloat(p->mass), p->numVertices, PhysicsHelper::points2cpvs(p->vertices, cpvs, p->numVertices), PhysicsHelper::point2cpv(Point::ZERO)); delete[] cpvs; // calculate total momentum totalFixtureMomentum += p->momentum; } } } fd->momentum = PhysicsHelper::cpfloat2float(totalFixtureMomentum); totalBodyMomentum = PhysicsHelper::cpfloat2float(totalFixtureMomentum); } // set bodies total mass bodyDef->mass = totalMass; bodyDef->momentum = totalBodyMomentum; } }
/* * this method saves the attribute together with the host string that * defines the type of object that this attribute is associated to (like * position or document) and the hosts database id. */ void AttributeMap::save( dbID id ) { checkHost(); QSqlQuery attribQuery; attribQuery.prepare( "SELECT id, valueIsList FROM attributes WHERE hostObject=:host AND hostId=:hostId AND name=:name" ); attribQuery.bindValue( ":host", mHost ); attribQuery.bindValue( ":hostId", id.toString() ); Iterator it; for ( it = begin(); it != end(); ++it ) { Attribute att = it.value(); kDebug() << ">> oo- saving attribute with name " << it.key() << " for " << id.toString() << " att-name: " << att.name(); attribQuery.bindValue( ":name", att.name() ); attribQuery.exec(); QString attribId; if ( attribQuery.next() ) { // the attrib exists. Check the values attribId = attribQuery.value(0).toString(); // the id if ( att.value().isNull() || att.mDelete ) { // the value is empty. the existing entry needs to be dropped dbDeleteAttribute( attribId ); return; } } else { // the attrib does not yet exist. Create if att value is not null. if ( att.value().isNull() ) { kDebug() << "oo- skip writing of attribute, value is empty"; } else { kDebug() << "oo- writing of attribute name " << att.name(); QSqlQuery insQuery; insQuery.prepare( "INSERT INTO attributes (hostObject, hostId, name, valueIsList, relationTable, " "relationIDColumn, relationStringColumn) " "VALUES (:host, :hostId, :name, :valueIsList, :relTable, :relIDCol, :relStringCol )" ); insQuery.bindValue( ":host", mHost ); insQuery.bindValue( ":hostId", id.toString() ); insQuery.bindValue( ":name", att.name() ); insQuery.bindValue( ":valueIsList", att.listValue() ); // Write the relation table info. These remain empty for non related attributes. insQuery.bindValue( ":relTable", att.mTable ); insQuery.bindValue( ":relIDCol", att.mIdCol ); insQuery.bindValue( ":relStringCol", att.mStringCol ); insQuery.exec(); dbID attId = KraftDB::self()->getLastInsertID(); attribId = attId.toString(); } } // store the id to be able to drop not longer existent values kDebug() << "adding attribute id " << attribId << " for attribute " << att.name(); // now there is a valid entry in the attribute table. Check the values. QSqlQuery valueQuery( "SELECT id, value FROM attributeValues WHERE attributeId=" + attribId ); typedef QMap<QString, QString> ValueMap; ValueMap valueMap; while ( valueQuery.next() ) { QString idStr = valueQuery.value( 0 ).toString(); // id QString valStr = valueQuery.value( 1 ).toString(); // value valueMap[valStr] = idStr; } // create a stringlist with the current values of the attribute if ( att.listValue() ) { QStringList newValues; newValues = att.mValue.toStringList(); kDebug() << "new values are: " << newValues.join( ", " ); if ( newValues.empty() ) { // delete the entire attribute. dbDeleteValue( attribId ); // deletes all values dbDeleteAttribute( attribId ); valueMap.clear(); } else { // we really have new values QSqlQuery insValue; insValue.prepare( "INSERT INTO attributeValues (attributeId, value) VALUES (:attribId, :val)" ); insValue.bindValue( ":attribId", attribId ); // loop over all existing new values of the attribute. for ( QStringList::Iterator valIt = newValues.begin(); valIt != newValues.end(); ++valIt ) { QString curValue = *valIt; if ( valueMap.contains( curValue ) ) { // the valueMap is already saved. remove it from the valueMap string kDebug() << "Value " << curValue << " is already present with id " << valueMap[curValue]; valueMap.remove( curValue ); } else { // the value is not yet there, insert it. insValue.bindValue( ":val", curValue ); insValue.exec(); } } } } else { // only a single entry for the attribte, update if needed. QString newValue = att.mValue.toString(); // access the attribute object directly to get the numeric kDebug() << "NEW value String: " << newValue; // value in case the attribute is bound to a relation table if ( newValue.isEmpty() ) { // delete the entire attribute dbDeleteValue( attribId ); // deletes all values dbDeleteAttribute( attribId ); valueMap.clear(); } else { if ( valueMap.empty() ) { // there is no entry yet that could be updated. QSqlQuery insertQuery; insertQuery.prepare( "INSERT INTO attributeValues (attributeId, value ) VALUES (:id, :val)" ); insertQuery.bindValue( ":id", attribId ); insertQuery.bindValue( ":val", newValue ); insertQuery.exec(); kDebug() << "insert new attrib value for non list: " << newValue; } else { QString oldValue = valueMap.begin().key(); QString id = valueMap.begin().value(); if ( newValue != oldValue ) { kDebug() << "Updating " << id << " from " << oldValue << " to " << newValue; QSqlQuery updateQuery; updateQuery.prepare( "UPDATE attributeValues SET value=:val WHERE id=:id" ); updateQuery.bindValue( ":val", newValue ); updateQuery.bindValue( ":id", id ); kDebug() << "do the update!"; updateQuery.exec(); } valueMap.remove( oldValue ); } } } // remove all still existing entries in the valueMap because they point to values which are // in the db but were deleted from the attribute if ( ! valueMap.isEmpty() ) { ValueMap::Iterator mapIt; for ( mapIt = valueMap.begin(); mapIt != valueMap.end(); ++mapIt ) { QString valId = mapIt.value(); dbDeleteValue( attribId, valId ); } } } }