예제 #1
0
Variant ArrayData::current() const {
  return m_pos != invalid_index ? getValue(m_pos) : Variant(false);
}
예제 #2
0
Variant ArrayPair::key(VariableEnvironment &env) const {
  if (m_key) {
    return m_key->eval(env);
  }
  return Variant();
}
예제 #3
0
Variant BlendMultiband::exec() {
	std::vector< cv::Mat* >* matIn = NULL; // CV_32FC3 - ARRAY
	std::vector< cv::Mat* >* matOut = NULL; // CV_32FC3 - SCALAR
	std::vector< cv::Mat* >* matSelect = NULL; // CV_32FC3 - ARRAY

	{
		if (this->workspaceHandle.count(std::string("matIn")) == 1) {
			matIn = this->workspaceHandle[std::string("matIn")];
		}

		if (this->workspaceHandle.count(std::string("matOut")) == 1) {
			matOut = this->workspaceHandle[std::string("matOut")];
		}

		if (this->workspaceHandle.count(std::string("matSelect")) == 1) {
			matSelect = this->workspaceHandle[std::string("matSelect")];
		}

		CV_Assert(matIn == NULL || matIn->size() == 0 || matIn->at(0)->empty() == true || matIn->at(0)->type() == CV_32FC3);
		CV_Assert(matOut == NULL || matOut->size() == 0 || matOut->at(0)->empty() == true || matOut->at(0)->type() == CV_32FC3);
		CV_Assert(matSelect == NULL || matSelect->size() == 0 || matSelect->at(0)->empty() == true || matSelect->at(0)->type() == CV_32FC3);
	}

	std::string strImplementation = std::string("CUSTOM");

	{
		if (this->settingsHandle.count(std::string("strImplementation")) == 1) {
			strImplementation = this->settingsHandle[std::string("strImplementation")].getString();
		}
	}

	int intDepth = 4;

	{
		if (this->settingsHandle.count(std::string("intDepth")) == 1) {
			intDepth = this->settingsHandle[std::string("intDepth")].getInt();
		}
	}

	int intInterpolation = cv::INTER_LINEAR;

	{
		if (this->settingsHandle.count(std::string("strInterpolation")) == 1) {
			if (this->settingsHandle[std::string("strInterpolation")].getString() == std::string("NEAREST")) {
				intInterpolation = cv::INTER_NEAREST;

			} else if (this->settingsHandle[std::string("strInterpolation")].getString() == std::string("LINEAR")) {
				intInterpolation = cv::INTER_LINEAR;

			} else if (this->settingsHandle[std::string("strInterpolation")].getString() == std::string("CUBIC")) {
				intInterpolation = cv::INTER_CUBIC;

			} else if (this->settingsHandle[std::string("strInterpolation")].getString() == std::string("AREA")) {
				intInterpolation = cv::INTER_AREA;

			} else if (this->settingsHandle[std::string("strInterpolation")].getString() == std::string("LANCZOS")) {
				intInterpolation = cv::INTER_LANCZOS4;

			}
		}
	}

	if (strImplementation == std::string("OPENCV")) {
		cv::Ptr< cv::detail::Blender > blenderHandle = cv::detail::Blender::createDefault(cv::detail::Blender::MULTI_BAND, false);

		{
			cv::detail::MultiBandBlender* multibandblenderHandle = (cv::detail::MultiBandBlender*) (blenderHandle.get());

			multibandblenderHandle->setNumBands(intDepth);
		}

		{
			blenderHandle->prepare(cv::Rect(0.0, 0.0, System::obtain()->intWidth, System::obtain()->intHeight));
		}

		{
			for (int intFor1 = 0; intFor1 < matIn->size(); intFor1 += 1) {
				cv::Mat matHandle[2] = { };

				{
					cv::multiply(*matIn->at(intFor1), cv::Scalar(255, 255, 255), matHandle[0], 1.0, CV_16SC3);
				}

				{
					cv::Mat matTemp = cv::Mat();

					cv::deflate(*matSelect->at(intFor1), matTemp, 1);

					cv::compare(matTemp, cv::Scalar(0.999), matHandle[1], cv::CMP_GT);

					cv::multiply(matHandle[1], cv::Scalar(255), matHandle[1], 1.0, CV_8UC1);
				}

				{
					blenderHandle->feed(matHandle[0], matHandle[1], cv::Point(0, 0));
				}

				{
					System::obtain()->execProgress(this->strName, matIn->size(), intFor1 + 1);
				}
			}
		}

		{
			cv::Mat matHandle = cv::Mat();

			blenderHandle->blend(matHandle, cv::Mat());

			cv::multiply(matHandle, cv::Scalar(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0), *matOut->at(0), 1.0, CV_32FC3);
		}

	} else if (strImplementation == std::string("CUSTOM")) {
		std::vector< std::vector< cv::Mat > > pyramidHandle;

		{
			for (int intFor1 = 0; intFor1 < matIn->size(); intFor1 += 1) {
				std::vector< cv::Mat > matHandle;

				{
					cv::Mat matTemp = cv::Mat();

					cv::copy(*matIn->at(intFor1), matTemp);

					matHandle.push_back(matTemp);

					this->build(&matHandle, intDepth);
				}

				{
					pyramidHandle.push_back(matHandle);
				}

				{
					System::obtain()->execProgress(this->strName, matIn->size(), intFor1 + 1);
				}
			}
		}

		std::vector< cv::Mat > matBlend;

		{
			for (int intFor1 = 0; intFor1 < pyramidHandle.at(0).size(); intFor1 += 1) {
				matBlend.push_back(cv::Mat(pyramidHandle.at(0).at(intFor1).size(), CV_32FC3, cv::Scalar(0.0, 0.0, 0.0)));
			}

			for (int intFor1 = 0; intFor1 < matIn->size(); intFor1 += 1) {
				for (int intFor2 = 0; intFor2 < pyramidHandle.at(intFor1).size(); intFor2 += 1) {
					cv::Mat matHandle = cv::Mat();

					{
						cv::resize(*matSelect->at(intFor1), matHandle, pyramidHandle.at(intFor1).at(intFor2).size(), 0, 0, intInterpolation);
					}

					{
						cv::multiply(pyramidHandle.at(intFor1).at(intFor2), matHandle, pyramidHandle.at(intFor1).at(intFor2), 1.0, CV_32FC3);
					}

					{
						cv::add(matBlend.at(intFor2), pyramidHandle.at(intFor1).at(intFor2), matBlend.at(intFor2), cv::noArray(), CV_32FC3);
					}
				}
			}
		}

		{
			this->rebuild(&matBlend, 0);
		}

		{
			cv::copy(matBlend.at(0), *matOut->at(0));
		}

	}

	return Variant();
}
예제 #4
0
Variant _jobject_to_variant(JNIEnv * env, jobject obj) {

	jclass c = env->GetObjectClass(obj);
	bool array;
	String name = _get_class_name(env, c, &array);
	//print_line("name is " + name + ", array "+Variant(array));

	if (name == "java.lang.String") {

		return String::utf8(env->GetStringUTFChars( (jstring)obj, NULL ));
	};


	if (name == "[Ljava.lang.String;") {

		jobjectArray arr = (jobjectArray)obj;
		int stringCount = env->GetArrayLength(arr);
		//print_line("String array! " + String::num(stringCount));
		DVector<String> sarr;

		for (int i=0; i<stringCount; i++) {
			jstring string = (jstring) env->GetObjectArrayElement(arr, i);
			const char *rawString = env->GetStringUTFChars(string, 0);
			sarr.push_back(String(rawString));
		}

		return sarr;
	};

	if (name == "java.lang.Boolean") {

		jmethodID boolValue = env->GetMethodID(c, "booleanValue", "()Z");
		bool ret = env->CallBooleanMethod(obj, boolValue);
		return ret;
	};

	if (name == "java.lang.Integer") {

		jclass nclass = env->FindClass("java/lang/Number");
		jmethodID intValue = env->GetMethodID(nclass, "intValue", "()I");
		int ret = env->CallIntMethod(obj, intValue);
		return ret;
	};

	if (name == "[I") {

		jintArray arr = (jintArray)obj;
		int fCount = env->GetArrayLength(arr);
		DVector<int> sarr;
		sarr.resize(fCount);

		DVector<int>::Write w = sarr.write();
		env->GetIntArrayRegion(arr,0,fCount,w.ptr());
		w = DVector<int>::Write();
		return sarr;
	};

	if (name == "java.lang.Float" || name == "java.lang.Double") {

		jclass nclass = env->FindClass("java/lang/Number");
		jmethodID doubleValue = env->GetMethodID(nclass, "doubleValue", "()D");
		double ret = env->CallDoubleMethod(obj, doubleValue);
		return ret;
	};

	if (name == "[D") {

		jdoubleArray arr = (jdoubleArray)obj;
		int fCount = env->GetArrayLength(arr);
		RealArray sarr;
		sarr.resize(fCount);

		RealArray::Write w = sarr.write();

		for (int i=0; i<fCount; i++) {

			double n;
			env->GetDoubleArrayRegion(arr, i, 1, &n);
			w.ptr()[i] = n;

		};
		return sarr;
	};

	if (name == "[F") {

		jfloatArray arr = (jfloatArray)obj;
		int fCount = env->GetArrayLength(arr);
		RealArray sarr;
		sarr.resize(fCount);


		RealArray::Write w = sarr.write();

		for (int i=0; i<fCount; i++) {

			float n;
			env->GetFloatArrayRegion(arr, i, 1, &n);
			w.ptr()[i] = n;

		};
		return sarr;
	};


	if (name == "[Ljava.lang.Object;") {

		jobjectArray arr = (jobjectArray)obj;
		int objCount = env->GetArrayLength(arr);
		Array varr;

		for (int i=0; i<objCount; i++) {
			jobject jobj = env->GetObjectArrayElement(arr, i);
			Variant v = _jobject_to_variant(env, jobj);
			varr.push_back(v);
		}

		return varr;
	};

	if (name == "com.android.godot.Dictionary") {

		Dictionary ret;
		jclass oclass = c;
		jmethodID get_keys = env->GetMethodID(oclass, "get_keys", "()[Ljava/lang/String;");
		jobjectArray arr = (jobjectArray)env->CallObjectMethod(obj, get_keys);

		StringArray keys = _jobject_to_variant(env, arr);

		jmethodID get_values = env->GetMethodID(oclass, "get_values", "()[Ljava/lang/Object;");
		arr = (jobjectArray)env->CallObjectMethod(obj, get_values);

		Array vals = _jobject_to_variant(env, arr);

		//print_line("adding " + String::num(keys.size()) + " to Dictionary!");
		for (int i=0; i<keys.size(); i++) {

			ret[keys[i]] = vals[i];
		};

		return ret;
	};

	return Variant();
};
예제 #5
0
MonoArray *godot_icall_String_md5_buffer(MonoString *p_str) {
	Vector<uint8_t> ret = GDMonoMarshal::mono_string_to_godot(p_str).md5_buffer();
	// TODO Check possible Array/Vector<uint8_t> problem?
	return GDMonoMarshal::Array_to_mono_array(Variant(ret));
}
예제 #6
0
Variant Deserializer::ReadVariant(VariantType type)
{
    switch (type)
    {
    case VAR_INT:
        return Variant(ReadInt());
        
    case VAR_BOOL:
        return Variant(ReadBool());
        
    case VAR_FLOAT:
        return Variant(ReadFloat());
        
    case VAR_VECTOR2:
        return Variant(ReadVector2());
        
    case VAR_VECTOR3:
        return Variant(ReadVector3());
        
    case VAR_VECTOR4:
        return Variant(ReadVector4());
        
    case VAR_QUATERNION:
        return Variant(ReadQuaternion());
        
    case VAR_COLOR:
        return Variant(ReadColor());
        
    case VAR_STRING:
        return Variant(ReadString());
        
    case VAR_BUFFER:
        return Variant(ReadBuffer());
        
        // Deserializing pointers is not supported. Return null
    case VAR_VOIDPTR:
    case VAR_PTR:
        ReadUInt();
        return Variant((void*)0);
        
    case VAR_RESOURCEREF:
        return Variant(ReadResourceRef());
        
    case VAR_RESOURCEREFLIST:
        return Variant(ReadResourceRefList());
        
    case VAR_VARIANTVECTOR:
        return Variant(ReadVariantVector());
        
    case VAR_VARIANTMAP:
        return Variant(ReadVariantMap());
        
    case VAR_INTRECT:
        return Variant(ReadIntRect());
        
    case VAR_INTVECTOR2:
        return Variant(ReadIntVector2());
        
    case VAR_MATRIX3:
        return Variant(ReadMatrix3());
        
    case VAR_MATRIX3X4:
        return Variant(ReadMatrix3x4());
        
    case VAR_MATRIX4:
        return Variant(ReadMatrix4());
        
    default:
        return Variant();
    }
}
예제 #7
0
파일: ext_xml.cpp 프로젝트: RavenB/hhvm
void _xml_characterDataHandler(void *userData, const XML_Char *s, int len) {
  auto parser = getParserFromToken(userData);

  if (parser) {
    Variant retval;
    Array args = Array::Create();

    if (parser->characterDataHandler.toBoolean()) {
      args.append(Variant(parser));
      args.append(_xml_xmlchar_zval(s, len, parser->target_encoding));
      xml_call_handler(parser, parser->characterDataHandler, args);
    }

    if (!parser->data.isNull()) {
      int i;
      int doprint = 0;

      String decoded_value;
      int decoded_len;
      decoded_value = xml_utf8_decode(s,len,
                                          parser->target_encoding);
      decoded_len = decoded_value.size();
      for (i = 0; i < decoded_len; i++) {
        switch (decoded_value[i]) {
        case ' ':
        case '\t':
        case '\n':
        default:
          doprint = 1;
          break;
        }
        if (doprint) {
          break;
        }
      }
      if (doprint || (! parser->skipwhite)) {
        if (parser->lastwasopen) {
          String myval;
          // check if value exists, if yes append to that
          if (parser->ctag.toArrRef().exists(s_value)) {
            myval = parser->ctag.toArray().rvalAt(s_value).toString();
            myval += decoded_value;
            parser->ctag.toArrRef().set(s_value, myval);
          } else {
            parser->ctag.toArrRef().set(
              s_value,
              decoded_value
            );
          }
        } else {
          Array tag;
          String myval;
          String mytype;

          auto curtag = parser->data.toArrRef().pop();
          SCOPE_EXIT {
            try {
              parser->data.toArrRef().append(curtag);
            } catch (...) {}
          };

          if (curtag.toArrRef().exists(s_type)) {
            mytype = curtag.toArrRef().rvalAt(s_type).toString();
            if (!strcmp(mytype.data(), "cdata") &&
                curtag.toArrRef().exists(s_value)) {
              myval = curtag.toArrRef().rvalAt(s_value).toString();
              myval += decoded_value;
              curtag.toArrRef().set(s_value, myval);
              return;
            }
          }
          if (parser->level <= XML_MAXLEVEL) {
            tag = Array::Create();
            _xml_add_to_info(parser, parser->ltags[parser->level-1] +
                             parser->toffset);
            tag.set(s_tag, String(parser->ltags[parser->level-1] +
                                  parser->toffset, CopyString));
            tag.set(s_value, decoded_value);
            tag.set(s_type, s_cdata);
            tag.set(s_level, parser->level);
            parser->data.toArrRef().append(tag);
          } else if (parser->level == (XML_MAXLEVEL + 1)) {
            raise_warning("Maximum depth exceeded - Results truncated");
          }
        }
      }
    }
  }
예제 #8
0
Variant Object::_call_bind(const StringName& p_name, const Variant& p_arg1, const Variant& p_arg2, const Variant& p_arg3, const Variant& p_arg4) {

	ERR_FAIL_COND_V(p_argcount<1,Variant());

	return call(p_name, p_arg1, p_arg2, p_arg3, p_arg4);
};
예제 #9
0
Variant Object::getvar(const Variant& p_key, bool *r_valid) const {

	if (r_valid)
		*r_valid=false;
	return Variant();
}
예제 #10
0
Variant CanvasItem::edit_get_state() const {


	return Variant();
}
예제 #11
0
Variant Object::get_meta(const String& p_name) const {

	ERR_FAIL_COND_V(!metadata.has(p_name),Variant());
	return metadata[p_name];
}
예제 #12
0
Array TypeAnnotation::getScalarArrayRep() const {
  auto rep = Array::Create();

  bool nullable = (bool) m_nullable;
  if (nullable) {
    rep.add(s_nullable, true_varNR);
  }

  bool allowsUnknownFields = (bool) m_allowsUnknownFields;
  if (allowsUnknownFields) {
    rep.add(s_allows_unknown_fields, true_varNR);
  }

  TypeStructure::Kind kind = getKind();
  rep.add(s_kind, Variant(static_cast<uint8_t>(kind)));

  switch (kind) {
  case TypeStructure::Kind::T_tuple:
    assert(m_typeArgs);
    rep.add(s_elem_types, Variant(argsListToScalarArray(m_typeArgs)));
    break;
  case TypeStructure::Kind::T_fun:
    assert(m_typeArgs);
    // return type is the first of the typeArgs
    rep.add(s_return_type, Variant(m_typeArgs->getScalarArrayRep()));
    rep.add(s_param_types,
            Variant(argsListToScalarArray(m_typeArgs->m_typeList)));
    break;
  case TypeStructure::Kind::T_array:
  case TypeStructure::Kind::T_dict:
  case TypeStructure::Kind::T_vec:
  case TypeStructure::Kind::T_keyset:
    if (m_typeArgs) {
      rep.add(s_generic_types, Variant(argsListToScalarArray(m_typeArgs)));
    }
    break;
  case TypeStructure::Kind::T_shape:
    shapeFieldsToScalarArray(rep, m_typeArgs);
    break;
  case TypeStructure::Kind::T_typevar:
    rep.add(s_name, Variant(m_name));
    break;
  case TypeStructure::Kind::T_typeaccess: {
    // for now, only store the vanilla names (strings) as part of the
    // access list
    rep.add(s_root_name, Variant(m_name));
    auto accList = Array::Create();
    auto typeEl = m_typeArgs;
    int i = 0;
    while (typeEl) {
      accList.add(i, Variant(typeEl->vanillaName()));
      ++i;
      typeEl = typeEl->m_typeList;
    }
    rep.add(s_access_list, Variant(accList));
    break;
  }
  case TypeStructure::Kind::T_xhp:
    rep.add(s_classname, Variant(m_name));
    break;
  case TypeStructure::Kind::T_unresolved:
    rep.add(s_classname, Variant(m_name));
    if (m_typeArgs) {
      rep.add(s_generic_types, Variant(argsListToScalarArray(m_typeArgs)));
    }
    break;
  default:
    break;
  }

  if (!m_generics.empty()) {
    rep.add(s_typevars, Variant(m_generics));
  }

  rep.setEvalScalar();
  return rep;
}
예제 #13
0
bool EditorFileSystem::_check_missing_imported_files(const String &p_path) {

	if (!reimport_on_missing_imported_files)
		return true;

	Error err;
	FileAccess *f = FileAccess::open(p_path + ".import", FileAccess::READ, &err);

	if (!f) {
		print_line("could not open import for " + p_path);
		return false;
	}

	VariantParser::StreamFile stream;
	stream.f = f;

	String assign;
	Variant value;
	VariantParser::Tag next_tag;

	int lines = 0;
	String error_text;

	List<String> to_check;

	while (true) {

		assign = Variant();
		next_tag.fields.clear();
		next_tag.name = String();

		err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, NULL, true);
		if (err == ERR_FILE_EOF) {
			memdelete(f);
			return OK;
		} else if (err != OK) {
			ERR_PRINTS("ResourceFormatImporter::load - " + p_path + ".import:" + itos(lines) + " error: " + error_text);
			memdelete(f);
			return false;
		}

		if (assign != String()) {
			if (assign.begins_with("path")) {
				to_check.push_back(value);
			} else if (assign == "files") {
				Array fa = value;
				for (int i = 0; i < fa.size(); i++) {
					to_check.push_back(fa[i]);
				}
			}

		} else if (next_tag.name != "remap" && next_tag.name != "deps") {
			break;
		}
	}

	memdelete(f);

	for (List<String>::Element *E = to_check.front(); E; E = E->next()) {
		if (!FileAccess::exists(E->get())) {
			print_line("missing " + E->get() + ", reimport");
			return false;
		}
	}
	return true;
}
예제 #14
0
        Variant &Variant::operator=(T &&rhs)
        {
            Variant( static_cast<T&&>( rhs ) ).Swap( *this );

            return *this;
        }
예제 #15
0
		bool	Parser::parseExpression (Lexer& lexer, Lookup& lookup, Int32u* slot, const Extractor** output)
		{
			BinaryOp				binaryOp;
			stack<BinaryOp>			binaryOps;
			stack<const Extractor*>	operands;
			const Extractor*		value;

			while (true)
			{
				switch (lexer.getType ())
				{
					case Lexer::PLUS:
						lexer.next ();

						if (!this->parseExpression (lexer, lookup, slot, &value))
							return false;

						break;

					case Lexer::MINUS:
						lexer.next ();

						if (!this->parseExpression (lexer, lookup, slot, &value))
							return false;

						value = new NumberUnaryExtractor (value, [] (Float64 number)
						{
							return Variant (-number);
						});

						this->extractors.push_back (value);

						break;

					case Lexer::NOT:
						lexer.next ();

						if (!this->parseExpression (lexer, lookup, slot, &value))
							return false;

						value = new BooleanUnaryExtractor (value, [] (bool value)
						{
							return Variant (!value);
						});

						this->extractors.push_back (value);

						break;

					case Lexer::PARENTHESIS_BEGIN:
						lexer.next ();

						if (!this->parseExpression (lexer, lookup, slot, &value) ||
						    !this->parseType (lexer, Lexer::PARENTHESIS_END, "closing parenthesis"))
							return false;

						break;

					default:
						if (!this->parseValue (lexer, lookup, slot, &value))
							return false;

						break;
				}

				operands.push (value);

				switch (lexer.getType ())
				{
					case Lexer::AMPERSAND:
						binaryOp = make_pair (1, [] (const Extractor* lhs, const Extractor* rhs) -> Extractor*
						{
							return new AndLogicalExtractor (lhs, rhs);
						});

						break;

					case Lexer::DIFFERENT:
						binaryOp = make_pair (2, [] (const Extractor* lhs, const Extractor* rhs) -> Extractor*
						{
							return new VariantBinaryExtractor (lhs, rhs, [] (const Variant& a, const Variant& b)
							{
								return Variant (a != b);
							});
						});

						break;

					case Lexer::DIVIDE:
						binaryOp = make_pair (4, [] (const Extractor* lhs, const Extractor* rhs) -> Extractor*
						{
							return new NumberBinaryExtractor (lhs, rhs, [] (Float64 a, Float64 b)
							{
								return b != 0 ? Variant (a / b) : Variant::empty;
							});
						});

						break;

					case Lexer::EQUAL:
						binaryOp = make_pair (2, [] (const Extractor* lhs, const Extractor* rhs) -> Extractor*
						{
							return new VariantBinaryExtractor (lhs, rhs, [] (const Variant& a, const Variant& b)
							{
								return Variant (a == b);
							});
						});

						break;

					case Lexer::GREATER_EQUAL:
						binaryOp = make_pair (2, [] (const Extractor* lhs, const Extractor* rhs) -> Extractor*
						{
							return new VariantBinaryExtractor (lhs, rhs, [] (const Variant& a, const Variant& b)
							{
								return Variant (a >= b);
							});
						});

						break;

					case Lexer::GREATER_THAN:
						binaryOp = make_pair (2, [] (const Extractor* lhs, const Extractor* rhs) -> Extractor*
						{
							return new VariantBinaryExtractor (lhs, rhs, [] (const Variant& a, const Variant& b)
							{
								return Variant (a > b);
							});
						});

						break;

					case Lexer::LOWER_EQUAL:
						binaryOp = make_pair (2, [] (const Extractor* lhs, const Extractor* rhs) -> Extractor*
						{
							return new VariantBinaryExtractor (lhs, rhs, [] (const Variant& a, const Variant& b)
							{
								return Variant (a <= b);
							});
						});

						break;

					case Lexer::LOWER_THAN:
						binaryOp = make_pair (2, [] (const Extractor* lhs, const Extractor* rhs) -> Extractor*
						{
							return new VariantBinaryExtractor (lhs, rhs, [] (const Variant& a, const Variant& b)
							{
								return Variant (a < b);
							});
						});

						break;

					case Lexer::MINUS:
						binaryOp = make_pair (3, [] (const Extractor* lhs, const Extractor* rhs) -> Extractor*
						{
							return new NumberBinaryExtractor (lhs, rhs, [] (Float64 a, Float64 b)
							{
								return Variant (a - b);
							});
						});

						break;

					case Lexer::MODULO:
						binaryOp = make_pair (4, [] (const Extractor* lhs, const Extractor* rhs) -> Extractor*
						{
							return new NumberBinaryExtractor (lhs, rhs, [] (Float64 a, Float64 b)
							{
								return b != 0 ? Variant (fmod (a, b)) : Variant::empty;
							});
						});

						break;

					case Lexer::MULTIPLY:
						binaryOp = make_pair (4, [] (const Extractor* lhs, const Extractor* rhs) -> Extractor*
						{
							return new NumberBinaryExtractor (lhs, rhs, [] (Float64 a, Float64 b)
							{
								return Variant (a * b);
							});
						});

						break;

					case Lexer::PIPE:
						binaryOp = make_pair (1, [] (const Extractor* lhs, const Extractor* rhs) -> Extractor*
						{
							return new OrLogicalExtractor (lhs, rhs);
						});

						break;

					case Lexer::PLUS:
						binaryOp = make_pair (3, [] (const Extractor* lhs, const Extractor* rhs) -> Extractor*
						{
							return new NumberBinaryExtractor (lhs, rhs, [] (Float64 a, Float64 b)
							{
								return Variant (a + b);
							});
						});

						break;

					default:
						for (; !binaryOps.empty (); binaryOps.pop ())
						{
							value = operands.top ();

							operands.pop ();

							value = binaryOps.top ().second (operands.top (), value);

							operands.pop ();
							operands.push (value);

							this->extractors.push_back (value);
						}

						if (operands.top ()->getFlags () == 0)
							return this->fail (lexer, "inconsistent expression");

						*output = operands.top ();

						return true;
				}

				lexer.next ();

				for (; !binaryOps.empty () && binaryOps.top ().first >= binaryOp.first; binaryOps.pop ())
				{
					value = operands.top ();

					operands.pop ();

					value = binaryOps.top ().second (operands.top (), value);

					operands.pop ();
					operands.push (value);

					this->extractors.push_back (value);
				}

				binaryOps.push (binaryOp);
			}
		}
예제 #16
0
Variant Object::call(const StringName& p_name, VARIANT_ARG_DECLARE) {
#if 0
	if (p_name==CoreStringNames::get_singleton()->_free) {
#ifdef DEBUG_ENABLED
		if (cast_to<Reference>()) {
			ERR_EXPLAIN("Can't 'free' a reference.");
			ERR_FAIL_V(Variant());
		}
#endif
		//must be here, must be before everything,
		memdelete(this);
		return Variant();
	}

	VARIANT_ARGPTRS;

	int argc=0;
	for(int i=0;i<VARIANT_ARG_MAX;i++) {
		if (argptr[i]->get_type()==Variant::NIL)
			break;
		argc++;
	}

	Variant::CallError error;

	Variant ret;

	if (script_instance) {
		ret = script_instance->call(p_name,argptr,argc,error);
		if (_test_call_error(p_name,error))
			return ret;
	}

	MethodBind *method=ObjectTypeDB::get_method(get_type_name(),p_name);

	if (method) {


		Variant ret = method->call(this,argptr,argc,error);
		if (_test_call_error(p_name,error))
			return ret;

		return ret;
	} else {

	}

	return Variant();
#else

	VARIANT_ARGPTRS;

	int argc=0;
	for(int i=0;i<VARIANT_ARG_MAX;i++) {
		if (argptr[i]->get_type()==Variant::NIL)
			break;
		argc++;
	}

	Variant::CallError error;

	Variant ret = call(p_name,argptr,argc,error);
	return ret;

#endif

}
예제 #17
0
bool Polygon2DEditor::forward_input_event(const InputEvent& p_event) {

	if (node==NULL)
		return false;

	switch(p_event.type) {

		case InputEvent::MOUSE_BUTTON: {

			const InputEventMouseButton &mb=p_event.mouse_button;

			Matrix32 xform = canvas_item_editor->get_canvas_transform() * node->get_global_transform();


			Vector2 gpoint = Point2(mb.x,mb.y);
			Vector2 cpoint = canvas_item_editor->get_canvas_transform().affine_inverse().xform(gpoint);
			cpoint=canvas_item_editor->snap_point(cpoint);
			cpoint = node->get_global_transform().affine_inverse().xform(cpoint);


			Vector<Vector2> poly = Variant(node->get_polygon());

			//first check if a point is to be added (segment split)
			real_t grab_treshold=EDITOR_DEF("poly_editor/point_grab_radius",8);

			switch(mode) {


				case MODE_CREATE: {

					if (mb.button_index==BUTTON_LEFT && mb.pressed) {


						if (!wip_active) {

							wip.clear();
							wip.push_back( cpoint-node->get_offset() );
							wip_active=true;
							edited_point_pos=cpoint;
							canvas_item_editor->get_viewport_control()->update();
							edited_point=1;
							return true;
						} else {


							if (wip.size()>1 && xform.xform(wip[0]+node->get_offset()).distance_to(gpoint)<grab_treshold) {
								//wip closed
								_wip_close();

								return true;
							} else {

								wip.push_back( cpoint-node->get_offset() );
								edited_point=wip.size();
								canvas_item_editor->get_viewport_control()->update();
								return true;

								//add wip point
							}
						}
					} else if (mb.button_index==BUTTON_RIGHT && mb.pressed && wip_active) {
						_wip_close();
					}



				} break;

				case MODE_EDIT: {

					if (mb.button_index==BUTTON_LEFT) {
						if (mb.pressed) {

							if (mb.mod.control) {


								if (poly.size() < 3) {

									undo_redo->create_action("Edit Poly");
									undo_redo->add_undo_method(node,"set_polygon",poly);
									poly.push_back(cpoint);
									undo_redo->add_do_method(node,"set_polygon",poly);
									undo_redo->add_do_method(canvas_item_editor->get_viewport_control(),"update");
									undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(),"update");
									undo_redo->commit_action();
									return true;
								}

								//search edges
								int closest_idx=-1;
								Vector2 closest_pos;
								real_t closest_dist=1e10;
								for(int i=0;i<poly.size();i++) {

									Vector2 points[2] ={ xform.xform(poly[i]+node->get_offset()),
										xform.xform(poly[(i+1)%poly.size()]+node->get_offset()) };

									Vector2 cp = Geometry::get_closest_point_to_segment_2d(gpoint,points);
									if (cp.distance_squared_to(points[0])<CMP_EPSILON2 || cp.distance_squared_to(points[1])<CMP_EPSILON2)
										continue; //not valid to reuse point

									real_t d = cp.distance_to(gpoint);
									if (d<closest_dist && d<grab_treshold) {
										closest_dist=d;
										closest_pos=cp;
										closest_idx=i;
									}


								}

								if (closest_idx>=0) {

									pre_move_edit=poly;
									poly.insert(closest_idx+1,xform.affine_inverse().xform(closest_pos)-node->get_offset());
									edited_point=closest_idx+1;
									edited_point_pos=xform.affine_inverse().xform(closest_pos);
									node->set_polygon(Variant(poly));
									canvas_item_editor->get_viewport_control()->update();
									return true;
								}
							} else {

								//look for points to move

								int closest_idx=-1;
								Vector2 closest_pos;
								real_t closest_dist=1e10;
								for(int i=0;i<poly.size();i++) {

									Vector2 cp =xform.xform(poly[i]+node->get_offset());

									real_t d = cp.distance_to(gpoint);
									if (d<closest_dist && d<grab_treshold) {
										closest_dist=d;
										closest_pos=cp;
										closest_idx=i;
									}

								}

								if (closest_idx>=0) {

									pre_move_edit=poly;
									edited_point=closest_idx;
									edited_point_pos=xform.affine_inverse().xform(closest_pos);
									canvas_item_editor->get_viewport_control()->update();
									return true;
								}
							}
						} else {

							if (edited_point!=-1) {

								//apply

								ERR_FAIL_INDEX_V(edited_point,poly.size(),false);
								poly[edited_point]=edited_point_pos-node->get_offset();
								undo_redo->create_action("Edit Poly");
								undo_redo->add_do_method(node,"set_polygon",poly);
								undo_redo->add_undo_method(node,"set_polygon",pre_move_edit);
								undo_redo->add_do_method(canvas_item_editor->get_viewport_control(),"update");
								undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(),"update");
								undo_redo->commit_action();

								edited_point=-1;
								return true;
							}
						}
					} if (mb.button_index==BUTTON_RIGHT && mb.pressed && edited_point==-1) {



						int closest_idx=-1;
						Vector2 closest_pos;
						real_t closest_dist=1e10;
						for(int i=0;i<poly.size();i++) {

							Vector2 cp =xform.xform(poly[i]+node->get_offset());

							real_t d = cp.distance_to(gpoint);
							if (d<closest_dist && d<grab_treshold) {
								closest_dist=d;
								closest_pos=cp;
								closest_idx=i;
							}

						}

						if (closest_idx>=0) {


							undo_redo->create_action("Edit Poly (Remove Point)");
							undo_redo->add_undo_method(node,"set_polygon",poly);
							poly.remove(closest_idx);
							undo_redo->add_do_method(node,"set_polygon",poly);
							undo_redo->add_do_method(canvas_item_editor->get_viewport_control(),"update");
							undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(),"update");
							undo_redo->commit_action();
							return true;
						}

					}



				} break;
			}



		} break;
		case InputEvent::MOUSE_MOTION: {

			const InputEventMouseMotion &mm=p_event.mouse_motion;

			if (edited_point!=-1 && (wip_active || mm.button_mask&BUTTON_MASK_LEFT)) {

				Vector2 gpoint = Point2(mm.x,mm.y);
				Vector2 cpoint = canvas_item_editor->get_canvas_transform().affine_inverse().xform(gpoint);
				cpoint=canvas_item_editor->snap_point(cpoint);
				edited_point_pos = node->get_global_transform().affine_inverse().xform(cpoint);

				canvas_item_editor->get_viewport_control()->update();

			}

		} break;
	}

	return false;
}
예제 #18
0
Variant Object::call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error) {

	r_error.error=Variant::CallError::CALL_OK;

	if (p_method==CoreStringNames::get_singleton()->_free) {
		//free must be here, before anything, always ready
#ifdef DEBUG_ENABLED
		if (p_argcount!=0) {
			r_error.argument=0;
			r_error.error=Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
			return Variant();
		}
		if (cast_to<Reference>()) {
			r_error.argument=0;
			r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
			ERR_EXPLAIN("Can't 'free' a reference.");
			ERR_FAIL_V(Variant());
		}

		if (_lock_index.get()>1) {
			r_error.argument=0;
			r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
			ERR_EXPLAIN("Object is locked and can't be freed.");
			ERR_FAIL_V(Variant());

		}

#endif
		//must be here, must be before everything,
		memdelete(this);
		r_error.error=Variant::CallError::CALL_OK;
		return Variant();
	}

	Variant ret;
	OBJ_DEBUG_LOCK
	if (script_instance) {
		ret = script_instance->call(p_method,p_args,p_argcount,r_error);
		//force jumptable
		switch(r_error.error) {

			case Variant::CallError::CALL_OK:
				return ret;
			case Variant::CallError::CALL_ERROR_INVALID_METHOD:
				break;
			case Variant::CallError::CALL_ERROR_INVALID_ARGUMENT:
			case Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
			case Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
				return ret;
			case Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL: {}

		}
	}

	MethodBind *method=ObjectTypeDB::get_method(get_type_name(),p_method);

	if (method) {

		ret=method->call(this,p_args,p_argcount,r_error);
	} else {
		r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
	}

	return ret;
}
예제 #19
0
파일: variant.cpp 프로젝트: KOgames/hhvm
TEST(Variant, Casts) {
  // Test Resource cast operations
  {
    EXPECT_FALSE(isa<DummyResource>(Variant()));
    EXPECT_TRUE(isa_or_null<DummyResource>(Variant()));
    EXPECT_FALSE(isa<DummyResource>(Variant(true)));
    EXPECT_FALSE(isa_or_null<DummyResource>(Variant(true)));

    auto dummy = req::make<DummyResource>();
    Variant var(dummy);
    Variant empty;
    EXPECT_TRUE(isa<DummyResource>(var));
    EXPECT_TRUE(isa_or_null<DummyResource>(var));

    EXPECT_FALSE(isa<File>(var));
    EXPECT_FALSE(isa_or_null<File>(var));

    // cast tests
    // Bad types and null pointers should throw.
    EXPECT_EQ(cast<DummyResource>(var), dummy);
    EXPECT_EQ(cast<ResourceData>(var), dummy);
    try {
      cast<File>(var);
      EXPECT_FALSE(true);
    } catch(...) {
      EXPECT_TRUE(true);
    }
    try {
      cast<c_Map>(var);
      EXPECT_FALSE(true);
    } catch(...) {
      EXPECT_TRUE(true);
    }
    try {
      cast<DummyResource>(empty);
      EXPECT_FALSE(true);
    } catch(...) {
      EXPECT_TRUE(true);
    }

    // cast_or_null tests
    // Bad types should throw, null pointers are ok.
    EXPECT_EQ(cast_or_null<ResourceData>(empty), nullptr);
    EXPECT_EQ(cast_or_null<ResourceData>(var), dummy);

    try {
      cast_or_null<File>(var);
      EXPECT_FALSE(true);
    } catch(...) {
      EXPECT_TRUE(true);
    }
    try {
      cast_or_null<c_Map>(var);
      EXPECT_FALSE(true);
    } catch(...) {
      EXPECT_TRUE(true);
    }

    // dyn_cast tests
    // Bad types are ok, null pointers should throw.
    EXPECT_EQ(dyn_cast<DummyResource>(var), dummy);
    EXPECT_EQ(dyn_cast<ResourceData>(var), dummy);
    EXPECT_EQ(dyn_cast<File>(var), nullptr);
    EXPECT_EQ(dyn_cast<c_Map>(var), nullptr);
    try {
      dyn_cast<DummyResource>(Variant());
      EXPECT_FALSE(true);
    } catch(...) {
      EXPECT_TRUE(true);
    }

    // dyn_cast_or_null
    // Bad types and null pointers are ok.  Should never throw.
    EXPECT_EQ(dyn_cast_or_null<ResourceData>(empty), nullptr);
    EXPECT_EQ(dyn_cast_or_null<ResourceData>(var), dummy);
    EXPECT_EQ(dyn_cast_or_null<c_Map>(var), nullptr);
  }

  // Test Object cast operations
  {
    EXPECT_FALSE(isa<c_Vector>(Variant()));
    EXPECT_TRUE(isa_or_null<c_Vector>(Variant()));
    EXPECT_FALSE(isa<c_Vector>(Variant(true)));
    EXPECT_FALSE(isa_or_null<c_Vector>(Variant(true)));

    auto dummy = req::make<c_Vector>();
    Variant var(dummy);
    Variant empty;
    EXPECT_TRUE(isa<c_Vector>(var));
    EXPECT_TRUE(isa_or_null<c_Vector>(var));

    EXPECT_FALSE(isa<c_Map>(var));
    EXPECT_FALSE(isa_or_null<c_Map>(var));

    // cast tests
    // Bad types and null pointers should throw.
    EXPECT_EQ(cast<c_Vector>(var), dummy);
    EXPECT_EQ(cast<ObjectData>(var), dummy);
    try {
      cast<c_Map>(var);
      EXPECT_FALSE(true);
    } catch(...) {
      EXPECT_TRUE(true);
    }
    try {
      cast<c_Vector>(empty);
      EXPECT_FALSE(true);
    } catch(...) {
      EXPECT_TRUE(true);
    }
    try {
      cast<File>(empty);
      EXPECT_FALSE(true);
    } catch(...) {
      EXPECT_TRUE(true);
    }

    // cast_or_null tests
    // Bad types should throw, null pointers are ok.
    EXPECT_EQ(cast_or_null<c_Vector>(empty), nullptr);
    EXPECT_EQ(cast_or_null<c_Vector>(var), dummy);

    try {
      cast_or_null<File>(var);
      EXPECT_FALSE(true);
    } catch(...) {
      EXPECT_TRUE(true);
    }
    try {
      cast_or_null<c_Map>(var);
      EXPECT_FALSE(true);
    } catch(...) {
      EXPECT_TRUE(true);
    }

    // dyn_cast tests
    // Bad types are ok, null pointers should throw.
    EXPECT_EQ(dyn_cast<c_Vector>(var), dummy);
    EXPECT_EQ(dyn_cast<ObjectData>(var), dummy);
    EXPECT_EQ(dyn_cast<c_Map>(var), nullptr);
    EXPECT_EQ(dyn_cast<File>(var), nullptr);
    try {
      dyn_cast<c_Vector>(empty);
      EXPECT_FALSE(true);
    } catch(...) {
      EXPECT_TRUE(true);
    }

    // dyn_cast_or_null
    // Bad types and null pointers are ok.  Should never throw.
    EXPECT_EQ(dyn_cast_or_null<c_Map>(empty), nullptr);
    EXPECT_EQ(dyn_cast_or_null<c_Vector>(var), dummy);
    EXPECT_EQ(dyn_cast_or_null<c_Map>(var), nullptr);
  }
}
예제 #20
0
bool SSLSocket::enableCrypto(bool activate /* = true */) {
  if (activate && !m_data->m_ssl_active) {
    double timeout = m_data->m_connect_timeout;
    bool blocked = m_data->m_is_blocked;
    if (!m_data->m_state_set) {
      if (m_data->m_client) {
        SSL_set_connect_state(m_data->m_handle);
      } else {
        SSL_set_accept_state(m_data->m_handle);
      }
      m_data->m_state_set = true;
    }

    if (m_data->m_client && setBlocking(false)) {
      m_data->m_is_blocked = false;
    }

    int n;
    bool retry = true;
    do {
      if (m_data->m_client) {
        struct timeval tvs, tve;
        struct timezone tz;

        gettimeofday(&tvs, &tz);
        n = SSL_connect(m_data->m_handle);
        gettimeofday(&tve, &tz);

        timeout -= (tve.tv_sec + (double) tve.tv_usec / 1000000) -
          (tvs.tv_sec + (double) tvs.tv_usec / 1000000);
        if (timeout < 0) {
          raise_warning("SSL: connection timeout");
          return false;
        }
      } else {
        n = SSL_accept(m_data->m_handle);
      }

      if (n <= 0) {
        retry = handleError(n, true);
      } else {
        break;
      }
    } while (retry);

    if (m_data->m_client &&
        m_data->m_is_blocked != blocked &&
        setBlocking(blocked)) {
      m_data->m_is_blocked = blocked;
    }

    if (n == 1) {
      X509 *peer_cert = SSL_get_peer_certificate(m_data->m_handle);
      if (!applyVerificationPolicy(peer_cert)) {
        SSL_shutdown(m_data->m_handle);
      } else {
        m_data->m_ssl_active = true;

        /* allow the script to capture the peer cert
         * and/or the certificate chain */
        if (m_context[s_capture_peer_cert].toBoolean()) {
          m_context.set(s_peer_certificate,
                        Variant(req::make<Certificate>(peer_cert)));
          peer_cert = nullptr;
        }

        if (m_context[s_capture_peer_cert_chain].toBoolean()) {
          Array arr;
          STACK_OF(X509) *chain = SSL_get_peer_cert_chain(m_data->m_handle);
          if (chain) {
            for (int i = 0; i < sk_X509_num(chain); i++) {
              X509 *mycert = X509_dup(sk_X509_value(chain, i));
              arr.append(Variant(req::make<Certificate>(mycert)));
            }
          }
          m_context.set(s_peer_certificate_chain, arr);
        }
      }

      if (peer_cert) {
        X509_free(peer_cert);
      }
    } else  {
      n = errno == EAGAIN ? 0 : -1;
    }

    return n >= 0;

  } else if (!activate && m_data->m_ssl_active) {
    /* deactivate - common for server/client */
    SSL_shutdown(m_data->m_handle);
    m_data->m_ssl_active = false;
  }
  return true;
}
예제 #21
0
파일: shape_sw.cpp 프로젝트: 3miu/godot
Variant HeightMapShapeSW::get_data() const {

	ERR_FAIL_V(Variant());

}
예제 #22
0
파일: main.cpp 프로젝트: BradWBeer/godot
Error Main::setup(const char *execpath,int argc, char *argv[],bool p_second_phase) {

	RID_OwnerBase::init_rid();

	OS::get_singleton()->initialize_core();
	ObjectTypeDB::init();

	MAIN_PRINT("Main: Initialize CORE");

	register_core_types();
	register_core_driver_types();

	MAIN_PRINT("Main: Initialize Globals");


	Thread::_main_thread_id = Thread::get_caller_ID();

	globals = memnew( Globals );
	input_map = memnew( InputMap );


	path_remap = memnew( PathRemap );
	translation_server = memnew( TranslationServer );
	performance = memnew( Performance );
	globals->add_singleton(Globals::Singleton("Performance",performance));

	MAIN_PRINT("Main: Parse CMDLine");

	/* argument parsing and main creation */
	List<String> args;
	List<String> main_args;

	for(int i=0;i<argc;i++) {

		args.push_back(String::utf8(argv[i]));
	}

	List<String>::Element *I=args.front();

	I=args.front();

	while (I) {

		I->get()=unescape_cmdline(I->get().strip_escapes());
//		print_line("CMD: "+I->get());
		I=I->next();
	}

	I=args.front();

	video_mode = OS::get_singleton()->get_default_video_mode();

	String video_driver="";
	String audio_driver="";
	String game_path=".";
	String debug_mode;
	String debug_host;
	String main_pack;
	bool quiet_stdout=false;
	int rtm=-1;

	String remotefs;
	String remotefs_pass;

	String screen = "";

	List<String> pack_list;
	Vector<String> breakpoints;
	bool use_custom_res=true;
	bool force_res=false;

	I=args.front();

	packed_data = PackedData::get_singleton();
	if (!packed_data)
		packed_data = memnew(PackedData);

#ifdef MINIZIP_ENABLED

	//XXX: always get_singleton() == 0x0
	zip_packed_data = ZipArchive::get_singleton();
	//TODO: remove this temporary fix
	if (!zip_packed_data) {
		zip_packed_data = memnew(ZipArchive);
	}

	packed_data->add_pack_source(zip_packed_data);
#endif

	bool editor=false;

	while(I) {

		List<String>::Element *N=I->next();

		if (I->get() == "-noop") {

			// no op
		} else if (I->get()=="-h" || I->get()=="--help" || I->get()=="/?") { // resolution

			goto error;


		} else if (I->get()=="-r") { // resolution

			if (I->next()) {

				String vm=I->next()->get();

				if (vm.find("x")==-1) { // invalid parameter format

					OS::get_singleton()->print("Invalid -r argument: %s\n",vm.utf8().get_data());
					goto error;


				}

				int w=vm.get_slice("x",0).to_int();
				int h=vm.get_slice("x",1).to_int();

				if (w==0 || h==0) {

					OS::get_singleton()->print("Invalid -r resolution, x and y must be >0\n");
					goto error;

				}

				video_mode.width=w;
				video_mode.height=h;
				force_res=true;

				N=I->next()->next();
			} else {
				OS::get_singleton()->print("Invalid -p argument, needs resolution\n");
				goto error;


			}
		} else if (I->get()=="-p") { // position

			if (I->next()) {

				String vm=I->next()->get();

				if (vm.find("x")==-1) { // invalid parameter format

					OS::get_singleton()->print("Invalid -p argument: %s\n",vm.utf8().get_data());
					goto error;


				}

				int x=vm.get_slice("x",0).to_int();
				int y=vm.get_slice("x",1).to_int();

				init_custom_pos=Point2(x,y);
				init_use_custom_pos=true;

				N=I->next()->next();
			} else {
				OS::get_singleton()->print("Invalid -r argument, needs position\n");
				goto error;


			}


		} else if (I->get()=="-mx") { // video driver

			init_maximized=true;
		} else if (I->get()=="-w") { // video driver

			init_windowed=true;
		} else if (I->get()=="-vd") { // video driver

			if (I->next()) {

				video_driver=I->next()->get();
				N=I->next()->next();
			} else {
				OS::get_singleton()->print("Invalid -cd argument, needs driver name\n");
				goto error;

			}
		} else if (I->get()=="-lang") { // language

			if (I->next()) {

				locale=I->next()->get();
				N=I->next()->next();
			} else {
				OS::get_singleton()->print("Invalid -lang argument, needs language code\n");
				goto error;

			}
		} else if (I->get()=="-rfs") { // language

			if (I->next()) {

				remotefs=I->next()->get();
				N=I->next()->next();
			} else {
				goto error;

			}
		} else if (I->get()=="-rfs_pass") { // language

			if (I->next()) {

				remotefs_pass=I->next()->get();
				N=I->next()->next();
			} else {
				goto error;

			}
		} else if (I->get()=="-rthread") { // language

			if (I->next()) {

				if (I->next()->get()=="safe")
					rtm=OS::RENDER_THREAD_SAFE;
				else if (I->next()->get()=="unsafe")
					rtm=OS::RENDER_THREAD_UNSAFE;
				else if (I->next()->get()=="separate")
					rtm=OS::RENDER_SEPARATE_THREAD;


				N=I->next()->next();
			} else {
				goto error;

			}

		} else if (I->get()=="-ad") { // video driver

			if (I->next()) {

				audio_driver=I->next()->get();
				N=I->next()->next();
			} else {
				goto error;

			}

		} else if (I->get()=="-f") { // fullscreen

			//video_mode.fullscreen=false;
			init_fullscreen=true;
		} else if (I->get()=="-e" || I->get()=="-editor") { // fonud editor

			editor=true;
		} else if (I->get()=="-nowindow") { // fullscreen

			OS::get_singleton()->set_no_window_mode(true);
		} else if (I->get()=="-quiet") { // fullscreen

			quiet_stdout=true;
		} else if (I->get()=="-v") { // fullscreen
			OS::get_singleton()->_verbose_stdout=true;
		} else if (I->get()=="-path") { // resolution

			if (I->next()) {

				String p = I->next()->get();
				if (OS::get_singleton()->set_cwd(p)==OK) {
					//nothing
				} else {
					game_path=I->next()->get(); //use game_path instead
				}
				N=I->next()->next();
			} else {
				goto error;

			}
		} else if (I->get()=="-bp") { // /breakpoints

			if (I->next()) {

				String bplist = I->next()->get();
				breakpoints= bplist.split(",");
				N=I->next()->next();
			} else {
				goto error;

			}


		} else if (I->get()=="-fdelay") { // resolution

			if (I->next()) {

				OS::get_singleton()->set_frame_delay(I->next()->get().to_int());
				N=I->next()->next();
			} else {
				goto error;

			}

		} else if (I->get()=="-timescale") { // resolution

			if (I->next()) {

				OS::get_singleton()->set_time_scale(I->next()->get().to_double());
				N=I->next()->next();
			} else {
				goto error;

			}


		} else if (I->get() == "-pack") {

			if (I->next()) {

				pack_list.push_back(I->next()->get());
				N = I->next()->next();
			} else {

				goto error;
			};

		} else if (I->get() == "-main_pack") {

			if (I->next()) {

				main_pack=I->next()->get();
				N = I->next()->next();
			} else {

				goto error;
			};

		} else if (I->get()=="-debug" || I->get()=="-d") {
			debug_mode="local";
		} else if (I->get()=="-debugcol" || I->get()=="-dc") {
			debug_collisions=true;
		} else if (I->get()=="-debugnav" || I->get()=="-dn") {
			debug_navigation=true;
		} else if (I->get()=="-editor_scene") {

			if (I->next()) {

				Globals::get_singleton()->set("editor_scene",game_path=I->next()->get());
			} else {
				goto error;

			}

		} else if (I->get()=="-rdebug") {
			if (I->next()) {

				debug_mode="remote";
				debug_host=I->next()->get();
				if (debug_host.find(":")==-1) { //wrong host
					OS::get_singleton()->print("Invalid debug host string\n");
					goto error;
				}
				N=I->next()->next();
			} else {
				goto error;

			}
		} else {

			//test for game path
			bool gpfound=false;

			if (!I->get().begins_with("-") && game_path=="") {
				DirAccess* da = DirAccess::open(I->get());
				if (da!=NULL) {
					game_path=I->get();
					gpfound=true;
					memdelete(da);
				}

			}

			if (!gpfound) {
				main_args.push_back(I->get());
			}
		}

		I=N;
	}


	GLOBAL_DEF("debug/max_remote_stdout_chars_per_second",2048);
	if (debug_mode == "remote") {

		ScriptDebuggerRemote *sdr = memnew( ScriptDebuggerRemote );
		uint16_t debug_port = GLOBAL_DEF("debug/remote_port",6007);
		if (debug_host.find(":")!=-1) {
		    debug_port=debug_host.get_slicec(':',1).to_int();
		    debug_host=debug_host.get_slicec(':',0);
		}
		Error derr = sdr->connect_to_host(debug_host,debug_port);

		if (derr!=OK) {
			memdelete(sdr);
		} else {
			script_debugger=sdr;

		}
	} else if (debug_mode=="local") {

		script_debugger = memnew( ScriptDebuggerLocal );
	}


	if (remotefs!="") {

		file_access_network_client=memnew(FileAccessNetworkClient);
		int port;
		if (remotefs.find(":")!=-1) {
			port=remotefs.get_slicec(':',1).to_int();
			remotefs=remotefs.get_slicec(':',0);
		} else {
			port=6010;
		}

		Error err = file_access_network_client->connect(remotefs,port,remotefs_pass);
		if (err) {
			OS::get_singleton()->printerr("Could not connect to remotefs: %s:%i\n",remotefs.utf8().get_data(),port);
			goto error;
		}

		FileAccess::make_default<FileAccessNetwork>(FileAccess::ACCESS_RESOURCES);
	}
	if (script_debugger) {
		//there is a debugger, parse breakpoints

		for(int i=0;i<breakpoints.size();i++) {

			String bp = breakpoints[i];
			int sp=bp.find_last(":");
			if (sp==-1) {
				ERR_EXPLAIN("Invalid breakpoint: '"+bp+"', expected file:line format.");
				ERR_CONTINUE(sp==-1);
			}

			script_debugger->insert_breakpoint(bp.substr(sp+1,bp.length()).to_int(),bp.substr(0,sp));
		}
	}


#ifdef TOOLS_ENABLED
	if (editor) {
		packed_data->set_disabled(true);
		globals->set_disable_platform_override(true);
		StreamPeerSSL::initialize_certs=false; //will be initialized by editor
	}

#endif


	if (globals->setup(game_path,main_pack)!=OK) {

#ifdef TOOLS_ENABLED
		editor=false;
#else
		OS::get_singleton()->print("error: Couldn't load game path '%s'\n",game_path.ascii().get_data());

		goto error;
#endif
	}

	if (editor) {
		main_args.push_back("-editor");
		init_maximized=true;
		use_custom_res=false;
	}

	if (bool(Globals::get_singleton()->get("application/disable_stdout"))) {
		quiet_stdout=true;
	}
	if (bool(Globals::get_singleton()->get("application/disable_stderr"))) {
		_print_error_enabled = false;
	};

	if (quiet_stdout)
		_print_line_enabled=false;

	OS::get_singleton()->set_cmdline(execpath, main_args);

#ifdef TOOLS_ENABLED

	if (main_args.size()==0 && (!Globals::get_singleton()->has("application/main_loop_type")) && (!Globals::get_singleton()->has("application/main_scene") || String(Globals::get_singleton()->get("application/main_scene"))==""))
		use_custom_res=false; //project manager (run without arguments)

#endif

	input_map->load_from_globals();

	if (video_driver=="") // specified in engine.cfg
		video_driver=_GLOBAL_DEF("display/driver",Variant((const char*)OS::get_singleton()->get_video_driver_name(0)));

	if (!force_res && use_custom_res && globals->has("display/width"))
		video_mode.width=globals->get("display/width");
	if (!force_res &&use_custom_res && globals->has("display/height"))
		video_mode.height=globals->get("display/height");
	if (use_custom_res && globals->has("display/fullscreen"))
		video_mode.fullscreen=globals->get("display/fullscreen");
	if (use_custom_res && globals->has("display/resizable"))
		video_mode.resizable=globals->get("display/resizable");
	if (use_custom_res && globals->has("display/borderless_window"))
		video_mode.borderless_window = globals->get("display/borderless_window");

	if (!force_res && use_custom_res && globals->has("display/test_width") && globals->has("display/test_height")) {
		int tw = globals->get("display/test_width");
		int th = globals->get("display/test_height");
		if (tw>0 && th>0) {
			video_mode.width=tw;
			video_mode.height=th;
		}
	}


	GLOBAL_DEF("display/width",video_mode.width);
	GLOBAL_DEF("display/height",video_mode.height);
	GLOBAL_DEF("display/fullscreen",video_mode.fullscreen);
	GLOBAL_DEF("display/resizable",video_mode.resizable);
	GLOBAL_DEF("display/borderless_window", video_mode.borderless_window);
	GLOBAL_DEF("display/test_width",0);
	GLOBAL_DEF("display/test_height",0);
	OS::get_singleton()->_pixel_snap=GLOBAL_DEF("display/use_2d_pixel_snap",false);
	OS::get_singleton()->_keep_screen_on=GLOBAL_DEF("display/keep_screen_on",true);
	if (rtm==-1) {
		rtm=GLOBAL_DEF("render/thread_model",OS::RENDER_THREAD_SAFE);
		if (rtm>=1) //hack for now
			rtm=1;

	}

	if (rtm>=0 && rtm<3) {
		if (editor) {
			rtm=OS::RENDER_THREAD_SAFE;
		}
		OS::get_singleton()->_render_thread_mode=OS::RenderThreadMode(rtm);
	}



	/* Determine Video Driver */

	if (audio_driver=="") { // specified in engine.cfg
		audio_driver=GLOBAL_DEF("audio/driver",OS::get_singleton()->get_audio_driver_name(0));
	}


	for (int i=0;i<OS::get_singleton()->get_video_driver_count();i++) {

		if (video_driver==OS::get_singleton()->get_video_driver_name(i)) {

			video_driver_idx=i;
			break;
		}
	}

	if (video_driver_idx<0) {

		OS::get_singleton()->alert( "Invalid Video Driver: "+video_driver );
		video_driver_idx = 0;
		//goto error;
	}

	for (int i=0;i<OS::get_singleton()->get_audio_driver_count();i++) {

		if (audio_driver==OS::get_singleton()->get_audio_driver_name(i)) {

			audio_driver_idx=i;
			break;
		}
	}

	if (audio_driver_idx<0) {

		OS::get_singleton()->alert( "Invalid Audio Driver: "+audio_driver );
		audio_driver_idx = 0;
		//goto error;
	}

	{
		String orientation = GLOBAL_DEF("display/orientation","landscape");

		if (orientation=="portrait")
			OS::get_singleton()->set_screen_orientation(OS::SCREEN_PORTRAIT);
		else if (orientation=="reverse_landscape")
			OS::get_singleton()->set_screen_orientation(OS::SCREEN_REVERSE_LANDSCAPE);
		else if (orientation=="reverse_portrait")
			OS::get_singleton()->set_screen_orientation(OS::SCREEN_REVERSE_PORTRAIT);
		else if (orientation=="sensor_landscape")
			OS::get_singleton()->set_screen_orientation(OS::SCREEN_SENSOR_LANDSCAPE);
		else if (orientation=="sensor_portrait")
			OS::get_singleton()->set_screen_orientation(OS::SCREEN_SENSOR_PORTRAIT);
		else if (orientation=="sensor")
			OS::get_singleton()->set_screen_orientation(OS::SCREEN_SENSOR);
		else
			OS::get_singleton()->set_screen_orientation(OS::SCREEN_LANDSCAPE);
	}

	OS::get_singleton()->set_iterations_per_second(GLOBAL_DEF("physics/fixed_fps",60));
	OS::get_singleton()->set_target_fps(GLOBAL_DEF("application/target_fps",0));

	if (!OS::get_singleton()->_verbose_stdout) //overrided
		OS::get_singleton()->_verbose_stdout=GLOBAL_DEF("debug/verbose_stdout",false);

	message_queue = memnew( MessageQueue );

	Globals::get_singleton()->register_global_defaults();

	if (p_second_phase)
		return setup2();


	return OK;

	error:

	video_driver="";
	audio_driver="";
	game_path="";

	args.clear();
	main_args.clear();

	print_help(execpath);

	if (performance)
		memdelete(performance);
	if (input_map)
		memdelete(input_map);
	if (translation_server)
		memdelete( translation_server );
	if (globals)
		memdelete(globals);
	if (script_debugger)
		memdelete(script_debugger);
	if (packed_data)
		memdelete(packed_data);
	if (file_access_network_client)
		memdelete(file_access_network_client);
	if(path_remap)
		memdelete(path_remap);

// Note 1: *zip_packed_data live into *packed_data
// Note 2: PackedData::~PackedData destroy this.
//#ifdef MINIZIP_ENABLED
//	if (zip_packed_data)
//		memdelete( zip_packed_data );
//#endif

	unregister_core_driver_types();
	unregister_core_types();

	OS::get_singleton()->_cmdline.clear();

	if (message_queue)
		memdelete( message_queue);
	OS::get_singleton()->finalize_core();
	locale=String();

	return ERR_INVALID_PARAMETER;
}
예제 #23
0
	virtual Variant call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error) {

		//print_line("attempt to call "+String(p_method));

		r_error.error=Variant::CallError::CALL_OK;

		Map<StringName,MethodData >::Element *E=method_map.find(p_method);
		if (!E) {

			print_line("no exists");
			r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
			return Variant();
		}


		int ac = E->get().argtypes.size();
		if (ac<p_argcount) {

			print_line("fewargs");
			r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
			r_error.argument=ac;
			return Variant();
		}

		if (ac>p_argcount) {

			print_line("manyargs");
			r_error.error=Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
			r_error.argument=ac;
			return Variant();
		}



		for(int i=0;i<p_argcount;i++) {

			if (!Variant::can_convert(p_args[i]->get_type(),E->get().argtypes[i])) {

				r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
				r_error.argument=i;
				r_error.expected=E->get().argtypes[i];
			}
		}


		jvalue *v=NULL;

		if (p_argcount) {

			v=(jvalue*)alloca( sizeof(jvalue)*p_argcount );
		}

		JNIEnv *env = ThreadAndroid::get_env();

		//print_line("argcount "+String::num(p_argcount));
		for(int i=0;i<p_argcount;i++) {

			v[i] = _variant_to_jvalue(env, E->get().argtypes[i], p_args[i]);
		}

		//print_line("calling method!!");

		Variant ret;

		switch(E->get().ret_type) {

			case Variant::NIL: {


				//print_line("call void");
				env->CallVoidMethodA(instance,E->get().method,v);
			} break;
			case Variant::BOOL: {

				ret = env->CallBooleanMethodA(instance,E->get().method,v);
				//print_line("call bool");
			} break;
			case Variant::INT: {

				ret = env->CallIntMethodA(instance,E->get().method,v);
				//print_line("call int");
			} break;
			case Variant::REAL: {

				ret = env->CallFloatMethodA(instance,E->get().method,v);
			} break;
			case Variant::STRING: {

				jobject o = env->CallObjectMethodA(instance,E->get().method,v);
				String str = env->GetStringUTFChars((jstring)o, NULL );
				ret=str;
			} break;
			case Variant::STRING_ARRAY: {

				jobjectArray arr = (jobjectArray)env->CallObjectMethodA(instance,E->get().method,v);

				ret = _jobject_to_variant(env, arr);

			} break;
			case Variant::INT_ARRAY: {

				jintArray arr = (jintArray)env->CallObjectMethodA(instance,E->get().method,v);

				int fCount = env->GetArrayLength(arr);
				DVector<int> sarr;
				sarr.resize(fCount);

				DVector<int>::Write w = sarr.write();
				env->GetIntArrayRegion(arr,0,fCount,w.ptr());
				w = DVector<int>::Write();
				ret=sarr;
			} break;
			case Variant::REAL_ARRAY: {

				jfloatArray arr = (jfloatArray)env->CallObjectMethodA(instance,E->get().method,v);

				int fCount = env->GetArrayLength(arr);
				DVector<float> sarr;
				sarr.resize(fCount);

				DVector<float>::Write w = sarr.write();
				env->GetFloatArrayRegion(arr,0,fCount,w.ptr());
				w = DVector<float>::Write();
				ret=sarr;
			} break;

			case Variant::DICTIONARY: {

				//print_line("call dictionary");
				jobject obj = env->CallObjectMethodA(instance, E->get().method, v);
				ret = _jobject_to_variant(env, obj);

			} break;
			default: {


				print_line("failure..");
				ERR_FAIL_V(Variant());
			} break;
		}

		//print_line("success");

		return ret;
	}
예제 #24
0
파일: main.cpp 프로젝트: BradWBeer/godot
bool Main::start() {

	ERR_FAIL_COND_V(!_start_success,false);

	bool editor=false;
	String doc_tool;
	bool doc_base=true;
	String game_path;
	String script;
	String test;
	String screen;
	String optimize;
	String optimize_preset;
	String _export_platform;
	String _import;
	String _import_script;
	String dumpstrings;
	bool noquit=false;
	bool convert_old=false;
	bool export_debug=false;
	bool project_manager_request = false;
	List<String> args = OS::get_singleton()->get_cmdline_args();
	for (int i=0;i<args.size();i++) {
		//parameters that do not have an argument to the right
		if (args[i]=="-nodocbase") {
			doc_base=false;
		} else if (args[i]=="-noquit") {
			noquit=true;
		} else if (args[i]=="-convert_old") {
			convert_old=true;
		} else if (args[i]=="-editor" || args[i]=="-e") {
			editor=true;
		} else if (args[i] == "-pm" || args[i] == "-project_manager") {
			project_manager_request = true;
		} else if (args[i].length() && args[i][0] != '-' && game_path == "") {
			game_path=args[i];
		}
		//parameters that have an argument to the right
		else if (i < (args.size()-1)) {
			bool parsed_pair=true;
			if (args[i]=="-doctool") {
				doc_tool=args[i+1];
			} else if (args[i]=="-script" || args[i]=="-s") {
				script=args[i+1];
			} else if (args[i]=="-level" || args[i]=="-l") {
				OS::get_singleton()->_custom_level=args[i+1];
			} else if (args[i]=="-test") {
				test=args[i+1];
			} else if (args[i]=="-optimize") {
				optimize=args[i+1];
			} else if (args[i]=="-optimize_preset") {
				optimize_preset=args[i+1];
			} else if (args[i]=="-export") {
				editor=true; //needs editor
				_export_platform=args[i+1];
			} else if (args[i]=="-export_debug") {
				editor=true; //needs editor
				_export_platform=args[i+1];
				export_debug=true;
			} else if (args[i]=="-import") {
				editor=true; //needs editor
				_import=args[i+1];
			} else if (args[i]=="-import_script") {
				editor=true; //needs editor
				_import_script=args[i+1];
			} else if (args[i]=="-dumpstrings") {
				editor=true; //needs editor
				dumpstrings=args[i+1];
			} else {
				// The parameter does not match anything known, don't skip the next argument
				parsed_pair=false;
			}
			if (parsed_pair) {
				i++;
			}
		}
	}

	if (editor)
		Globals::get_singleton()->set("editor_active",true);


	String main_loop_type;
#ifdef TOOLS_ENABLED
	if(doc_tool!="") {

		DocData doc;
		doc.generate(doc_base);

		DocData docsrc;
		if (docsrc.load(doc_tool)==OK) {
			print_line("Doc exists. Merging..");
			doc.merge_from(docsrc);
		} else {
			print_line("No Doc exists. Generating empty.");

		}

		doc.save(doc_tool);

		return false;
	}

	if (optimize!="")
		editor=true; //need editor



#endif

	if (_export_platform!="") {
		if (game_path=="") {
			String err="Command line param ";
			err+=export_debug?"-export_debug":"-export";
			err+=" passed but no destination path given.\n";
			err+="Please specify the binary's file path to export to. Aborting export.";
			ERR_PRINT(err.utf8().get_data());
			return false;
		}
	}

	if(script=="" && game_path=="" && String(GLOBAL_DEF("application/main_scene",""))!="") {
		game_path=GLOBAL_DEF("application/main_scene","");
	}


	MainLoop *main_loop=NULL;
	if (editor) {
		main_loop = memnew(SceneTree);
	};

	if (test!="") {
#ifdef DEBUG_ENABLED
		main_loop = test_main(test,args);

		if (!main_loop)
			return false;

#endif

	} else if (script!="") {

		Ref<Script> script_res = ResourceLoader::load(script);
		ERR_EXPLAIN("Can't load script: "+script);
		ERR_FAIL_COND_V(script_res.is_null(),false);

		if( script_res->can_instance() /*&& script_res->inherits_from("SceneTreeScripted")*/) {


			StringName instance_type=script_res->get_instance_base_type();
			Object *obj = ObjectTypeDB::instance(instance_type);
			MainLoop *script_loop = obj?obj->cast_to<MainLoop>():NULL;
			if (!script_loop) {
				if (obj)
					memdelete(obj);
				ERR_EXPLAIN("Can't load script '"+script+"', it does not inherit from a MainLoop type");
				ERR_FAIL_COND_V(!script_loop,false);
			}


			script_loop->set_init_script(script_res);
			main_loop=script_loop;
		} else {

			return false;
		}

	} else {
		main_loop_type=GLOBAL_DEF("application/main_loop_type","");
	}

	if (!main_loop && main_loop_type=="")
		main_loop_type="SceneTree";

	if (!main_loop) {
		if (!ObjectTypeDB::type_exists(main_loop_type)) {
			OS::get_singleton()->alert("godot: error: MainLoop type doesn't exist: "+main_loop_type);
			return false;
		} else {

			Object *ml = ObjectTypeDB::instance(main_loop_type);
			if (!ml) {
				ERR_EXPLAIN("Can't instance MainLoop type");
				ERR_FAIL_V(false);
			}

			main_loop=ml->cast_to<MainLoop>();
			if (!main_loop) {

				memdelete(ml);
				ERR_EXPLAIN("Invalid MainLoop type");
				ERR_FAIL_V(false);

			}
		}
	}

	if (main_loop->is_type("SceneTree")) {

		SceneTree *sml = main_loop->cast_to<SceneTree>();

		if (debug_collisions) {
			sml->set_debug_collisions_hint(true);
		}
		if (debug_navigation) {
			sml->set_debug_navigation_hint(true);
		}
#ifdef TOOLS_ENABLED


		EditorNode *editor_node=NULL;
		if (editor) {

			editor_node = memnew( EditorNode );
			sml->get_root()->add_child(editor_node);

			//root_node->set_editor(editor);
			//startup editor

			if (_export_platform!="") {

				editor_node->export_platform(_export_platform,game_path,export_debug,"",true);
				game_path=""; //no load anything
			}
		}
#endif

		if (!editor) {
			//standard helpers that can be changed from main config

			String stretch_mode = GLOBAL_DEF("display/stretch_mode","disabled");
			String stretch_aspect = GLOBAL_DEF("display/stretch_aspect","ignore");
			Size2i stretch_size = Size2(GLOBAL_DEF("display/width",0),GLOBAL_DEF("display/height",0));

			SceneTree::StretchMode sml_sm=SceneTree::STRETCH_MODE_DISABLED;
			if (stretch_mode=="2d")
				sml_sm=SceneTree::STRETCH_MODE_2D;
			else if (stretch_mode=="viewport")
				sml_sm=SceneTree::STRETCH_MODE_VIEWPORT;

			SceneTree::StretchAspect sml_aspect=SceneTree::STRETCH_ASPECT_IGNORE;
			if (stretch_aspect=="keep")
				sml_aspect=SceneTree::STRETCH_ASPECT_KEEP;
			else if (stretch_aspect=="keep_width")
				sml_aspect=SceneTree::STRETCH_ASPECT_KEEP_WIDTH;
			else if (stretch_aspect=="keep_height")
				sml_aspect=SceneTree::STRETCH_ASPECT_KEEP_HEIGHT;

			sml->set_screen_stretch(sml_sm,sml_aspect,stretch_size);

			sml->set_auto_accept_quit(GLOBAL_DEF("application/auto_accept_quit",true));
			String appname = Globals::get_singleton()->get("application/name");
			appname = TranslationServer::get_singleton()->translate(appname);
			OS::get_singleton()->set_window_title(appname);


		} else {
			GLOBAL_DEF("display/stretch_mode","disabled");
			Globals::get_singleton()->set_custom_property_info("display/stretch_mode",PropertyInfo(Variant::STRING,"display/stretch_mode",PROPERTY_HINT_ENUM,"disabled,2d,viewport"));
			GLOBAL_DEF("display/stretch_aspect","ignore");
			Globals::get_singleton()->set_custom_property_info("display/stretch_aspect",PropertyInfo(Variant::STRING,"display/stretch_aspect",PROPERTY_HINT_ENUM,"ignore,keep,keep_width,keep_height"));
			sml->set_auto_accept_quit(GLOBAL_DEF("application/auto_accept_quit",true));


		}


		if (game_path!="" && !project_manager_request) {

			String local_game_path=game_path.replace("\\","/");

			if (!local_game_path.begins_with("res://")) {
				bool absolute=(local_game_path.size()>1) && (local_game_path[0]=='/' || local_game_path[1]==':');

				if (!absolute) {

					if (Globals::get_singleton()->is_using_datapack()) {

						local_game_path="res://"+local_game_path;

					} else {
						int sep=local_game_path.find_last("/");

						if (sep==-1) {
							DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
							local_game_path=da->get_current_dir()+"/"+local_game_path;
							memdelete(da)						;
						} else {

							DirAccess *da = DirAccess::open(local_game_path.substr(0,sep));
							if (da) {
								local_game_path=da->get_current_dir()+"/"+local_game_path.substr(sep+1,local_game_path.length());;
								memdelete(da);
							}
						}
					}

				}
			}

			local_game_path=Globals::get_singleton()->localize_path(local_game_path);

#ifdef TOOLS_ENABLED
			if (editor) {


				if (_import!="") {

					//editor_node->import_scene(_import,local_game_path,_import_script);
					if (!noquit)
						sml->quit();
					game_path=""; //no load anything
				} else {

					Error serr = editor_node->load_scene(local_game_path);

					if (serr==OK) {

						if (optimize!="") {

							editor_node->save_optimized_copy(optimize,optimize_preset);
							if (!noquit)
								sml->quit();
						}

						if (dumpstrings!="") {

							editor_node->save_translatable_strings(dumpstrings);
							if (!noquit)
								sml->quit();
						}
					}
				}
				OS::get_singleton()->set_context(OS::CONTEXT_EDITOR);

				//editor_node->set_edited_scene(game);
			} else {
#endif

				{
					//autoload
					List<PropertyInfo> props;
					Globals::get_singleton()->get_property_list(&props);

					//first pass, add the constants so they exist before any script is loaded
					for(List<PropertyInfo>::Element *E=props.front();E;E=E->next()) {

						String s = E->get().name;
						if (!s.begins_with("autoload/"))
							continue;
						String name = s.get_slicec('/',1);
						String path = Globals::get_singleton()->get(s);
						bool global_var=false;
						if (path.begins_with("*")) {
							global_var=true;
						}

						if (global_var) {
							for(int i=0;i<ScriptServer::get_language_count();i++) {
								ScriptServer::get_language(i)->add_global_constant(name,Variant());
							}
						}

					}

					//second pass, load into global constants
					List<Node*> to_add;
					for(List<PropertyInfo>::Element *E=props.front();E;E=E->next()) {

						String s = E->get().name;
						if (!s.begins_with("autoload/"))
							continue;
						String name = s.get_slicec('/',1);
						String path = Globals::get_singleton()->get(s);
						bool global_var=false;
						if (path.begins_with("*")) {
							global_var=true;
							path=path.substr(1,path.length()-1);
						}

						RES res = ResourceLoader::load(path);
						ERR_EXPLAIN("Can't autoload: "+path);
						ERR_CONTINUE(res.is_null());
						Node *n=NULL;
						if (res->is_type("PackedScene")) {
							Ref<PackedScene> ps = res;
							n=ps->instance();
						} else if (res->is_type("Script")) {
							Ref<Script> s = res;
							StringName ibt = s->get_instance_base_type();
							bool valid_type = ObjectTypeDB::is_type(ibt,"Node");
							ERR_EXPLAIN("Script does not inherit a Node: "+path);
							ERR_CONTINUE( !valid_type );

							Object *obj = ObjectTypeDB::instance(ibt);

							ERR_EXPLAIN("Cannot instance script for autoload, expected 'Node' inheritance, got: "+String(ibt));
							ERR_CONTINUE( obj==NULL );

							n = obj->cast_to<Node>();
							n->set_script(s.get_ref_ptr());
						}

						ERR_EXPLAIN("Path in autoload not a node or script: "+path);
						ERR_CONTINUE(!n);
						n->set_name(name);

						//defer so references are all valid on _ready()
						//sml->get_root()->add_child(n);
						to_add.push_back(n);

						if (global_var) {
							for(int i=0;i<ScriptServer::get_language_count();i++) {
								ScriptServer::get_language(i)->add_global_constant(name,n);
							}
						}

					}

					for(List<Node*>::Element *E=to_add.front();E;E=E->next()) {

						sml->get_root()->add_child(E->get());
					}



				}

				Node *scene=NULL;
				Ref<PackedScene> scenedata = ResourceLoader::load(local_game_path);
				if (scenedata.is_valid())
					scene=scenedata->instance();

				ERR_EXPLAIN("Failed loading scene: "+local_game_path);
				ERR_FAIL_COND_V(!scene,false)
				//sml->get_root()->add_child(scene);
				sml->add_current_scene(scene);

				String iconpath = GLOBAL_DEF("application/icon","Variant()""");
				if (iconpath!="") {
					Image icon;
					if (icon.load(iconpath)==OK)
						OS::get_singleton()->set_icon(icon);
				}


				//singletons
#ifdef TOOLS_ENABLED
			}
#endif
		}

#ifdef TOOLS_ENABLED

		/*if (_export_platform!="") {

			sml->quit();
		}*/

		/*
		if (sml->get_root_node()) {

			Console *console = memnew( Console );

			sml->get_root_node()->cast_to<RootNode>()->set_console(console);
			if (GLOBAL_DEF("console/visible_default",false).operator bool()) {

				console->show();
			} else {P

				console->hide();
			};
		}
*/
		if (project_manager_request || (script=="" && test=="" && game_path=="" && !editor)) {

			ProjectManager *pmanager = memnew( ProjectManager );
			sml->get_root()->add_child(pmanager);
			OS::get_singleton()->set_context(OS::CONTEXT_PROJECTMAN);
		}

#endif
	}

	OS::get_singleton()->set_main_loop( main_loop );

	return true;
}
예제 #25
0
MonoArray *godot_icall_String_sha256_buffer(MonoString *p_str) {
	Vector<uint8_t> ret = GDMonoMarshal::mono_string_to_godot(p_str).sha256_buffer();
	return GDMonoMarshal::Array_to_mono_array(Variant(ret));
}
예제 #26
0
int main(int argc, char* argv[])
#endif
{  

#ifdef CAESARIA_USE_STEAM
  if( !steamapi::Handler::checkSteamRunning() )
    return EXIT_FAILURE;

  if( !steamapi::Handler::init() )
    return EXIT_FAILURE;
#endif

  vfs::Directory workdir;
#ifdef CAESARIA_PLATFORM_ANDROID
  workdir  = vfs::Path( SDL_AndroidGetExternalStoragePath() );
#else
  workdir = vfs::Path( argv[0] ).directory();
#endif
  Logger::registerWriter( Logger::consolelog, "" );

  Logger::warning( "Options: working directory is " + workdir.toString() );

  GameSettings::instance().setwdir( workdir.toString() );
  for (int i = 0; i < (argc - 1); i++)
  {
    if( !strcmp( argv[i], "-R" ) )
    {
      const char* opts = argv[i+1];
      workdir = vfs::Path( opts );
      Logger::warning( "Options: setting workdir to %s", opts  );
      GameSettings::instance().setwdir( std::string( opts, strlen( opts ) ) );
      i++;
    }
    else if( !strcmp( argv[i], "-Lc" ) )
    {
      const char* opts = argv[i+1];
      Logger::warning( "Options: setting language to %s", opts );
      GameSettings::set( GameSettings::language, Variant( opts ) );
      i++;
    }
    else if( !strcmp( argv[i], "-c3gfx" ) )
    {
      const char* opts = argv[i+1];
      Logger::warning( "Options: using native C3 resources from %s", opts );
      GameSettings::set( GameSettings::c3gfx, Variant( opts ) );
      i++;
    }
  }

  Logger::registerWriter( Logger::filelog, workdir.toString() );

  try
  {
    Game game;
    game.initialize();
    while( game.exec() );
  }
  catch( Exception& e )
  {
    Logger::warning( "Critical error: " + e.getDescription() );
    Stacktrace::print();
  }

#ifdef CAESARIA_USE_STEAM
  steamapi::Handler::close();
#endif

  return 0;
}
예제 #27
0
Variant php_mysql_do_connect_on_link(std::shared_ptr<MySQL> mySQL,
                                     String server, String username,
                                     String password, String database,
                                     int client_flags, bool persistent,
                                     bool async, int connect_timeout_ms,
                                     int query_timeout_ms) {
  if (connect_timeout_ms < 0) {
    connect_timeout_ms = mysqlExtension::ConnectTimeout;
  }
  if (query_timeout_ms < 0) {
    query_timeout_ms = MySQL::GetDefaultReadTimeout();
  }
  if (server.empty()) server = MySQL::GetDefaultServer();
  if (username.empty()) username = MySQL::GetDefaultUsername();
  if (password.empty()) password = MySQL::GetDefaultPassword();
  if (database.empty()) database = MySQL::GetDefaultDatabase();

  // server format: hostname[:port][:/path/to/socket]
  // ipv6 hostname:port is of the form [1:2:3:4:5]:port
  String host, socket;
  int port;
  int savePersistent = false;

  auto slash_pos = server.find('/');
  if (slash_pos != std::string::npos) {
    socket = server.substr(slash_pos);
    server = server.substr(0, slash_pos - 1);
  }

  HostURL hosturl(std::string(server), MySQL::GetDefaultPort());
  if (hosturl.isValid()) {
    host = hosturl.getHost();
    port = hosturl.getPort();
  } else {
    host = server;
    port = MySQL::GetDefaultPort();
  }

  if (socket.empty()) {
    socket = MySQL::GetDefaultSocket();
  }

  if (MySQL::IsAllowPersistent() &&
      MySQL::GetCurrentNumPersistent() < MySQL::GetMaxNumPersistent() &&
      persistent) {
    auto p_mySQL = MySQL::GetPersistent(host, port, socket, username,
                                        password, client_flags);

    if (p_mySQL != nullptr) {
      mySQL = p_mySQL;
    } else {
      savePersistent = true;
    }
  }

  if (mySQL == nullptr) {
    mySQL = std::make_shared<MySQL>(host.c_str(), port, username.c_str(),
                                    password.c_str(), database.c_str());
  }

  if (mySQL->getState() == MySQLState::INITED) {
    if (async) {
#ifdef FACEBOOK
      if (!mySQL->async_connect(host, port, socket, username, password,
                                database)) {
        MySQL::SetDefaultConn(mySQL); // so we can report errno by mysql_errno()
        mySQL->setLastError("mysql_real_connect_nonblocking_init");
        return false;
      }
#else
      throw_not_implemented("mysql_async_connect_start");
#endif
    } else {
      if (!mySQL->connect(host, port, socket, username, password,
                          database, client_flags, connect_timeout_ms)) {
        MySQL::SetDefaultConn(mySQL); // so we can report errno by mysql_errno()
        mySQL->setLastError("mysql_connect");
        return false;
      }
    }
  } else {
    if (!MySQL::IsAllowReconnect()) {
      raise_warning("MySQL: Reconnects are not allowed");
      return false;
    }
    if (!mySQL->reconnect(host, port, socket, username, password,
                          database, client_flags, connect_timeout_ms)) {
      MySQL::SetDefaultConn(mySQL); // so we can report errno by mysql_errno()
      mySQL->setLastError("mysql_connect");
      return false;
    }
  }

  if (savePersistent) {
    MySQL::SetPersistent(host, port, socket, username, password,
                         client_flags, mySQL);
    MySQL::SetCurrentNumPersistent(MySQL::GetCurrentNumPersistent() + 1);
  }
  MySQL::SetDefaultConn(mySQL);
  return Variant(req::make<MySQLResource>(mySQL));
}
예제 #28
0
		bool	Parser::parseValue (Lexer& lexer, Lookup& lookup, Int32u* slot, const Extractor** output)
		{
			const Extractor*	argument;
			Extractors			arguments;
			const Constant*		constant;
			const Function*		function;
			string				name;
			Float64				number;

			switch (lexer.getType ())
			{
				case Lexer::IDENTIFIER:
					name = lexer.getCurrent ();

					lexer.next ();

					if (lexer.getType () == Lexer::PARENTHESIS_BEGIN)
					{
						function = 0;

						for (Int32u i = 0; Function::functions[i].name; ++i)
						{
							if (Function::functions[i].name == name)
							{
								function = &Function::functions[i];

								break;
							}
						}

						if (!function)
							return this->fail (lexer, string ("unknown function name '") + lexer.getCurrent () + "'");

						lexer.next ();

						while (lexer.getType () != Lexer::PARENTHESIS_END)
						{
							if (arguments.size () > 0 && !this->parseType (lexer, Lexer::COMMA, "argument separator"))
								return false;

							if (!this->parseExpression (lexer, lookup, slot, &argument))
								return false;

							arguments.push_back (argument);
						}

						lexer.next ();

						if (arguments.size () < function->min || (function->max > 0 && arguments.size () > function->max))
							return this->fail (lexer, "wrong number of arguments");

						*output = function->builder (arguments, slot);
					}
					else
					{
						constant = 0;

						for (Int32u i = 0; Constant::constants[i].name; ++i)
						{
							if (Constant::constants[i].name == name)
							{
								constant = &Constant::constants[i];

								break;
							}
						}

						if (constant)
							*output = new ConstantExtractor (constant->value);
						else
							*output = new FieldExtractor (lookup.store (name));
					}

					break;

				case Lexer::NUMBER:
					if (!Convert::toFloat (&number, lexer.getCurrent ().data (), lexer.getCurrent ().length ()))
						return this->fail (lexer, "invalid number");

					*output = new ConstantExtractor (Variant (number));

					lexer.next ();

					break;

				case Lexer::STRING:
					*output = new ConstantExtractor (Variant (lexer.getCurrent ()));

					lexer.next ();

					break;

				default:
					this->fail (lexer, "unexpected character");

					return false;
			}

			this->extractors.push_back (*output);

			return true;
		}
예제 #29
0
void GDTokenizerText::_advance() {

	if (error_flag) {
		//parser broke
		_make_error(last_error);
		return;
	}

	if (code_pos>=len) {
		_make_token(TK_EOF);
		return;
	}
#define GETCHAR(m_ofs) ((m_ofs+code_pos)>=len?0:_code[m_ofs+code_pos])
#define INCPOS(m_amount) { code_pos+=m_amount; column+=m_amount; }
	while (true) {


		bool is_node_path=false;

		switch(GETCHAR(0)) {
			case 0:
				_make_token(TK_EOF);
				break;
			case '\\':
				INCPOS(1);
				if (GETCHAR(0)=='\r') {
					INCPOS(1);
				}

				if (GETCHAR(0)!='\n') {
					_make_error("Expected newline after '\\'.");
					return;
				}

				INCPOS(1);

				while(GETCHAR(0)==' ' || GETCHAR(0)=='\t') {
					INCPOS(1);
				}

				continue;
			case '\t':
			case '\r':
			case ' ':
				INCPOS(1);
				continue;
			case '\n': {
				line++;
				INCPOS(1);
				column=0;
				int i=0;
				while(GETCHAR(i)==' ' || GETCHAR(i)=='\t') {
					i++;
				}

				_make_newline(i);
				return;
			}
#if 1 //py style tokenizer
			case '#': { // line comment skip

				while(GETCHAR(0)!='\n') {
					code_pos++;
					if (GETCHAR(0)==0) { //end of file
						_make_error("Unterminated Comment");
						return;
					}
				}
				INCPOS(1);
				column=0;
				line++;
				int i=0;
				while(GETCHAR(i)==' ' || GETCHAR(i)=='\t') {
					i++;
				}
				_make_newline(i);
				return;

			} break;
#endif
			case '/': {

				switch(GETCHAR(1)) {
#if 0 // c style tokenizer
					case '*': { // block comment
						int pos = code_pos+2;
						int new_line=line;
						int new_col=column+2;

						while(true) {
							if (_code[pos]=='0') {
								_make_error("Unterminated Comment");
								code_pos=pos;
								return;
							}
							if (_code[pos]=='*' && _code[pos+1]=='/') {
								new_col+=2;
								pos+=2; //compensate
								break;
							} else if (_code[pos]=='\n') {
								new_line++;
								new_col=0;
							} else {
								new_col++;
							}
							pos++;
						}

						column=new_col;
						line=new_line;
						code_pos=pos;
						continue;

					} break;
					case '/': { // line comment skip

						while(GETCHAR(0)!='\n') {
							code_pos++;
							if (GETCHAR(0)==0) { //end of file
								_make_error("Unterminated Comment");
								return;
							}
						}
						INCPOS(1);
						column=0;
						line++;
						continue;

					} break;
#endif
					case '=': { // diveq

						_make_token(TK_OP_ASSIGN_DIV);
						INCPOS(1);

					} break;
					default:
						_make_token(TK_OP_DIV);

				}
			} break;
			case '=': {
				if (GETCHAR(1)=='=') {
					_make_token(TK_OP_EQUAL);
					INCPOS(1);

				} else
					_make_token(TK_OP_ASSIGN);

			} break;
			case '<': {
				if (GETCHAR(1)=='=') {

					_make_token(TK_OP_LESS_EQUAL);
					INCPOS(1);
				} else if (GETCHAR(1)=='<') {
					if (GETCHAR(2)=='=') {
						_make_token(TK_OP_ASSIGN_SHIFT_LEFT);
						INCPOS(1);
					} else {
						_make_token(TK_OP_SHIFT_LEFT);
					}
					INCPOS(1);
				} else
					_make_token(TK_OP_LESS);

			} break;
			case '>': {
				if (GETCHAR(1)=='=') {
					_make_token(TK_OP_GREATER_EQUAL);
					INCPOS(1);
				} else if (GETCHAR(1)=='>') {
					if (GETCHAR(2)=='=') {
						_make_token(TK_OP_ASSIGN_SHIFT_RIGHT);
						INCPOS(1);

					} else {
						_make_token(TK_OP_SHIFT_RIGHT);
					}
					INCPOS(1);
				} else {
					_make_token(TK_OP_GREATER);
				}

			} break;
			case '!': {
				if (GETCHAR(1)=='=') {
					_make_token(TK_OP_NOT_EQUAL);
					INCPOS(1);
				} else {
					_make_token(TK_OP_NOT);
				}

			} break;
			//case '"' //string - no strings in shader
			//case '\'' //string - no strings in shader
			case '{':
				_make_token(TK_CURLY_BRACKET_OPEN);
				break;
			case '}':
				_make_token(TK_CURLY_BRACKET_CLOSE);
				break;
			case '[':
				_make_token(TK_BRACKET_OPEN);
				break;
			case ']':
				_make_token(TK_BRACKET_CLOSE);
				break;
			case '(':
				_make_token(TK_PARENTHESIS_OPEN);
				break;
			case ')':
				_make_token(TK_PARENTHESIS_CLOSE);
				break;
			case ',':
				_make_token(TK_COMMA);
				break;
			case ';':
				_make_token(TK_SEMICOLON);
				break;
			case '?':
				_make_token(TK_QUESTION_MARK);
				break;
			case ':':
				_make_token(TK_COLON); //for methods maybe but now useless.
				break;
			case '^': {
				if (GETCHAR(1)=='=') {
					_make_token(TK_OP_ASSIGN_BIT_XOR);
					INCPOS(1);
				} else {
					_make_token(TK_OP_BIT_XOR);
				}

			} break;
			case '~':
				_make_token(TK_OP_BIT_INVERT);
				break;
			case '&': {
				if (GETCHAR(1)=='&') {

					_make_token(TK_OP_AND);
					INCPOS(1);
				} else if (GETCHAR(1)=='=') {
					_make_token(TK_OP_ASSIGN_BIT_AND);
					INCPOS(1);
				} else {
					_make_token(TK_OP_BIT_AND);
				}
			} break;
			case '|': {
				if (GETCHAR(1)=='|') {

					_make_token(TK_OP_OR);
					INCPOS(1);
				} else if (GETCHAR(1)=='=') {
					_make_token(TK_OP_ASSIGN_BIT_OR);
					INCPOS(1);
				} else {
					_make_token(TK_OP_BIT_OR);
				}
			} break;
			case '*': {

				if (GETCHAR(1)=='=') {
					_make_token(TK_OP_ASSIGN_MUL);
					INCPOS(1);
				} else {
					_make_token(TK_OP_MUL);
				}
			} break;
			case '+': {

				if (GETCHAR(1)=='=') {
					_make_token(TK_OP_ASSIGN_ADD);
					INCPOS(1);
				//}  else if (GETCHAR(1)=='+') {
				//	_make_token(TK_OP_PLUS_PLUS);
				//	INCPOS(1);
				} else {
					_make_token(TK_OP_ADD);
				}

			} break;
			case '-': {

				if (GETCHAR(1)=='=') {
					_make_token(TK_OP_ASSIGN_SUB);
					INCPOS(1);
				//}  else if (GETCHAR(1)=='-') {
				//	_make_token(TK_OP_MINUS_MINUS);
				//	INCPOS(1);
				} else {
					_make_token(TK_OP_SUB);
				}
			} break;
			case '%': {

				if (GETCHAR(1)=='=') {
					_make_token(TK_OP_ASSIGN_MOD);
					INCPOS(1);
				} else {
					_make_token(TK_OP_MOD);
				}
			} break;
			case '@':
				if (CharType(GETCHAR(1))!='"') {
					_make_error("Unexpected '@'");
					return;
				}
				INCPOS(1);
				is_node_path=true;
			case '"': {

				int i=1;
				String str;
				while(true) {
					if (CharType(GETCHAR(i)==0)) {

						_make_error("Unterminated String");
						return;
					} else if (CharType(GETCHAR(i)=='"')) {
						break;
					} else if (CharType(GETCHAR(i)=='\\')) {
						//escaped characters...
						i++;
						CharType next = GETCHAR(i);
						if (next==0) {
							_make_error("Unterminated String");
							return;
						}
						CharType res=0;

						switch(next) {

							case 'a': res=7; break;
							case 'b': res=8; break;
							case 't': res=9; break;
							case 'n': res=10; break;
							case 'v': res=11; break;
							case 'f': res=12; break;
							case 'r': res=13; break;
							case '\'': res='\''; break;
							case '\"': res='\"'; break;
							case '\\': res='\\'; break;
							case 'x': {
								//hexnumbarh - oct is deprecated

								int read=0;
								for(int j=0;j<4;j++) {
									CharType c = GETCHAR(i+j);
									if (c==0) {
										_make_error("Unterminated String");
										return;
									}
									if (!_is_hex(c)) {
										if (j==0 || !(j&1)) {
											_make_error("Malformed hex constant in string");
											return;
										} else
											break;
									}
									CharType v;
									if (c>='0' && c<='9') {
										v=c-'0';
									} else if (c>='a' && c<='f') {
										v=c-'a';
										v+=10;
									} else if (c>='A' && c<='F') {
										v=c-'A';
										v+=10;
									} else {
										ERR_PRINT("BUG");
										v=0;
									}

									res<<=4;
									res|=v;

									read++;
								}
								i+=read-1;


							} break;
							default: {

								_make_error("Invalid escape sequence");
								return;
							} break;
						}

						str+=res;

					} else {
						str+=CharType(GETCHAR(i));
					}
					i++;
				}
				INCPOS(i);

				if (is_node_path) {
					_make_constant(NodePath(str));
				} else {
					_make_constant(str);
				}

			} break;
			default: {

				if (_is_number(GETCHAR(0)) || (GETCHAR(0)=='.' && _is_number(GETCHAR(1)))) {
					// parse number
					bool period_found=false;
					bool exponent_found=false;
					bool hexa_found=false;
					bool sign_found=false;

					String str;
					int i=0;

					while(true) {
						if (GETCHAR(i)=='.') {
							if (period_found || exponent_found) {
                                _make_error("Invalid numeric constant at '.'");
								return;
							}
							period_found=true;
						} else if (GETCHAR(i)=='x') {
                            if (hexa_found || str.length()!=1 || !( (i==1 && str[0]=='0') || (i==2 && str[1]=='0' && str[0]=='-') ) ) {
                                _make_error("Invalid numeric constant at 'x'");
								return;
							}
							hexa_found=true;
                        } else if (!hexa_found && GETCHAR(i)=='e') {
							if (hexa_found || exponent_found) {
                                _make_error("Invalid numeric constant at 'e'");
								return;
							}
							exponent_found=true;
						} else if (_is_number(GETCHAR(i))) {
							//all ok
						} else if (hexa_found && _is_hex(GETCHAR(i))) {

						} else if ((GETCHAR(i)=='-' || GETCHAR(i)=='+') && exponent_found) {
							if (sign_found) {
                                _make_error("Invalid numeric constant at '-'");
								return;
							}
							sign_found=true;
						} else
							break;

						str+=CharType(GETCHAR(i));
						i++;
					}

                    if (!( _is_number(str[str.length()-1]) || (hexa_found && _is_hex(str[str.length()-1])))) {
                        _make_error("Invalid numeric constant: "+str);
						return;
					}

					INCPOS(str.length());
                    if (hexa_found) {
                        int val = str.hex_to_int();
                        _make_constant(val);
                    } else if (period_found) {
						real_t val = str.to_double();
						//print_line("*%*%*%*% to convert: "+str+" result: "+rtos(val));
						_make_constant(val);
                    } else {
						int val = str.to_int();
						_make_constant(val);

					}

					return;
				}

				if (GETCHAR(0)=='.') {
					//parse period
					_make_token(TK_PERIOD);
					break;
				}

				if (_is_text_char(GETCHAR(0))) {
					// parse identifier
					String str;
					str+=CharType(GETCHAR(0));

					int i=1;
					while(_is_text_char(GETCHAR(i))) {
						str+=CharType(GETCHAR(i));
						i++;
					}

					bool identifier=false;

					if (str=="null") {
						_make_constant(Variant());

					} else if (str=="true") {
						_make_constant(true);

					} else if (str=="false") {
						_make_constant(false);
					} else {

						bool found=false;

						struct _bit { Variant::Type type; const char *text;};
						//built in types

						static const  _bit type_list[]={
							//types
							{Variant::BOOL,"bool"},
							{Variant::INT,"int"},
							{Variant::REAL,"float"},
							{Variant::STRING,"String"},
							{Variant::VECTOR2,"vec2"},
							{Variant::VECTOR2,"Vector2"},
							{Variant::RECT2,"Rect2"},
							{Variant::MATRIX32,"Matrix32"},
							{Variant::MATRIX32,"mat32"},
							{Variant::VECTOR3,"vec3"},
							{Variant::VECTOR3,"Vector3"},
							{Variant::_AABB,"AABB"},
							{Variant::_AABB,"Rect3"},
							{Variant::PLANE,"Plane"},
							{Variant::QUAT,"Quat"},
							{Variant::MATRIX3,"mat3"},
							{Variant::MATRIX3,"Matrix3"},
							{Variant::TRANSFORM,"trn"},
							{Variant::TRANSFORM,"Transform"},
							{Variant::COLOR,"Color"},
							{Variant::IMAGE,"Image"},
							{Variant::_RID,"RID"},
							{Variant::OBJECT,"Object"},
							{Variant::INPUT_EVENT,"InputEvent"},
							{Variant::NODE_PATH,"NodePath"},
							{Variant::DICTIONARY,"dict"},
							{Variant::DICTIONARY,"Dictionary"},
							{Variant::ARRAY,"Array"},
							{Variant::RAW_ARRAY,"RawArray"},
							{Variant::INT_ARRAY,"IntArray"},
							{Variant::REAL_ARRAY,"FloatArray"},
							{Variant::STRING_ARRAY,"StringArray"},
							{Variant::VECTOR2_ARRAY,"Vector2Array"},
							{Variant::VECTOR3_ARRAY,"Vector3Array"},
							{Variant::COLOR_ARRAY,"ColorArray"},
							{Variant::VARIANT_MAX,NULL},
						};

						{


							int idx=0;

							while(type_list[idx].text) {

								if (str==type_list[idx].text) {
									_make_type(type_list[idx].type);
									found=true;
									break;
								}
								idx++;
							}
						}

						if (!found) {

							//built in func?

							for(int i=0;i<GDFunctions::FUNC_MAX;i++) {

								if (str==GDFunctions::get_func_name(GDFunctions::Function(i))) {

									_make_built_in_func(GDFunctions::Function(i));
									found=true;
									 break;
								}
							}

							//keywor
						}

						if (!found) {


							struct _kws { Token token; const char *text;};

							static const  _kws keyword_list[]={
								//ops
								{TK_OP_IN,"in"},
								{TK_OP_NOT,"not"},
								{TK_OP_OR,"or"},
								{TK_OP_AND,"and"},
								//func
								{TK_PR_FUNCTION,"func"},
								{TK_PR_FUNCTION,"function"},
								{TK_PR_CLASS,"class"},
								{TK_PR_EXTENDS,"extends"},
								{TK_PR_TOOL,"tool"},
								{TK_PR_STATIC,"static"},
								{TK_PR_EXPORT,"export"},
								{TK_PR_VAR,"var"},
								{TK_PR_PRELOAD,"preload"},
								{TK_PR_ASSERT,"assert"},
								{TK_PR_YIELD,"yield"},
								{TK_PR_CONST,"const"},
								//controlflow
								{TK_CF_IF,"if"},
								{TK_CF_ELIF,"elif"},
								{TK_CF_ELSE,"else"},
								{TK_CF_FOR,"for"},
								{TK_CF_WHILE,"while"},
								{TK_CF_DO,"do"},
								{TK_CF_SWITCH,"switch"},
								{TK_CF_BREAK,"break"},
								{TK_CF_CONTINUE,"continue"},
								{TK_CF_RETURN,"return"},
								{TK_CF_PASS,"pass"},
								{TK_SELF,"self"},
								{TK_ERROR,NULL}
							};

							int idx=0;
							found=false;

							while(keyword_list[idx].text) {

								if (str==keyword_list[idx].text) {
									_make_token(keyword_list[idx].token);
									found=true;
									break;
								}
								idx++;
							}
						}

						if (!found)
							identifier=true;
					}


					if (identifier) {
						_make_identifier(str);
					}
					INCPOS(str.length());
					return;
				}

				_make_error("Unknown character");
				return;

			} break;
		}

		INCPOS(1);
		break;
	}

}
예제 #30
0
Variant ArrayData::value(int32_t &pos) const {
  return pos != invalid_index ? getValue(pos) : Variant(false);
}