Esempio n. 1
0
void MenuPowers::loadPower(FileParser &infile) {
	// @ATTR power.id|integer|A power id from powers/powers.txt for this slot.
	if (infile.key == "id") {
		int id = popFirstInt(infile.val);
		if (id > 0) {
			skip_section = false;
			power_cell.back().id = static_cast<short>(id);
		}
		else {
			infile.error("MenuPowers: Power index out of bounds 1-%d, skipping power.", INT_MAX);
		}
		return;
	}

	if (power_cell.back().id <= 0) {
		skip_section = true;
		power_cell.pop_back();
		slots.pop_back();
		upgradeButtons.pop_back();
		logError("MenuPowers: There is a power without a valid id as the first attribute. IDs must be the first attribute in the power menu definition.");
	}

	if (skip_section)
		return;

	// @ATTR power.tab|integer|Tab index to place this power on, starting from 0.
	if (infile.key == "tab") power_cell.back().tab = static_cast<short>(toInt(infile.val));
	// @ATTR power.position|x (integer), y (integer)|Position of this power icon; relative to MenuPowers "pos".
	else if (infile.key == "position") power_cell.back().pos = toPoint(infile.val);

	// @ATTR power.requires_physoff|integer|Power requires Physical and Offense stat of this value.
	else if (infile.key == "requires_physoff") power_cell.back().requires_physoff = static_cast<short>(toInt(infile.val));
	// @ATTR power.requires_physdef|integer|Power requires Physical and Defense stat of this value.
	else if (infile.key == "requires_physdef") power_cell.back().requires_physdef = static_cast<short>(toInt(infile.val));
	// @ATTR power.requires_mentoff|integer|Power requires Mental and Offense stat of this value.
	else if (infile.key == "requires_mentoff") power_cell.back().requires_mentoff = static_cast<short>(toInt(infile.val));
	// @ATTR power.requires_mentdef|integer|Power requires Mental and Defense stat of this value.
	else if (infile.key == "requires_mentdef") power_cell.back().requires_mentdef = static_cast<short>(toInt(infile.val));

	// @ATTR power.requires_defense|integer|Power requires Defense stat of this value.
	else if (infile.key == "requires_defense") power_cell.back().requires_defense = static_cast<short>(toInt(infile.val));
	// @ATTR power.requires_offense|integer|Power requires Offense stat of this value.
	else if (infile.key == "requires_offense") power_cell.back().requires_offense = static_cast<short>(toInt(infile.val));
	// @ATTR power.requires_physical|integer|Power requires Physical stat of this value.
	else if (infile.key == "requires_physical") power_cell.back().requires_physical = static_cast<short>(toInt(infile.val));
	// @ATTR power.requires_mental|integer|Power requires Mental stat of this value.
	else if (infile.key == "requires_mental") power_cell.back().requires_mental = static_cast<short>(toInt(infile.val));

	// @ATTR power.requires_point|boolean|Power requires a power point to unlock.
	else if (infile.key == "requires_point") power_cell.back().requires_point = toBool(infile.val);
	// @ATTR power.requires_level|integer|Power requires at least this level for the hero.
	else if (infile.key == "requires_level") power_cell.back().requires_level = static_cast<short>(toInt(infile.val));
	// @ATTR power.requires_power|integer|Power requires another power id.
	else if (infile.key == "requires_power") power_cell.back().requires_power.push_back(static_cast<short>(toInt(infile.val)));

	// @ATTR power.visible_requires_status|string|Hide the power if we don't have this campaign status.
	else if (infile.key == "visible_requires_status") power_cell.back().visible_requires_status.push_back(infile.val);
	// @ATTR power.visible_requires_not_status|string|Hide the power if we have this campaign status.
	else if (infile.key == "visible_requires_not_status") power_cell.back().visible_requires_not.push_back(infile.val);

	// @ATTR power.upgrades|id (integer), ...|A list of upgrade power ids that this power slot can upgrade to. Each of these powers should have a matching upgrade section.
	else if (infile.key == "upgrades") {
		upgradeButtons.back() = new WidgetButton("images/menus/buttons/button_plus.png");
		std::string repeat_val = infile.nextValue();
		while (repeat_val != "") {
			power_cell.back().upgrades.push_back(static_cast<short>(toInt(repeat_val)));
			repeat_val = infile.nextValue();
		}

		if (!power_cell.back().upgrades.empty())
			power_cell.back().upgrade_level = 1;
	}

	else infile.error("MenuPowers: '%s' is not a valid key.", infile.key.c_str());
}
Esempio n. 2
0
//在interpreter中检测table是否存在
//与record交互,根据条件获取表中信息
vector<Row> APIManager::select(string tablename, vector<Conditions>& condition)
{
    int tableIndex = catalogmanager.findTable(tablename);
    vector<Row> result;
    CONDITION_TYPE conditionType;
    conditionType = condition[0].condition_type; // where clause's type
    int attributeIndex = catalogmanager.getAttriNum(catalogmanager.Vtable[tableIndex], condition[0].attribute);
    int type = catalogmanager.Vtable[tableIndex].attributes[attributeIndex].type;
    if(catalogmanager.Vtable[tableIndex].attributes[attributeIndex].indexName == "NULL") // no index
    {
        switch (conditionType)
        {
            case EQUAL:
            {
                switch (type)
                {
                    case INT:
                        result = recordmanager.select(catalogmanager.Vtable[tableIndex], condition[0].attribute, toInt(condition[0].attributeValue), EQUAL);
                        break;
                    case FLOAT:
                        result = recordmanager.select(catalogmanager.Vtable[tableIndex], condition[0].attribute, toFloat(condition[0].attributeValue), EQUAL);
                        break;
                    case CHAR:
                        result = recordmanager.select(catalogmanager.Vtable[tableIndex], condition[0].attribute, condition[0].attributeValue, EQUAL);
                        break;
                }
                break;
            }
            case NOT_EQUAL:
            {
                switch (type)
                {
                    case INT:
                        result = recordmanager.select(catalogmanager.Vtable[tableIndex], condition[0].attribute, toInt(condition[0].attributeValue), NOT_EQUAL);
                        break;
                    case FLOAT:
                        result = recordmanager.select(catalogmanager.Vtable[tableIndex], condition[0].attribute, toFloat(condition[0].attributeValue), NOT_EQUAL);
                        break;
                    case CHAR:
                        result = recordmanager.select(catalogmanager.Vtable[tableIndex], condition[0].attribute, condition[0].attributeValue, NOT_EQUAL);
                        break;
                }
                break;
            }
            case GREATER:
            {
                switch (type)
                {
                    case INT:
                        result = recordmanager.select(catalogmanager.Vtable[tableIndex], condition[0].attribute, toInt(condition[0].attributeValue), GREATER);
                        break;
                    case FLOAT:
                        result = recordmanager.select(catalogmanager.Vtable[tableIndex], condition[0].attribute, toFloat(condition[0].attributeValue), GREATER);
                        break;
                    case CHAR:
                        result = recordmanager.select(catalogmanager.Vtable[tableIndex], condition[0].attribute, condition[0].attributeValue, GREATER);
                        break;
                }
                break;
            }
            case GREATER_EQUAL:
            {
                switch (type)
                {
                    case INT:
                        result = recordmanager.select(catalogmanager.Vtable[tableIndex], condition[0].attribute, toInt(condition[0].attributeValue), GREATER_EQUAL);
                        break;
                    case FLOAT:
                        result = recordmanager.select(catalogmanager.Vtable[tableIndex], condition[0].attribute, toFloat(condition[0].attributeValue), GREATER_EQUAL);
                        break;
                    case CHAR:
                        result = recordmanager.select(catalogmanager.Vtable[tableIndex], condition[0].attribute, condition[0].attributeValue, GREATER_EQUAL);
                        break;
                }
                break;
            }
            case SMALLER:
            {
                switch (type)
                {
                    case INT:
                        result = recordmanager.select(catalogmanager.Vtable[tableIndex], condition[0].attribute, toInt(condition[0].attributeValue), SMALLER);
                        break;
                    case FLOAT:
                        result = recordmanager.select(catalogmanager.Vtable[tableIndex], condition[0].attribute, toFloat(condition[0].attributeValue), SMALLER);
                        break;
                    case CHAR:
                        result = recordmanager.select(catalogmanager.Vtable[tableIndex], condition[0].attribute, condition[0].attributeValue, SMALLER);
                        break;
                }
                break;
            }
            case SMALLER_EQUAL:
            {
                switch (type)
                {
                    case INT:
                        result = recordmanager.select(catalogmanager.Vtable[tableIndex], condition[0].attribute, toInt(condition[0].attributeValue), SMALLER_EQUAL);
                        break;
                    case FLOAT:
                        result = recordmanager.select(catalogmanager.Vtable[tableIndex], condition[0].attribute, toFloat(condition[0].attributeValue), SMALLER_EQUAL);
                        break;
                    case CHAR:
                        result = recordmanager.select(catalogmanager.Vtable[tableIndex], condition[0].attribute, condition[0].attributeValue, SMALLER_EQUAL);
                        break;
                }
                break;
            }
            case ALL:
            {
                switch (type)
                {
                    case INT:
                        result = recordmanager.select(catalogmanager.Vtable[tableIndex], condition[0].attribute, toInt(condition[0].attributeValue), ALL);
                        break;
                    case FLOAT:
                        result = recordmanager.select(catalogmanager.Vtable[tableIndex], condition[0].attribute, toFloat(condition[0].attributeValue), ALL);
                        break;
                    case CHAR:
                        result = recordmanager.select(catalogmanager.Vtable[tableIndex], condition[0].attribute, condition[0].attributeValue, ALL);
                        break;
                }
                break;
            }
        }

    }
    else // have index
    {
        switch (conditionType)
        {
            case EQUAL:
            {
                switch (type)
                {
                    case INT:
                        result.push_back(indexmanager.findEqualRecord(catalogmanager.Vtable[tableIndex].attributes[attributeIndex], format(toInt(condition[0].attributeValue)), catalogmanager.Vtable[tableIndex]));
                        break;
                    case FLOAT:
                        result.push_back(indexmanager.findEqualRecord(catalogmanager.Vtable[tableIndex].attributes[attributeIndex], format(toFloat(condition[0].attributeValue)), catalogmanager.Vtable[tableIndex]));
                        break;
                    case CHAR:
                        result.push_back(indexmanager.findEqualRecord(catalogmanager.Vtable[tableIndex].attributes[attributeIndex], condition[0].attributeValue, catalogmanager.Vtable[tableIndex]));
                        break;
                }
                break;
            }
            case NOT_EQUAL:
            {
                switch (type)
                {
                    case INT:
                        result = indexmanager.findRangeRecord(catalogmanager.Vtable[tableIndex].attributes[attributeIndex], format(toInt(condition[0].attributeValue)), catalogmanager.Vtable[tableIndex], NOT_EQUAL);
                        break;
                    case FLOAT:
                        result = indexmanager.findRangeRecord(catalogmanager.Vtable[tableIndex].attributes[attributeIndex], format(toFloat(condition[0].attributeValue)), catalogmanager.Vtable[tableIndex], NOT_EQUAL);
                        break;
                    case CHAR:
                        result = indexmanager.findRangeRecord(catalogmanager.Vtable[tableIndex].attributes[attributeIndex], condition[0].attributeValue, catalogmanager.Vtable[tableIndex], NOT_EQUAL);
                        break;
                }
                break;
            }
            case GREATER:
            {
                switch (type)
                {
                    case INT:
                        result = indexmanager.findRangeRecord(catalogmanager.Vtable[tableIndex].attributes[attributeIndex], format(toInt(condition[0].attributeValue)), catalogmanager.Vtable[tableIndex], GREATER);
                        break;
                    case FLOAT:
                        result = indexmanager.findRangeRecord(catalogmanager.Vtable[tableIndex].attributes[attributeIndex], format(toFloat(condition[0].attributeValue)), catalogmanager.Vtable[tableIndex], GREATER);
                        break;
                    case CHAR:
                        result = indexmanager.findRangeRecord(catalogmanager.Vtable[tableIndex].attributes[attributeIndex], condition[0].attributeValue, catalogmanager.Vtable[tableIndex], GREATER);
                        break;
                }
                break;
            }
            case GREATER_EQUAL:
            {
                switch (type)
                {
                    case INT:
                        result = indexmanager.findRangeRecord(catalogmanager.Vtable[tableIndex].attributes[attributeIndex], format(toInt(condition[0].attributeValue)), catalogmanager.Vtable[tableIndex], GREATER_EQUAL);
                        break;
                    case FLOAT:
                        result = indexmanager.findRangeRecord(catalogmanager.Vtable[tableIndex].attributes[attributeIndex], format(toFloat(condition[0].attributeValue)), catalogmanager.Vtable[tableIndex], GREATER_EQUAL);
                        break;
                    case CHAR:
                        result = indexmanager.findRangeRecord(catalogmanager.Vtable[tableIndex].attributes[attributeIndex], condition[0].attributeValue, catalogmanager.Vtable[tableIndex], GREATER_EQUAL);
                        break;
                }
                break;
            }
            case SMALLER:
            {
                switch (type)
                {
                    case INT:
                        result = indexmanager.findRangeRecord(catalogmanager.Vtable[tableIndex].attributes[attributeIndex], format(toInt(condition[0].attributeValue)), catalogmanager.Vtable[tableIndex], SMALLER);
                        break;
                    case FLOAT:
                        result = indexmanager.findRangeRecord(catalogmanager.Vtable[tableIndex].attributes[attributeIndex], format(toFloat(condition[0].attributeValue)), catalogmanager.Vtable[tableIndex], SMALLER);
                        break;
                    case CHAR:
                        result = indexmanager.findRangeRecord(catalogmanager.Vtable[tableIndex].attributes[attributeIndex], condition[0].attributeValue, catalogmanager.Vtable[tableIndex], SMALLER);
                        break;
                }
                break;
            }
            case SMALLER_EQUAL:
            {
                switch (type)
                {
                    case INT:
                        result = indexmanager.findRangeRecord(catalogmanager.Vtable[tableIndex].attributes[attributeIndex], format(toInt(condition[0].attributeValue)), catalogmanager.Vtable[tableIndex], SMALLER_EQUAL);
                        break;
                    case FLOAT:
                        result = indexmanager.findRangeRecord(catalogmanager.Vtable[tableIndex].attributes[attributeIndex], format(toFloat(condition[0].attributeValue)), catalogmanager.Vtable[tableIndex], SMALLER_EQUAL);
                        break;
                    case CHAR:
                        result = indexmanager.findRangeRecord(catalogmanager.Vtable[tableIndex].attributes[attributeIndex], condition[0].attributeValue, catalogmanager.Vtable[tableIndex], SMALLER_EQUAL);
                        break;
                }
                break;
            }
            case ALL:
            {
                switch (type)
                {
                    case INT:
                        result = recordmanager.select(catalogmanager.Vtable[tableIndex], condition[0].attribute, toInt(condition[0].attributeValue), ALL);
                        break;
                    case FLOAT:
                        result = recordmanager.select(catalogmanager.Vtable[tableIndex], condition[0].attribute, toFloat(condition[0].attributeValue), ALL);
                        break;
                    case CHAR:
                        result = recordmanager.select(catalogmanager.Vtable[tableIndex], condition[0].attribute, condition[0].attributeValue, ALL);
                        break;
                }
                break;
            }
        }
        

    }
    if(condition.size() > 1) // more than one condition
    {
        for(size_t i = 1; i < condition.size(); ++i)
        {
            attributeIndex = catalogmanager.getAttriNum(catalogmanager.Vtable[tableIndex], condition[i].attribute);
            type = catalogmanager.Vtable[tableIndex].attributes[attributeIndex].type;
            conditionType = condition[i].condition_type;
            switch (conditionType)
            {
                case EQUAL:
                {
                    switch (type)
                    {
                        case INT:
                            result = recordmanager.select(catalogmanager.Vtable[tableIndex], result, condition[i].attribute, toInt(condition[i].attributeValue), EQUAL);

                            break;
                        case FLOAT:
                            result = recordmanager.select(catalogmanager.Vtable[tableIndex], result, condition[i].attribute, toFloat(condition[i].attributeValue), EQUAL);
                            break;
                        case CHAR:
                            result = recordmanager.select(catalogmanager.Vtable[tableIndex], result, condition[i].attribute, condition[i].attributeValue, EQUAL);
                            break;
                    }
                    break;
                }
                case NOT_EQUAL:
                {
                    switch (type)
                    {
                        case INT:
                            result = recordmanager.select(catalogmanager.Vtable[tableIndex], result, condition[i].attribute, toInt(condition[i].attributeValue), NOT_EQUAL);
                            break;
                        case FLOAT:
                            result = recordmanager.select(catalogmanager.Vtable[tableIndex], result, condition[i].attribute, toFloat(condition[i].attributeValue), NOT_EQUAL);
                            break;
                        case CHAR:
                            result = recordmanager.select(catalogmanager.Vtable[tableIndex], result, condition[i].attribute, condition[i].attributeValue, NOT_EQUAL);
                            break;
                    }
                    break;
                }
                case GREATER:
                {
                    switch (type)
                    {
                        case INT:
                            result = recordmanager.select(catalogmanager.Vtable[tableIndex], result, condition[i].attribute, toInt(condition[i].attributeValue), GREATER);
                            break;
                        case FLOAT:
                            result = recordmanager.select(catalogmanager.Vtable[tableIndex], result, condition[i].attribute, toFloat(condition[i].attributeValue), GREATER);
                            break;
                        case CHAR:
                            result = recordmanager.select(catalogmanager.Vtable[tableIndex], result, condition[i].attribute, condition[i].attributeValue, GREATER);
                            break;
                    }
                    break;
                }
                case GREATER_EQUAL:
                {
                    switch (type)
                    {
                        case INT:
                            result = recordmanager.select(catalogmanager.Vtable[tableIndex], result, condition[i].attribute, toInt(condition[i].attributeValue), GREATER_EQUAL);
                            break;
                        case FLOAT:
                            result = recordmanager.select(catalogmanager.Vtable[tableIndex], result, condition[i].attribute, toFloat(condition[i].attributeValue), GREATER_EQUAL);
                            break;
                        case CHAR:
                            result = recordmanager.select(catalogmanager.Vtable[tableIndex], result, condition[i].attribute, condition[i].attributeValue, GREATER_EQUAL);
                            break;
                    }
                    break;
                }
                case SMALLER:
                {
                    switch (type)
                    {
                        case INT:
                            result = recordmanager.select(catalogmanager.Vtable[tableIndex], result, condition[i].attribute, toInt(condition[i].attributeValue), SMALLER);
                            break;
                        case FLOAT:
                            result = recordmanager.select(catalogmanager.Vtable[tableIndex], result, condition[i].attribute, toFloat(condition[i].attributeValue), SMALLER);
                            break;
                        case CHAR:
                            result = recordmanager.select(catalogmanager.Vtable[tableIndex], result, condition[i].attribute, condition[i].attributeValue, SMALLER);
                            break;
                    }
                    break;
                }
                case SMALLER_EQUAL:
                {
                    switch (type)
                    {
                        case INT:
                            result = recordmanager.select(catalogmanager.Vtable[tableIndex], result, condition[i].attribute, toInt(condition[i].attributeValue), SMALLER_EQUAL);
                            break;
                        case FLOAT:
                            result = recordmanager.select(catalogmanager.Vtable[tableIndex], result, condition[i].attribute, toFloat(condition[i].attributeValue), SMALLER_EQUAL);
                            break;
                        case CHAR:
                            result = recordmanager.select(catalogmanager.Vtable[tableIndex], result, condition[i].attribute, condition[i].attributeValue, SMALLER_EQUAL);
                            break;
                    }
                    break;
                }
                case ALL:
                {
                    switch (type)
                    {
                        case INT:
                            result = recordmanager.select(catalogmanager.Vtable[tableIndex],result, condition[i].attribute, toInt(condition[i].attributeValue), ALL);
                            break;
                        case FLOAT:
                            result = recordmanager.select(catalogmanager.Vtable[tableIndex], result, condition[i].attribute, toFloat(condition[i].attributeValue), ALL);
                            break;
                        case CHAR:
                            result = recordmanager.select(catalogmanager.Vtable[tableIndex], result, condition[i].attribute, condition[i].attributeValue, ALL);
                            break;
                    }
                    break;
                }
            }        }
    }
    return result;
}
Esempio n. 3
0
void DrawWidget::drawChannel(QPaintDevice &pd, Channel *ch, QPainter &p, double leftTime, double currentTime, double zoomX, double viewBottom, double zoomY, int viewType)
{
  ZoomLookup *z;
  if(viewType == DRAW_VIEW_SUMMARY) z = &ch->summaryZoomLookup;
  else z = &ch->normalZoomLookup;

  ChannelLocker channelLocker(ch);

  QColor current = ch->color;
 	QColor invert(255 - current.red(), 255 - current.green(), 255 - current.blue());
 	p.setPen(current);

 	int viewBottomOffset = toInt(viewBottom / zoomY);
  printf("viewBottomOffset=%d, %f, %f\n", viewBottomOffset, viewBottom, zoomY);
  viewBottom = double(viewBottomOffset) * zoomY;
  
  // baseX is the no. of chunks a pixel must represent.
 	double baseX = zoomX / ch->timePerChunk();

  z->setZoomLevel(baseX);
  
  double currentChunk = ch->chunkFractionAtTime(currentTime);
  double leftFrameTime = currentChunk - ((currentTime - leftTime) / ch->timePerChunk());
  
  //double leftFrameTime = leftTime / ch->timePerChunk();

 	double frameTime = leftFrameTime;
  //if(frameTime < 0.0) frameTime = 0.0;
  int n = 0;
  int baseElement = int(floor(frameTime / baseX));
  if(baseElement < 0) { n -= baseElement; baseElement = 0; }
  int lastBaseElement = int(floor(double(ch->totalChunks()) / baseX));
  
  Q3PointArray pointArray(pd.width()*2);
  //QPointArray topPoints(width()*2);
  //QPointArray bottomPoints(width()*2);
  //int pointIndex = 0;
  //int pointIndex = 0;
      
 	if (baseX > 1) { // More samples than pixels
    int theWidth = pd.width();
    //if(baseElement + theWidth > z->size()) z->setSize(baseElement + theWidth);
    if(lastBaseElement > z->size()) z->setSize(lastBaseElement);
    for(; n < theWidth && baseElement < lastBaseElement; n++, baseElement++) {
      myassert(baseElement >= 0);
      ZoomElement &ze = z->at(baseElement);
      if(!ze.isValid()) {
        if(calcZoomElement(ch, ze, baseElement, baseX)) continue;
      }
     
      if(ze.high() != 0.0f && ze.high() - ze.low() < 1.0) { //if range is closer than one semi-tone then draw a line between them
      //if(ze.noteLow > 0) {
        p.setPen(ze.color());
        //p.setPen(QPen(ze.color(), lineWidth));
        //Note: lineTo doen't draw a pixel on the last point of the line
        p.drawLine(n, pd.height() - lineTopHalfWidth - toInt(ze.high() / zoomY) + viewBottomOffset, n, pd.height() + lineBottomHalfWidth - toInt(ze.low() / zoomY) + viewBottomOffset);
        //pointArray.setPoint(pointIndex++, n, height() - lineTopHalfWidth    - toInt(ze.high / zoomY) + viewBottomOffset);
        //pointArray.setPoint(pointIndex++, n, height() + lineBottomHalfWidth - toInt(ze.low  / zoomY) + viewBottomOffset);
      }
    }
    //myassert(pointIndex <= width()*2);
    //p.setPen(ch->color);
    //p.drawLineSegments(pointArray, 0, pointIndex/2);

 	} else { // More pixels than samples
    float err = 0.0, pitch = 0.0, prevPitch = 0.0, vol;
    int intChunk = (int) floor(frameTime); // Integer version of frame time
    if(intChunk < 0) intChunk = 0;
    double stepSize = 1.0 / baseX; // So we skip some pixels
    int x = 0, y;
  
    //double start = 0 - stepSize;
    double start = (double(intChunk) - frameTime) * stepSize;
    double stop = pd.width() + (2 * stepSize);
    int squareSize = (int(sqrt(stepSize)) / 2) * 2 + 1; //make it an odd number
    int halfSquareSize = squareSize/2;
    int penX=0, penY=0;
    //topPoints.setPoint(pointIndex, toInt(start), 0);
    //bottomPoints.setPoint(pointIndex++, toInt(start), height());
    
    for (double n = start; n < stop && intChunk < (int)ch->totalChunks(); n += stepSize, intChunk++) {
      myassert(intChunk >= 0);
      //if (intChunk < 0) continue; // So we don't go off the beginning of the array
      AnalysisData *data = ch->dataAtChunk(intChunk);
      err = data->getCorrelation();
      //vol = dB2ViewVal(data->logrms(), ch->rmsCeiling, ch->rmsFloor);
      vol = dB2Normalised(data->getLogRms(), ch->rmsCeiling, ch->rmsFloor);
      //if (err >= CERTAIN_THRESHOLD) {
      
      //float val = MIN(ch->dataAtChunk(intChunk)->volumeValue, 1.0);
      if(gdata->pitchContourMode() == 0)
        //p.setPen(QPen(colorBetween(colorGroup().background(), ch->color, err*2.0-1.0), lineWidth));
        //p.setPen(QPen(colorBetween(gdata->backgroundColor(),  ch->color, err*sqrt(data->rms)*10.0), lineWidth));
        if(viewType == DRAW_VIEW_PRINT)
          p.setPen(QPen(colorBetween(QColor(255, 255, 255), ch->color, err*vol), lineWidth));
        else
          p.setPen(QPen(colorBetween(gdata->backgroundColor(), ch->color, err*vol), lineWidth));
      else
        p.setPen(QPen(ch->color, lineWidth));
      
      x = toInt(n);
      //note = (data->isValid()) ? data->note : 0.0f;
      //note = (ch->isVisibleNote(data->noteIndex)) ? data->note : 0.0f;
      pitch = (ch->isVisibleChunk(data)) ? data->getPitch() : 0.0f;
      myassert(pitch >= 0.0 && pitch <= gdata->topPitch());
      //pitch = bound(pitch, 0, gdata->topPitch());
      y = pd.height() - 1 - toInt(pitch / zoomY) + viewBottomOffset;
      //y = height() - 1 - int((note / zoomY) - (viewBottom / zoomY));
      if(pitch > 0.0f) {
        if(fabs(prevPitch - pitch) < 1.0 && n != start) { //if closer than one semi-tone from previous then draw a line between them
          //p.lineTo(x, y);
          p.drawLine(penX, penY, x, y);
          penX = x; penY = y;
        } else {
          p.drawPoint(x, y);
          //p.moveTo(x, y);
          penX = x; penY = y;
        }
        if(stepSize > 10) { //draw squares on the data points
          //p.setPen(invert);
          p.setBrush(Qt::NoBrush);
          p.drawRect(x - halfSquareSize, y - halfSquareSize, squareSize, squareSize);
          //p.setPen(QPen(current, 2));
        }
        //} else {
        //  p.moveTo(x, height()-1-int(((note-viewBottom) / zoomY)));
        //}
      }
      prevPitch = pitch;
    }
  }
}
Esempio n. 4
0
int dos_qvariant_toInt(const ::DosQVariant *vptr)
{
    auto variant = static_cast<const QVariant *>(vptr);
    return variant->toInt();
}
Esempio n. 5
0
Val Float64Impl::ToInt() const
    { return toInt(GetLayout()); }
Esempio n. 6
0
int toInt( const std::string& number )
{
  return toInt( number.c_str() );
}
std::int32_t Decimal128::toInt(RoundingMode roundMode) const {
    std::uint32_t throwAwayFlag = 0;
    return toInt(&throwAwayFlag, roundMode);
}
Esempio n. 8
0
Int
getUndoTextBuffer(TextBuffer tb)
{   long caret = -1;

    if ( tb->undo_buffer != NULL )
    {   UndoBuffer ub = tb->undo_buffer;
        UndoCell cell;

        if ( (cell = ub->current) == NULL )	/* No further undo's */
            fail;

        while(cell != NULL)
        {   DEBUG(NAME_undo, Cprintf("Undo using cell %d: ",
                                     Distance(cell, ub->buffer)));
            switch( cell->type )
            {
            case UNDO_DELETE:
            {   UndoDelete d = (UndoDelete) cell;
                string s;

                s.size = d->len;
                s.iswide = d->iswide;
                if ( d->iswide )
                    s.s_textA = d->text.A;
                else
                    s.s_textW = d->text.W;

                DEBUG(NAME_undo, Cprintf("Undo delete at %ld, len=%ld\n",
                                         d->where, d->len));
                insert_textbuffer(tb, d->where, 1, &s);
                caret = max(caret, d->where + d->len);
                break;
            }
            case UNDO_INSERT:
            {   UndoInsert i = (UndoInsert) cell;
                DEBUG(NAME_undo, Cprintf("Undo insert at %ld, len=%ld\n",
                                         i->where, i->len));
                delete_textbuffer(tb, i->where, i->len);
                caret = max(caret, i->where);
                break;
            }
            case UNDO_CHANGE:
            {   UndoChange c = (UndoChange) cell;
                string s;

                s.size = c->len;
                s.iswide = c->iswide;
                if ( c->iswide )
                    s.s_textA = c->text.A;
                else
                    s.s_textW = c->text.W;

                DEBUG(NAME_undo, Cprintf("Undo change at %ld, len=%ld\n",
                                         c->where, c->len));

                change_textbuffer(tb, c->where, &s);
                caret = max(caret, c->where + c->len);
                break;
            }
            }

            cell = cell->previous;
            if ( cell == NULL || cell->marked == TRUE )
            {   ub->current = cell;

                if ( cell == ub->checkpoint )	/* reached non-modified checkpoint */
                {   DEBUG(NAME_undo, Cprintf("Reset modified to @off\n"));
                    CmodifiedTextBuffer(tb, OFF);
                }

                changedTextBuffer(tb);
                ub->undone = TRUE;

                answer(toInt(caret));
            }
        }
    }

    fail;
}
bool SBMLModelSimulation::LoadSettings(const string& settingsFName)
{
    string fName(settingsFName);

    if(!fName.size())
    {
        Log(Logger::LOG_ERROR)<<"Empty file name for setings file";
        return false;
    }
    else
    {
        map<string, string> settings;
        map<string, string>::iterator it;
        //Read each line in the settings file
        vector<string> lines = getLinesInFile(fName);
        for(u_int i = 0; i < lines.size(); i++)
        {
            vector<string> line = splitString(lines[i], ":");
            if(line.size() == 2)
            {
                settings.insert( pair<string, string>(line[0], line[1]));
            }
            else
            {
                Log(lDebug2)<<"Empty line in settings file: "<<lines[i];
            }
        }

        Log(lDebug3)<<"Settings File =============";
        for (it = settings.begin() ; it != settings.end(); it++ )
        {
            Log(lDebug) << (*it).first << " => " << (*it).second;
        }
        Log(lDebug)<<"===========================";

        //Assign values
        it = settings.find("start");
        mSettings.start = (it != settings.end())   ? toDouble((*it).second) : 0;

        it = settings.find("duration");
        mSettings.duration = (it != settings.end())    ? toDouble((*it).second) : 0;

        it = settings.find("steps");
        mSettings.steps = (it != settings.end())       ? toInt((*it).second) : 50;

        it = settings.find("absolute");
        mSettings.absolute = (it != settings.end())    ? toDouble((*it).second) : 1.e-7;

        it = settings.find("relative");
        mSettings.relative = (it != settings.end())    ? toDouble((*it).second) : 1.e-4;

        it = settings.find("variables");
        if(it != settings.end())
        {
            vector<string> vars = splitString((*it).second, ",");
            for(u_int i = 0; i < vars.size(); i++)
            {
                mSettings.variables.push_back(trim(vars[i]));
            }
        }

        it = settings.find("amount");
        if(it != settings.end())
        {
            vector<string> vars = splitString((*it).second, ",");
            for(u_int i = 0; i < vars.size(); i++)
            {
                string rec = trim(vars[i]);
                if(rec.size())
                {
                    mSettings.amounts.push_back(rec);
                }
            }
        }

        it = settings.find("concentration");
        if(it != settings.end())
        {
            vector<string> vars = splitString((*it).second, ",");
            for(u_int i=0; i < vars.size(); i++)
            {
                string rec = trim(vars[i]);
                if(rec.size())
                {
                    mSettings.concentrations.push_back(rec);
                }
            }
        }
    }

    if(mEngine)
    {
        mEngine->setSimulateOptions(mSettings);
    }

    return true;
}
Esempio n. 10
0
long long BigInteger::getAsNumber(){
    return toInt(number);
}
Esempio n. 11
0
 Input::NamedPair makePair(ChannelType type, Action action, const QString& name) {
     auto input = Input(UserInputMapper::ACTIONS_DEVICE, toInt(action), type);
     return Input::NamedPair(input, name);
 }
Esempio n. 12
0
size_t Yield::generateGatherQuantity(const ServerItem *item) const {
  const YieldEntry &entry = _entries.find(item)->second;
  double d = entry._gatherDistribution();
  return max<size_t>(
      1, toInt(d));  // User always gets at least one item when gathering
}
Esempio n. 13
0
size_t Yield::generateInitialQuantity(const YieldEntry &entry) {
  const double raw = entry._initDistribution();
  const double withMinimum = max<double>(entry._initMin, raw);
  return toInt(withMinimum);
}
Esempio n. 14
0
QVariant QDBusDemarshaller::toVariantInternal()
{
    switch (q_dbus_message_iter_get_arg_type(&iterator)) {
    case DBUS_TYPE_BYTE:
        return QVariant::fromValue(toByte());
    case DBUS_TYPE_INT16:
	return QVariant::fromValue(toShort());
    case DBUS_TYPE_UINT16:
	return QVariant::fromValue(toUShort());
    case DBUS_TYPE_INT32:
        return toInt();
    case DBUS_TYPE_UINT32:
        return toUInt();
    case DBUS_TYPE_DOUBLE:
        return toDouble();
    case DBUS_TYPE_BOOLEAN:
        return toBool();
    case DBUS_TYPE_INT64:
        return toLongLong();
    case DBUS_TYPE_UINT64:
        return toULongLong();
    case DBUS_TYPE_STRING:
        return toStringUnchecked();
    case DBUS_TYPE_OBJECT_PATH:
        return QVariant::fromValue(toObjectPathUnchecked());
    case DBUS_TYPE_SIGNATURE:
        return QVariant::fromValue(toSignatureUnchecked());
    case DBUS_TYPE_VARIANT:
        return QVariant::fromValue(toVariant());

    case DBUS_TYPE_ARRAY:
        switch (q_dbus_message_iter_get_element_type(&iterator)) {
        case DBUS_TYPE_BYTE:
            // QByteArray
            return toByteArrayUnchecked();
        case DBUS_TYPE_STRING:
            return toStringListUnchecked();
        case DBUS_TYPE_DICT_ENTRY:
            return QVariant::fromValue(duplicate());

        default:
            return QVariant::fromValue(duplicate());
        }

    case DBUS_TYPE_STRUCT:
        return QVariant::fromValue(duplicate());

    case DBUS_TYPE_UNIX_FD:
        if (capabilities & QDBusConnection::UnixFileDescriptorPassing)
            return QVariant::fromValue(toUnixFileDescriptor());
        // fall through

    default:
//        qWarning("QDBusDemarshaller: Found unknown D-Bus type %d '%c'",
//                 q_dbus_message_iter_get_arg_type(&iterator),
//                 q_dbus_message_iter_get_arg_type(&iterator));
        char *ptr = 0;
        ptr += q_dbus_message_iter_get_arg_type(&iterator);
        q_dbus_message_iter_next(&iterator);

        // I hope you never dereference this pointer!
        return QVariant::fromValue<void *>(ptr);
    };
}
Esempio n. 15
0
void StatBlock::loadHeroStats() {
	// set the default global cooldown
	cooldown = parse_duration("66ms");

	// Redefine numbers from config file if present
	FileParser infile;
	// @CLASS StatBlock: Hero stats|Description of engine/stats.txt
	if (infile.open("engine/stats.txt")) {
		while (infile.next()) {
			int value = toInt(infile.val);

			bool valid = loadCoreStat(&infile);

			if (infile.key == "max_points_per_stat") {
				// @ATTR max_points_per_stat|int|Maximum points for each primary stat.
				max_points_per_stat = value;
			}
			else if (infile.key == "sfx_step") {
				// @ATTR sfx_step|string|An id for a set of step sound effects. See items/step_sounds.txt.
				sfx_step = infile.val;
			}
			else if (infile.key == "stat_points_per_level") {
				// @ATTR stat_points_per_level|int|The amount of stat points awarded each level.
				stat_points_per_level = value;
			}
			else if (infile.key == "power_points_per_level") {
				// @ATTR power_points_per_level|int|The amount of power points awarded each level.
				power_points_per_level = value;
			}
			else if (!valid) {
				infile.error("StatBlock: '%s' is not a valid key.", infile.key.c_str());
			}
		}
		infile.close();
	}

	if (max_points_per_stat == 0) max_points_per_stat = max_spendable_stat_points / 4 + 1;
	statsLoaded = true;

	// load the XP table
	// @CLASS StatBlock: XP table|Description of engine/xp_table.txt
	if (infile.open("engine/xp_table.txt")) {
		while(infile.next()) {
			if (infile.key == "level") {
				// @ATTR level|int, int : Level, XP|The amount of XP required for this level.
				unsigned lvl_id = popFirstInt(infile.val);
				unsigned long lvl_xp = toUnsignedLong(popFirstString(infile.val));

				if (lvl_id > xp_table.size())
					xp_table.resize(lvl_id);

				xp_table[lvl_id - 1] = lvl_xp;
			}
		}
		infile.close();
	}

	if (xp_table.empty()) {
		logError("StatBlock: No XP table defined.");
		xp_table.push_back(0);
	}

	max_spendable_stat_points = static_cast<int>(xp_table.size()) * stat_points_per_level;
}
Esempio n. 16
0
void AddPresetItemAction::processRegulations(QStandardItem *item)
{
    int remoteStationId = item->parent()->data(UserRoles::RemoteStationIdRole).toInt();
    reportPreset->addCurrentPresetContent(toInt(ObjectTypes::Regulations), remoteStationId);
}
Esempio n. 17
0
void MenuDevConsole::execute() {
    std::string command = input_box->getText();
    if (command == "") return;

    input_scrollback.push_back(command);
    input_scrollback_pos = input_scrollback.size();
    input_box->setText("");

    log_history->add(command, false, &color_echo);

    std::vector<std::string> args;
    command += ' ';

    std::string arg = popFirstString(command, ' ');
    while (arg != "") {
        args.push_back(arg);
        arg = popFirstString(command, ' ');
    }


    if (args.empty()) {
        return;
    }

    if (args[0] == "help") {
        log_history->add("teleport - " + msg->get("teleports the player to a specific tile, and optionally, a specific map"), false);
        log_history->add("unset_status - " + msg->get("unsets the given campaign statuses if they are set"), false);
        log_history->add("set_status - " + msg->get("sets the given campaign statuses"), false);
        log_history->add("give_xp - " + msg->get("rewards the player with the specified amount of experience points"), false);
        log_history->add("give_currency - " + msg->get("adds the specified amount of currency to the player's inventory"), false);
        log_history->add("give_item - " + msg->get("adds an item to the player's inventory"), false);
        log_history->add("spawn_enemy - " + msg->get("spawns an enemy matching the given category next to the player"), false);
        log_history->add("toggle_devhud - " + msg->get("turns on/off the developer hud"), false);
        log_history->add("clear - " + msg->get("clears the command history"), false);
        log_history->add("help - " + msg->get("displays this text"), false);
    }
    else if (args[0] == "clear") {
        log_history->clear();
    }
    else if (args[0] == "toggle_devhud") {
        DEV_HUD = !DEV_HUD;
        log_history->add(msg->get("Toggled the developer hud"), false);
    }
    else if (args[0] == "spawn_enemy") {
        if (args.size() > 1) {
            Enemy_Level el = enemyg->getRandomEnemy(args[1], 0, 0);
            if (el.type != "") {
                Point spawn_pos = floor(mapr->collider.get_random_neighbor(floor(pc->stats.pos), 1));
                powers->spawn(args[1], spawn_pos);
                log_history->add(msg->get("Spawning enemy from category: ") + args[1]);
            }
            else {
                log_history->add(msg->get("ERROR: Invalid enemy category"), false, &color_error);
            }
        }
        else {
            log_history->add(msg->get("ERROR: Too few arguments"), false, &color_error);
        }
    }
    else if (args[0] == "give_item") {
        if (args.size() > 1) {
            int id = toInt(args[1]);
            if (id <= 0 || (unsigned)id >= items->items.size() || items->items[id].name == "") {
                log_history->add(msg->get("ERROR: Invalid item ID"), false, &color_error);
                return;
            }

            int quantity = (args.size() > 2) ? toInt(args[2]) : 1;

            if (quantity > 0) {
                if (id == CURRENCY_ID) {
                    camp->rewardCurrency(quantity);
                }
                else {
                    ItemStack stack;
                    stack.item = id;
                    stack.quantity = quantity;
                    camp->rewardItem(stack);
                }
                log_history->add(msg->get("Added item: ") + items->items[id].name + " (" + toString(typeid(int), &quantity) + ")", false);
            }
        }
        else {
            log_history->add(msg->get("ERROR: Too few arguments"), false, &color_error);
        }
    }
    else if (args[0] == "give_currency") {
        int quantity = (args.size() > 1) ? toInt(args[1]) : 0;
        if (quantity > 0) {
            camp->rewardCurrency(quantity);
            log_history->add(msg->get("Added currency: ") + toString(typeid(int), &quantity), false);
        }
        if (args.size() < 2) {
            log_history->add(msg->get("ERROR: Too few arguments"), false, &color_error);
        }
    }
    else if (args[0] == "give_xp") {
        int quantity = (args.size() > 1) ? toInt(args[1]) : 0;
        if (quantity > 0) {
            camp->rewardXP(quantity, true);
            log_history->add(msg->get("Added XP: ") + toString(typeid(int), &quantity), false);
        }
        if (args.size() < 2) {
            log_history->add(msg->get("ERROR: Too few arguments"), false, &color_error);
        }
    }
    else if (args[0] == "set_status") {
        for (unsigned i = 1; i < args.size(); ++i) {
            camp->setStatus(args[i]);
            log_history->add(msg->get("Set campaign status: ") + args[i], false);
        }
        if (args.size() < 2) {
            log_history->add(msg->get("ERROR: Too few arguments"), false, &color_error);
        }
    }
    else if (args[0] == "unset_status") {
        for (unsigned i = 1; i < args.size(); ++i) {
            if (camp->checkStatus(args[i])) {
                camp->unsetStatus(args[i]);
                log_history->add(msg->get("Unset campaign status: ") + args[i], false);
            }
            else {
                log_history->add(msg->get("ERROR: Unknown campaign status: ") + args[i], false, &color_error);
            }
        }
        if (args.size() < 2) {
            log_history->add(msg->get("ERROR: Too few arguments"), false, &color_error);
        }
    }
    else if (args[0] == "teleport") {
        if (args.size() > 2) {
            FPoint dest;
            dest.x = toInt(args[1]) + 0.5f;
            dest.y = toInt(args[2]) + 0.5f;

            if (args.size() > 3) {
                if (fileExists(mods->locate(args[3]))) {
                    mapr->teleportation = true;
                    mapr->teleport_destination.x = dest.x;
                    mapr->teleport_destination.y = dest.y;
                    mapr->teleport_mapname = args[3];
                    log_history->add(msg->get("Teleporting to: " + args[1] + ", " + args[2] + ", " + args[3]), false);
                }
                else {
                    log_history->add(msg->get("ERROR: Unknown map: ") + args[3], false, &color_error);
                }
            }
            else {
                mapr->teleportation = true;
                mapr->teleport_destination.x = dest.x;
                mapr->teleport_destination.y = dest.y;
                log_history->add(msg->get("Teleporting to: " + args[1] + ", " + args[2]), false);
            }
        }
        else {
            log_history->add(msg->get("ERROR: Too few arguments"), false, &color_error);
        }
    }
    else {
        log_history->add(msg->get("ERROR: Unknown command"), false, &color_error);
    }
}
Esempio n. 18
0
void AddPresetItemAction::processCommand(QStandardItem *item)
{
    model::UnitItemId commandId = item->data(UserRoles::CommandIdRole).value<model::UnitItemId>();
    model::UnitItemId senderId = item->data(UserRoles::ControlObjectIdRole).value<model::UnitItemId>();
    reportPreset->addCurrentPresetContent(toInt(ObjectTypes::Command), senderId, commandId);
}
Esempio n. 19
0
TEftpState FTPServer::parseCommand(String response, String &info) {
  TEftpState newState = TEftpState_Unknown;
  auto posEnd = response.indexOf('\r');
  if (response.startsWith("USER")) {
    receivedCredentials.username =
        response.substring(String("USER ").length(), posEnd);
    info = receivedCredentials.username;
    newState = TEftpState_User;
  } else if (response.startsWith("PASS")) {
    receivedCredentials.password =
        response.substring(String("PASS ").length(), posEnd);
    if ((credentials.username == receivedCredentials.username) &&
        (credentials.password == receivedCredentials.password))
      newState = TEftpState_AuthOk;
    else
      newState = TEftpState_AuthFail;
  } else if (response.startsWith("PORT")) {
    auto lastComma = response.lastIndexOf(",");
    auto secondLastComma = response.lastIndexOf(",", lastComma - 1);
    auto hiPort = response.substring(secondLastComma + 1, lastComma);
    auto loPort = response.substring(lastComma + 1, posEnd);
    activeDataPortHi = hiPort.toInt();
    activeDataPortLo = loPort.toInt();
    newState = TEftpState_Port;
  }

  else if (response.startsWith("PWD"))
    newState = TEftpState_CurrentDir;
  else if (response.startsWith("QUIT"))
    newState = TEftpState_Quit;
  else if (response.startsWith("FEAT"))
    newState = TEftpState_Features;
  else if (response.startsWith("SYST"))
    newState = TEftpState_System;
  else if (response.startsWith("PASV"))
    newState = TEftpState_Passive;
  else if (response.startsWith("LIST"))
    newState = TEftpState_List;
  else if (response.startsWith("TYPE"))
    newState = TEftpState_Type;
  else if (response.startsWith("CDUP"))
    newState = TEftpState_ParentDir;

  else if (response.startsWith("CLIENT"))
    newState = TEftpState_Client,
    info = response.substring(String("CLIENT ").length(), posEnd);

  else if (response.startsWith("REST"))
    newState = TEftpState_RestartAt,
    info = response.substring(String("REST ").length(), posEnd);
  else if (response.startsWith("RETR"))
    newState = TEftpState_RetrieveFile,
    info = response.substring(String("RETR ").length(), posEnd);
  else if (response.startsWith("DELE"))
    newState = TEftpState_DeleteFile,
    info = response.substring(String("DELE ").length(), posEnd);
  else if (response.startsWith("STOR"))
    newState = TEftpState_Store,
    info = response.substring(String("STOR ").length(), posEnd);
  else if (response.startsWith("MKD"))
    newState = TEftpState_MakeDir,
    info = response.substring(String("MKD ").length(), posEnd);

  else if (response.startsWith("APPE"))
    newState = TEftpState_Append,
    info = response.substring(String("APPE ").length(), posEnd);
  else if (response.startsWith("CWD"))
    newState = TEftpState_ChangeDir,
    info = response.substring(String("CWD ").length(), posEnd);
  else if (response.startsWith("RNFR"))
    newState = TEftpState_RenameFrom,
    info = response.substring(String("RNFR ").length(), posEnd);
  else if (response.startsWith("RNTO"))
    newState = TEftpState_RenameTo,
    info = response.substring(String("RNTO ").length(), posEnd);

  else if (response.startsWith("RMD"))
    newState = TEftpState_DeleteDir,
    info = response.substring(String("RMD ").length(), posEnd);

  else
    info = response.substring(0, posEnd);

  if ((-1 != aliveTimer) && (response.length() > 0))
    aliveTimer = millis() + timeoutSec * 1000;
  return newState;
}
Esempio n. 20
0
//------------------------------------------------------------------------------
bool ScoreSegmentIterator::next(void)
{
  if(ch)
    {
      while(rowCounter < numRows)
	{
	  int j = rowCounter;
	  double startOfRowTime = startOfPageTime + j * totalRowTime;
	  double endOfRowTime = startOfRowTime + totalRowTime;
	  _lineCenterY = toInt(sw->_boarderY) + halfStaveHeight + staveHeight * j;
	  while(++subRowCounter < 4)
	    {
	      switch(subRowCounter)
		{
		case 1:
		  if(startOfRowTime < lookBehindTime3)
		    {
		      //draw any parts of the next page
		      _leftTime = startOfRowTime + totalPageTime;
		      _rightTime = std::min(endOfRowTime, lookBehindTime3) + totalPageTime;
		      _leftX = (double)sw->_boarderX;
		      return (_isValid = true);
		    }
		  break;
		case 2:
		  if(endOfRowTime > lookBehindTime3+lookAheadGapTime && startOfRowTime < lookAheadTime2)
		    {
		      //normal case
		      _leftTime = std::max(startOfRowTime, lookBehindTime3 + lookAheadGapTime);
		      _rightTime = std::min(startOfRowTime + totalRowTime, lookAheadTime2);
		      _leftX = (double)sw->_boarderX + (_leftTime-startOfRowTime) * sw->_scaleX;
		      return (_isValid = true);
		    }
		  break;
		case 3:
		  if(endOfRowTime - totalPageTime > lookBehindTime2 + lookAheadGapTime)
		    {
		      _leftTime = std::max(startOfRowTime - totalPageTime, lookBehindTime2 + lookAheadGapTime);
		      _leftTime = std::min(_leftTime, endOfRowTime - totalPageTime);
		      _rightTime = endOfRowTime - totalPageTime;
		      _leftX = (double)sw->_boarderX + (_leftTime -(startOfRowTime - totalPageTime)) * sw->_scaleX;
		      return (_isValid = true);
		    }
		}
	    }
	  rowCounter++;
	  subRowCounter = -1;
	}
    }
  else
    {
      while(rowCounter < numRows)
	{
	  double startOfRowTime = startOfPageTime + rowCounter*totalRowTime;
	  double endOfRowTime = startOfRowTime + totalRowTime;
	  _lineCenterY = toInt(sw->_boarderY) + halfStaveHeight + staveHeight*rowCounter;
	  _leftX = sw->_boarderX;
	  _leftTime = startOfRowTime;
	  _rightTime = endOfRowTime;
	  rowCounter++;
	  return (_isValid = true);
	}
    }
  return (_isValid = false);
}
Esempio n. 21
0
int String::toInt() const
{
  return toInt(0);
}
Esempio n. 22
0
void TileSet::load(const std::string& filename) {
	if (current_map == filename) return;

	reset();

	FileParser infile;

	// @CLASS TileSet|Description of tilesets in tilesets/
	if (infile.open(filename)) {
		while (infile.next()) {
			if (infile.key == "img") {
				// @ATTR img|string|Filename of a tile sheet image.
				loadGraphics(infile.val);
			}
			else if (infile.key == "tile") {
				// @ATTR tile|index (integer), x (integer), y (integer), w (integer), h (integer), x offset (integer), y offset (integer)|A single tile definition.

				// Verify that we have graphics for tiles
				if (!sprites) {
					std::cerr << "No graphics for tileset definition '" << filename << "', aborting." << std::endl;
					exit(0);
				}

				unsigned index = popFirstInt(infile.val);

				if (index >= tiles.size())
					tiles.resize(index + 1);

				tiles[index].tile = sprites->getGraphics()->createSprite();

				tiles[index].tile->setClipX(popFirstInt(infile.val));
				tiles[index].tile->setClipY(popFirstInt(infile.val));
				tiles[index].tile->setClipW(popFirstInt(infile.val));
				tiles[index].tile->setClipH(popFirstInt(infile.val));
				tiles[index].offset.x = popFirstInt(infile.val);
				tiles[index].offset.y = popFirstInt(infile.val);
				max_size_x = std::max(max_size_x, (tiles[index].tile->getClip().w / TILE_W) + 1);
				max_size_y = std::max(max_size_y, (tiles[index].tile->getClip().h / TILE_H) + 1);
			}
			else if (infile.key == "transparency") {
				// @ATTR transparency|r (integer), g (integer), b (integer)|An RGB color to key out and treat as transparent.
				alpha_background = false;

				trans_r = (Uint8)popFirstInt(infile.val);
				trans_g = (Uint8)popFirstInt(infile.val);
				trans_b = (Uint8)popFirstInt(infile.val);

			}
			else if (infile.key == "animation") {
				// @ATTR animation|tile index (integer), x (integer), y (integer), duration (duration), ...|An animation for a tile. Durations are in 'ms' or 's'.
				int frame = 0;
				unsigned TILE_ID = toInt(infile.nextValue());

				if (TILE_ID >= anim.size())
					anim.resize(TILE_ID + 1);

				std::string repeat_val = infile.nextValue();
				while (repeat_val != "") {
					anim[TILE_ID].frames++;
					anim[TILE_ID].pos.resize(frame + 1);
					anim[TILE_ID].frame_duration.resize(frame + 1);
					anim[TILE_ID].pos[frame].x = toInt(repeat_val);
					anim[TILE_ID].pos[frame].y = toInt(infile.nextValue());
					anim[TILE_ID].frame_duration[frame] = parse_duration(infile.nextValue());

					frame++;
					repeat_val = infile.nextValue();
				}
			}
			else {
				infile.error("TileSet: '%s' is not a valid key.", infile.key.c_str());
			}
		}
		infile.close();
	}

	current_map = filename;
}
Esempio n. 23
0
status
computeLine(Line ln)
{ if ( notNil(ln->request_compute) )
  { int x1  = valInt(ln->start_x);
    int x2  = valInt(ln->end_x);
    int y1  = valInt(ln->start_y);
    int y2  = valInt(ln->end_y);
    int pen = valInt(ln->pen);
    int x, y, w, h;
    Area a = ln->area;

    if ( x1 < x2 )
    { x = x1;
      w = x2-x1;
    } else
    { x = x2;
      w = x1-x2;
    }
    if ( y1 < y2 )
    { y = y1;
      h = y2-y1;
    } else
    { y = y2;
      h = y1-y2;
    }

    if ( pen ==	1 )
    { w++;
      h++;
    } else if ( pen > 1 )
    { int ex = (h > 0 ? (pen*h)/(w+h) : 0); /* h = 0: horizontal line */
      int ey = (w > 0 ? (pen*w)/(w+h) : 0); /* w = 0: vertical line */
      int hx = ex/2;
      int hy = ey/2;

      x -= hx;
      w += ex;
      y -= hy;
      h += ey;
    }

    if ( ln->selected == ON )	/* should be solved elsewhere */
    { x -= 3;
      y -= 3;
      w += 6;
      h += 6;
    }

    CHANGING_GRAPHICAL(ln,
		       assign(a, x, toInt(x));
		       assign(a, y, toInt(y));
		       assign(a, w, toInt(w));
		       assign(a, h, toInt(h));

		       if ( adjustFirstArrowLine(ln) )
			 unionNormalisedArea(a, ln->first_arrow->area);
		       if ( adjustSecondArrowLine(ln) )
			 unionNormalisedArea(a, ln->second_arrow->area);

		       changedEntireImageGraphical(ln));

    assign(ln, request_compute, NIL);
  }
Esempio n. 24
0
void CorrelationWidget::paintEvent( QPaintEvent * )
{
  Channel *active = gdata->getActiveChannel();

  AnalysisData *data = NULL;
  int chunk=0;
  double dh2 = double(height()-1) / 2.0;
  int j, x, y;
    
  beginDrawing(false);
    
  if(active) {
    
    active->lock();
    chunk = active->currentChunk();
    data = active->dataAtChunk(chunk);

    //int centerX = width() / 2;
    if(data) {
      double freq = data->getFundamentalFreq();
      double period = double(active->rate()) / freq;
      //double numPeriods = double(active->size()) / period;
      double scaleX = period * double(width()) / double(active->nsdfData.size()); //pixels per period
      
      //draw alternating background color indicating period
      if(gdata->view->backgroundShading() && period > 4.0 && period < double(active->nsdfData.size())) {
        int n = int(ceil(double(width()) / scaleX)); //number of colored patches
        p.setPen(Qt::NoPen);
        QColor color1 = colorBetween(gdata->backgroundColor(), gdata->shading1Color(), data->getCorrelation());
        QColor color2 = colorBetween(gdata->backgroundColor(), gdata->shading2Color(), data->getCorrelation());
        for(j = 0; j<n; j++) {
          x = toInt(scaleX*double(j));
          p.setBrush((j%2) ? color1 : color2);
          p.drawRect(x, 0, toInt(scaleX*double(j+1)) - toInt(scaleX*double(j)), height());
        }
        p.setPen(colorBetween(gdata->backgroundColor(), Qt::black, 0.3 * data->getCorrelation()));
        for(j = 0; j<n; j++) {
          x = toInt(scaleX*double(j));
          p.drawLine(x, 0, x, height());
        }
      } else {
        clearBackground();
      }
      QString numPeriodsText;
      numPeriodsText.sprintf("Period = %lf", period);
      p.setPen(Qt::black);
      p.drawText(5, height() - 8, numPeriodsText);
    } else {
      clearBackground();
    }
  } else {
    clearBackground();
  }

  //draw the horizontal center line
  p.setPen(QPen(colorBetween(colorGroup().background(), Qt::black, 0.3), 0));
  p.drawLine(0, toInt(dh2), width(), toInt(dh2));

  if(active) { 
    if(gdata->doingFreqAnalysis()) {
      int w = width() / 2; //only do every second pixel (for speed)
      //draw the waveform
      if(int(pointArray.size()) != w) pointArray.resize(w);
      if(lookup.size() != w) lookup.resize(w);

      NoteData *currentNote = active->getCurrentNote();
      Array1d<float> *input = &(active->nsdfData);
      if(currentNote) {
        if(aggregateMode == 1) input = &currentNote->nsdfAggregateData;
        else if(aggregateMode == 2) input = &currentNote->nsdfAggregateDataScaled;
      }
      //bresenham1d(*input, lookup);
      maxAbsDecimate1d(*input, lookup);
      for(int j=0; j<w; j++) {
        pointArray.setPoint(j, j*2, toInt(dh2 - lookup[j]*dh2));
      }

      p.setPen(QPen(active->color, 0));
      p.drawPolyline(pointArray);
    }
    if(data && (aggregateMode == 0)) {
      double ratio = double(width()) / double(active->nsdfData.size()); //pixels per index
      //float highest = active->nsdfData.at(data->highestCorrelationIndex);
      //float chosen = active->nsdfData.at(data->chosenCorrelationIndex);
      
      //draw a dot at all the period estimates
      p.setPen(Qt::blue);
      p.setBrush(Qt::blue);
      for(j=0; j<int(data->getPeriodEstimatesSize()); j++) {
        x = toInt(double(data->getPeriodEstimatesAt(j)) * ratio);
        y = toInt(dh2 - data->getPeriodEstimatesAmpAt(j) * dh2);
        p.drawEllipse(x-2, y-2, 5, 5);
      }
      
      if(data->getHighestCorrelationIndex() >= 0) {
        float highest = data->getPeriodEstimatesAmpAt(data->getHighestCorrelationIndex());
        //draw threshold line
        p.setPen(QPen(colorBetween(colorGroup().background(), Qt::black, 0.3), 0));
        y = toInt(dh2 - (highest * active->threshold()) * dh2);
        p.drawLine(0, y, width(), y);
      
        //draw a dot at the highest correlation period
        p.setPen(Qt::black);
        p.setBrush(Qt::black);
        //x = toInt(double(data->highestCorrelationIndex) * ratio);
        x = toInt(double(data->getPeriodEstimatesAt(data->getHighestCorrelationIndex())) * ratio);
        y = toInt(dh2 - highest * dh2);
        p.drawEllipse(x-2, y-2, 5, 5);
      }
      
      //draw a dot at the chosen correlation period
      if(data->getChosenCorrelationIndex() >= 0) {
        p.setPen(Qt::red);
        p.setBrush(Qt::red);
        //x = toInt(double(data->chosenCorrelationIndex) * ratio);
        //y = toInt(dh2 - chosen * dh2);
        x = toInt(double(data->getPeriodEstimatesAt(data->getChosenCorrelationIndex())) * ratio);
        y = toInt(dh2 - data->getPeriodEstimatesAmpAt(data->getChosenCorrelationIndex()) * dh2);
        p.drawEllipse(x-2, y-2, 5, 5);
      }

      //draw a line at the chosen correlation period
      if(data->getChosenCorrelationIndex() >= 0) {
        p.setPen(Qt::green);
        p.setBrush(Qt::green);
        //x = toInt(double(data->periodOctaveEstimate) * ratio);
        x = toInt(double(active->periodOctaveEstimate(chunk)) * ratio);
        p.drawLine(x, 0, x, height());
      }
    }
    
    active->unlock();
    
  }
  endDrawing();
}
Esempio n. 25
0
//在interpreter中检测table是否存在
//与rm交互,根据条件删除表中数据
//与im交互删除index(如果存在)
int APIManager:: deleteValue(string tablename, vector<Conditions> &condition)
{
    int total = 0;
    int tableIndex = catalogmanager.findTable(tablename);
    for(size_t i =0; i < condition.size(); ++i)
    {
        int attriNum = catalogmanager.getAttriNum(catalogmanager.Vtable[tableIndex], condition[i].attribute);
        switch (catalogmanager.Vtable[tableIndex].attributes[attriNum].type) {
            case INT:
                 total += recordmanager.deleteRow(catalogmanager.Vtable[tableIndex], condition[i].attribute, toInt(condition[i].attributeValue), condition[i].condition_type);
                break;
            case FLOAT:
                total += recordmanager.deleteRow(catalogmanager.Vtable[tableIndex], condition[i].attribute, toFloat(condition[i].attributeValue), condition[i].condition_type);
                break;
            case CHAR:
                total += recordmanager.deleteRow(catalogmanager.Vtable[tableIndex], condition[i].attribute, condition[i].attributeValue, condition[i].condition_type);
                break;
        }
    }
    for(size_t i = 0; i <  condition.size(); ++i)
    {
        int attriNum = catalogmanager.getAttriNum(catalogmanager.Vtable[tableIndex], condition[i].attribute);
        if(catalogmanager.Vtable[tableIndex].attributes[attriNum].indexName != "NULL")
        {
            switch (catalogmanager.Vtable[tableIndex].attributes[attriNum].type) {
                case INT:
                    indexmanager.afterDelete(catalogmanager.Vtable[tableIndex].attributes[attriNum], format(toInt(condition[i].attributeValue)), catalogmanager.Vtable[tableIndex]);
                    break;
                case FLOAT:
                    indexmanager.afterDelete(catalogmanager.Vtable[tableIndex].attributes[attriNum], format(toFloat(condition[i].attributeValue)), catalogmanager.Vtable[tableIndex]);
                    break;
                case CHAR:
                    indexmanager.afterDelete(catalogmanager.Vtable[tableIndex].attributes[attriNum], condition[i].attributeValue, catalogmanager.Vtable[tableIndex]);
                    break;
            }
        }
    }
    return total;
}
Esempio n. 26
0
bool StatBlock::loadCoreStat(FileParser *infile) {
	// @CLASS StatBlock: Core stats|Description of engine/stats.txt and enemies in enemies/

	if (infile->key == "speed") {
		// @ATTR speed|float|Movement speed
		float fvalue = toFloat(infile->val, 0);
		speed = speed_default = fvalue / MAX_FRAMES_PER_SEC;
		return true;
	}
	else if (infile->key == "cooldown") {
		// @ATTR cooldown|int|Cooldown between attacks in 'ms' or 's'.
		cooldown = parse_duration(infile->val);
		return true;
	}
	else if (infile->key == "cooldown_hit") {
		// @ATTR cooldown_hit|duration|Duration of cooldown after being hit in 'ms' or 's'.
		cooldown_hit = parse_duration(infile->val);
		return true;
	}
	else if (infile->key == "stat") {
		// @ATTR stat|string, int : Stat name, Value|The starting value for this stat.
		std::string stat = popFirstString(infile->val);
		int value = popFirstInt(infile->val);

		for (size_t i=0; i<STAT_COUNT; ++i) {
			if (STAT_KEY[i] == stat) {
				starting[i] = value;
				return true;
			}
		}

		for (size_t i = 0; i < DAMAGE_TYPES.size(); ++i) {
			if (DAMAGE_TYPES[i].min == stat) {
				starting[STAT_COUNT + (i*2)] = value;
				return true;
			}
			else if (DAMAGE_TYPES[i].max == stat) {
				starting[STAT_COUNT + (i*2) + 1] = value;
				return true;
			}
		}
	}
	else if (infile->key == "stat_per_level") {
		// @ATTR stat_per_level|predefined_string, int : Stat name, Value|The value for this stat added per level.
		std::string stat = popFirstString(infile->val);
		int value = popFirstInt(infile->val);

		for (unsigned i=0; i<STAT_COUNT; i++) {
			if (STAT_KEY[i] == stat) {
				per_level[i] = value;
				return true;
			}
		}

		for (size_t i = 0; i < DAMAGE_TYPES.size(); ++i) {
			if (DAMAGE_TYPES[i].min == stat) {
				per_level[STAT_COUNT + (i*2)] = value;
				return true;
			}
			else if (DAMAGE_TYPES[i].max == stat) {
				per_level[STAT_COUNT + (i*2) + 1] = value;
				return true;
			}
		}
	}
	else if (infile->key == "stat_per_primary") {
		// @ATTR stat_per_primary|predefined_string, predefined_string, int : Primary Stat, Stat name, Value|The value for this stat added for every point allocated to this primary stat.
		std::string prim_stat = popFirstString(infile->val);
		size_t prim_stat_index = getPrimaryStatIndex(prim_stat);

		std::string stat = popFirstString(infile->val);
		int value = popFirstInt(infile->val);

		for (unsigned i=0; i<STAT_COUNT; i++) {
			if (STAT_KEY[i] == stat) {
				per_primary[prim_stat_index][i] = value;
				return true;
			}
		}

		for (size_t i = 0; i < DAMAGE_TYPES.size(); ++i) {
			if (DAMAGE_TYPES[i].min == stat) {
				per_primary[prim_stat_index][STAT_COUNT + (i*2)] = value;
				return true;
			}
			else if (DAMAGE_TYPES[i].max == stat) {
				per_primary[prim_stat_index][STAT_COUNT + (i*2) + 1] = value;
				return true;
			}
		}
	}
	else if (infile->key == "vulnerable") {
		// @ATTR vulnerable|predefined_string, int : Element, Value|Percentage weakness to this element.
		std::string element = popFirstString(infile->val);
		int value = popFirstInt(infile->val);

		for (unsigned int i=0; i<ELEMENTS.size(); i++) {
			if (element == ELEMENTS[i].id) {
				vulnerable[i] = vulnerable_base[i] = value;
				return true;
			}
		}
	}
	else if (infile->key == "power_filter") {
		// @ATTR power_filter|list(power_id)|Only these powers are allowed to hit this entity.
		std::string power_id = popFirstString(infile->val);
		while (!power_id.empty()) {
			power_filter.push_back(toInt(power_id));
			power_id = popFirstString(infile->val);
		}
		return true;
	}

	return false;
}
Esempio n. 27
0
MenuVendor::MenuVendor(StatBlock *_stats)
	: Menu()
	, stats(_stats)
	, closeButton(new WidgetButton("images/menus/buttons/button_x.png"))
	, tabControl(new WidgetTabControl())
	, slots_cols(1)
	, slots_rows(1)
	, activetab(VENDOR_BUY)
	, color_normal(font->getColor("menu_normal"))
	, npc(NULL)
	, buyback_stock() {
	setBackground("images/menus/vendor.png");

	tabControl->setTabTitle(VENDOR_BUY, msg->get("Inventory"));
	tabControl->setTabTitle(VENDOR_SELL, msg->get("Buyback"));

	// Load config settings
	FileParser infile;
	// @CLASS MenuVendor|Description of menus/vendor.txt
	if(infile.open("menus/vendor.txt")) {
		while(infile.next()) {
			if (parseMenuKey(infile.key, infile.val))
				continue;

			// @ATTR close|point|Position of the close button.
			if(infile.key == "close") {
				Point pos = toPoint(infile.val);
				closeButton->setBasePos(pos.x, pos.y);
			}
			// @ATTR slots_area|point|Position of the top-left slot.
			else if(infile.key == "slots_area") {
				slots_area.x = popFirstInt(infile.val);
				slots_area.y = popFirstInt(infile.val);
			}
			// @ATTR vendor_cols|int|The number of columns in the grid of slots.
			else if (infile.key == "vendor_cols") {
				slots_cols = std::max(1, toInt(infile.val));
			}
			// @ATTR vendor_rows|int|The number of rows in the grid of slots.
			else if (infile.key == "vendor_rows") {
				slots_rows = std::max(1, toInt(infile.val));
			}
			// @ATTR label_title|label|The position of the text that displays the NPC's name.
			else if (infile.key == "label_title") {
				title =  eatLabelInfo(infile.val);
			}
			else {
				infile.error("MenuVendor: '%s' is not a valid key.", infile.key.c_str());
			}
		}
		infile.close();
	}

	VENDOR_SLOTS = slots_cols * slots_rows;
	slots_area.w = slots_cols*ICON_SIZE;
	slots_area.h = slots_rows*ICON_SIZE;

	stock[VENDOR_BUY].initGrid(VENDOR_SLOTS, slots_area, slots_cols);
	stock[VENDOR_SELL].initGrid(VENDOR_SLOTS, slots_area, slots_cols);

	tablist.add(tabControl);
	tablist_buy.setPrevTabList(&tablist);
	tablist_sell.setPrevTabList(&tablist);

	tablist_buy.lock();
	tablist_sell.lock();

	for (unsigned i = 0; i < VENDOR_SLOTS; i++) {
		tablist_buy.add(stock[VENDOR_BUY].slots[i]);
	}
	for (unsigned i = 0; i < VENDOR_SLOTS; i++) {
		tablist_sell.add(stock[VENDOR_SELL].slots[i]);
	}

	align();
}
Esempio n. 28
0
/**
 * load a statblock, typically for an enemy definition
 */
void StatBlock::load(const std::string& filename) {
	// @CLASS StatBlock: Enemies|Description of enemies in enemies/
	FileParser infile;
	if (!infile.open(filename))
		return;

	bool clear_loot = true;
	bool flee_range_defined = false;

	while (infile.next()) {
		if (infile.new_section) {
			// APPENDed file
			clear_loot = true;
		}

		int num = toInt(infile.val);
		float fnum = toFloat(infile.val);
		bool valid = loadCoreStat(&infile) || loadSfxStat(&infile);

		// @ATTR name|string|Name
		if (infile.key == "name") name = msg->get(infile.val);
		// @ATTR humanoid|bool|This creature gives human traits when transformed into, such as the ability to talk with NPCs.
		else if (infile.key == "humanoid") humanoid = toBool(infile.val);

		// @ATTR level|int|Level
		else if (infile.key == "level") level = num;

		// enemy death rewards and events
		// @ATTR xp|int|XP awarded upon death.
		else if (infile.key == "xp") xp = num;
		else if (infile.key == "loot") {
			// @ATTR loot|repeatable(loot)|Possible loot that can be dropped on death.

			// loot entries format:
			// loot=[id],[percent_chance]
			// optionally allow range:
			// loot=[id],[percent_chance],[count_min],[count_max]

			if (clear_loot) {
				loot_table.clear();
				clear_loot = false;
			}

			loot_table.push_back(Event_Component());
			loot->parseLoot(infile.val, &loot_table.back(), &loot_table);
		}
		else if (infile.key == "loot_count") {
			// @ATTR loot_count|int, int : Min, Max|Sets the minimum (and optionally, the maximum) amount of loot this creature can drop. Overrides the global drop_max setting.
			loot_count.x = popFirstInt(infile.val);
			loot_count.y = popFirstInt(infile.val);
			if (loot_count.x != 0 || loot_count.y != 0) {
				loot_count.x = std::max(loot_count.x, 1);
				loot_count.y = std::max(loot_count.y, loot_count.x);
			}
		}
		// @ATTR defeat_status|string|Campaign status to set upon death.
		else if (infile.key == "defeat_status") defeat_status = infile.val;
		// @ATTR convert_status|string|Campaign status to set upon being converted to a player ally.
		else if (infile.key == "convert_status") convert_status = infile.val;
		// @ATTR first_defeat_loot|item_id|Drops this item upon first death.
		else if (infile.key == "first_defeat_loot") first_defeat_loot = num;
		// @ATTR quest_loot|string, string, item_id : Required status, Required not status, Item|Drops this item when campaign status is met.
		else if (infile.key == "quest_loot") {
			quest_loot_requires_status = popFirstString(infile.val);
			quest_loot_requires_not_status = popFirstString(infile.val);
			quest_loot_id = popFirstInt(infile.val);
		}

		// behavior stats
		// @ATTR flying|bool|Creature can move over gaps/water.
		else if (infile.key == "flying") flying = toBool(infile.val);
		// @ATTR intangible|bool|Creature can move through walls.
		else if (infile.key == "intangible") intangible = toBool(infile.val);
		// @ATTR facing|bool|Creature can turn to face their target.
		else if (infile.key == "facing") facing = toBool(infile.val);

		// @ATTR waypoint_pause|duration|Duration to wait at each waypoint in 'ms' or 's'.
		else if (infile.key == "waypoint_pause") waypoint_pause = parse_duration(infile.val);

		// @ATTR turn_delay|duration|Duration it takes for this creature to turn and face their target in 'ms' or 's'.
		else if (infile.key == "turn_delay") turn_delay = parse_duration(infile.val);
		// @ATTR chance_pursue|int|Percentage change that the creature will chase their target.
		else if (infile.key == "chance_pursue") chance_pursue = num;
		// @ATTR chance_flee|int|Percentage chance that the creature will run away from their target.
		else if (infile.key == "chance_flee") chance_flee = num;

		else if (infile.key == "power") {
			// @ATTR power|["melee", "ranged", "beacon", "on_hit", "on_death", "on_half_dead", "on_join_combat", "on_debuff"], power_id, int : State, Power, Chance|A power that has a chance of being triggered in a certain state.
			AIPower ai_power;

			std::string ai_type = popFirstString(infile.val);

			ai_power.id = powers->verifyID(popFirstInt(infile.val), &infile, false);
			if (ai_power.id == 0)
				continue; // verifyID() will print our error message

			ai_power.chance = popFirstInt(infile.val);

			if (ai_type == "melee") ai_power.type = AI_POWER_MELEE;
			else if (ai_type == "ranged") ai_power.type = AI_POWER_RANGED;
			else if (ai_type == "beacon") ai_power.type = AI_POWER_BEACON;
			else if (ai_type == "on_hit") ai_power.type = AI_POWER_HIT;
			else if (ai_type == "on_death") ai_power.type = AI_POWER_DEATH;
			else if (ai_type == "on_half_dead") ai_power.type = AI_POWER_HALF_DEAD;
			else if (ai_type == "on_join_combat") ai_power.type = AI_POWER_JOIN_COMBAT;
			else if (ai_type == "on_debuff") ai_power.type = AI_POWER_DEBUFF;
			else {
				infile.error("StatBlock: '%s' is not a valid enemy power type.", ai_type.c_str());
				continue;
			}

			if (ai_power.type == AI_POWER_HALF_DEAD)
				half_dead_power = true;

			powers_ai.push_back(ai_power);
		}

		else if (infile.key == "passive_powers") {
			// @ATTR passive_powers|list(power_id)|A list of passive powers this creature has.
			powers_passive.clear();
			std::string p = popFirstString(infile.val);
			while (p != "") {
				powers_passive.push_back(toInt(p));
				p = popFirstString(infile.val);
			}
		}

		// @ATTR melee_range|float|Minimum distance from target required to use melee powers.
		else if (infile.key == "melee_range") melee_range = fnum;
		// @ATTR threat_range|float, float: Engage distance, Stop distance|The first value is the radius of the area this creature will be able to start chasing the hero. The second, optional, value is the radius at which this creature will stop pursuing their target and defaults to double the first value.
		else if (infile.key == "threat_range") {
			threat_range = toFloat(popFirstString(infile.val));

			std::string tr_far = popFirstString(infile.val);
			if (!tr_far.empty())
				threat_range_far = toFloat(tr_far);
			else
				threat_range_far = threat_range * 2;
		}
		// @ATTR flee_range|float|The radius at which this creature will start moving to a safe distance. Defaults to half of the threat_range.
		else if (infile.key == "flee_range") {
			flee_range = fnum;
			flee_range_defined = true;
		}
		// @ATTR combat_style|["default", "aggressive", "passive"]|How the creature will enter combat. Default is within range of the hero; Aggressive is always in combat; Passive must be attacked to enter combat.
		else if (infile.key == "combat_style") {
			if (infile.val == "default") combat_style = COMBAT_DEFAULT;
			else if (infile.val == "aggressive") combat_style = COMBAT_AGGRESSIVE;
			else if (infile.val == "passive") combat_style = COMBAT_PASSIVE;
			else infile.error("StatBlock: Unknown combat style '%s'", infile.val.c_str());
		}

		// @ATTR animations|filename|Filename of an animation definition.
		else if (infile.key == "animations") animations = infile.val;

		// @ATTR suppress_hp|bool|Hides the enemy HP bar for this creature.
		else if (infile.key == "suppress_hp") suppress_hp = toBool(infile.val);

		else if (infile.key == "categories") {
			// @ATTR categories|list(string)|Categories that this enemy belongs to.
			categories.clear();
			std::string cat;
			while ((cat = popFirstString(infile.val)) != "") {
				categories.push_back(cat);
			}
		}

		// @ATTR flee_duration|duration|The minimum amount of time that this creature will flee. They may flee longer than the specified time.
		else if (infile.key == "flee_duration") flee_duration = parse_duration(infile.val);
		// @ATTR flee_cooldown|duration|The amount of time this creature must wait before they can start fleeing again.
		else if (infile.key == "flee_cooldown") flee_cooldown = parse_duration(infile.val);

		// this is only used for EnemyGroupManager
		// we check for them here so that we don't get an error saying they are invalid
		else if (infile.key == "rarity") ; // but do nothing

		else if (!valid) {
			infile.error("StatBlock: '%s' is not a valid key.", infile.key.c_str());
		}
	}
	infile.close();

	hp = starting[STAT_HP_MAX];
	mp = starting[STAT_MP_MAX];

	if (!flee_range_defined)
		flee_range = threat_range / 2;

	applyEffects();
}
Esempio n. 29
0
void DrawWidget::drawChannelFilled(Channel *ch, QPainter &p, double leftTime, double currentTime, double zoomX, double viewBottom, double zoomY, int viewType)
{
  ZoomLookup *z;
  if(viewType == DRAW_VIEW_SUMMARY) z = &ch->summaryZoomLookup;
  else z = &ch->normalZoomLookup;
    
  ChannelLocker channelLocker(ch);

  QColor current = ch->color;
  QColor invert(255 - current.red(), 255 - current.green(), 255 - current.blue());
  p.setPen(current);

  int viewBottomOffset = toInt(viewBottom / zoomY);
  viewBottom = double(viewBottomOffset) * zoomY;
  
  // baseX is the no. of chunks a pixel must represent.
  double baseX = zoomX / ch->timePerChunk();

  z->setZoomLevel(baseX);
  
  double currentChunk = ch->chunkFractionAtTime(currentTime);
  double leftFrameTime = currentChunk - ((currentTime - leftTime) / ch->timePerChunk());
  
  //double leftFrameTime = leftTime / ch->timePerChunk();

  double frameTime = leftFrameTime;
  //if(frameTime < 0.0) frameTime = 0.0;
  int n = 0;
  int baseElement = int(floor(frameTime / baseX));
  if(baseElement < 0) { n -= baseElement; baseElement = 0; }
  int lastBaseElement = int(floor(double(ch->totalChunks()) / baseX));
  
  int firstN = n;
  int lastN = firstN;
  
  //QPointArray pointArray(width()*2);
  //QPointArray topPoints(width()*2);
/*  Q3PointArray bottomPoints(width()*2);
  Q3PointArray evenMidPoints(width()*2);
  Q3PointArray oddMidPoints(width()*2);
  Q3PointArray evenMidPoints2(width()*2);
  Q3PointArray oddMidPoints2(width()*2);*/
  QPolygon bottomPoints(width()*2);
  QPolygon evenMidPoints(width()*2);
  QPolygon oddMidPoints(width()*2);
  QPolygon evenMidPoints2(width()*2);
  QPolygon oddMidPoints2(width()*2);
  std::vector<QRect> noteRect(width()*2);
  std::vector<QRect> noteRect2(width()*2);
  std::vector<bool> isNoteRectEven(width()*2);
  //int pointIndex = 0;
  int pointIndex = 0;
  int evenMidPointIndex = 0;
  int oddMidPointIndex = 0;
  int evenMidPointIndex2 = 0;
  int oddMidPointIndex2 = 0;
  int rectIndex = 0;
  int rectIndex2 = 0;

  if (baseX > 1) { // More samples than pixels
    int theWidth = width();
    //if(baseElement + theWidth > z->size()) z->setSize(baseElement + theWidth);
    if(lastBaseElement > z->size()) z->setSize(lastBaseElement);
    for(; n < theWidth && baseElement < lastBaseElement; n++, baseElement++) {
      myassert(baseElement >= 0);
      ZoomElement &ze = z->at(baseElement);
      //if(!z->hasValue(baseElement)) {
      if(!ze.isValid()) {
        if(!calcZoomElement(ch, ze, baseElement, baseX)) continue;
      }
     
      /*p.setPen(gdata->shading1Color());
      p.moveTo(n, 0);
      p.lineTo(n, height() - 1 - toInt(ze.high / zoomY) + viewBottomOffset);
      p.setPen(gdata->shading2Color());
      p.lineTo(n, height());*/
      int y = height() - 1 - toInt(ze.high() / zoomY) + viewBottomOffset;
      int y2, y3;
      //if(ze.noteIndex >= 0) {
      if(ze.noteIndex() != -1 && ch->dataAtChunk(ze.midChunk())->getNoteIndex() != -1) {
        myassert(ze.noteIndex() >= 0);
        myassert(ze.noteIndex() < int(ch->noteData.size()));
        myassert(ch->isValidChunk(ze.midChunk()));
        AnalysisData *data = ch->dataAtChunk(ze.midChunk());
        //double avgNote = ch->noteData[ze.noteIndex()].avgNote();
        //printf("avgFreq = %f, ", ch->noteData[ze.noteIndex].avgFreq());
        //printf("numPeriods = %f, ", ch->noteData[ze.noteIndex].numPeriods());
        //printf("noteLength = %f\n", ch->noteData[ze.noteIndex].noteLength());
        //y2 = height() - 1 - toInt((avgNote+0.5) / zoomY) + viewBottomOffset;
        //y3 = height() - 1 - toInt((avgNote-0.5) / zoomY) + viewBottomOffset;
        //y2 = height() - 1 - toInt((data->shortTermMean + data->shortTermDeviation) / zoomY) + viewBottomOffset;
        //y3 = height() - 1 - toInt((data->shortTermMean - data->shortTermDeviation) / zoomY) + viewBottomOffset;

        if(gdata->showMeanVarianceBars()) {
          //longTermMean bars
          y2 = height() - 1 - toInt((data->getLongTermMean() + data->getLongTermDeviation()) / zoomY) + viewBottomOffset;
          y3 = height() - 1 - toInt((data->getLongTermMean() - data->getLongTermDeviation()) / zoomY) + viewBottomOffset;
          if(ze.noteIndex() % 2 == 0) {
            evenMidPoints.setPoint(evenMidPointIndex++, n, y2);
            evenMidPoints.setPoint(evenMidPointIndex++, n, y3);
          } else {
            oddMidPoints.setPoint(oddMidPointIndex++, n, y2);
            oddMidPoints.setPoint(oddMidPointIndex++, n, y3);
          }
  
          //shortTermMean bars
          y2 = height() - 1 - toInt((data->getShortTermMean() + data->getShortTermDeviation()) / zoomY) + viewBottomOffset;
          y3 = height() - 1 - toInt((data->getShortTermMean() - data->getShortTermDeviation()) / zoomY) + viewBottomOffset;
          if(ze.noteIndex() % 2 == 0) {
            evenMidPoints2.setPoint(evenMidPointIndex2++, n, y2);
            evenMidPoints2.setPoint(evenMidPointIndex2++, n, y3);
          } else {
            oddMidPoints2.setPoint(oddMidPointIndex2++, n, y2);
            oddMidPoints2.setPoint(oddMidPointIndex2++, n, y3);
          }
        }
      //} else {
      //  y2 = y3 = 0;
      }
      //topPoints.setPoint(pointIndex, n, 0);
      //topPoints.setPoint(pointIndex, n, y);
      bottomPoints.setPoint(pointIndex++, n, y);
      bottomPoints.setPoint(pointIndex++, n, height());
      lastN = n;
    }
    //p.setPen(gdata->shading1Color());
    //p.drawLineSegments(topPoints, 0, pointIndex/2);
    p.setPen(Qt::NoPen);
    p.setBrush(gdata->shading1Color());
    p.drawRect(firstN, 0, lastN, height());
    p.setPen(gdata->shading2Color());
    //p.drawLineSegments(bottomPoints, 0, pointIndex/2);
    if(pointIndex > 1) p.drawLines(bottomPoints.constData(), pointIndex/2);

    if(gdata->showMeanVarianceBars()) {
      //shortTermMean bars
      p.setPen(Qt::green);
      //p.drawLineSegments(evenMidPoints2, 0, evenMidPointIndex2/2);
      if(evenMidPointIndex2 > 1) p.drawLines(evenMidPoints2.constData(), evenMidPointIndex2/2);
      p.setPen(Qt::yellow);
      //p.drawLineSegments(oddMidPoints2, 0, oddMidPointIndex2/2);
      if(oddMidPointIndex2 > 1) p.drawLines(oddMidPoints2.constData(), oddMidPointIndex2/2);

      //longTermMean bars
      p.setPen(Qt::yellow);
      //p.drawLineSegments(evenMidPoints, 0, evenMidPointIndex/2);
      if(evenMidPointIndex > 1) p.drawLines(evenMidPoints.constData(), evenMidPointIndex/2);
      p.setPen(Qt::green);
      //p.drawLineSegments(oddMidPoints, 0, oddMidPointIndex/2);
      if(oddMidPointIndex > 1) p.drawLines(oddMidPoints.constData(), oddMidPointIndex/2);
    }
  } else { // More pixels than samples
    float err = 0.0;
    float pitch = 0.0;
    int intChunk = (int) floor(frameTime); // Integer version of frame time
    if(intChunk < 0) intChunk = 0;
    double stepSize = 1.0 / baseX; // So we skip some pixels
    int x = 0, y, y2, y3;
  
    //double start = 0 - stepSize;
    double start = (double(intChunk) - frameTime) * stepSize;
    double stop = width() + (2 * stepSize);
    //int squareSize = (int(sqrt(stepSize)) / 2) * 2 + 1; //make it an odd number
    //int halfSquareSize = squareSize/2;
    //QPointArray topPoints(0);
    //QPointArray bottomPoints(0);
    //int pointIndex = 0;
    //topPoints.putPoints(pointIndex, 1, toInt(start), 0);
    //bottomPoints.putPoints(pointIndex, 1, toInt(start), height());
    //pointIndex++;
    //topPoints.setPoint(pointIndex, toInt(start), 0);
    bottomPoints.setPoint(pointIndex++, toInt(start), height());
    lastN = firstN = toInt(start);
    for (double n = start; n < stop && intChunk < (int)ch->totalChunks(); n += stepSize, intChunk++) {
      myassert(intChunk >= 0);
      //if (intChunk < 0) continue; // So we don't go off the beginning of the array
      AnalysisData *data = ch->dataAtChunk(intChunk);
      err = data->getCorrelation();
      //if (err >= CERTAIN_THRESHOLD) {
      
      //float val = MIN(ch->dataAtChunk(intChunk)->volumeValue, 1.0);
      if(gdata->pitchContourMode() == 0)
        //p.setPen(QPen(colorBetween(colorGroup().background(), ch->color, err*2.0-1.0), lineWidth));
        //p.setPen(QPen(colorBetween(gdata->backgroundColor(),  ch->color, err*sqrt(data->rms)*10.0), lineWidth));
        p.setPen(QPen(colorBetween(QColor(255, 255, 255), ch->color, err * dB2ViewVal(data->getLogRms())), lineWidth));
      else
        p.setPen(QPen(ch->color, lineWidth));
      
      x = toInt(n);
      lastN = x;
      //note = (data->isValid()) ? data->note : 0.0f;
      //note = (ch->isVisibleNote(data->noteIndex)) ? data->note : 0.0f;
      pitch = (ch->isVisibleChunk(data)) ? data->getPitch() : 0.0f;
      //if(ch->isVisibleChunk(data)) {
      if(data->getNoteIndex() >= 0) {
        isNoteRectEven[rectIndex] = (data->getNoteIndex() % 2) == 0;
        //note = data->note;
        //double avgNote = ch->noteData[data->noteIndex].avgNote();
        //y2 = height() - 1 - toInt((avgNote+0.5) / zoomY) + viewBottomOffset;
        //y3 = height() - 1 - toInt((avgNote-0.5) / zoomY) + viewBottomOffset;
        //y2 = height() - 1 - toInt((data->shortTermMean + data->shortTermDeviation) / zoomY) + viewBottomOffset;
        //y3 = height() - 1 - toInt((data->shortTermMean - data->shortTermDeviation) / zoomY) + viewBottomOffset;

        if(gdata->showMeanVarianceBars()) {
          //longTermMean bars
          y2 = height() - 1 - toInt((data->getLongTermMean() + data->getLongTermDeviation()) / zoomY) + viewBottomOffset;
          y3 = height() - 1 - toInt((data->getLongTermMean() - data->getLongTermDeviation()) / zoomY) + viewBottomOffset;
          noteRect[rectIndex].setLeft(x);
          noteRect[rectIndex].setRight(toInt(n+stepSize));
          noteRect[rectIndex].setTop(y2);
          noteRect[rectIndex++].setBottom(y3);
  
          //shortTermMean bars
          y2 = height() - 1 - toInt((data->getShortTermMean() + data->getShortTermDeviation()) / zoomY) + viewBottomOffset;
          y3 = height() - 1 - toInt((data->getShortTermMean() - data->getShortTermDeviation()) / zoomY) + viewBottomOffset;
          noteRect2[rectIndex2].setLeft(x);
          noteRect2[rectIndex2].setRight(toInt(n+stepSize));
          noteRect2[rectIndex2].setTop(y2);
          noteRect2[rectIndex2++].setBottom(y3);
        }
      //} else {
      //  note = 0.0f;
      }
      myassert(pitch >= 0.0 && pitch <= gdata->topPitch());
      //note = bound(note, 0, gdata->topNote());
      y = height() - 1 - toInt(pitch / zoomY) + viewBottomOffset;
      //y = height() - 1 - int((note / zoomY) - (viewBottom / zoomY));
      //topPoints.putPoints(pointIndex, 1, x, y);
      //bottomPoints.putPoints(pointIndex, 1, x, y);
      //pointIndex++;
      //topPoints.setPoint(pointIndex, x, y);
      bottomPoints.setPoint(pointIndex++, x, y);
    }
    //topPoints.putPoints(pointIndex, 1, topPoints.point(pointIndex-1).x(), 0);
    //bottomPoints.putPoints(pointIndex, 1, bottomPoints.point(pointIndex-1).x(), height());
    //pointIndex++;
    //topPoints.setPoint(pointIndex, topPoints.point(pointIndex-1).x(), 0);
    bottomPoints.setPoint(pointIndex, bottomPoints.point(pointIndex-1).x(), height());
    pointIndex++;

    //p.setPen(gdata->shading1Color());
    //p.setBrush(gdata->shading1Color());
    //p.drawPolygon(topPoints);
    //p.setPen(gdata->shading2Color());
    //p.setBrush(gdata->shading2Color());
    //p.drawPolygon(bottomPoints);
  
    myassert(pointIndex <= width()*2);
    //p.setPen(gdata->shading1Color());
    p.setPen(Qt::NoPen);
    p.setBrush(gdata->shading1Color());
    //p.drawPolygon(topPoints, false, 0, pointIndex);
    p.drawRect(firstN, 0, lastN, height());
    //p.setPen(gdata->shading2Color());
    p.setBrush(gdata->shading2Color());
    //p.drawPolygon(bottomPoints, false, 0, pointIndex);
    p.drawPolygon(bottomPoints.constData(), pointIndex, Qt::OddEvenFill);

    if(gdata->showMeanVarianceBars()) {
      //shortTermMean bars
      for(int j=0; j<rectIndex2; j++) {
        if(isNoteRectEven[j]) p.setBrush(Qt::green);
        else p.setBrush(Qt::yellow);
        p.drawRect(noteRect2[j]);
      }
      //longTermMean bars
      QColor seeThroughYellow = Qt::yellow;
      seeThroughYellow.setAlpha(255);
      QColor seeThroughGreen = Qt::green;
      seeThroughGreen.setAlpha(255);
      for(int j=0; j<rectIndex; j++) {
        //if(isNoteRectEven[j]) p.setBrush(QBrush(Qt::yellow, Qt::Dense3Pattern));
        //else p.setBrush(QBrush(Qt::green, Qt::Dense3Pattern));
        if(isNoteRectEven[j]) p.setBrush(seeThroughYellow);
        else p.setBrush(seeThroughGreen);
        p.drawRect(noteRect[j]);
      }
    }
  }
}
Esempio n. 30
0
void MenuPowers::loadUpgrade(FileParser &infile) {
	// @ATTR upgrade.id|integer|A power id from powers/powers.txt for this upgrade.
	if (infile.key == "id") {
		int id = popFirstInt(infile.val);
		if (id > 0) {
			skip_section = false;
			power_cell_upgrade.back().id = static_cast<short>(id);
		}
		else {
			skip_section = true;
			power_cell_upgrade.pop_back();
			infile.error("MenuPowers: Power index out of bounds 1-%d, skipping power.", INT_MAX);
		}
		return;
	}

	if (skip_section)
		return;

	// @ATTR upgrade.requires_physoff|integer|Upgrade requires Physical and Offense stat of this value.
	if (infile.key == "requires_physoff") power_cell_upgrade.back().requires_physoff = static_cast<short>(toInt(infile.val));
	// @ATTR upgrade.requires_physdef|integer|Upgrade requires Physical and Defense stat of this value.
	else if (infile.key == "requires_physdef") power_cell_upgrade.back().requires_physdef = static_cast<short>(toInt(infile.val));
	// @ATTR upgrade.requires_mentoff|integer|Upgrade requires Mental and Offense stat of this value.
	else if (infile.key == "requires_mentoff") power_cell_upgrade.back().requires_mentoff = static_cast<short>(toInt(infile.val));
	// @ATTR upgrade.requires_mentdef|integer|Upgrade requires Mental and Defense stat of this value.
	else if (infile.key == "requires_mentdef") power_cell_upgrade.back().requires_mentdef = static_cast<short>(toInt(infile.val));

	// @ATTR upgrade.requires_defense|integer|Upgrade requires Defense stat of this value.
	else if (infile.key == "requires_defense") power_cell_upgrade.back().requires_defense = static_cast<short>(toInt(infile.val));
	// @ATTR upgrade.requires_offense|integer|Upgrade requires Offense stat of this value.
	else if (infile.key == "requires_offense") power_cell_upgrade.back().requires_offense = static_cast<short>(toInt(infile.val));
	// @ATTR upgrade.requires_physical|integer|Upgrade requires Physical stat of this value.
	else if (infile.key == "requires_physical") power_cell_upgrade.back().requires_physical = static_cast<short>(toInt(infile.val));
	// @ATTR upgrade.requires_mental|integer|Upgrade requires Mental stat of this value.
	else if (infile.key == "requires_mental") power_cell_upgrade.back().requires_mental = static_cast<short>(toInt(infile.val));

	// @ATTR upgrade.requires_point|boolean|Upgrade requires a power point to unlock.
	else if (infile.key == "requires_point") power_cell_upgrade.back().requires_point = toBool(infile.val);
	// @ATTR upgrade.requires_level|integer|Upgrade requires at least this level for the hero.
	else if (infile.key == "requires_level") power_cell_upgrade.back().requires_level = static_cast<short>(toInt(infile.val));
	// @ATTR upgrade.requires_power|integer|Upgrade requires another power id.
	else if (infile.key == "requires_power") power_cell_upgrade.back().requires_power.push_back(static_cast<short>(toInt(infile.val)));

	// @ATTR upgrade.visible_requires_status|string|Hide the upgrade if we don't have this campaign status.
	else if (infile.key == "visible_requires_status") power_cell_upgrade.back().visible_requires_status.push_back(infile.val);
	// @ATTR upgrade.visible_requires_not_status|string|Hide the upgrade if we have this campaign status.
	else if (infile.key == "visible_requires_not_status") power_cell_upgrade.back().visible_requires_not.push_back(infile.val);

	else infile.error("MenuPowers: '%s' is not a valid key.", infile.key.c_str());
}