ValueMap Json_Parser::read_to_map(rapidjson::Document &doc,const char*keyname){ rapidjson::Value va; ValueMap jmap; if (doc.HasMember(keyname)) { va=doc[keyname]; if (va.IsBool()) { const bool flag=va.GetBool(); jmap[keyname]=flag; } else if (va.IsDouble()) { const double flag=va.GetDouble(); jmap[keyname]=flag; } else if (va.IsInt()) { const int flag=va.GetInt(); jmap[keyname]=flag; } else if (va.IsString()) { const std::string flag=va.GetString(); jmap[keyname]=Value(flag); } else if (va.IsNull()) { jmap[keyname]=nullptr; } else if(va.IsObject()) { cocos2d::ValueMap temp; auto it=va.MemberBegin(); for (;it!=va.MemberEnd();it++) { if (va.HasMember(it->name)) { read_to_map(temp,va,it->name.GetString()); } } jmap[keyname]=Value(temp); // CCLOG("map1层:%lu",temp.size()); } else if(va.IsArray()) { cocos2d::ValueVector temp; for (int i=0; i<va.Size();i++) { read_to_map_for_array(temp,va[i],i); } CCLOG("==%s,size:%lu",keyname,temp.size()); // CCLOG("ttt:%lu",ttt.size()); CCLOG("jma:%lu",jmap.size()); jmap[keyname]=Value(temp); //ttt[keyname]=Value(temp); CCLOG("=="); // CCLOG("vector1层:%lu",temp.size()); } } return jmap; }
/*@return the highest layer could build, otherwise NONE */ int MapModel::canBuildOnTilePosition(Point pos){ Point TileLoc = tileCoordForPosition(pos); //@debug modify label. { char buffer[30]; sprintf(buffer, "row:%.0f, col:%.0f", TileLoc.x, TileLoc.y); //getlblTilePos()->setString(buffer); } //@var later need to Resoucre Manager PFComponent *target = nullptr; if (_status == HUD_ID::DEFENSE) target = Building::build(selID); if (_status == HUD_ID::ATTACK) target = Troop::addTroop(selID); CCASSERT(target != nullptr, "target != nullptr"); for (int lr = SZ(_pfLayers) - 1; lr >= 0; lr--){ Point buildingLoc = mapCoordForPosition(pos, lr); //@procedure check for no tiles on the tile. bool noTileOnDirectly = true; if (lr < SZ(_pfLayers) - 1){ for (int tr = 0; tr < target->getOccupy().X; tr++) for (int tc = 0; tc < target->getOccupy().Y; tc++){ for (int offset = 0; offset <= 1; offset++){ Point checkTileLoc = Point(TileLoc.x + tr, TileLoc.y - tc * 2 + offset); if (isTileInsideLayer(checkTileLoc, lr)){ int tileGid = _pfLayers.at(lr + 1)->getTileGIDAt(checkTileLoc); if (tileGid != EMPTY_TILE) noTileOnDirectly = false; } } } } if (!noTileOnDirectly) continue; int couldTileCnt = 0; for (int tr = 0; tr < target->getOccupy().X; tr++) for (int tc = 0; tc < target->getOccupy().Y; tc++){ for (int offset = 1; offset <= 2; offset++){ Point checkTileLoc = Point(TileLoc.x + tr, TileLoc.y - tc * 2 + offset); if (isTileInsideLayer(checkTileLoc, lr)){ int tileGid = _pfLayers.at(lr)->getTileGIDAt(checkTileLoc); Value props = _tileMap->getPropertiesForGID(tileGid); if (!props.isNull()){ ValueMap map = props.asValueMap(); int type_int = 0; if (map.size() == 0) type_int = 0; else type_int = map.at("buildable").asInt(); if (1 == type_int){ couldTileCnt++; break; } } } } } if (couldTileCnt == target->getOccupy().X*target->getOccupy().Y) return lr + 1; } return -1; }
void taskLayer::showTask() { ValueMap taskMap = DataXML::getInstence()->getTask(); if (taskMap.size() != 0) { for (int i = 0; i < conditionIcons.size(); i++) { conditionIcons.at(i)->setTexture(CONDITION_NO_FILENAME); } int num = 0; for (auto v : taskMap) { std::string name = v.first; Sprite * sp = Sprite::createWithSpriteFrameName(DataXML::getInstence()->getPictureName(name)); sp->setNormalizedPosition(Vec2(0.5,0.5)); taskSprites.pushBack(sp); conditionIcons.at(num)->setName(name); labels.at(num)->setName(conditionIcons.at(num)->getName()); conditionIcons.at(num)->addChild(sp); num++; } }else{ for (int i = 0; i < conditionIcons.size(); i++) { labels.at(i)->setVisible(false); conditionIcons.at(i)->setTexture(CONDITION_YES_FILENAME); } } }
void GameManager::initRes() { std::string path = FileUtils::getInstance()->fullPathForFilename("load.xml"); ValueMap vm = FileUtils::getInstance()->getValueMapFromFile(path); for (int i = 0; i < vm.size(); i++) { char buf[12]; sprintf(buf, "%d", i+1); std::string s = vm.at(buf).asString(); SpriteFrameCache::getInstance()->addSpriteFramesWithFile(s); } vm.clear(); }
void taskLayer::addTool() { ValueMap toolMap = DataXML::getInstence()->getCurTool(); if (toolMap.size() != 0) { for (auto v : toolMap) { std::string fileName = v.second.asString(); taskTool = Sprite::createWithSpriteFrameName(fileName); taskTool->setPosition(685,570); this->addChild(taskTool); } }else { taskTool = Sprite::createWithSpriteFrameName(TOOLS_RIBBON_FILENAME); taskTool->setPosition(685,585); this->addChild(taskTool); } }
bool StartScene::canBuildOnTilePosition(Point pos) { Point towerLoc = this->tileCoordForPosition(pos); int tileGid = this->_background->getTileGIDAt(towerLoc); Value props = this->_tileMap->getPropertiesForGID(tileGid); ValueMap map = props.asValueMap(); int type_int; if (map.size() == 0) { type_int = 0; } else { type_int = map.at("buildable").asInt(); } if (1 == type_int) { return true; } return false; }
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; }
//设置wall属性,set的要是vector void TollgateMapLayer::setPropAtTileCoordForLayer(const char *prop, const Point &tileCoord, TMXLayer* layer)const { //for (auto tileCoord : tileCoord_vector) //{ if (!this->isValidTileCoord(tileCoord)){ return ; } int gid = layer->getTileGIDAt(tileCoord); Value properties = map->getPropertiesForGID(gid); ValueMap changePorp = properties.asValueMap(); if (changePorp.size() == 0){ ValueMap createMap; createMap[StringUtils::toString(prop)] = Value(1); layer->setProperties(createMap); } else { int type_int; type_int = changePorp[StringUtils::toString(prop)].asInt(); if (type_int < 9){ changePorp[StringUtils::toString(prop)] = Value(type_int + 1); } //} /*Value properties = map->getPropertiesForGID(gid); if (properties.isNull()){ return false; } return properties.asValueMap().find(prop) != properties.asValueMap().end();*/ } }
bool MapModel::canMoveTo(MapPoint checkMapLoc, int z){ if (!isCoordInsideLayer(checkMapLoc, z)) return false; if (!isCoordInsideLayer(checkMapLoc, z - 1)) return false; auto current = getTileGIDAt(checkMapLoc, z); auto below = getTileGIDAt(checkMapLoc, z - 1); if (current != EMPTY_TILE) return false; if (below == EMPTY_TILE) return false; Value props = _tileMap->getPropertiesForGID(below); if (!props.isNull()){ ValueMap map = props.asValueMap(); int type_int = 0; if (map.size() == 0) type_int = 0; else type_int = map.at("walkable").asInt(); if (1 == type_int) return true; } return false; }
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; } }
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(); }
// on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ){ return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); /* REGISTERING TOUCH EVENTS ===================================================== */ auto controls = EventListenerTouchAllAtOnce::create(); controls->onTouchesBegan = CC_CALLBACK_2(HelloWorld::onTouchesBegan, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(controls, this); /* NOTE: don't get in the habit of using auto everywhere An iron price to be paid (extra time == life) masquerading as convenience No reference can be made with auto and makes code unreadable Justified here since controls is a one-off and will not be referenced anywhere else but in this temporal block ALSO: This is what is called a observer pattern in the industry controls would be an "interface" of known `subscribers` to the _eventDispatcher `publisher` and events are "published" to the subscribers as they happen. Interface just means a contractual agreement between different parts of code to follow a uniform language */ /* CREATE A TMXTILEDMAP AND EXTRACT LAYER FOR DISPLAY ===================================================== */ _tileMap = TMXTiledMap::create("TileMap.tmx"); // DEPRECATED: _tileMap = new CCTMXTiledMap(); // _tileMap->initWithTMXFile("TileMap.tmx"); _background = _tileMap->getLayer("Background"); // DEPRECATED: _tileMap->layerNamed("Background"); _meta = _tileMap->layerNamed("Meta"); _meta->setVisible(false); this->addChild(_tileMap); TMXObjectGroup *objectGroup = _tileMap->objectGroupNamed("Objects"); // DEPRECATED: CCTMXObjectGroup *objectGroup = _tileMap->objectGroupNamed("Objects"); if(objectGroup == NULL) { CCLOG("tile map has no Objects object layer"); // DEPRECATED: CCLog("tile map has no objects object layer"); return false; } ValueMap spawnPoint = objectGroup->objectNamed("SpawnPoint"); // DEPRECATED: CCDictionary *spawnPoint = objectGroup->objectNamed("SpawnPoint"); Vec2 spawnHere = Point(300, 300); if(spawnPoint.size() != 0) { CCLOG("LOGCAT!!! There is a spawn point"); } else { CCLOG("LOGCAT!!! There isn't a spawn point. Using default 300 x 300."); } _player = Sprite::create("Player.png"); _player->setPosition(spawnHere); this->addChild(_player); this->setViewPointCenter(_player->getPosition()); this->setTouchEnabled(true); ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // create menu, it's an autorelease object // add a "close" icon to exit the progress. it's an autorelease object auto closeItem = MenuItemImage::create( "CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1(HelloWorld::menuCloseCallback, this)); closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 , origin.y + closeItem->getContentSize().height/2)); auto menu = Menu::create(closeItem, NULL); menu->setPosition(Vec2::ZERO); this->addChild(menu, 1); return true; }
CCObject * YHDataManagerImp::loadFile(const std::string & fullpath) { string suffix = pathExtensionWithString(fullpath); asciiToLower(suffix); // 装载对应的对象 CCObject * obj = NULL; if (suffix.compare("plist-array") == 0) { ValueVector vv = CCFileUtils::getInstance()->getValueVectorFromFile(fullpath); CCArray * arr = new CCArray(); arr->initWithCapacity((ssize_t)vv.size()); array_Value(arr, vv); obj = arr; } else if (suffix.compare("plist-dictionary") == 0) { ValueMap vm = FileUtils::getInstance()->getValueMapFromFile(fullpath); CCDictionary * dic = new CCDictionary(); dic->init(); dictionary_Value(dic, vm); obj = dic; } else if (suffix.compare("png") == 0 || suffix.compare("jpg") == 0 || suffix.compare("jpeg") == 0 || suffix.compare("tif") == 0 || suffix.compare("tiff") == 0 || suffix.compare("webp") == 0) { Image * image = new Image(); image->initWithImageFile(fullpath); obj = image; } else if (suffix.compare("plist") == 0) { ValueMap vm = CCFileUtils::getInstance()->getValueMapFromFile(fullpath); if (vm.size()) { CCDictionary * dic = new CCDictionary(); dic->init(); dictionary_Value(dic, vm); obj = dic; } else { ValueVector vv = CCFileUtils::getInstance()->getValueVectorFromFile(fullpath); if (vv.size()) { CCArray * arr = new CCArray(); arr->initWithCapacity((ssize_t)vv.size()); array_Value(arr, vv); obj = arr; } else { CCASSERT(false, "没有找到适合的解析文件方式。"); } } } else { std::string data = FileUtils::getInstance()->getStringFromFile(fullpath); YHByteArray * bytes = new YHByteArray(); bytes->init(data.length() + 1); bytes->writeBytes((char *)data.c_str(), data.length() + 1); obj = bytes; } return obj; }
void GB2ShapeCache::addShapesWithFile(const std::string &plist) { ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(plist); CCAssert(dict.size() != 0, "plist file empty or not existing"); ValueMap metadataDict = dict.at("metadata").asValueMap(); int format = metadataDict.at("format").asInt(); ptmRatio = metadataDict.at("ptm_ratio").asFloat(); CCAssert(format == 1, "Format not supported"); ValueMap bodyDict = dict.at("bodies").asValueMap(); b2Vec2 vertices[b2_maxPolygonVertices]; for (std::pair<std::string, Value> element : bodyDict) { auto bodyDef = new BodyDef(); std::string bodyName = element.first; ValueMap bodyData = element.second.asValueMap(); bodyDef->anchorPoint = PointFromString(bodyData.at("anchorpoint").asString()); ValueVector fixtureList = bodyData.at("fixtures").asValueVector(); auto nextFixtureDef = &(bodyDef->fixtures); for(Value fixture : fixtureList) { b2FixtureDef basicData; ValueMap fixtureData = fixture.asValueMap(); int callbackData = 0; 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(); basicData.isSensor = fixtureData.at("isSensor").asBool(); if(fixtureData.at("id").asString() != ""){ std::string userData = fixtureData.at("id").asString(); basicData.userData = &userData; callbackData = fixtureData.at("id").asInt(); } std::string fixtureType = fixtureData.at("fixture_type").asString(); if (fixtureType == "POLYGON") { ValueVector polygons = fixtureData.at("polygons").asValueVector(); for(Value polygon : polygons) { auto fix = new FixtureDef(); fix->fixture = basicData; // copy basic data fix->callbackData = callbackData; b2PolygonShape *polyshape = new b2PolygonShape(); int vindex = 0; ValueVector polygonData = polygon.asValueVector(); assert(polygonData.size() <= b2_maxPolygonVertices); for(Value offset : polygonData) { std::string pStr = offset.asString(); auto p = PointFromString(pStr); vertices[vindex].x = (p.x / ptmRatio) ; vertices[vindex].y = (p.y / ptmRatio) ; vindex++; } polyshape->Set(vertices, vindex); fix->fixture.shape = polyshape; *nextFixtureDef = fix; nextFixtureDef = &(fix->next); } } else if (fixtureType == "CIRCLE") { auto fix = new FixtureDef(); fix->fixture = basicData; // copy basic data fix->callbackData = callbackData; ValueMap circleData = fixtureData.at("circle").asValueMap(); auto circleShape = new b2CircleShape(); circleShape->m_radius = circleData.at("radius").asFloat() / ptmRatio; auto 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; } } }