Ejemplo n.º 1
0
LLVMBool valmap_check(valmap_t map, LLVMValueRef v)
{
  ValueMap<Value*,void*> *vmap = (ValueMap<Value*,void*>*)map;
  Value *val = unwrap(v);
  return (LLVMBool)(vmap->find(val)!=vmap->end());
}
Ejemplo n.º 2
0
/*
 * For converting param specs for Regions and LinkPolicies
 */
ValueMap toValueMap(const char *yamlstring,
                    Collection<ParameterSpec> &parameters,
                    const std::string &nodeType,
                    const std::string &regionName) {

  ValueMap vm;

  // special value that applies to all regions.
  ParameterSpec dim_spec("Buffer dimensions for region's global dimensions. "
                    "Syntax: {dim: [2,3]}",  // description
	                  NTA_BasicType_UInt32,
							      0,                         // elementCount (an array of unknown size)
							      "",                        // constraints
							      "",                        // defaultValue
							      ParameterSpec::ReadWriteAccess);


  std::string paddedstring(yamlstring);
  // TODO: strip white space to determine if empty
  bool empty = (paddedstring.size() == 0);

  // TODO: utf-8 compatible?
  const YAML::Node doc = YAML::Load(paddedstring);
  if(!empty) {
    // A ValueMap is specified as a dictionary
    if (doc.Type() != YAML::NodeType::Map) {
      std::string ys(yamlstring);
      if (ys.size() > 30) {
        ys = ys.substr(0, 30) + "...";
      }
      NTA_THROW
          << "YAML string '" << ys
          << "' does not not specify a dictionary of key-value pairs. "
          << "Region and Link parameters must be specified as a dictionary";
    }
  }
  // Grab each value out of the YAML dictionary and put into the ValueMap
  // if it is allowed by the nodespec.
  for (auto i = doc.begin(); i != doc.end(); i++)
  {
    ParameterSpec ps;

    const auto key = i->first.as<std::string>();
    if (key == "dim")
      ps = dim_spec;
    else {
      if (!parameters.contains(key))
      {
        std::stringstream ss;
        for (UInt j = 0; j < parameters.getCount(); j++){
          ss << "   " << parameters.getByIndex(j).first << "\n";
        }

        if (nodeType == std::string("")) {
          NTA_THROW << "Unknown parameter '" << key << "'\n"
                    << "Valid parameters are:\n" << ss.str();
        } else {
          NTA_CHECK(regionName != std::string(""));
          NTA_THROW << "Unknown parameter '" << key << "' for region '"
                    << regionName << "' of type '" << nodeType << "'\n"
                    << "Valid parameters are:\n"
                    << ss.str();
        }
      }
      ps = parameters.getByName(key); // makes a copy of ParameterSpec
    }
    if (vm.contains(key))
        NTA_THROW << "Parameter '" << key << "' specified more than once in YAML document";
    try
    {
      if (ps.accessMode == ParameterSpec::ReadOnlyAccess) {
        NTA_THROW << "Parameter '" << key << "'. This is ReadOnly access. Cannot be set.";
      }
      Value v = toValue(i->second, ps.dataType);
      if (v.isScalar() && ps.count != 1)
      {
        NTA_THROW << "Parameter '" << key << "'. Bad value in runtime parameters. Expected array value but got scalar value";
      }
      if (!v.isScalar() && ps.count == 1)
      {
        NTA_THROW << "Parameter '" << key << "'. Bad value in runtime parameters. Expected scalar value but got array value";
      }
      vm.add(key, v);
    } catch (std::runtime_error &e) {
      NTA_THROW << "Unable to set parameter '" << key << "'. " << e.what();
    }
  } //end for

  // Populate ValueMap with default values if they were not specified in the YAML dictionary.
  for (size_t i = 0; i < parameters.getCount(); i++)
  {
    const std::pair<std::string, ParameterSpec>& item = parameters.getByIndex(i);
    if (!vm.contains(item.first))
    {
      const ParameterSpec & ps = item.second;
      if (ps.defaultValue != "")
      {
        // TODO: This check should be uncommented after dropping NuPIC 1.x nodes (which don't comply) //FIXME try this
        // if (ps.accessMode != ParameterSpec::CreateAccess)
        // {
        //   NTA_THROW << "Default value for non-create parameter: " << item.first;
        // }

        try {
#ifdef YAMLDEBUG
          NTA_DEBUG << "Adding default value '" << ps.defaultValue
                    << "' to parameter " << item.first << " of type "
                    << BasicType::getName(ps.dataType) << " count " << ps.count;
#endif
          // NOTE: this can handle both scalers and arrays
          //       Arrays MUST be in Yaml sequence format even if one element.
          //       i.e.  [1,2,3]
          Value v = toValue(ps.defaultValue, ps.dataType);
          if (v.isScalar() && ps.count != 1)
          {
            NTA_THROW << "Parameter '" << item.first << "'. Bad default value in spec. Expected array value but got scalar value";
          }
          if (!v.isScalar() && ps.count == 1)
          {
            NTA_THROW << "Parameter '" << item.first << "'. Bad default value in spec. Expected scalar value but got array value";
          }
          vm.add(item.first, v);
        } catch (...) {
          NTA_THROW << "Unable to set default value for item '" << item.first
                    << "' of datatype " << BasicType::getName(ps.dataType)
                    << " with value '" << ps.defaultValue << "'";
        }
      }
    }
  }

  return vm;
}
Ejemplo n.º 3
0
    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;
        }
    }
Ejemplo n.º 4
0
// 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 = (char*)name;
    ValueMap attributeDict;
    if (atts && atts[0])
    {
        for(int i = 0; atts[i]; i += 2) 
        {
            std::string key = (char*)atts[i];
            std::string value = (char*)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
            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* array[] = {"name", "type", "width", "height", "gid"};
        
        for(size_t i = 0; i < sizeof(array)/sizeof(array[0]); ++i )
        {
            const char* key = array[i];
            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);
        }
    }
}
bool ParticleSystem::initWithDictionary(ValueMap& dictionary, const std::string& dirname)
{
    bool ret = false;
    unsigned char *buffer = nullptr;
    unsigned char *deflated = nullptr;
    Image *image = nullptr;
    do 
    {
        int maxParticles = dictionary["maxParticles"].asInt();
        // self, not super
        if(this->initWithTotalParticles(maxParticles))
        {
            // Emitter name in particle designer 2.0
            _configName = dictionary["configName"].asString();

            // angle
            _angle = dictionary["angle"].asFloat();
            _angleVar = dictionary["angleVariance"].asFloat();

            // duration
            _duration = dictionary["duration"].asFloat();

            // blend function 
            if (_configName.length()>0)
            {
                _blendFunc.src = dictionary["blendFuncSource"].asFloat();
            }
            else
            {
                _blendFunc.src = dictionary["blendFuncSource"].asInt();
            }
            _blendFunc.dst = dictionary["blendFuncDestination"].asInt();

            // color
            _startColor.r = dictionary["startColorRed"].asFloat();
            _startColor.g = dictionary["startColorGreen"].asFloat();
            _startColor.b = dictionary["startColorBlue"].asFloat();
            _startColor.a = dictionary["startColorAlpha"].asFloat();

            _startColorVar.r = dictionary["startColorVarianceRed"].asFloat();
            _startColorVar.g = dictionary["startColorVarianceGreen"].asFloat();
            _startColorVar.b = dictionary["startColorVarianceBlue"].asFloat();
            _startColorVar.a = dictionary["startColorVarianceAlpha"].asFloat();

            _endColor.r = dictionary["finishColorRed"].asFloat();
            _endColor.g = dictionary["finishColorGreen"].asFloat();
            _endColor.b = dictionary["finishColorBlue"].asFloat();
            _endColor.a = dictionary["finishColorAlpha"].asFloat();

            _endColorVar.r = dictionary["finishColorVarianceRed"].asFloat();
            _endColorVar.g = dictionary["finishColorVarianceGreen"].asFloat();
            _endColorVar.b = dictionary["finishColorVarianceBlue"].asFloat();
            _endColorVar.a = dictionary["finishColorVarianceAlpha"].asFloat();

            // particle size
            _startSize = dictionary["startParticleSize"].asFloat();
            _startSizeVar = dictionary["startParticleSizeVariance"].asFloat();
            _endSize = dictionary["finishParticleSize"].asFloat();
            _endSizeVar = dictionary["finishParticleSizeVariance"].asFloat();

            // position
            float x = dictionary["sourcePositionx"].asFloat();
            float y = dictionary["sourcePositiony"].asFloat();
            this->setPosition( Vec2(x,y) );            
            _posVar.x = dictionary["sourcePositionVariancex"].asFloat();
            _posVar.y = dictionary["sourcePositionVariancey"].asFloat();

            // Spinning
            _startSpin = dictionary["rotationStart"].asFloat();
            _startSpinVar = dictionary["rotationStartVariance"].asFloat();
            _endSpin= dictionary["rotationEnd"].asFloat();
            _endSpinVar= dictionary["rotationEndVariance"].asFloat();

            _emitterMode = (Mode) dictionary["emitterType"].asInt();

            // Mode A: Gravity + tangential accel + radial accel
            if (_emitterMode == Mode::GRAVITY)
            {
                // gravity
                modeA.gravity.x = dictionary["gravityx"].asFloat();
                modeA.gravity.y = dictionary["gravityy"].asFloat();

                // speed
                modeA.speed = dictionary["speed"].asFloat();
                modeA.speedVar = dictionary["speedVariance"].asFloat();

                // radial acceleration
                modeA.radialAccel = dictionary["radialAcceleration"].asFloat();
                modeA.radialAccelVar = dictionary["radialAccelVariance"].asFloat();

                // tangential acceleration
                modeA.tangentialAccel = dictionary["tangentialAcceleration"].asFloat();
                modeA.tangentialAccelVar = dictionary["tangentialAccelVariance"].asFloat();
                
                // rotation is dir
                modeA.rotationIsDir = dictionary["rotationIsDir"].asBool();
            }

            // or Mode B: radius movement
            else if (_emitterMode == Mode::RADIUS)
            {
                if (_configName.length()>0)
                {
                    modeB.startRadius = dictionary["maxRadius"].asInt();
                }
                else
                {
                    modeB.startRadius = dictionary["maxRadius"].asFloat();
                }
                modeB.startRadiusVar = dictionary["maxRadiusVariance"].asFloat();
                if (_configName.length()>0)
                {
                    modeB.endRadius = dictionary["minRadius"].asInt();
                }
                else
                {
                    modeB.endRadius = dictionary["minRadius"].asFloat();
                }
                
                if (dictionary.find("minRadiusVariance") != dictionary.end())
                {
                    modeB.endRadiusVar = dictionary["minRadiusVariance"].asFloat();
                }
                else
                {
                    modeB.endRadiusVar = 0.0f;
                }
                
                if (_configName.length()>0)
                {
                    modeB.rotatePerSecond = dictionary["rotatePerSecond"].asInt();
                }
                else
                {
                    modeB.rotatePerSecond = dictionary["rotatePerSecond"].asFloat();
                }
                modeB.rotatePerSecondVar = dictionary["rotatePerSecondVariance"].asFloat();

            } else {
                CCASSERT( false, "Invalid emitterType in config file");
                CC_BREAK_IF(true);
            }

            // life span
            _life = dictionary["particleLifespan"].asFloat();
            _lifeVar = dictionary["particleLifespanVariance"].asFloat();

            // emission Rate
            _emissionRate = _totalParticles / _life;

            //don't get the internal texture if a batchNode is used
            if (!_batchNode)
            {
                // Set a compatible default for the alpha transfer
                _opacityModifyRGB = false;

                // texture        
                // Try to get the texture from the cache
                std::string textureName = dictionary["textureFileName"].asString();
                
                size_t rPos = textureName.rfind('/');
               
                if (rPos != string::npos)
                {
                    string textureDir = textureName.substr(0, rPos + 1);
                    
                    if (!dirname.empty() && textureDir != dirname)
                    {
                        textureName = textureName.substr(rPos+1);
                        textureName = dirname + textureName;
                    }
                }
                else if (!dirname.empty() && !textureName.empty())
                {
                	textureName = dirname + textureName;
                }
                
                Texture2D *tex = nullptr;
                
                if (textureName.length() > 0)
                {
                    // set not pop-up message box when load image failed
                    bool notify = FileUtils::getInstance()->isPopupNotify();
                    FileUtils::getInstance()->setPopupNotify(false);
                    tex = Director::getInstance()->getTextureCache()->addImage(textureName);
                    // reset the value of UIImage notify
                    FileUtils::getInstance()->setPopupNotify(notify);
                }
                
                if (tex)
                {
                    setTexture(tex);
                }
                else if( dictionary.find("textureImageData") != dictionary.end() )
                {                        
                    std::string textureData = dictionary.at("textureImageData").asString();
                    CCASSERT(!textureData.empty(), "");
                    
                    auto dataLen = textureData.size();
                    if (dataLen != 0)
                    {
                        // if it fails, try to get it from the base64-gzipped data    
                        int decodeLen = base64Decode((unsigned char*)textureData.c_str(), (unsigned int)dataLen, &buffer);
                        CCASSERT( buffer != nullptr, "CCParticleSystem: error decoding textureImageData");
                        CC_BREAK_IF(!buffer);
                        
                        ssize_t deflatedLen = ZipUtils::inflateMemory(buffer, decodeLen, &deflated);
                        CCASSERT( deflated != nullptr, "CCParticleSystem: error ungzipping textureImageData");
                        CC_BREAK_IF(!deflated);
                        
                        // For android, we should retain it in VolatileTexture::addImage which invoked in Director::getInstance()->getTextureCache()->addUIImage()
                        image = new Image();
                        bool isOK = image->initWithImageData(deflated, deflatedLen);
                        CCASSERT(isOK, "CCParticleSystem: error init image with Data");
                        CC_BREAK_IF(!isOK);
                        
                        setTexture(Director::getInstance()->getTextureCache()->addImage(image, textureName.c_str()));

                        image->release();
                    }
                }
                
                _yCoordFlipped = dictionary.find("yCoordFlipped") == dictionary.end() ? 1 : dictionary.at("yCoordFlipped").asInt();

                if( !this->_texture)
                    CCLOGWARN("cocos2d: Warning: ParticleSystemQuad system without a texture");
            }
            ret = true;
        }
    } while (0);
    free(buffer);
    free(deflated);
    return ret;
}
Ejemplo n.º 6
0
CTobCompiler::EToken CTobCompiler::CompilePass1()
{
    EToken r, LastToken;
    CString str, buf, sizebuf;
    CByteArray* bin;
    SValueType* val;
    SExpression* exp;

    for(;;)
    {
        BOOL bSkipGetToken = FALSE;
        if ((r = GetToken(str)) <= 0) return r;
_SkipGetToken:
        if (r == SYM_DEF)
        {
/*
            if (m_bin.GetSize() > 0)
            {
                m_err = "const token can not defined after data";
                return ERR_NORMAL;
            }
*/
            if ((r = GetToken(str)) < 0) return r;
            if (r != SYM_TOKEN)
            {
                m_err = "not found token after '@'";
                return ERR_NORMAL;
            }

            if (str == "_IGNORECASE")
            {
                m_Option.bIgnoreCase = TRUE;
                continue;
            }

            if ((r = GetToken(buf)) < 0) return r;
            if (r == SYM_BIN)
            {
                bin = new CByteArray;
                if ((r = GetBinary(*bin)) < 0) { delete bin; return r; }
                AddMap(m_binmap, str, bin);
            }
            else if (r == SYM_STR)
            {
                bin = new CByteArray;
                if ((r = GetString(*bin)) < 0) { delete bin; return r; }
                AddMap(m_binmap, str, bin);
            }
            else if (r == SYM_INT)
            {
                ULONG Length;
                BOOL bHex = (buf[0] == '0' && buf[1] == 'x');

                r = GetToken(sizebuf);
                LastToken = r;
                if (r == SYM_TYPE)
                {
                    r = GetToken(sizebuf);
                    if (r != SYM_TOKEN)
                    {
                        m_err = "not found type after ':'";
                        return ERR_NORMAL;
                    }

                    Length = GetSizeFromType(sizebuf[0]);
                    if (Length == -1)
                    {
                        m_err.Format("unknown type '%c' after ':'", sizebuf[0]);
                        return ERR_NORMAL;
                    }
                }
                else
                {
                    Length = -1;
                }
                val = new SValueType((int)strtoul(buf, NULL, bHex ? 16 : 10), Length);
                AddMap(m_valmap, str, val);

                if (Length == -1)
                    bSkipGetToken = TRUE;

                r = SYM_INT;
            }
            else if (r == SYM_FLOAT)
            {
                AddMap(m_valmap, str, new SValueType(atof(buf)));
            }
            else
            {
                m_err.Format("not found '[' or ''' or '\"' or number after '@%s'", (LPCTSTR)str);
                return ERR_NORMAL;
            }

            if (m_Option.bIgnoreCase)
                str.MakeUpper();

            if (str == "_DEFI")
            {
                if (r != SYM_INT || val->ival < 1 || val->ival > 4)
                {
                    m_err = "_DEFI must be 1/2/3/4";
                    return ERR_NORMAL;
                }
                m_Option.DefInt = val->ival;
            }
            else if (str == "_DEFF")
            {
                if (r != SYM_INT || val->ival != 4 && val->ival != 8)
                {
                    m_err = "_DEFF must be 4/8";
                    return ERR_NORMAL;
                }
                m_Option.DefFloat = val->ival;
            }
            else if (str == "_MOD")
            {
                if (r != SYM_INT)
                {
                    m_err = "_MOD must be number";
                    return ERR_NORMAL;
                }

                while (m_bin.GetSize() % val->ival)
                    m_bin.Add(0);
            }
            else if (str == "_INCLUDE")
            {
                FILE *fsrc;
                WCHAR szPath[MAX_PATH];
                CByteArray *bin;

                if (m_Option.bIgnoreCase)
                    str.MakeLower();

                if (!m_binmap.Lookup(str, bin))
                    continue;

                m_binmap.RemoveKey(str);

                MultiByteToWideChar(
                    CP_GB2312,
                    0,
                    (LPSTR)bin->GetData(),
                    -1,
                    szPath,
                    countof(szPath));

                delete bin;

                fsrc = m_fsrc;
                m_fsrc = _wfopen(szPath, L"rb");
                if (m_fsrc == NULL)
                {
                    m_fsrc = fsrc;
                    m_err.Format("can't open include file '%S'", szPath);
                    return ERR_SEVERE;
                }
                else
                {
                    EToken r;
                    for(;;)
                    {
                        r = CompilePass1();
                        if (r == ERR_EOF)
                            break;

                        if (r < 0)
                        {
                            if (!ErrorHandlerInternal(GetErrorString(m_err)))
                                break;
                        }

                        if (r == ERR_SEVERE)
                            break;
                    }

                    fclose(m_fsrc);
                    m_fsrc = fsrc;
                    if (r < 0)
                        return r;
                }
            }

            if (bSkipGetToken)
            {
                str = sizebuf;
                r = LastToken;
                goto _SkipGetToken;
            }
        }
        else if (r == SYM_BIN)
        {
            if ((r = GetBinary(m_bin)) < 0) return r;
        }
        else if (r == SYM_STR)
        {
            if ((r = GetString(m_bin)) < 0) return r;
        }
        else if (r == SYM_TOKEN)
        {
            if (!m_binmap.Lookup(str, bin))
            {
                m_err.Format("unknown token '%s'", (LPCTSTR)str);
                return ERR_NORMAL;
            }
            m_bin.Append(*bin);
        }
        else if (r == SYM_LABEL)
        {
            if ((r = GetToken(str)) < 0) return r;
            if (r != SYM_TOKEN)
            {
                m_err = "not found token after '#'";
                return ERR_NORMAL;
            }
            if (m_valmap.Lookup(str, val))
            {
                m_err.Format("already defined label token '%s'", (LPCTSTR)str);
                return ERR_NORMAL;
            }
            m_valmap.SetAt(str, new SValueType(m_bin.GetSize()));
        }
        else if (r == SYM_EXP_BEGIN)
        {
            int i = m_exparr.GetSize();
            do
            {
                int len = m_Option.DefInt;
                BOOL hastype = FALSE;
                exp = new SExpression(m_bin.GetSize(), m_line);
                for(;;)
                {
                    if ((r = GetToken(buf)) < 0)
                    {
                        delete exp;
                        return r;
                    }

                    if (r == SYM_TOKEN)
                    {
                        val = NULL;
                        if (!hastype && len > 0 && m_valmap.Lookup(buf, val) && val->isfloat)
                            len = -m_Option.DefFloat;
                        exp->m_item.Add(buf);
                        if (val != NULL && val->m_size != -1)
                            len = val->isfloat ? -val->m_size : val->m_size;
                    }
                    else if (r == SYM_ADD)
                    {
                        exp->m_item.Add("+");
                    }
                    else if (r == SYM_SUB)
                    {
                        exp->m_item.Add("-");
                    }
                    else if (r == SYM_DEF)
                    {
                        exp->m_item.Add("@");
                    }
                    else if (r == SYM_INT)
                    {
                        exp->m_item.Add(buf);
                    }
                    else if (r == SYM_FLOAT)
                    {
                        if (!hastype && len > 0)
                            len = -m_Option.DefFloat;
                        exp->m_item.Add(buf);
                    }
                    else if (r == SYM_TYPE)
                    {
                        int newlen;
                        if ((r = GetToken(buf)) < 0) { delete exp; return r; }
                        if (r != SYM_TOKEN)
                        {
                            delete exp;
                            m_err = "not found type after ':'";
                            return ERR_NORMAL;
                        }

                        newlen = GetSizeFromType(buf[0]);
                        if (newlen == -1)
                        {
                            delete exp;
                            m_err.Format("unknown type '%c' after ':'", buf[0]);
                            return ERR_NORMAL;
                        }

                        if (hastype && newlen != len)
                        {
                            delete exp;
                            m_err = "found different types in one expression";
                            return ERR_NORMAL;
                        }
                        hastype = TRUE;
                        len = newlen;
                    }
                    else if (r == SYM_BIN)
                    {
                        if (exp->m_item.GetSize() > 0)
                        {
                            delete exp;
                            m_err = "found different types in one expression";
                            return ERR_NORMAL;
                        }
                        if ((r = GetBinary(m_bin)) < 0) { delete exp; return r; }
                    }
                    else if (r == SYM_STR)
                    {
                        if (exp->m_item.GetSize() > 0)
                        {
                            delete exp;
                            m_err = "found different types in one expression";
                            return ERR_NORMAL;
                        }
                        if ((r = GetString(m_bin)) < 0) { delete exp; return r; }
                    }
                    else if (r == SYM_NEXT || r == SYM_EXP_END)
                    {
                        break;
                    }
                    else
                    {
                        delete exp;
                        m_err.Format("unknown or bad symbol1 '%s' in expression", (LPCTSTR)str);
                        return ERR_NORMAL;
                    }
                }
                if (exp->m_item.GetSize() <= 0)
                {
                    delete exp;
                }
                else
                {
                    exp->m_size = len;
                    m_exparr.Add(exp);
                    if (len < 0) len = -len;
                    while(len--)
                        m_bin.Add(0);
                }
            }
            while(r != SYM_EXP_END);
            for(int j = m_exparr.GetSize(); i < j; ++i)
                m_exparr[i]->m_self = m_bin.GetSize();
        }
        else
        {
            m_err.Format("unknown or bad symbol2 '%s'", (LPCTSTR)str);
            return ERR_NORMAL;
        }
    }
}
Ejemplo n.º 7
0
String AsJSON(const Value& v, const String& sep, bool pretty)
{
	String r;
	if(v.GetType() == VALUEMAP_V) {
		r << "{";
		String sep1;
		if(pretty) {
			r << "\r\n";
			sep1 = sep + '\t';
		}
		ValueMap m = v;
		ValueArray va = m.GetValues();
		for(int i = 0; i < m.GetCount(); i++) {
			if(i) {
				r << ",";
				if(pretty)
					r << "\r\n";
			}
			if(pretty)
				r << sep1;
			r << AsJSON((String)m.GetKey(i)) << (pretty ? ": " : ":")
			  << AsJSON(va[i], sep1, pretty);
		}
		if(pretty)
			r << "\r\n" << sep;
		r << "}";
		return r;
	}
	if(v.GetType() == VALUEARRAY_V) {
		r << "[";
		String sep1;
		if(pretty) {
			r << "\r\n";
			sep1 = sep + '\t';
		}
		ValueArray va = v;
		for(int i = 0; i < va.GetCount(); i++) {
			if(i) {
				r << ",";
				if(pretty)
					r << "\r\n";
			}
			if(pretty)
				r << sep1;
			r << AsJSON(va[i], sep1, pretty);
		}
		if(pretty)
			r << "\r\n" << sep;
		r << "]";
		return r;
	}
	if(IsNumber(v) && IsNull(v))
		return "null";
	if(v.GetType() == INT_V)
		return Format("%d", (int)v);
	if(v.GetType() == BOOL_V)
		return (bool)v ? "true" : "false";
	if(IsNumber(v))
		return Format("%.16g", (double)v);
	if(IsString(v))
		return AsCString((String)v, INT_MAX, NULL, ASCSTRING_JSON);
	if(IsDateTime(v))
		return AsJSON((Time)v);
	if(IsNull(v))
		return "null";
	NEVER_("Non-JSON value in AsJSON: " + v.GetTypeName());
	return "null";
}
Ejemplo n.º 8
0
static jobject ValueMap2SFSObject(JNIEnv* env, const ValueMap& valueMap, jobject javaObj)
{
    jclass cls = env->GetObjectClass(javaObj);
    if (!cls) return javaObj;

    for (auto it = valueMap.begin(); it != valueMap.end(); ++it)
    {
        jobject javaKey = env->NewStringUTF(it->first.c_str());
        if (it->second.getType() == Value::Type::BYTE)
        {
            jmethodID mid = env->GetMethodID(cls, "putByte", "(Ljava/lang/String;B)V");
            if (mid) env->CallVoidMethod(javaObj, mid, javaKey, it->second.asByte());
        }
        else if (it->second.getType() == Value::Type::INTEGER)
        {
            jmethodID mid = env->GetMethodID(cls, "putInt", "(Ljava/lang/String;I)V");
            if (mid) env->CallVoidMethod(javaObj, mid, javaKey, it->second.asInt());
        }
        else if (it->second.getType() == Value::Type::FLOAT)
        {
            jmethodID mid = env->GetMethodID(cls, "putFloat", "(Ljava/lang/String;F)V");
            if (mid) env->CallVoidMethod(javaObj, mid, javaKey, it->second.asFloat());
        }
        else if (it->second.getType() == Value::Type::DOUBLE)
        {
            jmethodID mid = env->GetMethodID(cls, "putFloat", "(Ljava/lang/String;F)V");
            if (mid) env->CallVoidMethod(javaObj, mid, javaKey, it->second.asDouble());
        }
        else if (it->second.getType() == Value::Type::BOOLEAN)
        {
            jmethodID mid = env->GetMethodID(cls, "putBool", "(Ljava/lang/String;Z)V");
            if (mid) env->CallVoidMethod(javaObj, mid, javaKey, it->second.asBool());
        }
        else if (it->second.getType() == Value::Type::STRING)
        {
            jmethodID mid = env->GetMethodID(cls, "putUtfString", "(Ljava/lang/String;Ljava/lang/String;)V");
            if (mid)
            {
                jobject javaValue = env->NewStringUTF(it->second.asString().c_str());
                env->CallVoidMethod(javaObj, mid, javaKey, javaValue);
                env->DeleteLocalRef(javaValue);
            }
        }
        else if (it->second.getType() == Value::Type::VECTOR)
        {
            jmethodID mid = env->GetMethodID(cls, "putSFSArray", "(Ljava/lang/String;Lcom/smartfoxserver/v2/entities/data/ISFSArray;)V");
            if (mid)
            {
                jobject javaSFSArray = getSFSArray(env);
                jobject javaValue = ValueVector2SFSArray(env, it->second.asValueVector(), javaSFSArray);
                env->CallVoidMethod(javaObj, mid, javaKey, javaValue);
                env->DeleteLocalRef(javaValue);
            }
        }
        else if (it->second.getType() == Value::Type::MAP)
        {
            jmethodID mid = env->GetMethodID(cls, "putSFSObject", "(Ljava/lang/String;Lcom/smartfoxserver/v2/entities/data/ISFSObject;)V");
            if (mid)
            {
                jobject sub_obj = getSFSObject(env);
                jobject javaValue = ValueMap2SFSObject(env, it->second.asValueMap(), sub_obj);
                env->CallVoidMethod(javaObj, mid, javaKey, javaValue);
                env->DeleteLocalRef(javaValue);
            }
        }
        else if (it->second.getType() == Value::Type::INT_KEY_MAP)
        {

        }
        env->DeleteLocalRef(javaKey);
    }
    env->DeleteLocalRef(cls);

    return javaObj;
}
Ejemplo n.º 9
0
// 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;
}
Ejemplo n.º 10
0
PushBoxScene::PushBoxScene()
{
    TMXTiledMap* mytmx = TMXTiledMap::create("Pushbox/map.tmx");
    mytmx->setPosition(visibleSize.width / 2, visibleSize.height / 2);
    mytmx->setAnchorPoint(Vec2(0,0));
    myx = (visibleSize.width - mytmx->getContentSize().width) / 2;
    myy = (visibleSize.height - mytmx->getContentSize().height) / 2;
    this->addChild(mytmx, 0);

    count = 0;
    success = 0;
    /*mon = Sprite::create("Pushbox/player.png");
    mon->setAnchorPoint(Vec2(0, 0));
    mon->setPosition(Vec2(SIZE_BLOCK*1+myx, SIZE_BLOCK*8+myy));
    mon->setTag(TAG_PLAYER);
    this->addChild(mon, 1);*/



    TMXObjectGroup* objects = mytmx->getObjectGroup("wall");
    //从对象层中获取对象数组
    ValueVector container = objects->getObjects();
    //遍历对象
    for (auto obj : container) {
        ValueMap values = obj.asValueMap();
        int x = values.at("x").asInt();
        int y = values.at("y").asInt();
        Sprite* temp = Sprite::create("Pushbox/wall.png");
        temp->setAnchorPoint(Point(0, 0));
        temp->setPosition(Point(x,y+64));
        mywall.pushBack(temp);
        this->addChild(temp, 1);
    }

    TMXObjectGroup* objects1 = mytmx->getObjectGroup("box");
    //从对象层中获取对象数组
    ValueVector container1 = objects1->getObjects();
    //遍历对象
    for (auto obj : container1) {
        ValueMap values = obj.asValueMap();
        int x = values.at("x").asInt();
        int y = values.at("y").asInt();
        Sprite* temp = Sprite::create("Pushbox/box.png");
        temp->setAnchorPoint(Point(0, 0));
        temp->setPosition(Point(x, y+64));
        mybox.pushBack(temp);
        this->addChild(temp, 3);
    }

    TMXObjectGroup* objects2 = mytmx->getObjectGroup("player");
    //从对象层中获取对象数组
    ValueVector container2 = objects2->getObjects();
    //遍历对象
    for (auto obj : container2) {
        ValueMap values = obj.asValueMap();
        int x = values.at("x").asInt();
        int y = values.at("y").asInt();
        Sprite* temp = Sprite::create("Pushbox/player.png");
        temp->setAnchorPoint(Point(0, 0));
        temp->setPosition(Point(x, y+64));
        mon = temp;
        this->addChild(temp, 2);
    }

    TMXObjectGroup* objects3 = mytmx->getObjectGroup("goal");
    //从对象层中获取对象数组
    ValueVector container3 = objects3->getObjects();
    //遍历对象
    for (auto obj : container3) {
        ValueMap values = obj.asValueMap();
        int x = values.at("x").asInt();
        int y = values.at("y").asInt();
        Sprite* temp = Sprite::create("Pushbox/goal.png");
        temp->setAnchorPoint(Point(0, 0));
        temp->setPosition(Point(x, y+64));
        mygoal.pushBack(temp);
        this->addChild(temp, 1);
    }
}
Ejemplo n.º 11
0
SimpleKLRetriever::SimpleKLRetriever(const ValueMap &col_probs_, double default_col_prob_, double dir_prior_):
	col_probs(col_probs_.copy()),
	default_col_prob(default_col_prob_),
	dir_prior(dir_prior_)
{
}
 void          kill_array(ValueType* type)                   { _map->kill_array(type); }
 void          kill_field(ciField* field, bool all_offsets)  { _map->kill_field(field, all_offsets); }
 // implementation for abstract methods of ValueNumberingVisitor
 void          kill_memory()                                 { _map->kill_memory(); }
Ejemplo n.º 15
0
bool CNFServerChangeScrollLayer::InitLayer(int nItemNum)
{
    do
    {
        //初始化父类
        CC_BREAK_IF(CCLayerColor::initWithColor(Color4B(0,0,0,0))==false);
        
        
        //版本变化
        //独占触屏注册值小于-128才能屏蔽Menu(Menu默认是-128)
//        CCDirector::getInstance()->getTouchDispatcher()->addTargetedDelegate(this, -129, true);
        
        auto listener = EventListenerTouchOneByOne::create();
        listener->setSwallowTouches(true);
        
        listener->onTouchBegan = CC_CALLBACK_2(CNFServerChangeScrollLayer::onTouchBegan, this);
        listener->onTouchMoved = CC_CALLBACK_2(CNFServerChangeScrollLayer::onTouchMoved, this);
        listener->onTouchEnded = CC_CALLBACK_2(CNFServerChangeScrollLayer::onTouchEnded, this);
        listener->onTouchEnded = CC_CALLBACK_2(CNFServerChangeScrollLayer::onTouchCancelled, this);
        
        _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
        
        
//        setTouchEnabled(true);
        
        
        //初始x轴坐标
        m_fStartNodePosX = _X_START_POS_ + _NF_SCREEN_WIDTH_DIS_;
        
        ;		//页面数量
        int nPageNum = nItemNum%_ONE_PAGE_SERVER_NUM_ > 0 ? nItemNum/_ONE_PAGE_SERVER_NUM_+1 : nItemNum/_ONE_PAGE_SERVER_NUM_;
        
        //每一页宽度
        m_fPageWidth = _PAGE_WIDTH_;
        
        //页面高度
        float	fPageHeight = _PAGE_HEIGHT_;
        
        //x轴最小坐标
        m_fEndLayerPos = m_fPageWidth*(1-nPageNum);
        
        //x,y轴之间的间隔
        float fItemDisX = 11;
        float fItemDisY = 20;
        
        
        /************************************************************************/
        /*			创建按钮 
         
         
         */
        /************************************************************************/
        
//        版本变化
//        CCDictionary *pDicLang = CCDictionary::createWithContentsOfFile("ui_xml/serverselect_xml.xml");
//        CC_BREAK_IF(pDicLang==NULL);
        
        ValueMap pDicLang = FileUtils::getInstance()->getValueMapFromFile("ui_xml/serverselect_xml.xml");
         
        
        
        
        
        Menu * pMenu = Menu::create();
        CC_BREAK_IF(pMenu==NULL);
        pMenu->setPosition(Vec2::ZERO);
        addChild(pMenu,enZOrderFront,enTagMenu);
        
        //创建数组
        Ref *pObj = NULL;
        for (int k=1;k<=nItemNum;k++)
        {
            int i = k%_ONE_PAGE_SERVER_NUM_ > 0 ? k%_ONE_PAGE_SERVER_NUM_ : _ONE_PAGE_SERVER_NUM_;			//页面内ITem的ID:1~12
            int j = k%_ONE_PAGE_SERVER_NUM_ > 0 ? k/_ONE_PAGE_SERVER_NUM_+1 : k/_ONE_PAGE_SERVER_NUM_;		//当前页面ID
            
            int nCrossNum = i%3 == 0 ? 3 : i%3;				//横排
            int nVerticalNum = i%3 > 0 ? i/3+1 : i/3;		//竖排
            

            
            //创建按钮
            auto pBtn = MenuItemSprite::create(Sprite::create("ui/btn_enter_n.png"), Sprite::create("ui/btn_enter_p.png"), Sprite::create("ui/btn_enter_n.png"), CC_CALLBACK_1(CNFServerChangeScrollLayer::OnBtnCallBack, this) );
            CC_BREAK_IF(pBtn==NULL);
            pBtn->setPosition(Vec2( fItemDisX+ (nCrossNum-1)*(pBtn->getContentSize().width+fItemDisX) + m_fStartNodePosX + pBtn->getContentSize().width*0.5f + (j-1)*m_fPageWidth , fPageHeight-nVerticalNum*(pBtn->getContentSize().height+fItemDisY) + fItemDisY ));
            pMenu->addChild(pBtn,enZOrderFront,enTagBtn+k);
            
            //服务器名称label
//            std::string* 注意这里没有“*” pStrServerName = pDicLang.at("server_name").asString();
            std::string pStrServerName = pDicLang.at("server_name").asString();
            
            char szName[NAME_LEN] = {0};
            sprintf(szName,pStrServerName.c_str(),k);
            
            //版本变化
//            CCLabelTTF * pLabelServerName = CCLabelTTF::create(szName,"Arial",20);
//            CC_BREAK_IF(pLabelServerName==NULL);
            
            Label * pLabelServerName = Label::createWithSystemFont(szName, "Arial", 20);
            CC_BREAK_IF(pLabelServerName==NULL);
            
            pLabelServerName->setPosition(pBtn->getPosition());
            addChild(pLabelServerName,enZOrderFront);
            
        }
        
        
        //显示区域
        m_DisPlayRect = Rect(m_fStartNodePosX ,10 ,m_fPageWidth,fPageHeight);
        
        m_bTouching = false;
        m_bIsTouchBtn = false;
        
        
//        schedule(schedule_selector(CNFServerChangeScrollLayer::OnBtnCallBack2), 1.0f, kRepeatForever, 0);
        
        return true;
    } while (false);
    log("Fun CQXPVEItemScrollLayer::initWithNodes Error!");
    
    
    return false;
    
}
Ejemplo n.º 16
0
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;
        
    }
    
}
Ejemplo n.º 17
0
BOOL CTobCompiler::CompilePass2(F_ErrorHandler ErrorHandler)
{
    BOOL haserr = FALSE;
    int i, j, m, n = m_exparr.GetSize();
    int pos, len, factor;
    double v;
    BYTE* b; float f;
    SValueType* val;
    CString err;

    m_line = 0;
    for(i = 0; i < n; ++i)
    {
        v = 0.0;
        factor = 1;
        const SExpression* exp = m_exparr.ElementAt(i);
        m = exp->m_item.GetSize();
        pos = exp->m_pos;
        len = exp->m_size;
        if (len < 0) len = -len;
        for(j = 0; j < m; ++j)
        {
            const CString& str = exp->m_item[j];
            if (str == "+")
            {
                factor = 1;
            }
            else if (str == "-")
            {
                factor = -1;
            }
            else if (str == "@")
            {
                v += exp->m_self * factor;
                factor = 1;
            }
            else
            {
                TCHAR c = str[0];
                if ((c >= '0' && c <= '9') || c == '.')
                {
                    BOOL bHex = (c == '0' && str[1] == 'x');
                    if (bHex)
                        v += strtoul(str, NULL, 16) * factor;
                    else
                        v += atof(str) * factor;
                }
                else
                {
                    if (m_valmap.Lookup(str, val))
                    {
                        v += val->dval * factor;
                        if (val->m_size != -1)
                            len = val->m_size;
                    }
                    else
                    {
                        m_err.Format("not found token '%s' at line %d", (LPCTSTR)str, exp->m_line);
                        haserr = TRUE;
                        if (!(this->*ErrorHandler)(GetErrorString(err)))
                            return FALSE;
                    }
                }
                factor = 1;
            }
        }
        if (exp->m_size > 0)
        {
            m = (int)v;
            b = (BYTE*)&m;
            len = min(len, sizeof(m));
        }
        else if (exp->m_size == -4)
        {
            f = (float)v;
            b = (BYTE*)&f;
            len = min(len, sizeof(f));
        }
        else
        {
            b = (BYTE*)&v;
            len = min(len, sizeof(f));
        }
        memcpy(&m_bin[pos], b, len);
/*
        for(j = len - 1; j >= 0; --j)
            m_bin[pos + j] = b[j];
*/
    }
    return !haserr;
}
bool FiledScene::init(){
	if (!Layer::init())
		return false;
	
	_isGameOver = false;
	auto visibleSize = Director::getInstance()->getVisibleSize();
	_screenWidth = visibleSize.width;
	_screenHeight = visibleSize.height;

	_tileMap = TMXTiledMap::create("field_map.tmx");
	_tileMap->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
	_tileMap->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2));

	// ②获取障碍层,并设置障碍层为不可见
	_collidable = _tileMap->getLayer("collidable");
	_collidable->setVisible(false);
	/********③初始化读取地图所有网格,并确定网格对象是否是障碍物,将信息保存到网格二维数组**************/
	for (int i = 0; i < _tileMap->getMapSize().width; i++) {
		// 内部网格集合([x,0]-[x-20]),存储网格
		Vector<Grid*> inner;
		for (int j = 0; j < _tileMap->getMapSize().height; j++) {
			// 设置网格对象的x轴和y轴以及是否可通过变量值
			Grid *o = Grid::create(i, j);
			// 将网格加入到集合
			inner.pushBack(o);
		}
		// 将内部集合加入到网格集合
		_gridVector.push_back(inner);
	}
	// 循环保存根据每个网格的x轴和y轴查找对应的地图的GID,判断是否可通过
	for (int i = 0; i < _gridVector.size(); i++) {
		Vector<Grid*> inner = _gridVector.at(i);
		// 循环内部网格集合
		for (int j = 0; j < inner.size(); j++) {
			// 获取每一个网格对象
			Grid *grid = inner.at(j);
			// 获取每一个网格对象对应的的坐标
			Vec2 tileCoord = Vec2(grid->getX(), grid->getY());
			// 使用TMXLayer类的tileGIDAt函数获取TileMap坐标系里的“全局唯一标识”GID
			int tileGid = _collidable->getTileGIDAt(tileCoord);
			if (tileGid) {
				// 使用GID来查找指定tile的属性,返回一个Value
				Value properties = _tileMap->getPropertiesForGID(tileGid);
				// 返回的Value实际是一个ValueMap
				ValueMap map = properties.asValueMap();
				// 查找ValueMap,判断是否有”可碰撞的“物体,如果有,设置网格对象的isPass变量为false
				std::string value = map.at("collidable").asString();
				if (value.compare("true") == 0) {
					grid->setPass(false);
				}
			}
		}
	}

	// 人物出场特效
	auto effects_player_out = Sprite::create("effects/effects_player_out/effects_player_out_11.png");
	effects_player_out->setPosition(Vec2(visibleSize.width*0.3,visibleSize.height*0.3));
	this->addChild(effects_player_out, 1);
	auto player_out_animate = getAnimateByName("effects/effects_player_out/effects_player_out_", 0.1f, 11);
	auto delay1 = DelayTime::create(1.5f);
	auto fadeOut = FadeOut::create(0.2f);
	auto sequence = Sequence::create(delay1, player_out_animate, fadeOut, nullptr);
	effects_player_out->runAction(sequence);

	_player = SpriteBase::create("player/player_sword/player_sword_stand.png");
	this->addChild(_player, 1);
	_player->setPosition(Vec2(visibleSize.width*0.3, visibleSize.height*0.3));
	this->addChild(_tileMap,0);
	_player->setFlippedX(true);
	XmlTools::readPlayerData(_player);

	/// 传送门
	ArmatureDataManager::getInstance()->addArmatureFileInfo("/buildings/gate/AnimationStart0.png", "/buildings/gate/AnimationStart0.plist", "/buildings/gate/AnimationStart.ExportJson");
	Armature *armature = Armature::create("AnimationStart");
	armature->getAnimation()->play("Start");
	this->addChild(armature);
	armature->setScale(0.3);
	armature->setPosition(Vec2(visibleSize.width*0.9, visibleSize.height*0.7));
	auto gate_effect = ParticleSystemQuad::create("effects/gate_effect.plist");
	this->addChild(gate_effect);
	gate_effect->setScale(0.3);
	gate_effect->setPosition(Vec2(visibleSize.width*0.9, visibleSize.height*0.75));
	gate_effect->setPositionType(kCCPositionTypeRelative);

	// 结束战斗按钮
	auto end_fight_button = Button::create("ui/end_fight.png");
	end_fight_button->setPosition(Vec2(visibleSize.width*0.95, visibleSize.height*0.97));
	end_fight_button->setScale(0.5f);
	this->addChild(end_fight_button, 0);
	//结束战斗对话框
	auto end_fight_dialog_bg = Sprite::create("ui/end_fight_dialog_bg.png");
	end_fight_dialog_bg->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
	end_fight_dialog_bg->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2));
	this->addChild(end_fight_dialog_bg, 3);

	// 确定结束战斗按钮
	auto end_fight_sub_button = Button::create("ui/end_fight_sub_button.png");
	end_fight_dialog_bg->addChild(end_fight_sub_button);
	end_fight_sub_button->setAnchorPoint(Vec2::ZERO);
	end_fight_sub_button->setPosition(Vec2(20, 30));
	end_fight_sub_button->addTouchEventListener([=](Ref* pSender, Widget::TouchEventType type){
		XmlTools::writePlayerData(_player);
		auto transition = TransitionSplitCols::create(2, Game::createScene());
		Director::getInstance()->pushScene(transition);
	});

	// 取消结束战斗按钮
	auto end_fight_cancel_button = Button::create("ui/end_fight_cancel_button.png");
	end_fight_dialog_bg->addChild(end_fight_cancel_button);
	end_fight_cancel_button->setAnchorPoint(Vec2::ZERO);
	end_fight_cancel_button->setPosition(Vec2(140, 30));
	end_fight_cancel_button->addTouchEventListener([=](Ref* pSender, Widget::TouchEventType type){
		end_fight_dialog_bg->setVisible(false);
	});

	end_fight_dialog_bg->setVisible(false);

	end_fight_button->addTouchEventListener([=](Ref* pSender, Widget::TouchEventType type){
		if (type == Widget::TouchEventType::ENDED){
			end_fight_dialog_bg->setVisible(true);
		}
	});

	// ⑤创建事件监听器
	auto gameListener = EventListenerTouchOneByOne::create();
	// 响应触摸事件函数
	gameListener->onTouchBegan = [](Touch* touch, Event* event){return true; };
	gameListener->onTouchEnded = [=](Touch *touch, Event *event){
		// OpenGL坐标
		Vec2 touchLocation = touch->getLocation();
		// 将触摸点坐标转换成相对的Node坐标
		Vec2 nodeLocation = this->convertToNodeSpace(touchLocation);
		// 玩家镜像反转
		if (_player->getPosition().x > nodeLocation.x) {
			if (_player->isFlippedX() == true){
				_player->setFlippedX(false);
			}
		}
		else{
			if (_player->isFlippedX() == false)
				_player->setFlippedX(true);
		}

		// 用玩家位置作为起点,触摸点作为终点,转换为网格坐标,在地图上查找最佳到达路径
		Vec2 from = tileCoordForPosition(_player->getPosition());
		Vec2 to = tileCoordForPosition(nodeLocation);
		// 如果终点是不可通过(即有障碍物)的位置,则直接return
		int tileGid = _collidable->getTileGIDAt(to);
		if (tileGid) {
			// 使用GID来查找指定tile的属性,返回一个Value
			Value properties = _tileMap->getPropertiesForGID(tileGid);
			// 返回的Value实际是一个ValueMap
			ValueMap map = properties.asValueMap();
			// 查找ValueMap,判断是否有”可碰撞的“物体,如果有,直接返回
			std::string value = map.at("collidable").asString();
			if (value.compare("true") == 0) {
				return;
			}
		}

		/**************玩家精灵移动到指定位置************************/
		// 在玩家精灵移动过程中,如果用户在此触摸屏幕移动玩家时,如果精灵没有运行动作,直接执行移动动作
		if (_player->getNumberOfRunningActions() == 0) {
			this->playerMover(nodeLocation);
		}
		else
		{
			//如果精灵正在运行动作,先停止精灵动作和层动作,再执行移动动作
			_player->stopAllActions();
			this->stopAllActions();
			this->playerMover(nodeLocation);
		}

		// 接触传送门, 如果boss被杀死, 则传送回主场景.
		if (_player->getBoundingBox().intersectsRect(armature->getBoundingBox())){
			if (monster_1->isVisible()==false){
				_player->setExp(_player->getExp() + 200);
				_player->setGold(_player->getGold() + 1000);
				XmlTools::writePlayerData(_player);

				const string player_task = FileUtils::getInstance()->fullPathForFilename("data/kill_count.xml");
				ssize_t  player_taskFile_size;
				char* pPlayerTaskContent = (char*)FileUtils::getInstance()->getFileData(player_task, "r", &player_taskFile_size);
				TiXmlDocument* player_task_el = new TiXmlDocument();
				player_task_el->Parse(pPlayerTaskContent, 0, TIXML_ENCODING_UTF8);
				TiXmlElement* rootElement = player_task_el->RootElement();//Root
				TiXmlElement* player_kill_count_1 = rootElement->FirstChildElement();
				string accept = player_kill_count_1->GetText();
				TiXmlElement* player_kill_count_2 = player_kill_count_1->NextSiblingElement();
				stringstream ss;
				string kill_count = player_kill_count_2->GetText();
				int kill_count_int;
				ss << kill_count;
				ss >> kill_count_int;

				if (accept=="true"){
					kill_count_int += 1;
					player_kill_count_2->Clear();
					string kill_count_str;
					stringstream ss;
					ss << kill_count_int;
					ss >> kill_count_str;
					TiXmlText* kill_count_text = new TiXmlText(kill_count_str.c_str());
					player_kill_count_2->LinkEndChild(kill_count_text);
					player_task_el->SaveFile(player_task.c_str());
				}
				
				auto transform_to = TransitionSplitCols::create(2.0f, Game::createScene());
				Director::getInstance()->pushScene(transform_to);
			}
Ejemplo n.º 19
0
TEST(ValueTest, ValueMap)
{
  boost::shared_ptr<Scalar> s(new Scalar(NTA_BasicType_Int32));
  s->value.int32 = 10;
  boost::shared_ptr<Array> a(new Array(NTA_BasicType_Real32));
  boost::shared_ptr<std::string> str(new std::string("hello world"));
  
  ValueMap vm;
  vm.add("scalar", s);
  vm.add("array", a);
  vm.add("string", str);
  ASSERT_ANY_THROW(vm.add("scalar", s));

  ASSERT_TRUE(vm.contains("scalar"));
  ASSERT_TRUE(vm.contains("array"));
  ASSERT_TRUE(vm.contains("string"));
  ASSERT_TRUE(!vm.contains("foo"));
  ASSERT_TRUE(!vm.contains("scalar2"));
  ASSERT_TRUE(!vm.contains("xscalar"));
  
  boost::shared_ptr<Scalar> s1 = vm.getScalar("scalar");
  ASSERT_TRUE(s1 == s);
  
  boost::shared_ptr<Array> a1 = vm.getArray("array");
  ASSERT_TRUE(a1 == a);
  
  boost::shared_ptr<Scalar> def(new Scalar(NTA_BasicType_Int32));
  Int32 x = vm.getScalarT("scalar", (Int32)20);
  ASSERT_EQ((Int32)10, x);
  
  x = vm.getScalarT("scalar2", (Int32)20);
  ASSERT_EQ((Int32)20, x);

  Value v = vm.getValue("array");
  ASSERT_EQ(Value::arrayCategory, v.getCategory());
  ASSERT_TRUE(v.getArray() == a);
}
Ejemplo n.º 20
0
  LLVMValueRef CloneInstruction(LLVMValueRef Src, LLVMBuilderRef Builder) {
    check_value_kind(Src, LLVMInstructionValueKind);
    if (!LLVMIsAInstruction(Src))
      report_fatal_error("Expected an instruction");

    const char *Name = LLVMGetValueName(Src);

    // Check if this is something we already computed.
    {
      auto i = VMap.find(Src);
      if (i != VMap.end()) {
        // If we have a hit, it means we already generated the instruction
        // as a dependancy to somethign else. We need to make sure
        // it is ordered properly.
        auto I = i->second;
        LLVMInstructionRemoveFromParent(I);
        LLVMInsertIntoBuilderWithName(Builder, I, Name);
        return I;
      }
    }

    // We tried everything, it must be an instruction
    // that hasn't been generated already.
    LLVMValueRef Dst = nullptr;

    LLVMOpcode Op = LLVMGetInstructionOpcode(Src);
    switch(Op) {
      case LLVMRet: {
        int OpCount = LLVMGetNumOperands(Src);
        if (OpCount == 0)
          Dst = LLVMBuildRetVoid(Builder);
        else
          Dst = LLVMBuildRet(Builder, CloneValue(LLVMGetOperand(Src, 0)));
        break;
      }
      case LLVMBr: {
        if (!LLVMIsConditional(Src)) {
          LLVMValueRef SrcOp = LLVMGetOperand(Src, 0);
          LLVMBasicBlockRef SrcBB = LLVMValueAsBasicBlock(SrcOp);
          Dst = LLVMBuildBr(Builder, DeclareBB(SrcBB));
          break;
        }

        LLVMValueRef Cond = LLVMGetCondition(Src);
        LLVMValueRef Else = LLVMGetOperand(Src, 1);
        LLVMBasicBlockRef ElseBB = DeclareBB(LLVMValueAsBasicBlock(Else));
        LLVMValueRef Then = LLVMGetOperand(Src, 2);
        LLVMBasicBlockRef ThenBB = DeclareBB(LLVMValueAsBasicBlock(Then));
        Dst = LLVMBuildCondBr(Builder, Cond, ThenBB, ElseBB);
        break;
      }
      case LLVMSwitch:
      case LLVMIndirectBr:
        break;
      case LLVMInvoke: {
        SmallVector<LLVMValueRef, 8> Args;
        int ArgCount = LLVMGetNumArgOperands(Src);
        for (int i = 0; i < ArgCount; i++)
          Args.push_back(CloneValue(LLVMGetOperand(Src, i)));
        LLVMValueRef Fn = CloneValue(LLVMGetCalledValue(Src));
        LLVMBasicBlockRef Then = DeclareBB(LLVMGetNormalDest(Src));
        LLVMBasicBlockRef Unwind = DeclareBB(LLVMGetUnwindDest(Src));
        Dst = LLVMBuildInvoke(Builder, Fn, Args.data(), ArgCount,
                              Then, Unwind, Name);
        break;
      }
      case LLVMUnreachable:
        Dst = LLVMBuildUnreachable(Builder);
        break;
      case LLVMAdd: {
        LLVMValueRef LHS = CloneValue(LLVMGetOperand(Src, 0));
        LLVMValueRef RHS = CloneValue(LLVMGetOperand(Src, 1));
        Dst = LLVMBuildAdd(Builder, LHS, RHS, Name);
        break;
      }
      case LLVMSub: {
        LLVMValueRef LHS = CloneValue(LLVMGetOperand(Src, 0));
        LLVMValueRef RHS = CloneValue(LLVMGetOperand(Src, 1));
        Dst = LLVMBuildSub(Builder, LHS, RHS, Name);
        break;
      }
      case LLVMMul: {
        LLVMValueRef LHS = CloneValue(LLVMGetOperand(Src, 0));
        LLVMValueRef RHS = CloneValue(LLVMGetOperand(Src, 1));
        Dst = LLVMBuildMul(Builder, LHS, RHS, Name);
        break;
      }
      case LLVMUDiv: {
        LLVMValueRef LHS = CloneValue(LLVMGetOperand(Src, 0));
        LLVMValueRef RHS = CloneValue(LLVMGetOperand(Src, 1));
        Dst = LLVMBuildUDiv(Builder, LHS, RHS, Name);
        break;
      }
      case LLVMSDiv: {
        LLVMValueRef LHS = CloneValue(LLVMGetOperand(Src, 0));
        LLVMValueRef RHS = CloneValue(LLVMGetOperand(Src, 1));
        Dst = LLVMBuildSDiv(Builder, LHS, RHS, Name);
        break;
      }
      case LLVMURem: {
        LLVMValueRef LHS = CloneValue(LLVMGetOperand(Src, 0));
        LLVMValueRef RHS = CloneValue(LLVMGetOperand(Src, 1));
        Dst = LLVMBuildURem(Builder, LHS, RHS, Name);
        break;
      }
      case LLVMSRem: {
        LLVMValueRef LHS = CloneValue(LLVMGetOperand(Src, 0));
        LLVMValueRef RHS = CloneValue(LLVMGetOperand(Src, 1));
        Dst = LLVMBuildSRem(Builder, LHS, RHS, Name);
        break;
      }
      case LLVMShl: {
        LLVMValueRef LHS = CloneValue(LLVMGetOperand(Src, 0));
        LLVMValueRef RHS = CloneValue(LLVMGetOperand(Src, 1));
        Dst = LLVMBuildShl(Builder, LHS, RHS, Name);
        break;
      }
      case LLVMLShr: {
        LLVMValueRef LHS = CloneValue(LLVMGetOperand(Src, 0));
        LLVMValueRef RHS = CloneValue(LLVMGetOperand(Src, 1));
        Dst = LLVMBuildLShr(Builder, LHS, RHS, Name);
        break;
      }
      case LLVMAShr: {
        LLVMValueRef LHS = CloneValue(LLVMGetOperand(Src, 0));
        LLVMValueRef RHS = CloneValue(LLVMGetOperand(Src, 1));
        Dst = LLVMBuildAShr(Builder, LHS, RHS, Name);
        break;
      }
      case LLVMAnd: {
        LLVMValueRef LHS = CloneValue(LLVMGetOperand(Src, 0));
        LLVMValueRef RHS = CloneValue(LLVMGetOperand(Src, 1));
        Dst = LLVMBuildAnd(Builder, LHS, RHS, Name);
        break;
      }
      case LLVMOr: {
        LLVMValueRef LHS = CloneValue(LLVMGetOperand(Src, 0));
        LLVMValueRef RHS = CloneValue(LLVMGetOperand(Src, 1));
        Dst = LLVMBuildOr(Builder, LHS, RHS, Name);
        break;
      }
      case LLVMXor: {
        LLVMValueRef LHS = CloneValue(LLVMGetOperand(Src, 0));
        LLVMValueRef RHS = CloneValue(LLVMGetOperand(Src, 1));
        Dst = LLVMBuildXor(Builder, LHS, RHS, Name);
        break;
      }
      case LLVMAlloca: {
        LLVMTypeRef Ty = CloneType(LLVMGetAllocatedType(Src));
        Dst = LLVMBuildAlloca(Builder, Ty, Name);
        break;
      }
      case LLVMLoad: {
        LLVMValueRef Ptr = CloneValue(LLVMGetOperand(Src, 0));
        Dst = LLVMBuildLoad(Builder, Ptr, Name);
        LLVMSetAlignment(Dst, LLVMGetAlignment(Src));
        break;
      }
      case LLVMStore: {
        LLVMValueRef Val = CloneValue(LLVMGetOperand(Src, 0));
        LLVMValueRef Ptr = CloneValue(LLVMGetOperand(Src, 1));
        Dst = LLVMBuildStore(Builder, Val, Ptr);
        LLVMSetAlignment(Dst, LLVMGetAlignment(Src));
        break;
      }
      case LLVMGetElementPtr: {
        LLVMValueRef Ptr = CloneValue(LLVMGetOperand(Src, 0));
        SmallVector<LLVMValueRef, 8> Idx;
        int NumIdx = LLVMGetNumIndices(Src);
        for (int i = 1; i <= NumIdx; i++)
          Idx.push_back(CloneValue(LLVMGetOperand(Src, i)));
        if (LLVMIsInBounds(Src))
          Dst = LLVMBuildInBoundsGEP(Builder, Ptr, Idx.data(), NumIdx, Name);
        else
          Dst = LLVMBuildGEP(Builder, Ptr, Idx.data(), NumIdx, Name);
        break;
      }
      case LLVMAtomicCmpXchg: {
        LLVMValueRef Ptr = CloneValue(LLVMGetOperand(Src, 0));
        LLVMValueRef Cmp = CloneValue(LLVMGetOperand(Src, 1));
        LLVMValueRef New = CloneValue(LLVMGetOperand(Src, 2));
        LLVMAtomicOrdering Succ = LLVMGetCmpXchgSuccessOrdering(Src);
        LLVMAtomicOrdering Fail = LLVMGetCmpXchgFailureOrdering(Src);
        LLVMBool SingleThread = LLVMIsAtomicSingleThread(Src);

        Dst = LLVMBuildAtomicCmpXchg(Builder, Ptr, Cmp, New, Succ, Fail,
                                     SingleThread);
      } break;
      case LLVMBitCast: {
        LLVMValueRef V = CloneValue(LLVMGetOperand(Src, 0));
        Dst = LLVMBuildBitCast(Builder, V, CloneType(Src), Name);
        break;
      }
      case LLVMICmp: {
        LLVMIntPredicate Pred = LLVMGetICmpPredicate(Src);
        LLVMValueRef LHS = CloneValue(LLVMGetOperand(Src, 0));
        LLVMValueRef RHS = CloneValue(LLVMGetOperand(Src, 1));
        Dst = LLVMBuildICmp(Builder, Pred, LHS, RHS, Name);
        break;
      }
      case LLVMPHI: {
        // We need to agressively set things here because of loops.
        VMap[Src] = Dst = LLVMBuildPhi(Builder, CloneType(Src), Name);

        SmallVector<LLVMValueRef, 8> Values;
        SmallVector<LLVMBasicBlockRef, 8> Blocks;

        unsigned IncomingCount = LLVMCountIncoming(Src);
        for (unsigned i = 0; i < IncomingCount; ++i) {
          Blocks.push_back(DeclareBB(LLVMGetIncomingBlock(Src, i)));
          Values.push_back(CloneValue(LLVMGetIncomingValue(Src, i)));
        }

        LLVMAddIncoming(Dst, Values.data(), Blocks.data(), IncomingCount);
        return Dst;
      }
      case LLVMCall: {
        SmallVector<LLVMValueRef, 8> Args;
        int ArgCount = LLVMGetNumArgOperands(Src);
        for (int i = 0; i < ArgCount; i++)
          Args.push_back(CloneValue(LLVMGetOperand(Src, i)));
        LLVMValueRef Fn = CloneValue(LLVMGetCalledValue(Src));
        Dst = LLVMBuildCall(Builder, Fn, Args.data(), ArgCount, Name);
        LLVMSetTailCall(Dst, LLVMIsTailCall(Src));
        break;
      }
      case LLVMResume: {
        Dst = LLVMBuildResume(Builder, CloneValue(LLVMGetOperand(Src, 0)));
        break;
      }
      case LLVMLandingPad: {
        // The landing pad API is a bit screwed up for historical reasons.
        Dst = LLVMBuildLandingPad(Builder, CloneType(Src), nullptr, 0, Name);
        unsigned NumClauses = LLVMGetNumClauses(Src);
        for (unsigned i = 0; i < NumClauses; ++i)
          LLVMAddClause(Dst, CloneValue(LLVMGetClause(Src, i)));
        LLVMSetCleanup(Dst, LLVMIsCleanup(Src));
        break;
      }
      case LLVMExtractValue: {
        LLVMValueRef Agg = CloneValue(LLVMGetOperand(Src, 0));
        if (LLVMGetNumIndices(Src) != 1)
          report_fatal_error("Expected only one indice");
        auto I = LLVMGetIndices(Src)[0];
        Dst = LLVMBuildExtractValue(Builder, Agg, I, Name);
        break;
      }
      case LLVMInsertValue: {
        LLVMValueRef Agg = CloneValue(LLVMGetOperand(Src, 0));
        LLVMValueRef V = CloneValue(LLVMGetOperand(Src, 1));
        if (LLVMGetNumIndices(Src) != 1)
          report_fatal_error("Expected only one indice");
        auto I = LLVMGetIndices(Src)[0];
        Dst = LLVMBuildInsertValue(Builder, Agg, V, I, Name);
        break;
      }
      default:
        break;
    }

    if (Dst == nullptr) {
      fprintf(stderr, "%d is not a supported opcode\n", Op);
      exit(-1);
    }

    check_value_kind(Dst, LLVMInstructionValueKind);
    return VMap[Src] = Dst;
  }
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();
}
Ejemplo n.º 22
0
void ValueTest::RunTests()
{
  // scalar
  {
    boost::shared_ptr<Scalar>  s(new Scalar(NTA_BasicType_Int32));
    s->value.int32 = 10;
    Value v(s);
    TEST(v.isScalar());
    TEST(! v.isString());
    TEST(! v.isArray());
    TESTEQUAL(Value::scalarCategory, v.getCategory());
    TESTEQUAL(NTA_BasicType_Int32, v.getType());
      
    boost::shared_ptr<Scalar> s1 = v.getScalar();
    TEST(s1 == s);
      
    SHOULDFAIL(v.getArray());
    SHOULDFAIL(v.getString());
      
    TESTEQUAL("Scalar of type Int32", v.getDescription());
      
    
    Int32 x = v.getScalarT<Int32>();
    TESTEQUAL(10, x);
    
    SHOULDFAIL(v.getScalarT<UInt32>());

  }

  // array
  {
    boost::shared_ptr<Array>  s(new Array(NTA_BasicType_Int32));
    s->allocateBuffer(10);
    Value v(s);
    TEST(v.isArray());
    TEST(! v.isString());
    TEST(! v.isScalar());
    TESTEQUAL(Value::arrayCategory, v.getCategory());
    TESTEQUAL(NTA_BasicType_Int32, v.getType());
      
    boost::shared_ptr<Array> s1 = v.getArray();
    TEST(s1 == s);
      
    SHOULDFAIL(v.getScalar());
    SHOULDFAIL(v.getString());
    SHOULDFAIL(v.getScalarT<Int32>());

    TESTEQUAL("Array of type Int32", v.getDescription());
  }

  // string
  {
    boost::shared_ptr<std::string> s(new std::string("hello world"));
    Value v(s);
    TEST(! v.isArray());
    TEST(v.isString());
    TEST(! v.isScalar());
    TESTEQUAL(Value::stringCategory, v.getCategory());
    TESTEQUAL(NTA_BasicType_Byte, v.getType());
      
    boost::shared_ptr<std::string> s1 = v.getString();
    TESTEQUAL("hello world", s1->c_str());
      
    SHOULDFAIL(v.getScalar());
    SHOULDFAIL(v.getArray());
    SHOULDFAIL(v.getScalarT<Int32>());
      
    TESTEQUAL("string (hello world)", v.getDescription());
  }

  // ValueMap
  {
    boost::shared_ptr<Scalar> s(new Scalar(NTA_BasicType_Int32));
    s->value.int32 = 10;
    boost::shared_ptr<Array> a(new Array(NTA_BasicType_Real32));
    boost::shared_ptr<std::string> str(new std::string("hello world"));
    
    ValueMap vm;
    vm.add("scalar", s);
    vm.add("array", a);
    vm.add("string", str);
    SHOULDFAIL(vm.add("scalar", s));

    TEST(vm.contains("scalar"));
    TEST(vm.contains("array"));
    TEST(vm.contains("string"));
    TEST(!vm.contains("foo"));
    TEST(!vm.contains("scalar2"));
    TEST(!vm.contains("xscalar"));
    
    boost::shared_ptr<Scalar> s1 = vm.getScalar("scalar");
    TEST(s1 == s);
    
    boost::shared_ptr<Array> a1 = vm.getArray("array");
    TEST(a1 == a);
    
    boost::shared_ptr<Scalar> def(new Scalar(NTA_BasicType_Int32));
    Int32 x = vm.getScalarT("scalar", (Int32)20);
    TESTEQUAL((Int32)10, x);
    
    x = vm.getScalarT("scalar2", (Int32)20);
    TESTEQUAL((Int32)20, x);

    Value v = vm.getValue("array");
    TESTEQUAL(Value::arrayCategory, v.getCategory());
    TEST(v.getArray() == a);
  }
}
Ejemplo n.º 23
0
bool
MapObject::construct(JSContext* cx, unsigned argc, Value* vp)
{
    CallArgs args = CallArgsFromVp(argc, vp);

    if (!ThrowIfNotConstructing(cx, args, "Map"))
        return false;

    Rooted<MapObject*> obj(cx, MapObject::create(cx));
    if (!obj)
        return false;

    if (!args.get(0).isNullOrUndefined()) {
        RootedValue adderVal(cx);
        if (!GetProperty(cx, obj, obj, cx->names().set, &adderVal))
            return false;

        if (!IsCallable(adderVal))
            return ReportIsNotFunction(cx, adderVal);

        bool isOriginalAdder = IsNativeFunction(adderVal, MapObject::set);
        RootedValue mapVal(cx, ObjectValue(*obj));
        FastInvokeGuard fig(cx, adderVal);
        InvokeArgs& args2 = fig.args();

        ForOfIterator iter(cx);
        if (!iter.init(args[0]))
            return false;
        RootedValue pairVal(cx);
        RootedObject pairObj(cx);
        Rooted<HashableValue> hkey(cx);
        ValueMap* map = obj->getData();
        while (true) {
            bool done;
            if (!iter.next(&pairVal, &done))
                return false;
            if (done)
                break;
            if (!pairVal.isObject()) {
                JS_ReportErrorNumber(cx, GetErrorMessage, nullptr,
                                     JSMSG_INVALID_MAP_ITERABLE, "Map");
                return false;
            }

            pairObj = &pairVal.toObject();
            if (!pairObj)
                return false;

            RootedValue key(cx);
            if (!GetElement(cx, pairObj, pairObj, 0, &key))
                return false;

            RootedValue val(cx);
            if (!GetElement(cx, pairObj, pairObj, 1, &val))
                return false;

            if (isOriginalAdder) {
                if (!hkey.setValue(cx, key))
                    return false;

                RelocatableValue rval(val);
                if (!map->put(hkey, rval)) {
                    ReportOutOfMemory(cx);
                    return false;
                }
                WriteBarrierPost(cx->runtime(), map, key);
            } else {
                if (!args2.init(2))
                    return false;

                args2.setCallee(adderVal);
                args2.setThis(mapVal);
                args2[0].set(key);
                args2[1].set(val);

                if (!fig.invoke(cx))
                    return false;
            }
        }
    }

    args.rval().setObject(*obj);
    return true;
}
Ejemplo n.º 24
0
void Face::initFaceForKey(std::string key, __Array* faceStates) {
    // load file plist
    auto frameCache = SpriteFrameCache::getInstance();
    char plistFile[200];
    sprintf(plistFile, "%s.plist", key.data());
    frameCache->addSpriteFramesWithFile(plistFile);
    
    // load animation
    auto animationCache = AnimationCache::getInstance();
    char animationFile[200];
    std::string firstSpriteFrameName = "";
    sprintf(animationFile, "ani-%s.plist", key.data());
    std::string path = FileUtils::getInstance()->fullPathForFilename(animationFile);
    ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(path);
    ValueVector animations = dict.at("Animations").asValueVector();
    __Array* animationNames = __Array::create();
    
    for (int i = 0; i < animations.size(); i++) {
        ValueMap animationDict = animations.at(i).asValueMap();
        ValueVector frames = animationDict.at("Frames").asValueVector();
        ValueMap properties = animationDict.at("Properties").asValueMap();
        std::string name = properties.at("Animation").asString();
        animationNames->addObject(__String::create(name.data()));
        float delayPerUnit = 1 / properties.at("FPS").asFloat();
        Animation* animation = NULL;
        
        if (frames.empty()) {
            continue;
        }
        
        ssize_t frameSize = frames.size();
        Vector<AnimationFrame*> animationFrames(frameSize);
        
        for (auto& frame : frames) {
            ValueMap frameValueMap = frame.asValueMap();
            std::string frameString = frameValueMap.at("FrameName").asString();
            if (firstSpriteFrameName == "") {
                firstSpriteFrameName = frameString;
            }
            float duration = frameValueMap.at("Duration").asFloat();
            SpriteFrame* spriteFrame = frameCache->getSpriteFrameByName(frameString);
            
            if (!spriteFrame) {
                continue;
            }
            
            AnimationFrame* animFrame = AnimationFrame::create(spriteFrame, duration, ValueMap());
            animationFrames.pushBack(animFrame);
        }
        
        if (frames.empty()) {
            assert(NULL);
            continue;
        } else if (frames.size() != frameSize) {
            assert(NULL);
        }
        
        animation = Animation::create(animationFrames, delayPerUnit);
        animationCache->addAnimation(animation, name);
    }
    
    this->initWithSpriteFrameName(firstSpriteFrameName);
    this->getTexture()->setAliasTexParameters();
    
    for (int i = 0; i < animationNames->count(); i++) {
        __String* animationName = (__String*) animationNames->getObjectAtIndex(i);
        std::string animationNameStr = animationName->getCString();
        for (int j = 0; j < faceStates->count(); j++) {
            FaceState* state = (FaceState*) faceStates->getObjectAtIndex(j);
            std::string stateString = state->getStateName();
            if (animationNameStr.find(stateString) != std::string::npos) {
                auto animation = animationCache->getAnimation(animationNameStr);
                auto animate = Animate::create(animation);
                if (state->isLoop()) {
                    Action* action = RepeatForever::create(animate);
                    this->registerState(stateString, action);
                } else {
                    Action* action = (Action*) animate;
                    this->registerState(stateString, action);
                }
                break;
            }
        }
    }
}
Ejemplo n.º 25
0
//
// 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);
}
Ejemplo n.º 26
0
void MapTerrainParser:: startElement(void *ctx, const char *name, const char **atts)
{
    CC_UNUSED_PARAM(ctx);
    
    string elementName(name);
    ValueMap attributeDict;
    if (atts && atts[0])
    {
        for(int i = 0; atts[i]; i += 2)
        {
            std::string key = (char*)atts[i];
            std::string value = (char*)atts[i+1];
            attributeDict.insert(std::make_pair(key, Value(value)));
        }
    }
    
    if (elementName == "map") {
        
        _layerTerrainInfo.clear();
        
    } else if (elementName == "tileset") {
        
        // create a new LayerTerrainInfo object.
        if (_terraininfo != nullptr)
            CC_SAFE_RELEASE_NULL(_terraininfo);
        
        
        _terraininfo = LayerTerrainInfo::create();
        CC_SAFE_RETAIN(_terraininfo);
        _terraininfo->setName(attributeDict["name"].asString());
        
        
    } else if (elementName == "terraintypes") {
        
        // <terraintypes> tag start
        _terraintypes = {};
        
    } else if (elementName == "terrain") {
        // get terrain types of current tile set in order
        _terraintypes.push_back(attributeDict["name"]);
        
    } else if (elementName == "tile") {
 
        std::vector<string> data;
        split(attributeDict["terrain"].asString(), ",", data);
        Value value;
        
        // entire tile have only one terrain type
        for (int i =0; i<data.size(); i++)
        {
            if (!data[i].empty()) {
                value = data[i];
                break;
            }
        }
        
        auto tileTerrain = LayerTerrainInfo::TileTerrain::create(attributeDict["id"].asInt(), value);
        //
        _tileTerrainInfo.pushBack(tileTerrain);
    }
}
Ejemplo n.º 27
0
void SpriteFrameCache::addSpriteFramesWithDictionary(ValueMap& dictionary, Texture2D* texture)
{
    /*
    Supported Zwoptex Formats:

    ZWTCoordinatesFormatOptionXMLLegacy = 0, // Flash Version
    ZWTCoordinatesFormatOptionXML1_0 = 1, // Desktop Version 0.0 - 0.4b
    ZWTCoordinatesFormatOptionXML1_1 = 2, // Desktop Version 1.0.0 - 1.0.1
    ZWTCoordinatesFormatOptionXML1_2 = 3, // Desktop Version 1.0.2+
    */


    ValueMap& framesDict = dictionary["frames"].asValueMap();
    int format = 0;

    // get the format
    if (dictionary.find("metadata") != dictionary.end())
    {
        ValueMap& metadataDict = dictionary["metadata"].asValueMap();
        format = metadataDict["format"].asInt();
    }

    // check the format
    CCASSERT(format >=0 && format <= 3, "format is not supported for SpriteFrameCache addSpriteFramesWithDictionary:textureFilename:");

    for (auto iter = framesDict.begin(); iter != framesDict.end(); ++iter)
    {
        ValueMap& frameDict = iter->second.asValueMap();
        std::string spriteFrameName = iter->first;
        SpriteFrame* spriteFrame = _spriteFrames.at(spriteFrameName);
        if (spriteFrame)
        {
            continue;
        }

        if(format == 0)
        {
            float x = frameDict["x"].asFloat();
            float y = frameDict["y"].asFloat();
            float w = frameDict["width"].asFloat();
            float h = frameDict["height"].asFloat();
            float ox = frameDict["offsetX"].asFloat();
            float oy = frameDict["offsetY"].asFloat();
            int ow = frameDict["originalWidth"].asInt();
            int oh = frameDict["originalHeight"].asInt();
            // check ow/oh
            if(!ow || !oh)
            {
                CCLOGWARN("cocos2d: WARNING: originalWidth/Height not found on the SpriteFrame. AnchorPoint won't work as expected. Regenrate the .plist");
            }
            // abs ow/oh
            ow = abs(ow);
            oh = abs(oh);
            // create frame
            spriteFrame = SpriteFrame::createWithTexture(texture,
                          Rect(x, y, w, h),
                          false,
                          Vec2(ox, oy),
                          Size((float)ow, (float)oh)
                                                        );
        }
        else if(format == 1 || format == 2)
        {
            Rect frame = RectFromString(frameDict["frame"].asString());
            bool rotated = false;

            // rotation
            if (format == 2)
            {
                rotated = frameDict["rotated"].asBool();
            }

            Vec2 offset = PointFromString(frameDict["offset"].asString());
            Size sourceSize = SizeFromString(frameDict["sourceSize"].asString());

            // create frame
            spriteFrame = SpriteFrame::createWithTexture(texture,
                          frame,
                          rotated,
                          offset,
                          sourceSize
                                                        );
        }
        else if (format == 3)
        {
            // get values
            Size spriteSize = SizeFromString(frameDict["spriteSize"].asString());
            Vec2 spriteOffset = PointFromString(frameDict["spriteOffset"].asString());
            Size spriteSourceSize = SizeFromString(frameDict["spriteSourceSize"].asString());
            Rect textureRect = RectFromString(frameDict["textureRect"].asString());
            bool textureRotated = frameDict["textureRotated"].asBool();

            // get aliases
            ValueVector& aliases = frameDict["aliases"].asValueVector();

            for(const auto &value : aliases) {
                std::string oneAlias = value.asString();
                if (_spriteFramesAliases.find(oneAlias) != _spriteFramesAliases.end())
                {
                    CCLOGWARN("cocos2d: WARNING: an alias with name %s already exists", oneAlias.c_str());
                }

                _spriteFramesAliases[oneAlias] = Value(spriteFrameName);
            }

            // create frame
            spriteFrame = SpriteFrame::createWithTexture(texture,
                          Rect(textureRect.origin.x, textureRect.origin.y, spriteSize.width, spriteSize.height),
                          textureRotated,
                          spriteOffset,
                          spriteSourceSize);
        }

        // add sprite frame
        _spriteFrames.insert(spriteFrameName, spriteFrame);
    }
}
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 = 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;
    }
}
Ejemplo n.º 29
0
void SpriteFrameCache::addSpriteFramesWithFile(const std::string& plist)
{
    CCASSERT(plist.size()>0, "plist filename should not be nullptr");
    
    std::string fullPath = FileUtils::getInstance()->fullPathForFilename(plist);
    if (fullPath.size() == 0)
    {
        // return if plist file doesn't exist
        CCLOG("cocos2d: SpriteFrameCache: can not find %s", plist.c_str());
        return;
    }

    if (_loadedFileNames->find(plist) == _loadedFileNames->end())
    {
		std::string::size_type pos = plist.find(".md");
		if (pos != std::string::npos) {
			Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(plist);

			if (texture)
			{
				auto module = TextureManager::getInstance()->getModule(plist);
				auto name = plist.substr(0, pos);
				for (int i = 0; i < module->getModuleCount(); ++i) {
					auto rect = module->getModuleRect(i);
					auto spriteFrame = SpriteFrame::createWithTexture(texture,
						rect,
						false,
						Vec2::ZERO,
						rect.size
						);
					_spriteFrames.insert(module->getModuleName(i), spriteFrame);
				}

				_loadedFileNames->insert(plist);
			}
			else
			{
				CCLOG("cocos2d: SpriteFrameCache: Couldn't load texture");
			}
		} else {
			ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(fullPath);

			string texturePath("");

			if (dict.find("metadata") != dict.end())
			{
				ValueMap& metadataDict = dict["metadata"].asValueMap();
				// try to read  texture file name from meta data
				texturePath = metadataDict["textureFileName"].asString();
			}

			if (!texturePath.empty())
			{
				// build texture path relative to plist file
				texturePath = FileUtils::getInstance()->fullPathFromRelativeFile(texturePath.c_str(), plist);
			}
			else
			{
				// build texture path by replacing file extension
				texturePath = plist;

				// remove .xxx
				size_t startPos = texturePath.find_last_of("."); 
				texturePath = texturePath.erase(startPos);

				// append .png
				texturePath = texturePath.append(".png");

				CCLOG("cocos2d: SpriteFrameCache: Trying to use file %s as texture", texturePath.c_str());
			}

			Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(texturePath.c_str());

			if (texture)
			{
				addSpriteFramesWithDictionary(dict, texture);
				_loadedFileNames->insert(plist);
			}
			else
			{
				CCLOG("cocos2d: SpriteFrameCache: Couldn't load texture");
			}
		}
    }
}
Ejemplo n.º 30
0
/*
 * 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 );
            }
        }
    }
}