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 endElement(void *ctx, const char *name) { CC_UNUSED_PARAM(ctx); SAXState curState = _stateStack.empty() ? SAX_DICT : _stateStack.top(); const std::string sName((char*)name); if( sName == "dict" ) { _stateStack.pop(); _dictStack.pop(); if ( !_dictStack.empty()) { _curDict = _dictStack.top(); } } else if (sName == "array") { _stateStack.pop(); _arrayStack.pop(); if (! _arrayStack.empty()) { _curArray = _arrayStack.top(); } } else if (sName == "true") { if (SAX_ARRAY == curState) { _curArray->push_back(Value(true)); } else if (SAX_DICT == curState) { (*_curDict)[_curKey] = Value(true); } } else if (sName == "false") { if (SAX_ARRAY == curState) { _curArray->push_back(Value(false)); } else if (SAX_DICT == curState) { (*_curDict)[_curKey] = Value(false); } } else if (sName == "string" || sName == "integer" || sName == "real") { if (SAX_ARRAY == curState) { if (sName == "string") _curArray->push_back(Value(_curValue)); else if (sName == "integer") _curArray->push_back(Value(atoi(_curValue.c_str()))); else _curArray->push_back(Value(utils::atof(_curValue.c_str()))); } else if (SAX_DICT == curState) { if (sName == "string") (*_curDict)[_curKey] = Value(_curValue); else if (sName == "integer") (*_curDict)[_curKey] = Value(atoi(_curValue.c_str())); else (*_curDict)[_curKey] = Value(utils::atof(_curValue.c_str())); } _curValue.clear(); } _state = SAX_NONE; }
void Menu::alignItemsInRowsWithArray(const ValueVector& columns) { vector<int> columnWidths; vector<int> columnHeights; int width = -10; int columnHeight = -5; size_t column = 0; int columnWidth = 0; int rowsOccupied = 0; int columnRows; for(const auto &child : _children) { // check if too many menu items for the amount of rows/columns CCASSERT(column < columns.size(), ""); columnRows = columns[column].asInt(); // can't have zero rows on a column CCASSERT(columnRows, ""); // columnWidth = fmaxf(columnWidth, [item contentSize].width); float tmp = child->getContentSize().width; columnWidth = (unsigned int)((columnWidth >= tmp || isnan(tmp)) ? columnWidth : tmp); columnHeight += (int)(child->getContentSize().height + 5); ++rowsOccupied; if (rowsOccupied >= columnRows) { columnWidths.push_back(columnWidth); columnHeights.push_back(columnHeight); width += columnWidth + 10; rowsOccupied = 0; columnWidth = 0; columnHeight = -5; ++column; } } // check if too many rows/columns for available menu items. CCASSERT(! rowsOccupied, ""); Size winSize = Director::getInstance()->getWinSize(); column = 0; columnWidth = 0; columnRows = 0; float x = (float)(-width / 2); float y = 0.0; for(const auto &child : _children) { if (columnRows == 0) { columnRows = columns[column].asInt(); y = (float) columnHeights[column]; } // columnWidth = fmaxf(columnWidth, [item contentSize].width); float tmp = child->getContentSize().width; columnWidth = (unsigned int)((columnWidth >= tmp || isnan(tmp)) ? columnWidth : tmp); child->setPosition(Vec2(x + columnWidths[column] / 2, y - winSize.height / 2)); y -= child->getContentSize().height + 10; ++rowsOccupied; if (rowsOccupied >= columnRows) { x += columnWidth + 5; rowsOccupied = 0; columnRows = 0; columnWidth = 0; ++column; } } }
// the XML parser calls here with all the elements void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) { CC_UNUSED_PARAM(ctx); TMXMapInfo *tmxMapInfo = this; std::string elementName = name; ValueMap attributeDict; if (atts && atts[0]) { for (int i = 0; atts[i]; i += 2) { std::string key = atts[i]; std::string value = atts[i+1]; attributeDict.insert(std::make_pair(key, Value(value))); } } if (elementName == "map") { std::string version = attributeDict["version"].asString(); if ( version != "1.0") { CCLOG("cocos2d: TMXFormat: Unsupported TMX version: %s", version.c_str()); } std::string orientationStr = attributeDict["orientation"].asString(); if (orientationStr == "orthogonal") { tmxMapInfo->setOrientation(TMXOrientationOrtho); } else if (orientationStr == "isometric") { tmxMapInfo->setOrientation(TMXOrientationIso); } else if (orientationStr == "hexagonal") { tmxMapInfo->setOrientation(TMXOrientationHex); } else if (orientationStr == "staggered") { tmxMapInfo->setOrientation(TMXOrientationStaggered); } else { CCLOG("cocos2d: TMXFomat: Unsupported orientation: %d", tmxMapInfo->getOrientation()); } Size s; s.width = attributeDict["width"].asFloat(); s.height = attributeDict["height"].asFloat(); tmxMapInfo->setMapSize(s); s.width = attributeDict["tilewidth"].asFloat(); s.height = attributeDict["tileheight"].asFloat(); tmxMapInfo->setTileSize(s); // The parent element is now "map" tmxMapInfo->setParentElement(TMXPropertyMap); } else if (elementName == "tileset") { // If this is an external tileset then start parsing that std::string externalTilesetFilename = attributeDict["source"].asString(); if (externalTilesetFilename != "") { // Tileset file will be relative to the map file. So we need to convert it to an absolute path if (_TMXFileName.find_last_of("/") != string::npos) { string dir = _TMXFileName.substr(0, _TMXFileName.find_last_of("/") + 1); externalTilesetFilename = dir + externalTilesetFilename; } else { externalTilesetFilename = _resources + "/" + externalTilesetFilename; } externalTilesetFilename = FileUtils::getInstance()->fullPathForFilename(externalTilesetFilename.c_str()); _currentFirstGID = attributeDict["firstgid"].asInt(); if (_currentFirstGID < 0) { _currentFirstGID = 0; } _recordFirstGID = false; tmxMapInfo->parseXMLFile(externalTilesetFilename.c_str()); } else { TMXTilesetInfo *tileset = new (std::nothrow) TMXTilesetInfo(); tileset->_name = attributeDict["name"].asString(); if (_recordFirstGID) { // unset before, so this is tmx file. tileset->_firstGid = attributeDict["firstgid"].asInt(); if (tileset->_firstGid < 0) { tileset->_firstGid = 0; } } else { tileset->_firstGid = _currentFirstGID; _currentFirstGID = 0; } tileset->_spacing = attributeDict["spacing"].asInt(); tileset->_margin = attributeDict["margin"].asInt(); Size s; s.width = attributeDict["tilewidth"].asFloat(); s.height = attributeDict["tileheight"].asFloat(); tileset->_tileSize = s; tmxMapInfo->getTilesets().pushBack(tileset); tileset->release(); } } else if (elementName == "tile") { if (tmxMapInfo->getParentElement() == TMXPropertyLayer) { TMXLayerInfo* layer = tmxMapInfo->getLayers().back(); Size layerSize = layer->_layerSize; uint32_t gid = static_cast<uint32_t>(attributeDict["gid"].asInt()); int tilesAmount = layerSize.width*layerSize.height; if (_xmlTileIndex < tilesAmount) { layer->_tiles[_xmlTileIndex++] = gid; } } else { TMXTilesetInfo* info = tmxMapInfo->getTilesets().back(); tmxMapInfo->setParentGID(info->_firstGid + attributeDict["id"].asInt()); tmxMapInfo->getTileProperties()[tmxMapInfo->getParentGID()] = Value(ValueMap()); tmxMapInfo->setParentElement(TMXPropertyTile); } } else if (elementName == "layer") { TMXLayerInfo *layer = new (std::nothrow) TMXLayerInfo(); layer->_name = attributeDict["name"].asString(); Size s; s.width = attributeDict["width"].asFloat(); s.height = attributeDict["height"].asFloat(); layer->_layerSize = s; Value& visibleValue = attributeDict["visible"]; layer->_visible = visibleValue.isNull() ? true : visibleValue.asBool(); Value& opacityValue = attributeDict["opacity"]; layer->_opacity = opacityValue.isNull() ? 255 : (unsigned char)(255.0f * opacityValue.asFloat()); float x = attributeDict["x"].asFloat(); float y = attributeDict["y"].asFloat(); layer->_offset = Vec2(x,y); tmxMapInfo->getLayers().pushBack(layer); layer->release(); // The parent element is now "layer" tmxMapInfo->setParentElement(TMXPropertyLayer); } else if (elementName == "objectgroup") { TMXObjectGroup *objectGroup = new (std::nothrow) TMXObjectGroup(); objectGroup->setGroupName(attributeDict["name"].asString()); Vec2 positionOffset; positionOffset.x = attributeDict["x"].asFloat() * tmxMapInfo->getTileSize().width; positionOffset.y = attributeDict["y"].asFloat() * tmxMapInfo->getTileSize().height; objectGroup->setPositionOffset(positionOffset); tmxMapInfo->getObjectGroups().pushBack(objectGroup); objectGroup->release(); // The parent element is now "objectgroup" tmxMapInfo->setParentElement(TMXPropertyObjectGroup); } else if (elementName == "image") { TMXTilesetInfo* tileset = tmxMapInfo->getTilesets().back(); // build full path std::string imagename = attributeDict["source"].asString(); if (_TMXFileName.find_last_of("/") != string::npos) { string dir = _TMXFileName.substr(0, _TMXFileName.find_last_of("/") + 1); tileset->_sourceImage = dir + imagename; } else { tileset->_sourceImage = _resources + (_resources.size() ? "/" : "") + imagename; } } else if (elementName == "data") { std::string encoding = attributeDict["encoding"].asString(); std::string compression = attributeDict["compression"].asString(); if (encoding == "") { tmxMapInfo->setLayerAttribs(tmxMapInfo->getLayerAttribs() | TMXLayerAttribNone); TMXLayerInfo* layer = tmxMapInfo->getLayers().back(); Size layerSize = layer->_layerSize; int tilesAmount = layerSize.width*layerSize.height; uint32_t *tiles = (uint32_t*) malloc(tilesAmount*sizeof(uint32_t)); // set all value to 0 memset(tiles, 0, tilesAmount*sizeof(int)); layer->_tiles = tiles; } else if (encoding == "base64") { int layerAttribs = tmxMapInfo->getLayerAttribs(); tmxMapInfo->setLayerAttribs(layerAttribs | TMXLayerAttribBase64); tmxMapInfo->setStoringCharacters(true); if (compression == "gzip") { layerAttribs = tmxMapInfo->getLayerAttribs(); tmxMapInfo->setLayerAttribs(layerAttribs | TMXLayerAttribGzip); } else if (compression == "zlib") { layerAttribs = tmxMapInfo->getLayerAttribs(); tmxMapInfo->setLayerAttribs(layerAttribs | TMXLayerAttribZlib); } CCASSERT( compression == "" || compression == "gzip" || compression == "zlib", "TMX: unsupported compression method" ); } } else if (elementName == "object") { TMXObjectGroup* objectGroup = tmxMapInfo->getObjectGroups().back(); // The value for "type" was blank or not a valid class name // Create an instance of TMXObjectInfo to store the object and its properties ValueMap dict; // Parse everything automatically const char* keys[] = {"name", "type", "width", "height", "gid"}; for (const auto& key : keys) { Value value = attributeDict[key]; dict[key] = value; } // But X and Y since they need special treatment // X int x = attributeDict["x"].asInt(); // Y int y = attributeDict["y"].asInt(); Vec2 p(x + objectGroup->getPositionOffset().x, _mapSize.height * _tileSize.height - y - objectGroup->getPositionOffset().x - attributeDict["height"].asInt()); p = CC_POINT_PIXELS_TO_POINTS(p); dict["x"] = Value(p.x); dict["y"] = Value(p.y); int width = attributeDict["width"].asInt(); int height = attributeDict["height"].asInt(); Size s(width, height); s = CC_SIZE_PIXELS_TO_POINTS(s); dict["width"] = Value(s.width); dict["height"] = Value(s.height); // Add the object to the objectGroup objectGroup->getObjects().push_back(Value(dict)); // The parent element is now "object" tmxMapInfo->setParentElement(TMXPropertyObject); } else if (elementName == "property") { if ( tmxMapInfo->getParentElement() == TMXPropertyNone ) { CCLOG( "TMX tile map: Parent element is unsupported. Cannot add property named '%s' with value '%s'", attributeDict["name"].asString().c_str(), attributeDict["value"].asString().c_str() ); } else if ( tmxMapInfo->getParentElement() == TMXPropertyMap ) { // The parent element is the map Value value = attributeDict["value"]; std::string key = attributeDict["name"].asString(); tmxMapInfo->getProperties().insert(std::make_pair(key, value)); } else if ( tmxMapInfo->getParentElement() == TMXPropertyLayer ) { // The parent element is the last layer TMXLayerInfo* layer = tmxMapInfo->getLayers().back(); Value value = attributeDict["value"]; std::string key = attributeDict["name"].asString(); // Add the property to the layer layer->getProperties().insert(std::make_pair(key, value)); } else if ( tmxMapInfo->getParentElement() == TMXPropertyObjectGroup ) { // The parent element is the last object group TMXObjectGroup* objectGroup = tmxMapInfo->getObjectGroups().back(); Value value = attributeDict["value"]; std::string key = attributeDict["name"].asString(); objectGroup->getProperties().insert(std::make_pair(key, value)); } else if ( tmxMapInfo->getParentElement() == TMXPropertyObject ) { // The parent element is the last object TMXObjectGroup* objectGroup = tmxMapInfo->getObjectGroups().back(); ValueMap& dict = objectGroup->getObjects().rbegin()->asValueMap(); std::string propertyName = attributeDict["name"].asString(); dict[propertyName] = attributeDict["value"]; } else if ( tmxMapInfo->getParentElement() == TMXPropertyTile ) { ValueMap& dict = tmxMapInfo->getTileProperties().at(tmxMapInfo->getParentGID()).asValueMap(); std::string propertyName = attributeDict["name"].asString(); dict[propertyName] = attributeDict["value"]; } } else if (elementName == "polygon") { // find parent object's dict and add polygon-points to it TMXObjectGroup* objectGroup = _objectGroups.back(); ValueMap& dict = objectGroup->getObjects().rbegin()->asValueMap(); // get points value string std::string value = attributeDict["points"].asString(); if (!value.empty()) { ValueVector pointsArray; pointsArray.reserve(10); // parse points string into a space-separated set of points stringstream pointsStream(value); string pointPair; while (std::getline(pointsStream, pointPair, ' ')) { // parse each point combo into a comma-separated x,y point stringstream pointStream(pointPair); string xStr, yStr; ValueMap pointDict; // set x if (std::getline(pointStream, xStr, ',')) { int x = atoi(xStr.c_str()) + (int)objectGroup->getPositionOffset().x; pointDict["x"] = Value(x); } // set y if (std::getline(pointStream, yStr, ',')) { int y = atoi(yStr.c_str()) + (int)objectGroup->getPositionOffset().y; pointDict["y"] = Value(y); } // add to points array pointsArray.push_back(Value(pointDict)); } dict["points"] = Value(pointsArray); } } else if (elementName == "polyline") { // find parent object's dict and add polyline-points to it TMXObjectGroup* objectGroup = _objectGroups.back(); ValueMap& dict = objectGroup->getObjects().rbegin()->asValueMap(); // get points value string std::string value = attributeDict["points"].asString(); if (!value.empty()) { ValueVector pointsArray; pointsArray.reserve(10); // parse points string into a space-separated set of points stringstream pointsStream(value); string pointPair; while (std::getline(pointsStream, pointPair, ' ')) { // parse each point combo into a comma-separated x,y point stringstream pointStream(pointPair); string xStr, yStr; ValueMap pointDict; // set x if (std::getline(pointStream, xStr, ',')) { int x = atoi(xStr.c_str()) + (int)objectGroup->getPositionOffset().x; pointDict["x"] = Value(x); } // set y if (std::getline(pointStream, yStr, ',')) { int y = atoi(yStr.c_str()) + (int)objectGroup->getPositionOffset().y; pointDict["y"] = Value(y); } // add to points array pointsArray.push_back(Value(pointDict)); } dict["polylinePoints"] = Value(pointsArray); } } }
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; } }
void Menu::alignItemsInColumnsWithArray(const ValueVector& rows) { int height = -5; size_t row = 0; int rowHeight = 0; int columnsOccupied = 0; int rowColumns = 0; for(const auto &child : _children) { CCASSERT(row < rows.size(), ""); rowColumns = rows[row].asInt(); // can not have zero columns on a row CCASSERT(rowColumns, ""); float tmp = child->getContentSize().height; rowHeight = (unsigned int)((rowHeight >= tmp || isnan(tmp)) ? rowHeight : tmp); ++columnsOccupied; if (columnsOccupied >= rowColumns) { height += rowHeight + 5; columnsOccupied = 0; rowHeight = 0; ++row; } } // check if too many rows/columns for available menu items CCASSERT(! columnsOccupied, ""); Size winSize = Director::getInstance()->getWinSize(); row = 0; rowHeight = 0; rowColumns = 0; float w = 0.0; float x = 0.0; float y = (float)(height / 2); for(const auto &child : _children) { if (rowColumns == 0) { rowColumns = rows[row].asInt(); w = winSize.width / (1 + rowColumns); x = w; } float tmp = child->getContentSize().height; rowHeight = (unsigned int)((rowHeight >= tmp || isnan(tmp)) ? rowHeight : tmp); child->setPosition(Vec2(x - winSize.width / 2, y - child->getContentSize().height / 2)); x += w; ++columnsOccupied; if (columnsOccupied >= rowColumns) { y -= rowHeight + 5; columnsOccupied = 0; rowColumns = 0; rowHeight = 0; ++row; } } }
void SpaceGameLayer::getObjects(float sf) { const string objectName = "objects"; auto objectGroup = level->getMap()->getObjectGroup(objectName); ValueVector obj = objectGroup->getObjects(); for (int i = 0;i < obj.size();i++) { ValueMap vm = obj.at(i).asValueMap(); int x = vm["x"].asInt(); int y = vm["y"].asInt(); float w = vm["width"].asInt(); float h = vm["height"].asInt(); x *= level->getScale(); y *= level->getScale();; w *= level->getScale();; h *= level->getScale();; string name = vm["name"].asString(); string type = vm["type"].asString(); if (name == "player_start") { hero = new Hero(scale); load_player_stats(); hero->setPosition(x, y); this->addChild(hero, 6); this->addChild(hero->player_sprite, 5); hero->addToGameObjects = &addToGameObjects; } if (name == "passage") { string sc = vm["to_scene"].asString(); string ps = vm["to_passage"].asString(); Passage *pass = new Passage(x, y, w, h, sc, ps); exits.pushBack(pass); pass->target = hero; this->addChild(pass, 6); this->setScale(sf); } if (name == "robot_soldier") { Robot_Soldier *fb = new Robot_Soldier(scale); fb->setPosition(x, y); gameObjects.pushBack(fb); fb->target = hero; this->addChild(fb, 6); } if (name == "laser_trap") { uint32_t direction = vm["direction"].asInt(); uint32_t range = vm["range"].asInt(); float delay = vm["delay"].asFloat(); float duration = vm["duration"].asFloat(); float off_time = vm["off_time"].asFloat(); Laser_Trap *fb = new Laser_Trap(scale,duration,off_time,direction, range, delay); fb->setPosition(x, y); gameObjects.pushBack(fb); fb->target = hero; this->addChild(fb, 6); } /*if(name == "premade_textbox"){ //PremadeTextBox *tb = new PremadeTextBox(x,y,w,h); tb->setPosition(x,y); gameObjects.pushBack(tb); this->addChild(tb,6); } if(name == "space_pig"){ SpacePig *sp = new SpacePig(); sp->setPosition(x,y); sp->setZone(w*(type=="zone"), h*(type=="zone")); gameObjects.pushBack(sp); this->addChild(sp,6); //sp->setScale(sf); } if(name == "flying_blocker"){ Flying_Blocker *fb = new Flying_Blocker(); fb->setPosition(x,y); gameObjects.pushBack(fb); fb->target = hero; this->addChild(fb,6); } if(name == "flying_blocker"){ Flying_Blocker *fb = new Flying_Blocker(); fb->setPosition(x,y); gameObjects.pushBack(fb); fb->target = hero; this->addChild(fb,6); } if(name == "patrol_ufo"){ Patrol_Ufo *fb = new Patrol_Ufo(); fb->setPosition(x,y); gameObjects.pushBack(fb); fb->target = hero; this->addChild(fb,6); } if(name == "spitting_projectiles"){ Spitting_Projectiles *sp = new Spitting_Projectiles; sp->setPosition(x+0.5*w,y+0.5*h); sp->setZone(w*(type=="zone"), h*(type=="zone")); gameObjects.pushBack(sp); this->addChild(sp,6); sp->setScale(sf); sp->target = hero; sp->addToGameObjects = &addToGameObjects; sp->currentGameLayer = this; } if(name == "damage"){ Damage_Zone *dmg = new Damage_Zone(x,y,w,h); dmg->setPosition(x,y); gameObjects.pushBack(dmg); this->addChild(dmg,6); this->setScale(sf); } if(name == "brain_sucker"){ BrainSucker *bs = new BrainSucker(); bs->setPosition(x,y); gameObjects.pushBack(bs); bs->target = hero; this->addChild(bs,6); this->setScale(sf); } if(name == "death_rain"){ DeathRain *dr = new DeathRain(w*(type=="zone"),h*(type=="zone")); dr->setPosition(x,y); dr->setZone(w*(type=="zone"), h*(type=="zone")); gameObjects.pushBack(dr); this->addChild(dr,6); dr->setScale(sf); dr->target = hero; dr->addToGameObjects = &addToGameObjects; dr->currentGameLayer = this; } if(name == "moving_plattform"){ MovingPlattform *mp = new MovingPlattform(x, y); this->addChild(mp,6); mp->setScale(sf); mp->target = hero; mp->addToGameObjects = &addToGameObjects; gameObjects.pushBack(mp); mp->currentGameLayer = this; } */ } if (hero != NULL) { if (hero->nextEntrance != "") { for (int i = 0;i < exits.size();i++) { if (hero->nextEntrance == exits.at(i)->idString) { hero->toucing_exit = true; hero->setPositionX(exits.at(i)->getPositionX()); hero->setPositionY(exits.at(i)->getPositionY()); } } } for (int i = 0;i < gameObjects.size();i++) { gameObjects.at(i)->target = hero; gameObjects.at(i)->player_screen = &screen; gameObjects.at(i)->map_data = this->level; gameObjects.at(i)->addToGameObjects = &addToGameObjects; } for (int i = 0;i < exits.size();i++) { exits.at(i)->target = hero; } } }
static jobject ValueVector2SFSArray(JNIEnv* env, const ValueVector& valueVector, jobject javaObj) { jclass cls = env->GetObjectClass(javaObj); if (!cls) return javaObj; for (auto it = valueVector.begin(); it != valueVector.end(); ++it) { if (it->getType() == Value::Type::BYTE) { jmethodID mid = env->GetMethodID(cls, "addByte", "(B)V"); if (mid) env->CallVoidMethod(javaObj, mid, it->asByte()); } else if (it->getType() == Value::Type::INTEGER) { jmethodID mid = env->GetMethodID(cls, "addInt", "(I)V"); if (mid) env->CallVoidMethod(javaObj, mid, it->asInt()); } else if (it->getType() == Value::Type::FLOAT) { jmethodID mid = env->GetMethodID(cls, "addFloat", "(F)V"); if (mid) env->CallVoidMethod(javaObj, mid, it->asFloat()); } else if (it->getType() == Value::Type::DOUBLE) { jmethodID mid = env->GetMethodID(cls, "addFloat", "(F)V"); if (mid) env->CallVoidMethod(javaObj, mid, it->asDouble()); } else if (it->getType() == Value::Type::BOOLEAN) { jmethodID mid = env->GetMethodID(cls, "addBool", "(Z)V"); if (mid) env->CallVoidMethod(javaObj, mid, it->asBool()); } else if (it->getType() == Value::Type::STRING) { jmethodID mid = env->GetMethodID(cls, "addUtfString", "(Ljava/lang/String;)V"); if (mid) { jobject javaValue = env->NewStringUTF(it->asString().c_str()); env->CallVoidMethod(javaObj, mid, javaValue); env->DeleteLocalRef(javaValue); } } else if (it->getType() == Value::Type::VECTOR) { jmethodID mid = env->GetMethodID(cls, "addSFSArray", "(Lcom/smartfoxserver/v2/entities/data/ISFSArray;)V"); if (mid) { jobject javaSFSArray = getSFSArray(env); jobject javaValue = ValueVector2SFSArray(env, it->asValueVector(), javaSFSArray); env->CallVoidMethod(javaObj, mid, javaValue); env->DeleteLocalRef(javaValue); } } else if (it->getType() == Value::Type::MAP) { jmethodID mid = env->GetMethodID(cls, "addSFSObject", "(Lcom/smartfoxserver/v2/entities/data/ISFSObject;)V"); if (mid) { jobject sub_obj = getSFSObject(env); jobject javaValue = ValueMap2SFSObject(env, it->asValueMap(), sub_obj); env->CallVoidMethod(javaObj, mid, javaValue); env->DeleteLocalRef(javaValue); } } else if (it->getType() == Value::Type::INT_KEY_MAP) { } } env->DeleteLocalRef(cls); return javaObj; }
CCBKeyframe* CCBReader::readKeyframe(PropertyType type) { CCBKeyframe *keyframe = new CCBKeyframe(); keyframe->autorelease(); keyframe->setTime(readFloat()); CCBKeyframe::EasingType easingType = static_cast<CCBKeyframe::EasingType>(readInt(false)); float easingOpt = 0; Value value; if (easingType == CCBKeyframe::EasingType::CUBIC_IN || easingType == CCBKeyframe::EasingType::CUBIC_OUT || easingType == CCBKeyframe::EasingType::CUBIC_INOUT || easingType == CCBKeyframe::EasingType::ELASTIC_IN || easingType == CCBKeyframe::EasingType::ELASTIC_OUT || easingType == CCBKeyframe::EasingType::ELASTIC_INOUT) { easingOpt = readFloat(); } keyframe->setEasingType(easingType); keyframe->setEasingOpt(easingOpt); if (type == PropertyType::CHECK) { value = readBool(); } else if (type == PropertyType::BYTE) { value = readByte(); } else if (type == PropertyType::COLOR3) { unsigned char r = readByte(); unsigned char g = readByte(); unsigned char b = readByte(); ValueMap colorMap; colorMap["r"] = r; colorMap["g"] = g; colorMap["b"] = b; value = colorMap; } else if (type == PropertyType::DEGREES) { value = readFloat(); } else if (type == PropertyType::SCALE_LOCK || type == PropertyType::POSITION || type == PropertyType::FLOAT_XY) { float a = readFloat(); float b = readFloat(); ValueVector ab; ab.push_back(Value(a)); ab.push_back(Value(b)); value = ab; } else if (type == PropertyType::SPRITEFRAME) { std::string spriteSheet = readCachedString(); std::string spriteFile = readCachedString(); SpriteFrame* spriteFrame; if (spriteSheet.length() == 0) { spriteFile = _CCBRootPath + spriteFile; Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(spriteFile.c_str()); Rect bounds = Rect(0, 0, texture->getContentSize().width, texture->getContentSize().height); spriteFrame = SpriteFrame::createWithTexture(texture, bounds); } else { spriteSheet = _CCBRootPath + spriteSheet; SpriteFrameCache* frameCache = SpriteFrameCache::getInstance(); // Load the sprite sheet only if it is not loaded if (_loadedSpriteSheets.find(spriteSheet) == _loadedSpriteSheets.end()) { frameCache->addSpriteFramesWithFile(spriteSheet.c_str()); _loadedSpriteSheets.insert(spriteSheet); } spriteFrame = frameCache->getSpriteFrameByName(spriteFile.c_str()); } keyframe->setObject(spriteFrame); } if (!value.isNull()) keyframe->setValue(value); return keyframe; }
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; } } }
void Inventory::addItem(InventoryObject *draggedObject) { items.pushBack(draggedObject); listView->pushBackCustomItem(draggedObject->getPicture()); EventListenerTouchOneByOne *backgroundListener = EventListenerTouchOneByOne::create(); backgroundListener->setSwallowTouches(true); backgroundListener->onTouchBegan = [draggedObject, this](Touch *touch, Event *event) { auto target = static_cast<ImageView *>(event->getCurrentTarget()); Size s = target->getContentSize(); Point locationInNode = target->convertToNodeSpace(touch->getLocation()); locationInNode = Point(locationInNode.x + s.width * 0.5f, locationInNode.y + s.height * 0.5f); Rect rect = Rect(0, 0, s.width, s.height); if (rect.containsPoint(locationInNode)) { draggedObject->startDrag(); simpleLayout->addChild(draggedObject->getPictureDrag()); draggedObject->getPictureDrag()->setPosition(touch->getLocation()); return true; } return false; }; backgroundListener->onTouchMoved = [draggedObject,this](Touch *touch, Event *event) { if(draggedObject->getPictureDrag() != nullptr) draggedObject->getPictureDrag()->setPosition(touch->getLocation()); }; backgroundListener->onTouchEnded = [draggedObject,this](Touch *touch, Event *event) { log("onTouchEnded draggedObject=%d", draggedObject ? draggedObject->getId() : 0); if(draggedObject->getPictureDrag() != nullptr) draggedObject->getPictureDrag()->setVisible(false); Vector<CollectObject *> gameObjects = FirstScene::getInstance()->getGameObjectsLayer()->getGameObjects(); for(int i = 0; i < gameObjects.size(); ++i) { log("collect obj=%d",gameObjects.at(i)->getId()); Size size = gameObjects.at(i)->getSpriteMain()->getContentSize(); Rect rect = Rect(0, 0, size.width, size.height); Point locationInNode = gameObjects.at(i)->getSpriteMain()->convertToNodeSpace(touch->getLocation()); //locationInNode = Point(locationInNode.x , locationInNode.y - size.height * 0.5f); log("!!!locationInNode=%f %f",locationInNode.x, locationInNode.y); if (rect.containsPoint(locationInNode)) { log("AHTUNG"); } } for(int i = 0; i < items.size(); ++i) { InventoryObject *droppedObject = items.at(i); Size s = droppedObject->getPicture()->getContentSize(); Rect rect = Rect(0, 0, s.width, s.height); Point locationInNode = droppedObject->getPicture()->convertToNodeSpace(touch->getLocation()); locationInNode = Point(locationInNode.x + s.width * 0.5f, locationInNode.y + s.height * 0.5f); log("2onTouchEnded draggedObject=%d obj=%d locationInNode=%f %f", draggedObject ? draggedObject->getId() : 0, droppedObject ? droppedObject->getId() : 0, locationInNode.x,locationInNode.y); if (droppedObject != draggedObject && rect.containsPoint(locationInNode)) { ValueMap *draggedObjectData = DataManager::getInstance()->getItemByID(draggedObject->getId()); ValueMap *draggedObjectCraft = &draggedObjectData->at("craft").asValueMap(); ValueMap *droppedObjectData = DataManager::getInstance()->getItemByID(droppedObject->getId()); ValueMap *droppedObjectCraft = &droppedObjectData->at("craft").asValueMap(); ValueVector draggedObjectCraftItems = draggedObjectCraft->at("items").asValueVector(); bool shouldCraft = false; for(int i = 0; i < draggedObjectCraftItems.size(); ++i) { if(draggedObjectCraftItems.at(i).asInt() == droppedObject->getId()) { shouldCraft = true; break; } } if(shouldCraft) { int draggedCapacity = draggedObjectCraft->at("capacity").asInt(); --draggedCapacity; draggedObjectCraft->at("capacity") = draggedCapacity; int droppedCapacity = droppedObjectCraft->at("capacity").asInt(); --droppedCapacity; droppedObjectCraft->at("capacity") = droppedCapacity; log("carft %d", draggedObjectCraft->at("result").asInt()); if(draggedObjectCraft->at("result").asInt() != 0) { addItem(InventoryObject::create(draggedObjectCraft->at("result").asInt())); } if(!draggedCapacity) { draggedObject->getPicture()->removeFromParent(); } if(!droppedCapacity) { droppedObject->getPicture()->removeFromParent(); } log("GOT IT! draggedCapacity=%d droppedCapacity=%d",draggedCapacity,droppedCapacity); DataManager::getInstance()->save(); } break; } } }; _eventDispatcher->addEventListenerWithSceneGraphPriority(backgroundListener, draggedObject->getPicture()); }
bool runOnFunction(Function &F) override { AliasAnalysis AA = getAnalysis<AliasAnalysis>(); DependenceAnalysis *DA = &(getAnalysis<DependenceAnalysis>()); // iterate over basic blocks Function *func = &F; unsigned bb_num = 0; for (Function::iterator BB = func->begin(), BE = func->end(); BB != BE; ++BB) { errs() << "BB-" << bb_num << "\n"; bb_num++; // iterator over instructions unsigned inst_num = 0; for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;++I) { Instruction *Ins = dyn_cast<Instruction>(I); if (!Ins) return false; LoadInst *Ld = dyn_cast<LoadInst>(I); StoreInst *St = dyn_cast<StoreInst>(I); if (!St && !Ld) continue; if (Ld && !Ld->isSimple()) return false; if (St && !St->isSimple()) return false; inst_num++; MemInstr.push_back(&*I); errs() << "MemInst-" << inst_num << ":" << *I << "\n"; } ValueVector::iterator I, IE, J, JE; for (I = MemInstr.begin(), IE = MemInstr.end(); I != IE; ++I) { for (J = I, JE = MemInstr.end(); J != JE; ++J) { std::vector<char> Dep; Instruction *Src = dyn_cast<Instruction>(*I); Instruction *Des = dyn_cast<Instruction>(*J); if (Src == Des) continue; if (isa<LoadInst>(Src) && isa<LoadInst>(Des)) continue; if (auto D = DA->depends(Src, Des, true)) { errs() << "Found Dependency between:\nSrc:" << *Src << "\nDes:" << *Des << "\n"; if (D->isFlow()) { errs () << "Flow dependence not handled"; return false; } if (D->isAnti()) { errs() << "Found Anti dependence \n"; AliasAnalysis::AliasResult AA_dep = AA.alias(Src, Des); AliasAnalysis::AliasResult AA_dep_1 = AA.alias(Des, Src); errs() << "The Ld->St alias result is " << AA_dep << "\n"; errs() << "The St->Ld alias result is " << AA_dep_1 << "\n"; unsigned Levels = D->getLevels(); errs() << "levels = " << Levels << "\n"; char Direction; for (unsigned II = 1; II <= Levels; ++II) { const SCEV *Distance = D->getDistance(II); const SCEVConstant *SCEVConst = dyn_cast_or_null<SCEVConstant>(Distance); if (SCEVConst) { const ConstantInt *CI = SCEVConst->getValue(); //int64_t it_dist = CI->getUniqueInteger().getSExtValue(); //int it_dist = CI->getUniqueInteger().getSExtValue(); unsigned it_dist = abs(CI->getUniqueInteger().getSExtValue()); errs() << "distance is not null\n"; //errs() << "distance = "<< *CI << "\n"; errs() << "distance = "<< it_dist << "\n"; if (CI->isNegative()) Direction = '<'; else if (CI->isZero()) Direction = '='; else Direction = '>'; Dep.push_back(Direction); } else if (D->isScalar(II)) { Direction = 'S'; Dep.push_back(Direction); } else { unsigned Dir = D->getDirection(II); if (Dir == Dependence::DVEntry::LT || Dir == Dependence::DVEntry::LE) Direction = '<'; else if (Dir == Dependence::DVEntry::GT || Dir == Dependence::DVEntry::GE) Direction = '>'; else if (Dir == Dependence::DVEntry::EQ) Direction = '='; else Direction = '*'; Dep.push_back(Direction); } } } } } } } errs() << "------Hello World!--------\n"; return false; }