Exemplo n.º 1
0
int main(int argc, char const *argv[]) {
	int TC;
	scanf("%d", &TC);
	while(TC--) {
		int a, b;
		scanf("%d %d", &a, &b);
		int digitsA = digits(a), digitsB = digits(b);
		char reversedValueA[digitsA], reversedValueB[digitsB];
		setArray(reversedValueA);
		setArray(reversedValueB);
		reversedToString(a, digitsA, reversedValueA);
		reversedToString(b, digitsB, reversedValueB);
		detArray(reversedValueA);
		detArray(reversedValueB);
		int ra = valueOf(digitsA, reversedValueA);
		int rb = valueOf(digitsB, reversedValueB);
		int sum = ra + rb;
		int digitsSum = digits(sum);
		char reversedValue[digitsSum];
		setArray(reversedValue);
		reversedToString(sum, digitsSum, reversedValue);
		printf("%d\n", valueOf(digitsSum, reversedValue));
	}
	return 0;
}
Exemplo n.º 2
0
void CheckVisitor::visit(ReturnNode* node)
{
    node -> expr() -> accept(*this);

    if ( node -> isInInlineCall() )
        return;

    if ( function_scopes.empty() )
        throw SemanticError("return is not in a function");

    auto enclosing_function = function_scopes.top() -> func;
    node -> function(enclosing_function);

    auto unqualified_type = node -> expr() -> getType().unqualified();
    if ( unqualified_type -> isObjectType() )
    {
        auto obj_type = static_cast<const ObjectType*>(unqualified_type);
        auto ref_to_obj_type = TypeFactory::getReference(obj_type);
//        auto copy_constr = obj_type -> resolveMethod(obj_type -> typeName(), {VariableType(TypeFactory::getReference(obj_type), true)});
        auto copy_constr = obj_type -> methodWith(obj_type -> typeName(), {ref_to_obj_type, VariableType(ref_to_obj_type, true)});

        if ( copy_constr == nullptr )
            throw SemanticError("Cannot initialize return value of type '" + enclosing_function -> type().returnType().getName() + "' with value of type '" + obj_type -> typeName() + "'");

        checkCall(copy_constr, {valueOf(node -> expr())});
    }
}
Exemplo n.º 3
0
JSValue* CInstance::defaultValue(ExecState* exec, PreferredPrimitiveType hint) const
{
    if (hint == PreferString)
        return stringValue(exec);
    if (hint == PreferNumber)
        return numberValue(exec);
    return valueOf(exec);
}
Exemplo n.º 4
0
const String & String::append(long n, int base)
{
  char *t = valueOf(n, base);
  *this+=t;
  free(t);

  return *this;
}
Exemplo n.º 5
0
JSValue* CInstance::defaultValue(JSType hint) const
{
    if (hint == StringType)
        return stringValue();
    if (hint == NumberType)
        return numberValue();
   if (hint == BooleanType)
        return booleanValue();
    return valueOf();
}
Exemplo n.º 6
0
JSValue* BalInstance::defaultValue(ExecState* exec, JSType hint) const
{
    if (hint == (JSType)StringType)
        return stringValue(exec);
    if (hint == (JSType)NumberType)
        return numberValue(exec);
    if (hint == (JSType)BooleanType)
        return booleanValue();
    return valueOf(exec);
}
Exemplo n.º 7
0
void CheckVisitor::visit(VarInferTypeDeclarationNode* node)
{
    auto type = node -> expr() -> getType().unqualified();
//    assert(type -> isObjectType());

    if ( type -> isObjectType() )
    {
        auto copy_constructor = static_cast<const ObjectType*>(type) -> resolveMethod(type -> typeName(), {TypeFactory::getReference(type)});
        node -> callInfo(checkCall(copy_constructor, {valueOf(node -> expr())}));
    }
}
Exemplo n.º 8
0
JSValue QtPixmapInstance::defaultValue(ExecState* exec, PreferredPrimitiveType ptype) const
{
    if (ptype == PreferNumber) {
        return jsBoolean(
                (data.type() == static_cast<QVariant::Type>(qMetaTypeId<QImage>()) && !(data.value<QImage>()).isNull())
                || (data.type() == static_cast<QVariant::Type>(qMetaTypeId<QPixmap>()) && !data.value<QPixmap>().isNull()));
    }

    if (ptype == PreferString)
        return valueOf(exec);

    return jsUndefined();
}
Exemplo n.º 9
0
NXMLElementReader* NXMLFilterPacketReader::startContentSubElement(
        const std::string& subTagName,
        const regina::xml::XMLPropertyDict& props) {
    if (! filter_)
        if (subTagName == "filter") {
            int type;
            if (valueOf(props.lookup("typeid"), type)) {
                NXMLElementReader* ans = forFilter(
                    static_cast<SurfaceFilterType>(type),
                    XMLReaderFunction(), 0, parent_);
                if (ans)
                    return ans;
                else
                    return new NXMLFilterReader();
            }
        }
    return new NXMLElementReader();
}
Exemplo n.º 10
0
const std::string& SqlResult::operator[](const char *name) const
{
	return valueOf(name);
}
Exemplo n.º 11
0
sp<Integer> Integer::valueOf(const char* string) {
    return valueOf(string, 10);
}
Exemplo n.º 12
0
sp<Double> Double::valueOf(const sp<String>& s) {
	return valueOf(s->c_str());
}
Exemplo n.º 13
0
sp<Integer> Integer::valueOf(const sp<String>& string) {
    return valueOf(string, 10);
}
Exemplo n.º 14
0
struct node* convert(char *numberString){
	unsigned int total = 0;
	int arsize;
	int charsize;
	unsigned int prevtot = 0;
	struct node *result = NULL;
	struct node *head = NULL;
	char base;
	int curr;
	unsigned int length;
	if(numberString[0] == '-' || numberString[0] == '0'){
		base = numberString[1];
		curr = 2;
		arsize = sizeof(numberString);
		charsize = sizeof(numberString[0]);
	}
	else {
		base = numberString[0];
		curr = 1;
		arsize = sizeof(numberString);
		charsize = sizeof(numberString[0]);
	}
	base = tolower(base);
	length = strlen(numberString);
	switch(base){
	case 'b':
		for(; curr < length; curr++){
			prevtot = total;
			total = (total * 2) + (unsigned int)valueOf(numberString[curr]);
			if(prevtot > total){
				result = (struct node *)malloc(sizeof(struct node));
				result->num = prevtot;
				result->next = head;
				if (head != NULL) head->prev = result;
				head = result;
				total = (unsigned int)valueOf(numberString[curr]);
			}
		}
		result = (struct node *)malloc(sizeof(struct node));
		result->num = total;
		result->next = head;
		if (head != NULL) head->prev = result;
		head = result;
		break;

	case 'o':
		for(; curr < length; curr++){
			prevtot = total;
			total = (total * 8) + (unsigned int)valueOf(numberString[curr]);
			if(prevtot > total){
				result = (struct node *)malloc(sizeof(struct node));
				result->num = prevtot;
				result->next = head;
				if (head != NULL) head->prev = result;
				head = result;
				total = (unsigned int)valueOf(numberString[curr]);
			}
		}
		result = (struct node *)malloc(sizeof(struct node));
		result->num = total;
		result->next = head;
		if (head != NULL) head->prev = result;
		head = result;
		break;

	case 'd':
		for(; curr < length; curr++){
			total = (total * 10) + (unsigned int)valueOf(numberString[curr]);
		}
		result = (struct node *)malloc(sizeof(struct node));
		result->num = total;
		result->next = NULL;
		result->prev = NULL;
		head = result;
		total = (unsigned int)valueOf(numberString[curr]);

		break;

	case 'x':
		for(; curr < length; curr++){
			prevtot = total;
			total = (total * 16) + (unsigned int)valueOf(numberString[curr]);
			if(prevtot > total){
				result = (struct node *)malloc(sizeof(struct node));
				result->num = prevtot;
				result->next = head;
				if (head != NULL) head->prev = result;
				head = result;
				total = (unsigned int)valueOf(numberString[curr]);
			}
		}
		result = (struct node *)malloc(sizeof(struct node));
		result->num = total;
		result->next = head;
		if (head != NULL) head->prev = result;
		head = result;
		break;
	}
	if(numberString[0] == '-'){
		result = (struct node *)malloc(sizeof(struct node));
		result->num = 0;
		result->next = head;
		if (head != NULL) head->prev = result;
		head = result;
	}
	return head;
}
Exemplo n.º 15
0
jobject integerValueOf(JNIEnv* env, jint value) {
	jclass integerClass = env->FindClass("java/lang/Integer");
    return valueOf(env, integerClass, "(I)Ljava/lang/Integer;", value);
}
Exemplo n.º 16
0
QList<ProjectExplorer::ToolChain *> RvctToolChainFactory::autoDetect()
{
    Utils::Environment env = Utils::Environment::systemEnvironment();

    QMap<QString, QList<Utils::EnvironmentItem> > rvcts;
    QList<Utils::EnvironmentItem> globalItems;

    // Find all RVCT..x variables
    for (Utils::Environment::const_iterator i = env.constBegin(); i != env.constEnd(); ++i) {
        if (i.key() == QLatin1String(RVCT_LICENSE_KEY))
            globalItems.append(Utils::EnvironmentItem(i.key(), i.value()));
        if (!i.key().startsWith(QLatin1String("RVCT")))
            continue;

        const QString key = i.key().left(6);
        QList<Utils::EnvironmentItem> values = rvcts.value(key);

        values.append(Utils::EnvironmentItem(i.key(), i.value()));

        rvcts.insert(key, values);
    }

    // Set up tool chains for each RVCT.. set
    QList<ProjectExplorer::ToolChain *> result;
    for (QMap<QString, QList<Utils::EnvironmentItem> >::const_iterator i = rvcts.constBegin();
         i != rvcts.constEnd(); ++i) {
        QList<Utils::EnvironmentItem> changes = i.value();
        changes.append(globalItems);

        Utils::FileName binary = Utils::FileName::fromUserInput(valueOf(changes, QLatin1String("BIN")));
        if (binary.isEmpty())
            continue;
        binary.appendPath(QLatin1String(RVCT_BINARY));
        QFileInfo fi(binary.toFileInfo());
        if (!fi.exists() || !fi.isExecutable())
            continue;

        RvctToolChain::RvctVersion v = RvctToolChain::version(binary);
        if (v.majorVersion == 0 && v.minorVersion == 0 && v.build == 0)
            continue; // Failed to start.

        //: %1 arm version, %2 major version, %3 minor version, %4 build number
        const QString name = tr("RVCT (%1 %2.%3 Build %4)");

        RvctToolChain *tc = new RvctToolChain(true);
        tc->setCompilerCommand(binary);
        tc->setEnvironmentChanges(changes);
        tc->setDisplayName(name.arg(armVersionString(tc->armVersion()))
                           .arg(v.majorVersion).arg(v.minorVersion).arg(v.build));
        tc->setVersion(v);
        tc->setDebuggerCommand(ProjectExplorer::ToolChainManager::instance()->defaultDebugger(tc->targetAbi()));
        result.append(tc);

        tc = new RvctToolChain(true);
        tc->setCompilerCommand(binary);
        tc->setEnvironmentChanges(changes);
        tc->setArmVersion(RvctToolChain::ARMv6);
        tc->setDisplayName(name.arg(armVersionString(tc->armVersion()))
                           .arg(v.majorVersion).arg(v.minorVersion).arg(v.build));
        tc->setVersion(v);
        tc->setDebuggerCommand(ProjectExplorer::ToolChainManager::instance()->defaultDebugger(tc->targetAbi()));
        result.append(tc);
    }

    return result;
}
Exemplo n.º 17
0
sp<Short> Short::valueOf(const char* string, int32_t radix) {
    return valueOf(String::valueOf(string), radix);
}
Exemplo n.º 18
0
jobject booleanValueOf(JNIEnv* env, jboolean value) {
	jclass booleanClass = env->FindClass("java/lang/Boolean");
    return valueOf(env, booleanClass, "(Z)Ljava/lang/Boolean;", value);
}
Exemplo n.º 19
0
void Token::read(FileIn & in, bool any)
{
    _couples.clear();

    const char * k;
    BooL str;

    // bypass comment
    for (;;) {
        k = in.readWord(any, str);

        if (str || (*k != '<')) {
            if (any)
                continue;
            else
                in.error("'&lt;...' expected");
        }

        k = in.readWord(any, str);

        if (str || (*k != '!'))
            break;

        int minus = 0;

        for (;;) {
            char c = *in.readWord(TRUE, str);

            if (! str) {
                if (c == '-')
                    minus += 1;
                else if ((c == '>') && (minus == 2))
                    break;
                else
                    minus = 0;
            }
        }
    }


    char last;

    // note : k is not a string
    if (*k == '?') {
        last = '?';
        k = in.readWord(any, str);
    }
    else
        last = '/';

    if (!str && (*k == '/')) {
        _close = TRUE;
        k = in.readWord(any, str);
    }
    else
        _close = FALSE;

    if (str)
        in.error("syntax error \"" + WrapperStr(k) + "\" unexpected");

    _what = k;

    while (k = in.readWord(any, str), str || (*k != '>')) {
        if (!str && (*k == last)) {
            k = in.readWord(any, str);

            if (str || (*k != '>'))
                in.error("syntax error near '" + WrapperStr(k)  + "'>' expected");

            _closed = TRUE;
            return;
        }

        if (str) {
            if (!any)
                in.error("syntax error near '" + WrapperStr(k) + "'");
        }
        else {
            Couple cpl;

            cpl.key = k;

            if (!any || !strcmp(k, "xmi:id")) {
                if (!any && !valueOf(k).isNull())
                    in.error("'" + cpl.key + "' duplicated");

                if ((*in.readWord(FALSE, str) != '=') || str) {
                    if (! any)
                        in.error("syntax error near '" + WrapperStr(k) + "', '=' expected");
                }
                else {
                    cpl.value = in.readWord(FALSE, str);

                    if (str)
                        _couples.append(cpl);
                    else if (! any)
                        in.error("syntax error after '='");
                }
            }
        }
    }

    _closed = FALSE;
}
Exemplo n.º 20
0
jobject doubleValueOf(JNIEnv* env, jdouble value) {
	jclass doubleClass = env->FindClass("java/lang/Double");
    return valueOf(env, doubleClass, "(D)Ljava/lang/Double;", value);
}
Exemplo n.º 21
0
void PA::LoadPA()
{
  advances.clear();

  // TODO: put this utility in an input stream class and inhert from that
  string data = FileUtil::Read("resources/database/PA.txt");

  int endline = 0;
  std::vector<PA::PAData::Required> currSteps;
  std::string currPA;
  std::string damage;
  std::string icon;
  std::string type;

  do {
    endline = (int)data.find("\n");
    string line = data.substr(0, endline);

    while (line.compare(0, 1, " ") == 0)
      line.erase(line.begin()); // remove leading whitespaces
    while (line.size() > 0 && line.compare(line.size() - 1, 1, " ") == 0)
      line.erase(line.end() - 1); // remove trailing whitespaces

    if (line[0] == '#') {
      // Skip comments
      data = data.substr(endline + 1);
      continue;
    }

    if (line.find("PA") != string::npos) {
      if (!currSteps.empty()) {
        if (currSteps.size() > 1) {
          std::cout << "PA entry 1: " << currPA << " " << (unsigned)atoi(icon.c_str()) << " " << (unsigned)atoi(damage.c_str()) << " " << type << endl;

          Element elemType = ChipLibrary::GetElementFromStr(type);

          advances.push_back(PA::PAData({ currPA, (unsigned)atoi(icon.c_str()), (unsigned)atoi(damage.c_str()), elemType, currSteps }));
          currSteps.clear();
        }
        else {
          //std::cout << "Error. PA " + currPA + " only has 1 required chip for recipe. PA's must have 2 or more chips. Skipping entry.\n";
          Logger::Log("Error. PA \"" + currPA + "\": only has 1 required chip for recipe. PA's must have 2 or more chips. Skipping entry.");
          currSteps.clear();
        }
      }
      
      currPA = valueOf("name", line);
      damage = valueOf("damage", line);
      icon = valueOf("iconIndex", line);
      type = valueOf("type", line);
    } else if (line.find("Chip") != string::npos) {
      string name = valueOf("name", line);
      string code = valueOf("code", line);

      currSteps.push_back(PA::PAData::Required({ name,code[0] }));

      //std::cout << "chip step: " << name << " " << code[0] << endl;

    }

    data = data.substr(endline + 1);
  } while (endline > -1);

  if (currSteps.size() > 1) {
    Element elemType = ChipLibrary::GetElementFromStr(type);

    //std::cout << "PA entry 2: " << currPA << " " << (unsigned)atoi(icon.c_str()) << " " << (unsigned)atoi(damage.c_str()) << " " << type << endl;
    advances.push_back(PA::PAData({ currPA, (unsigned)atoi(icon.c_str()), (unsigned)atoi(damage.c_str()), elemType, currSteps }));
    currSteps.clear();
  }
  else {
    //std::cout << "Error. PA " + currPA + " only has 1 required chip for recipe. PA's must have 2 or more chips. Skipping entry.\n";
    Logger::Log("Error. PA \"" + currPA + "\": only has 1 required chip for recipe. PA's must have 2 or more chips. Skipping entry.");
    currSteps.clear();
  }
}
Exemplo n.º 22
0
char* String::valueOf(int n, int base)
{
  return valueOf((long) n, base);
}
Exemplo n.º 23
0
sp<Short> Short::valueOf(const char* string) {
    return valueOf(string, 10);
}
Exemplo n.º 24
0
//--------------------------------------------------------------------------
// Function:	EnumType::valueOf
///\brief	This is an overloaded member function, provided for convenience.
///		It differs from the above function only in the type of
///		argument \a name.
// Programmer	Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
void EnumType::valueOf( const H5std_string& name, void *value ) const
{
    valueOf( name.c_str(), value );
}
Exemplo n.º 25
0
sp<Short> Short::valueOf(const sp<String>& string) {
    return valueOf(string, 10);
}
Exemplo n.º 26
0
sp<Integer> Integer::valueOf(const char* string, int32_t radix) {
    return valueOf(String::valueOf(string), radix);
}
Exemplo n.º 27
0
void getPolygonFromSVG(std::string allcoords, std::vector<VEC3>& curPoly, bool& closedPoly)
{
	closedPoly=false;
	std::stringstream is(allcoords);
	bool relative=false;
	bool push_point;
	std::string coord;
	int mode = -1;

	while ( std::getline( is, coord, ' ' ) )
	{
		float x,y;
		push_point=false;

		if(coord[0]=='m' || coord[0]=='l' || coord[0]=='t') //start point, line or quadratic bezier curve
		{
			mode = 0;
//							std::cout << "relative coordinates" << std::endl;
			relative=true;
		}
		else if(coord[0]=='M' || coord[0] == 'L' || coord[0]=='T') //same in absolute coordinates
		{
//							std::cout << "absolute coordinates" << std::endl;
			mode = 1;
			relative=false;
		}
		else if(coord[0]=='h' || coord[0] == 'H') //horizontal line
		{
			mode = 2;
			relative=(coord[0]=='h');
		}
		else if(coord[0]=='v' || coord[0] == 'V') //vertical line
		{
//							std::cout << "vertical line" << std::endl;
			mode = 3;
			relative=(coord[0]=='v');
		}
		else if(coord[0]=='c' || coord[0] == 'C') //bezier curve
		{
//							std::cout << "bezier line" << std::endl;
			mode = 4;
			relative=(coord[0]=='c');
		}
		else if(coord[0]=='s' || coord[0] == 'S' || coord[0]=='q' || coord[0] == 'Q') //bezier curve 2
		{
//							std::cout << "bezier line 2" << std::endl;
			mode = 5;
			relative= ((coord[0]=='s') || (coord[0]=='q'));
		}
		else if(coord[0]=='a' || coord[0] == 'A') //elliptic arc
		{
//							std::cout << "elliptic arc" << std::endl;
			mode =6;
			relative= (coord[0]=='a');
		}
		else if(coord[0]=='z')
		{
//							std::cout << "the end" << std::endl;
			closedPoly = true;
		}
		else //coordinates
		{
			switch(mode)
			{
				case 0 : //relative
				break;
				case 1 : //absolute
				break;
				case 2 : //horizontal
				{
					std::stringstream streamCoord(coord);
					std::string xS;
					std::getline(streamCoord, xS, ',' );

					valueOf(xS,x);

					VEC3 previous = (curPoly)[(curPoly).size()-1];
					y = previous[1];

					push_point=true;
				}
				break;
				case 3 : //vertical
				{
					std::stringstream streamCoord(coord);
					std::string yS;
					std::getline(streamCoord, yS, ',' );

					valueOf(yS,y);

					VEC3 previous = (curPoly)[(curPoly).size()-1];
					x = previous[0];

					push_point=true;
				}
				break;
				case 4 : //bezier
				{
					std::getline( is, coord, ' ' ); //ignore first control point
					std::getline( is, coord, ' ' ); //ignore second control point
				}
				break;
				case 5 : //bezier 2
				{
					std::getline( is, coord, ' ' ); //ignore control point

				}
				break;
				case 6 : //elliptic
					std::getline( is, coord, ' ' ); //ignore rx
					std::getline( is, coord, ' ' ); //ignore ry
					std::getline( is, coord, ' ' ); //ignore x-rotation
					std::getline( is, coord, ' ' ); //ignore large arc flag
					std::getline( is, coord, ' ' ); //ignore sweep flag
				break;
			}

			std::stringstream streamCoord(coord);
			std::string xS,yS;
			std::getline(streamCoord, xS, ',' );
			std::getline(streamCoord, yS, ',' );

			valueOf(xS,x);
			valueOf(yS,y);

			push_point = true;
		}

		//if there is a point to push
		if(push_point)
		{

			VEC3 previous;

			if(curPoly.size()>0)
				previous = (curPoly)[(curPoly).size()-1];

			if(relative)
			{
				x += previous[0];
				y += previous[1];
			}

//			std::cout << "coord " << x << " " << y << std::endl;

			if(curPoly.size()==0 || (curPoly.size()>0 && (x!=previous[0] || y!= previous[1])))
				curPoly.push_back(VEC3(x,y,0));
		}
	}
}
Exemplo n.º 28
0
std::shared_ptr< Doxel3D >  Doxel3D::valueOf(
    std::shared_ptr< Doxel3D > parent,
    const d::dant_t& dant,
    const hmImage_t& hmImage,
    const d::size3d_t& worldSize
) {
    // Задача: поместить 2D карту высот в 3D доксель.

    // Размер карты высот
    const size_t N = (size_t)hmImage.first.get<0>();
    const size_t M = (size_t)hmImage.first.get<1>();
    const size_t NM = N * M;
    assert( (N == M) && "Работаем только с квадратными картами." );

    if ( (N != 1) && ((N & (N - 1)) != 0) ) {
        throw "The side of heightmap need be the power of 2.";
    }

    // Центром мировой карты будет центр карты высот 'hmImage'
    const size_t halfN = N / 2;
    const size_t halfM = M / 2;
    const size_t halfNM = halfN * halfM;

    // Последний доксель встретим особо (см. ниже)
    const bool notLastDoxel = (N > 1);

    // Размер докселя - максимальная сторона карты высот (мир должен
    // целиком поместиться в этом докселе).

    // Размер ячейки карты высот
    const float cellSize = worldSize.get<0>() / N;
    // Высота мира в ячейках карты высот
    size_t L = (size_t)( worldSize.get<2>() / cellSize );
    if (L < 1)  { L = 1; }
    // @todo Позволить высоте мира превышать размеры, заданные длиной и шириной.
    assert( ((L <= N) && (L <= M)) && "Высота не может превышать длину / ширину карты высот." );

    // Размер докселя (см. выше TODO для L)
    const float doxelSize = std::max(
        worldSize.get<0>(),  std::max( worldSize.get<1>(), worldSize.get<2>() )
    );

    // Доксель делит объём тремя перпендикулярными плоскостями -
    // образуется 8-мь октантов и, соотв., новых докселей. Пройдёмся
    // по всей карте высот и расширим её на 1 измерение.

    // Коэффициент для расчёта высоты
    // Высота хранится в диапазоне [-1.0; 1.0]
    //const float kh = (float)L / 2.0f;

    // Подготовим квадранты карты высот - отдадим их потомкам.
    // смотрим сверху на плоскость XY. КВ полностью заполняет
    // плоскость XY. Поэтому можем выделить 2 группы горизонтальных
    // квадрантов.
    // @info Контроль чётности сделали выше.
    /* - Заменено. См. ниже.
    float* qI    = notLastDoxel ? new float[ halfNM ] : nullptr;
    float* qII   = notLastDoxel ? new float[ halfNM ] : nullptr;
    float* qIII  = notLastDoxel ? new float[ halfNM ] : nullptr;
    float* qIV   = notLastDoxel ? new float[ halfNM ] : nullptr;
    float* qV    = notLastDoxel ? new float[ halfNM ] : nullptr;
    float* qVI   = notLastDoxel ? new float[ halfNM ] : nullptr;
    float* qVII  = notLastDoxel ? new float[ halfNM ] : nullptr;
    float* qVIII = notLastDoxel ? new float[ halfNM ] : nullptr;
    *//* - Заменено. См. ниже.
    boost::array< float*,  8 >  dant = {
        // верхние квадранты (z >= 0)
        nullptr, nullptr, nullptr, nullptr,
        // нижние квадранты (z < 0)
        nullptr, nullptr, nullptr, nullptr
    };
    */
    // Только один октант будет инициирован *точкой* высоты. См. причину ниже.
    boost::array< std::shared_ptr< float >,  8 >  dantMap = {};


    // Сколько и каких элементов содержит этот доксель
    // @see TODO в цикле ниже.
    boost::array< size_t, 10 >  countElement;
    countElement.fill( 0 );

    // I Определяем содержание самого докселя.
    // II Создаём потомков, передаём им части карты высот.
    // 8 докселей = 8 частей карты.

    // Надо понимать, что докселя не интересует сколько и чего содержится в
    // потомках. Ему только интересно, что ОН САМ хранит в себе. А хранит он
    // *обобщённые* данные о 3D-карте, данные, которые можно поместить в AboutCellCD.
    for (size_t j = 0; j < M; ++j) {
        for (size_t i = 0; i < N; ++i) {
            /* - Не то.
            // Переводим координаты карты высот в 3D пространство докселя
            const float height = kh * hmImage.second.get()[ i + j * N ];
            const auto worldCoord = d::coord3d_t(
                (i - halfHM.get<0>()) * cellSize,
                (j - halfHM.get<1>()) * cellSize,
                height
            );
            */

            // [-1.0; 1.0]x
            const float height = hmImage.second.get()[ i + j * N ];
            if (height == std::numeric_limits< float >::infinity()) {
                // Высота может отсутствовать
                continue;
            }

            // Переводим координаты карты высот в 3D пространство
            const int x = (int)i - (int)halfN;
            const int y = (int)j - (int)halfM;
            //const int z = (int)( kh * height );

            // Считаем сколько и каких элементов содержит этот доксель.
            // Сейчас для простоты полагаем, что доксель содержит 1 элемент.
            // @todo Подключить работу с картой биомов, чтобы разнообразить
            //       кол-во элементов.
            //++countElement[0]; - Без TODO не имеет смысла.

            // Смотрим, как карта высот заполнила октанты докселя и
            // тут же формируем карты для потомков. Заполнение октанта
            // (он же - потомок д.) зависит от значеня координаты высоты.
            // Причём, т.к. карта высот - квадратная и полностью заполняет
            // плоскость XY, т.о. можем выделить 2 группы квадрантов, лежащих
            // в плоскости XY.

            //assert( ((x != 0) && (y != 0) && (z != 0)) && "Не должно быть такой координаты: работаем только с кратными 2-ке сторонами карты." );

            if ( notLastDoxel ) {

                const size_t qx = (size_t)( (x >= 0) ? x : (x + (int)halfN) );
                const size_t qy = (size_t)( (y >= 0) ? y : (y + (int)halfM) );
                const size_t u = qx + qy * halfN;

                /* - Если высота мира много меньше высоты докселя, объём данных
                     получается слишком большой (карта размещается в центре
                     докселя). Заменено. См. ниже Формируем *только*
                     поверхность, глубины не трогаем.
                // Квадранты карты высот заполняем по мере необходимости.
                // Нельзя утверждать, что первая координата октанта окажется
                // первой координатой квадранта. Поэтому инициализация отдана
                // отдельному методу.
                const auto initDantMap = [ &dantMap, halfNM ] ( int k ) -> int {
                    if ( !dantMap[k] )  {
                        dantMap[k] = std::shared_ptr< float >( new float[ halfNM ] );
                        std::fill_n( dantMap[k].get(),  halfNM,  std::numeric_limits< float >::infinity() );
                    }
                    return k;
                };

                // Выберем октант
                int kTop = -1;
                int kBottom = -1;
                if (height >= 0.0f) {
                    // высота достаёт до верхнего октанта
                    // (инициируются обе плоскости)
                    if ( (x >= 0) && (y >= 0) ) {
                        kTop = initDantMap( 0 );
                        kBottom = initDantMap( 4 );
                    } else if ( (x >= 0) && (y < 0) ) {
                        kTop = initDantMap( 1 );
                        kBottom = initDantMap( 5 );
                    } else if ( (x < 0) && (y < 0) ) {
                        kTop = initDantMap( 2 );
                        kBottom = initDantMap( 6 );
                    } else if ( (x < 0) && (y >= 0) ) {
                        kTop = initDantMap( 3 );
                        kBottom = initDantMap( 7 );
                    } else {
                        assert( false && "Здесь нас быть не должно." );
                    }

                // (height < 0.0f)
                } else {
                    // высота остаётся в нижних октантах
                    if ( (x >= 0) && (y >= 0) ) {
                        kBottom = initDantMap( 4 );
                    } else if ( (x >= 0) && (y < 0) ) {
                        kBottom = initDantMap( 5 );
                    } else if ( (x < 0) && (y < 0) ) {
                        kBottom = initDantMap( 6 );
                    } else if ( (x < 0) && (y >= 0) ) {
                        kBottom = initDantMap( 7 );
                    } else {
                        assert( false && "Здесь нас быть не должно." );
                    }
                }

                // @test
                if ((kTop == -1) && (kBottom == -1)) {
                    const bool test = true;
                }

                // Заполним октант картой высот.
                // То, что октанты могут быть не затронуты высотой, проверили выше.
                assert( ((kTop != -1) || (kBottom != -1)) && "Координата должна была попасть хотя бы в один октант." );

                //float childHeight = std::numeric_limits< float >::infinity();
                //assert( (childHeight == std::numeric_limits< float >::infinity()) || ((childHeight >= -1.0f) && (childHeight <= 1.0f)) );

                // Может быть затронуты сразу два октанта (КВ - снизу-вверх)
                // Высота в потомке - уже другая высота: доксель делит её навпил.
                if (kTop != -1) {
                    assert( (height >= 0.0f) && "В эту плоскость не должна попадать отрицательная высота." );
                    // В верхнюю плоскость попадает верхушка высота. И тут же проверяем:
                    assert( (kBottom != -1) && "Высота не может заполнить верхний октант, пропустив нижний." );
                    const float hh = (height - 0.5f) * 2.0f;
                    assert( ((hh >= -1.0f) && (hh <= 1.0f)) && "Высота для верхней плоскости октанта вне допустимых пределов." );
                    dantMap[ kTop ].get()[u] = hh;
                }
                if (kBottom != -1) {
                    // И в нижнюю плоскость попадает верхушка высоты. Но в эту
                    // плоскость попадает и положительная (заполняет вертикаль
                    // целиком) высота, и отрицательная (некоторых потомков у
                    // докселя не будет).
                    assert( ((height < 0.0f) || ((height >= 0.0f) && (kTop != -1)))
                        && "В нижнюю плоскость не должна попадать положительная высота, если она не попала в верхнюю плоскость." );
                    const float hh = (height >= 0.0f) ? 1.0f : (height + 0.5f) * 2.0f;
                    assert( ((hh >= -1.0f) && (hh <= 1.0f)) && "Высота для нижней плоскости октанта вне допустимых пределов." );
                    dantMap[ kBottom ].get()[u] = hh;
                }
                */

                // Один и только один октант должен быть инициирован

                // Определяем дант точки высоты в докселе
                d::dant_t dt;
                dt[0] = (height < 0.0f) ? 0 : 1;
                dt[1] = (x < 0.0f) ? 0 : 1;
                dt[2] = (y < 0.0f) ? 0 : 1;
                const auto dtK = (size_t)dt.to_ulong();
                // Квадранты карты высот заполняем по мере необходимости.
                // Нельзя утверждать, что первая координата октанта окажется
                // первой координатой квадранта. Поэтому инициализация отдана
                // отдельному методу.
                const auto initDantMap = [ &dantMap, halfNM ] ( int k ) -> void {
                    if ( !dantMap[k] )  {
                        dantMap[k] = std::shared_ptr< float >( new float[ halfNM ] );
                        std::fill_n( dantMap[k].get(),  halfNM,  std::numeric_limits< float >::infinity() );
                    }
                };
                initDantMap( dtK );

                // Высота в потомке - уже другая высота: доксель делит её навпил
                if ( dt[0] ) {
                    // верхняя плоскость
                    assert( (height >= 0.0f) && "В эту плоскость не должна попадать отрицательная высота." );
                    const float hh = (height - 0.5f) * 2.0f;
                    assert( ((hh >= -1.0f) && (hh <= 1.0f)) && "Высота для верхней плоскости октанта вне допустимых пределов." );
                    dantMap[ dtK ].get()[u] = hh;
                } else {
                    // нижняя плоскость
                    // Высота попадает исключительно в одну плоскость. См.
                    // предв. реализацию и причину отказа от неё выше.
                    const float hh = (height >= 0.0f) ? 1.0f : (height + 0.5f) * 2.0f;
                    assert( ((hh >= -1.0f) && (hh <= 1.0f)) && "Высота для нижней плоскости октанта вне допустимых пределов." );
                    dantMap[ dtK ].get()[u] = hh;
                }

            } // if ( !lastDoxel )

        } // for (size_t i = 0; i < N; ++i)

    } // for (size_t j = 0; j < M; ++j)


    // III Создаём доксель.
    // @see TODO в цикле выше.
    auto content = std::shared_ptr< AboutCellCD >( new AboutCellCD( 1 ) );
#ifdef INCLUDE_DEBUG_INFO_IN_CONTENT
    // Вводим дополнительную информацию, чтобы идентифицировать это доксель
    content->test["N"] = boost::any( N );
    content->test["M"] = boost::any( M );
    std::ostringstream os;
    os << worldSize;
    content->test["worldSize"] = boost::any( os.str() );
    content->test["height-first-point"] = (hmImage.second.get()[0] == std::numeric_limits< float >::infinity())
        ? boost::any( (std::string)"infinity" )
        : boost::any( hmImage.second.get()[0] );
    content->test["sequence"] = boost::any( countDoxel_ValueOf );
#endif
    auto doxel = std::shared_ptr< Doxel3D >( new Doxel3D( doxelSize, content, parent, dant ) );


    // IV Формируем потомков.
    // Размер потомков всегда в 2 раза меньше размера родителя по каждому
    // измерению докселя. Все потомки - одного размера. Все они - тоже доксели.
    // Создаём потомков:
    //   + если размер докселя больше 1 (пиксель карты высот) (доксель
    //     не последний)
    //   + если потомок имеет какое-либо содержание (октант инициализировали
    //     при просмотре карты высот)
    if ( notLastDoxel ) {
        // Потомки есть у всех докселей, кроме представляющих самый
        // глубокий уровень карты
        assert( !doxel->child() && "Потомков быть ещё не должно." );
        const d::size3d_t childWorldSize = d::size3d_t(
            worldSize.get<0>() / 2.0f,
            worldSize.get<1>() / 2.0f,
            // Высоту - сохраняем
            //worldSize.get<2>()
            worldSize.get<2>() / 2.0f
        );
        const d::sizeInt2d_t childHMSize = hmImage.first / 2;
        for (auto itr = dantMap.cbegin(); itr != dantMap.cend(); ++itr) {
            // Не каждый октант инициализирован (см. выше)
            if ( *itr != nullptr ) {
                const auto k = std::distance( dantMap.cbegin(), itr );
                const hmImage_t hmImage = std::make_pair( childHMSize,  dantMap[k] );
                const auto ch = valueOf(
                    // = parent
                    doxel,
                    // = dant
                    d::dant_t( k ),
                    hmImage,
                    childWorldSize
                );
                doxel->child( k, ch );

                // Тут же выгружаем потомка во внешнее хранилище, если хотим
                // съесть карту высот размером более 256 x 256 пикселей.
                //std::cout << "before unload " << *doxel << std::endl;
                /*ch->lazySave( true );*/
                // lazySave() полностью сохраняет д., если последним идёт корневой д..
                // Здесь же мы получаем д. наоборот: начиная с самого большого и заканчивая
                // мелочью. Поэтому следует обязательно вызвать flush().

            } else {
                // @test
                //const bool test = true;
            }
        }
    } // if ( notLastDoxel )


    // Выгружаем корневой доксель во внешнее хранилище (см. потомков)
    // lazySave() полностью сохраняет д., если последним идёт корневой д..
    // Здесь же мы получаем д. наоборот: начиная с самого большого и заканчивая
    // мелочью. Поэтому для КД следует обязательно вызвать flush().
    /*
    if ( doxel->root() ) {
        //std::cout << "before unload " << *doxel << std::endl;
        doxel->lazySave( !true );
        doxel->flush();

    } else {
        doxel->lazySave( !true );
    }
    */


    // @todo ...

    // Уборка...
    /* - std::shared_ptr
    for (auto itr = dant.cbegin(); itr != dant.cend(); ++itr) {
        float* h = *itr;
        delete[] h;
    }
    */

    // Считаем кол-во созданных методом докселей
    // (!) Помним, что кол-во создаваемых докселей всегда больше кол-ва потомков.
    // @see countChild()
    ++countDoxel_ValueOf;

    // @test Отчёт о получившемся докселе
    //std::cout << "[ " << countDoxel_ValueOf << " ]" << std::endl;
    //print( *doxel,  (std::string)"[ " + boost::lexical_cast< std::string >( countDoxel_ValueOf ) + " ]" );

    return doxel;
}
Exemplo n.º 29
0
QList<ProjectExplorer::HeaderPath> RvctToolChain::systemHeaderPaths() const
{
    return QList<ProjectExplorer::HeaderPath>()
            << ProjectExplorer::HeaderPath(valueOf(m_environmentChanges, QLatin1String("INC")),
                                           ProjectExplorer::HeaderPath::GlobalHeaderPath);
}
Exemplo n.º 30
0
jobject longValueOf(JNIEnv* env, jlong value) {
	jclass longClass = env->FindClass("java/lang/Long");
    return valueOf(env, longClass, "(J)Ljava/lang/Long;", value);
}