Exemple #1
0
Error DirAccessJAndroid::make_dir(String p_dir){

	ERR_FAIL_V(ERR_UNAVAILABLE);
}
static DVector<uint8_t> _lossless_pack_png(const Image& p_image) {


	Image img = p_image;
	if (img.get_format() > Image::FORMAT_INDEXED_ALPHA)
		img.decompress();


	ERR_FAIL_COND_V(img.get_format() > Image::FORMAT_INDEXED_ALPHA, DVector<uint8_t>());

	png_structp png_ptr;
	png_infop info_ptr;
	png_bytep * row_pointers;


	/* initialize stuff */
	png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);

	ERR_FAIL_COND_V(!png_ptr,DVector<uint8_t>());

	info_ptr = png_create_info_struct(png_ptr);

	ERR_FAIL_COND_V(!info_ptr,DVector<uint8_t>());

	if (setjmp(png_jmpbuf(png_ptr))) {
		ERR_FAIL_V(DVector<uint8_t>());
	}
	DVector<uint8_t> ret;
	ret.push_back('P');
	ret.push_back('N');
	ret.push_back('G');
	ret.push_back(' ');

	png_set_write_fn(png_ptr,&ret,_write_png_data,NULL);

	/* write header */
	if (setjmp(png_jmpbuf(png_ptr))) {
		ERR_FAIL_V(DVector<uint8_t>());
	}

	int pngf=0;
	int cs=0;

	switch(img.get_format()) {

		case Image::FORMAT_GRAYSCALE: {

			pngf=PNG_COLOR_TYPE_GRAY;
			cs=1;
		} break;
		case Image::FORMAT_GRAYSCALE_ALPHA: {

			pngf=PNG_COLOR_TYPE_GRAY_ALPHA;
			cs=2;
		} break;
		case Image::FORMAT_RGB: {

			pngf=PNG_COLOR_TYPE_RGB;
			cs=3;
		} break;
		case Image::FORMAT_RGBA: {

			pngf=PNG_COLOR_TYPE_RGB_ALPHA;
			cs=4;
		} break;
		default: {

			if (img.detect_alpha()) {

				img.convert(Image::FORMAT_RGBA);
				pngf=PNG_COLOR_TYPE_RGB_ALPHA;
				cs=4;
			} else {

				img.convert(Image::FORMAT_RGB);
				pngf=PNG_COLOR_TYPE_RGB;
				cs=3;
			}

		}
	}

	int w = img.get_width();
	int h = img.get_height();
	png_set_IHDR(png_ptr, info_ptr, w,h,
		     8, pngf, PNG_INTERLACE_NONE,
		     PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);

	png_write_info(png_ptr, info_ptr);


	/* write bytes */
	if (setjmp(png_jmpbuf(png_ptr))) {
		ERR_FAIL_V(DVector<uint8_t>());
	}


	DVector<uint8_t>::Read r = img.get_data().read();

	row_pointers = (png_bytep*)memalloc(sizeof(png_bytep)*h);
	for(int i=0;i<h;i++) {

		row_pointers[i]=(png_bytep)&r[i*w*cs];
	}
	png_write_image(png_ptr, row_pointers);

	memfree(row_pointers);

	/* end write */
	if (setjmp(png_jmpbuf(png_ptr))) {

		ERR_FAIL_V(DVector<uint8_t>());
	}

	png_write_end(png_ptr, NULL);


	return ret;
}
Exemple #3
0
PropertyInfo VisualServer::shader_node_get_type_info(ShaderNodeType p_type) {

	switch(p_type) {

		case NODE_IN: return PropertyInfo(Variant::STRING,"in");
		case NODE_OUT: return PropertyInfo(Variant::STRING,"out");
		case NODE_CONSTANT: return PropertyInfo(Variant::REAL,"const");
		case NODE_PARAMETER: return PropertyInfo(Variant::STRING,"param");
		case NODE_ADD: return PropertyInfo(Variant::NIL,"add");
		case NODE_SUB: return PropertyInfo(Variant::NIL,"sub");
		case NODE_MUL: return PropertyInfo(Variant::NIL,"mul");
		case NODE_DIV: return PropertyInfo(Variant::NIL,"div");
		case NODE_MOD: return PropertyInfo(Variant::NIL,"rem");
		case NODE_SIN: return PropertyInfo(Variant::NIL,"sin");
		case NODE_COS: return PropertyInfo(Variant::NIL,"cos");
		case NODE_TAN: return PropertyInfo(Variant::NIL,"tan");
		case NODE_ARCSIN: return PropertyInfo(Variant::NIL,"arcsin");
		case NODE_ARCCOS: return PropertyInfo(Variant::NIL,"arccos");
		case NODE_ARCTAN: return PropertyInfo(Variant::NIL,"arctan");
		case NODE_POW: return PropertyInfo(Variant::NIL,"pow");
		case NODE_LOG: return PropertyInfo(Variant::NIL,"log");
		case NODE_MAX: return PropertyInfo(Variant::NIL,"max");
		case NODE_MIN: return PropertyInfo(Variant::NIL,"min");
		case NODE_COMPARE: return PropertyInfo(Variant::NIL,"cmp");
		case NODE_TEXTURE: return PropertyInfo(Variant::_RID,"texture1D",PROPERTY_HINT_RESOURCE_TYPE,"Texture");
		case NODE_TIME: return PropertyInfo(Variant::NIL,"time");
		case NODE_NOISE: return PropertyInfo(Variant::NIL,"noise");
		case NODE_PASS: return PropertyInfo(Variant::NIL,"pass");
		case NODE_VEC_IN: return PropertyInfo(Variant::STRING,"vin");
		case NODE_VEC_OUT: return PropertyInfo(Variant::STRING,"vout");
		case NODE_VEC_CONSTANT: return PropertyInfo(Variant::VECTOR3,"vconst");
		case NODE_VEC_PARAMETER: return PropertyInfo(Variant::STRING,"vparam");
		case NODE_VEC_ADD: return PropertyInfo(Variant::NIL,"vadd");
		case NODE_VEC_SUB: return PropertyInfo(Variant::NIL,"vsub");
		case NODE_VEC_MUL: return PropertyInfo(Variant::NIL,"vmul");
		case NODE_VEC_DIV: return PropertyInfo(Variant::NIL,"vdiv");
		case NODE_VEC_MOD: return PropertyInfo(Variant::NIL,"vrem");
		case NODE_VEC_CROSS: return PropertyInfo(Variant::NIL,"cross");
		case NODE_VEC_DOT: return PropertyInfo(Variant::NIL,"dot");
		case NODE_VEC_POW: return PropertyInfo(Variant::NIL,"vpow");
		case NODE_VEC_NORMALIZE: return PropertyInfo(Variant::NIL,"normalize");
		case NODE_VEC_INTERPOLATE: return PropertyInfo(Variant::NIL,"mix");
		case NODE_VEC_SCREEN_TO_UV: return PropertyInfo(Variant::NIL,"scrn2uv");
		case NODE_VEC_TRANSFORM3: return PropertyInfo(Variant::NIL,"xform3");
		case NODE_VEC_TRANSFORM4: return PropertyInfo(Variant::NIL,"xform4");
		case NODE_VEC_COMPARE: return PropertyInfo(Variant::_RID,"vcmp",PROPERTY_HINT_RESOURCE_TYPE,"Texture");
		case NODE_VEC_TEXTURE_2D: return PropertyInfo(Variant::_RID,"texture2D",PROPERTY_HINT_RESOURCE_TYPE,"Texture");
		case NODE_VEC_TEXTURE_CUBE: return PropertyInfo(Variant::NIL,"texcube");
		case NODE_VEC_NOISE:	return PropertyInfo(Variant::NIL,"vec_noise");
		case NODE_VEC_0: return PropertyInfo(Variant::NIL,"vec_0");
		case NODE_VEC_1: return PropertyInfo(Variant::NIL,"vec_1");
		case NODE_VEC_2: return PropertyInfo(Variant::NIL,"vec_2");
		case NODE_VEC_BUILD: return PropertyInfo(Variant::NIL,"vbuild");
		case NODE_VEC_PASS: return PropertyInfo(Variant::NIL,"vpass");
		case NODE_COLOR_CONSTANT: return PropertyInfo(Variant::COLOR,"color_const");
		case NODE_COLOR_PARAMETER: return PropertyInfo(Variant::STRING,"color_param");
		case NODE_TEXTURE_PARAMETER:  return PropertyInfo(Variant::STRING,"tex1D_param");
		case NODE_TEXTURE_2D_PARAMETER:  return PropertyInfo(Variant::STRING,"tex2D_param");
		case NODE_TEXTURE_CUBE_PARAMETER:  return PropertyInfo(Variant::STRING,"texcube_param");
		case NODE_TRANSFORM_CONSTANT:  return PropertyInfo(Variant::TRANSFORM,"xform_const");
		case NODE_TRANSFORM_PARAMETER: return PropertyInfo(Variant::STRING,"xform_param");
		case NODE_LABEL: return PropertyInfo(Variant::STRING,"label");

		default: {}

	}

	ERR_FAIL_V( PropertyInfo(Variant::NIL,"error") );
}
Exemple #4
0
static String _parser_expr(const GDParser::Node *p_expr) {

	String txt;
	switch(p_expr->type) {

		case GDParser::Node::TYPE_IDENTIFIER: {

			const GDParser::IdentifierNode *id_node = static_cast<const GDParser::IdentifierNode *>(p_expr);
			txt=id_node->name;
		} break;
		case GDParser::Node::TYPE_CONSTANT: {
			const GDParser::ConstantNode *c_node = static_cast<const GDParser::ConstantNode *>(p_expr);
			if (c_node->value.get_type()==Variant::STRING)
				txt="\""+String(c_node->value)+"\"";
			else
				txt=c_node->value;

		} break;
		case GDParser::Node::TYPE_SELF: {
			txt="self";
		} break;
		case GDParser::Node::TYPE_ARRAY: {
			const GDParser::ArrayNode *arr_node = static_cast<const GDParser::ArrayNode *>(p_expr);
			txt+="[";
			for(int i=0;i<arr_node->elements.size();i++) {

				if (i>0)
					txt+=", ";
				txt+=_parser_expr(arr_node->elements[i]);
			}
			txt+="]";
		} break;
		case GDParser::Node::TYPE_DICTIONARY: {
			const GDParser::DictionaryNode *dict_node = static_cast<const GDParser::DictionaryNode *>(p_expr);
			txt+="{";
			for(int i=0;i<dict_node->elements.size();i++) {

				if (i>0)
					txt+=", ";

				const GDParser::DictionaryNode::Pair &p = dict_node->elements[i];
				txt+=_parser_expr(p.key);
				txt+=":";
				txt+=_parser_expr(p.value);
			}
			txt+="}";
		} break;
		case GDParser::Node::TYPE_OPERATOR: {

			const GDParser::OperatorNode *c_node = static_cast<const GDParser::OperatorNode *>(p_expr);
			switch(c_node->op) {

				case GDParser::OperatorNode::OP_PARENT_CALL:
					txt+=".";
				case GDParser::OperatorNode::OP_CALL: {

					ERR_FAIL_COND_V(c_node->arguments.size()<1,"");
					String func_name;
					const GDParser::Node *nfunc = c_node->arguments[0];
					int arg_ofs=0;
					if (nfunc->type==GDParser::Node::TYPE_BUILT_IN_FUNCTION) {

						const GDParser::BuiltInFunctionNode *bif_node = static_cast<const GDParser::BuiltInFunctionNode *>(nfunc);
						func_name=GDFunctions::get_func_name(bif_node->function);
						arg_ofs=1;
					} else if (nfunc->type==GDParser::Node::TYPE_TYPE) {

						const GDParser::TypeNode *t_node = static_cast<const GDParser::TypeNode *>(nfunc);
						func_name=Variant::get_type_name(t_node->vtype);
						arg_ofs=1;
					} else {

						ERR_FAIL_COND_V(c_node->arguments.size()<2,"");
						nfunc = c_node->arguments[1];
						ERR_FAIL_COND_V(nfunc->type!=GDParser::Node::TYPE_IDENTIFIER,"");

						if (c_node->arguments[0]->type!=GDParser::Node::TYPE_SELF)
							func_name=_parser_expr(c_node->arguments[0])+".";

						func_name+=_parser_expr(nfunc);
						arg_ofs=2;
					}

					txt+=func_name+"(";

					for(int i=arg_ofs;i<c_node->arguments.size();i++) {

						const GDParser::Node *arg=c_node->arguments[i];
						if (i>arg_ofs)
							txt+=", ";
						txt+=_parser_expr(arg);
					}

					txt+=")";

				} break;
				case GDParser::OperatorNode::OP_INDEX: {

					ERR_FAIL_COND_V(c_node->arguments.size()!=2,"");

					//index with []
					txt=_parser_expr(c_node->arguments[0])+"["+_parser_expr(c_node->arguments[1])+"]";

				} break;
				case GDParser::OperatorNode::OP_INDEX_NAMED: {

					ERR_FAIL_COND_V(c_node->arguments.size()!=2,"");

					txt=_parser_expr(c_node->arguments[0])+"."+_parser_expr(c_node->arguments[1]);

				} break;
				case GDParser::OperatorNode::OP_NEG: { txt="-"+_parser_expr(c_node->arguments[0]); } break;
				case GDParser::OperatorNode::OP_NOT: { txt="not "+_parser_expr(c_node->arguments[0]); } break;
				case GDParser::OperatorNode::OP_BIT_INVERT: { txt="~"+_parser_expr(c_node->arguments[0]); } break;
				case GDParser::OperatorNode::OP_PREINC: {} break;
				case GDParser::OperatorNode::OP_PREDEC: {} break;
				case GDParser::OperatorNode::OP_INC: {} break;
				case GDParser::OperatorNode::OP_DEC: {} break;
				case GDParser::OperatorNode::OP_IN: { txt=_parser_expr(c_node->arguments[0])+" in "+_parser_expr(c_node->arguments[1]); } break;
				case GDParser::OperatorNode::OP_EQUAL: { txt=_parser_expr(c_node->arguments[0])+"=="+_parser_expr(c_node->arguments[1]); } break;
				case GDParser::OperatorNode::OP_NOT_EQUAL: { txt=_parser_expr(c_node->arguments[0])+"!="+_parser_expr(c_node->arguments[1]); } break;
				case GDParser::OperatorNode::OP_LESS: { txt=_parser_expr(c_node->arguments[0])+"<"+_parser_expr(c_node->arguments[1]); } break;
				case GDParser::OperatorNode::OP_LESS_EQUAL: { txt=_parser_expr(c_node->arguments[0])+"<="+_parser_expr(c_node->arguments[1]); } break;
				case GDParser::OperatorNode::OP_GREATER: { txt=_parser_expr(c_node->arguments[0])+">"+_parser_expr(c_node->arguments[1]); } break;
				case GDParser::OperatorNode::OP_GREATER_EQUAL: { txt=_parser_expr(c_node->arguments[0])+">="+_parser_expr(c_node->arguments[1]); } break;
				case GDParser::OperatorNode::OP_AND: { txt=_parser_expr(c_node->arguments[0])+" and "+_parser_expr(c_node->arguments[1]); } break;
				case GDParser::OperatorNode::OP_OR: { txt=_parser_expr(c_node->arguments[0])+" or "+_parser_expr(c_node->arguments[1]); } break;
				case GDParser::OperatorNode::OP_ADD: { txt=_parser_expr(c_node->arguments[0])+"+"+_parser_expr(c_node->arguments[1]); } break;
				case GDParser::OperatorNode::OP_SUB: { txt=_parser_expr(c_node->arguments[0])+"-"+_parser_expr(c_node->arguments[1]); } break;
				case GDParser::OperatorNode::OP_MUL: { txt=_parser_expr(c_node->arguments[0])+"*"+_parser_expr(c_node->arguments[1]); } break;
				case GDParser::OperatorNode::OP_DIV: { txt=_parser_expr(c_node->arguments[0])+"/"+_parser_expr(c_node->arguments[1]); } break;
				case GDParser::OperatorNode::OP_MOD: { txt=_parser_expr(c_node->arguments[0])+"%"+_parser_expr(c_node->arguments[1]); } break;
				case GDParser::OperatorNode::OP_SHIFT_LEFT: { txt=_parser_expr(c_node->arguments[0])+"<<"+_parser_expr(c_node->arguments[1]); } break;
				case GDParser::OperatorNode::OP_SHIFT_RIGHT: { txt=_parser_expr(c_node->arguments[0])+">>"+_parser_expr(c_node->arguments[1]); } break;
				case GDParser::OperatorNode::OP_ASSIGN: { txt=_parser_expr(c_node->arguments[0])+"="+_parser_expr(c_node->arguments[1]); } break;
				case GDParser::OperatorNode::OP_ASSIGN_ADD: { txt=_parser_expr(c_node->arguments[0])+"+="+_parser_expr(c_node->arguments[1]); } break;
				case GDParser::OperatorNode::OP_ASSIGN_SUB: { txt=_parser_expr(c_node->arguments[0])+"-="+_parser_expr(c_node->arguments[1]); } break;
				case GDParser::OperatorNode::OP_ASSIGN_MUL: { txt=_parser_expr(c_node->arguments[0])+"*="+_parser_expr(c_node->arguments[1]); } break;
				case GDParser::OperatorNode::OP_ASSIGN_DIV: { txt=_parser_expr(c_node->arguments[0])+"/="+_parser_expr(c_node->arguments[1]); } break;
				case GDParser::OperatorNode::OP_ASSIGN_MOD: { txt=_parser_expr(c_node->arguments[0])+"%="+_parser_expr(c_node->arguments[1]); } break;
				case GDParser::OperatorNode::OP_ASSIGN_SHIFT_LEFT:{ txt=_parser_expr(c_node->arguments[0])+"<<="+_parser_expr(c_node->arguments[1]); } break;
				case GDParser::OperatorNode::OP_ASSIGN_SHIFT_RIGHT: { txt=_parser_expr(c_node->arguments[0])+">>="+_parser_expr(c_node->arguments[1]); } break;
				case GDParser::OperatorNode::OP_ASSIGN_BIT_AND: { txt=_parser_expr(c_node->arguments[0])+"&="+_parser_expr(c_node->arguments[1]); } break;
				case GDParser::OperatorNode::OP_ASSIGN_BIT_OR: { txt=_parser_expr(c_node->arguments[0])+"|="+_parser_expr(c_node->arguments[1]); } break;
				case GDParser::OperatorNode::OP_ASSIGN_BIT_XOR: { txt=_parser_expr(c_node->arguments[0])+"^="+_parser_expr(c_node->arguments[1]); } break;
				case GDParser::OperatorNode::OP_BIT_AND: { txt=_parser_expr(c_node->arguments[0])+"&"+_parser_expr(c_node->arguments[1]); } break;;
				case GDParser::OperatorNode::OP_BIT_OR: { txt=_parser_expr(c_node->arguments[0])+"|"+_parser_expr(c_node->arguments[1]); } break;
				case GDParser::OperatorNode::OP_BIT_XOR: { txt=_parser_expr(c_node->arguments[0])+"^"+_parser_expr(c_node->arguments[1]); } break;

			}

		} break;
		case GDParser::Node::TYPE_NEWLINE: {

			//skippie
		} break;
		default: {

			String error="Parser bug at "+itos(p_expr->line)+", invalid expression type: "+itos(p_expr->type);
			ERR_EXPLAIN(error);
			ERR_FAIL_V("");

		}

	}

	return txt;
	//return "("+txt+")";
}
Exemple #5
0
Error LWSClient::connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_ssl, PoolVector<String> p_protocols) {

	ERR_FAIL_COND_V(context != NULL, FAILED);

	IP_Address addr;

	if (!p_host.is_valid_ip_address()) {
		addr = IP::get_singleton()->resolve_hostname(p_host);
	} else {
		addr = p_host;
	}

	ERR_FAIL_COND_V(!addr.is_valid(), ERR_INVALID_PARAMETER);

	// prepare protocols
	if (p_protocols.size() == 0) // default to binary protocol
		p_protocols.append("binary");
	_lws_make_protocols(this, &LWSClient::_lws_gd_callback, p_protocols, &_lws_ref);

	// init lws client
	struct lws_context_creation_info info;
	struct lws_client_connect_info i;

	memset(&i, 0, sizeof i);
	memset(&info, 0, sizeof info);

	info.port = CONTEXT_PORT_NO_LISTEN;
	info.protocols = _lws_ref->lws_structs;
	info.gid = -1;
	info.uid = -1;
	//info.ws_ping_pong_interval = 5;
	info.user = _lws_ref;
#if defined(LWS_OPENSSL_SUPPORT)
	info.options |= LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
#endif
	context = lws_create_context(&info);

	if (context == NULL) {
		_lws_free_ref(_lws_ref);
		_lws_ref = NULL;
		ERR_EXPLAIN("Unable to create lws context");
		ERR_FAIL_V(FAILED);
	}

	char abuf[1024];
	char hbuf[1024];
	char pbuf[2048];
	String addr_str = (String)addr;
	strncpy(abuf, addr_str.ascii().get_data(), 1024);
	strncpy(hbuf, p_host.utf8().get_data(), 1024);
	strncpy(pbuf, p_path.utf8().get_data(), 2048);

	i.context = context;
	i.protocol = _lws_ref->lws_names;
	i.address = abuf;
	i.host = hbuf;
	i.path = pbuf;
	i.port = p_port;

	if (p_ssl) {
		i.ssl_connection = LCCSCF_USE_SSL;
		if (!verify_ssl)
			i.ssl_connection |= LCCSCF_ALLOW_SELFSIGNED;
	} else {
		i.ssl_connection = 0;
	}

	lws_client_connect_via_info(&i);
	return OK;
};
Exemple #6
0
Variant Object::call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error) {

	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;
}
Exemple #7
0
Node *Node::_get_node(const NodePath& p_path) const {

	if (!data.inside_tree && p_path.is_absolute()) {
		ERR_EXPLAIN("Can't use get_node() with absolute paths from outside the active scene tree.");
		ERR_FAIL_V(NULL);
	}

	Node *current=NULL;
	Node *root=NULL;

	if (!p_path.is_absolute()) {
		current=const_cast<Node*>(this); //start from this
	} else {

		root=const_cast<Node*>(this);;
		while (root->data.parent)
			root=root->data.parent; //start from root
	}


	for(int i=0;i<p_path.get_name_count();i++) {


		StringName name = p_path.get_name(i);
		Node *next = NULL;

		if (name==SceneStringNames::get_singleton()->dot) { // .

			next=current;

		} else if (name==SceneStringNames::get_singleton()->doubledot) { // ..

			if (current==NULL || !current->data.parent)
				return NULL;

			next=current->data.parent;
		} else if (current==NULL) {

			if (name==root->get_name())
				next=root;

		} else {

			next=NULL;

			for(int j=0;j<current->data.children.size();j++) {

				Node *child = current->data.children[j];

				if ( child->data.name == name ) {

					next = child;
					break;
				}
			}
			if (next == NULL) {
				return NULL;
			};
		}
		current=next;
	}

	return current;
}
static String get_constant_text(SL::DataType p_type, const Vector<SL::ConstantNode::Value> &p_values) {

	switch (p_type) {
		case SL::TYPE_BOOL: return p_values[0].boolean ? "true" : "false";
		case SL::TYPE_BVEC2:
		case SL::TYPE_BVEC3:
		case SL::TYPE_BVEC4: {

			StringBuffer<> text;

			text += "bvec";
			text += itos(p_type - SL::TYPE_BOOL + 1);
			text += "(";

			for (int i = 0; i < p_values.size(); i++) {
				if (i > 0)
					text += ",";

				text += p_values[i].boolean ? "true" : "false";
			}
			text += ")";
			return text.as_string();
		}

		// GLSL ES 2 doesn't support uints, so we just use signed ints instead...
		case SL::TYPE_UINT: return itos(p_values[0].uint);
		case SL::TYPE_UVEC2:
		case SL::TYPE_UVEC3:
		case SL::TYPE_UVEC4: {

			StringBuffer<> text;

			text += "ivec";
			text += itos(p_type - SL::TYPE_UINT + 1);
			text += "(";

			for (int i = 0; i < p_values.size(); i++) {
				if (i > 0)
					text += ",";

				text += itos(p_values[i].uint);
			}
			text += ")";
			return text.as_string();

		} break;

		case SL::TYPE_INT: return itos(p_values[0].sint);
		case SL::TYPE_IVEC2:
		case SL::TYPE_IVEC3:
		case SL::TYPE_IVEC4: {

			StringBuffer<> text;

			text += "ivec";
			text += itos(p_type - SL::TYPE_INT + 1);
			text += "(";

			for (int i = 0; i < p_values.size(); i++) {
				if (i > 0)
					text += ",";

				text += itos(p_values[i].sint);
			}
			text += ")";
			return text.as_string();

		} break;
		case SL::TYPE_FLOAT: return f2sp0(p_values[0].real) + "f";
		case SL::TYPE_VEC2:
		case SL::TYPE_VEC3:
		case SL::TYPE_VEC4: {

			StringBuffer<> text;

			text += "vec";
			text += itos(p_type - SL::TYPE_FLOAT + 1);
			text += "(";

			for (int i = 0; i < p_values.size(); i++) {
				if (i > 0)
					text += ",";

				text += f2sp0(p_values[i].real);
			}
			text += ")";
			return text.as_string();

		} break;
		case SL::TYPE_MAT2:
		case SL::TYPE_MAT3:
		case SL::TYPE_MAT4: {

			StringBuffer<> text;

			text += "mat";
			text += itos(p_type - SL::TYPE_MAT2 + 2);
			text += "(";

			for (int i = 0; i < p_values.size(); i++) {
				if (i > 0)
					text += ",";

				text += f2sp0(p_values[i].real);
			}
			text += ")";
			return text.as_string();

		} break;
		default: ERR_FAIL_V(String());
	}
}
Exemple #9
0
MethodBind* ObjectTypeDB::bind_methodfi(uint32_t p_flags, MethodBind *p_bind , const MethodDefinition &method_name, const Variant **p_defs, int p_defcount) {
	StringName mdname=method_name.name;
#else
MethodBind* ObjectTypeDB::bind_methodfi(uint32_t p_flags, MethodBind *p_bind , const char *method_name, const Variant **p_defs, int p_defcount) {
	StringName mdname=StaticCString::create(method_name);
#endif


	StringName rettype;
	if (mdname.operator String().find(":")!=-1) {
		rettype = mdname.operator String().get_slice(":",1);
		mdname = mdname.operator String().get_slice(":",0);
	}


	OBJTYPE_LOCK;
	ERR_FAIL_COND_V(!p_bind,NULL);
	p_bind->set_name(mdname);

	String instance_type=p_bind->get_instance_type();

	TypeInfo *type=types.getptr(instance_type);
	if (!type) {
		print_line("couldn't bind method "+mdname+" for instance: "+instance_type);
		memdelete(p_bind);
		ERR_FAIL_COND_V(!type,NULL);
	}

	if (type->method_map.has(mdname)) {
		memdelete(p_bind);
		// overloading not supported
		ERR_EXPLAIN("Method already bound: "+instance_type+"::"+mdname);
		ERR_FAIL_V(NULL);
	}
#ifdef DEBUG_METHODS_ENABLED
	p_bind->set_argument_names(method_name.args);
	p_bind->set_return_type(rettype);
	type->method_order.push_back(mdname);
#endif
	type->method_map[mdname]=p_bind;


	Vector<Variant> defvals;

#define PARSE_DEFVAL(m_defval)\
if (d##m_defval.used) defvals.insert(0,d##m_defval.val);\
else goto set_defvals;

	defvals.resize(p_defcount);
	for(int i=0;i<p_defcount;i++) {

		defvals[i]=*p_defs[p_defcount-i-1];
	}

	set_defvals:

	p_bind->set_default_arguments(defvals);
	p_bind->set_hint_flags(p_flags);
#undef PARSE_DEFVAL
	return p_bind;

}
Exemple #10
0
Error DynamicFontAtSize::_load() {

	int error = FT_Init_FreeType(&library);

	ERR_EXPLAIN(TTR("Error initializing FreeType."));
	ERR_FAIL_COND_V(error != 0, ERR_CANT_CREATE);

	// FT_OPEN_STREAM is extremely slow only on Android.
	if (OS::get_singleton()->get_name() == "Android" && font->font_mem == NULL && font->font_path != String()) {
		// cache font only once for each font->font_path
		if (_fontdata.has(font->font_path)) {

			font->set_font_ptr(_fontdata[font->font_path].ptr(), _fontdata[font->font_path].size());

		} else {

			FileAccess *f = FileAccess::open(font->font_path, FileAccess::READ);
			ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);

			size_t len = f->get_len();
			_fontdata[font->font_path] = Vector<uint8_t>();
			Vector<uint8_t> &fontdata = _fontdata[font->font_path];
			fontdata.resize(len);
			f->get_buffer(fontdata.ptr(), len);
			font->set_font_ptr(fontdata.ptr(), len);
			f->close();
		}
	}

	if (font->font_mem == NULL && font->font_path != String()) {

		FileAccess *f = FileAccess::open(font->font_path, FileAccess::READ);
		ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);

		memset(&stream, 0, sizeof(FT_StreamRec));
		stream.base = NULL;
		stream.size = f->get_len();
		stream.pos = 0;
		stream.descriptor.pointer = f;
		stream.read = _ft_stream_io;
		stream.close = _ft_stream_close;

		FT_Open_Args fargs;
		memset(&fargs, 0, sizeof(FT_Open_Args));
		fargs.flags = FT_OPEN_STREAM;
		fargs.stream = &stream;
		error = FT_Open_Face(library, &fargs, 0, &face);
	} else if (font->font_mem) {

		memset(&stream, 0, sizeof(FT_StreamRec));
		stream.base = (unsigned char *)font->font_mem;
		stream.size = font->font_mem_size;
		stream.pos = 0;

		FT_Open_Args fargs;
		memset(&fargs, 0, sizeof(FT_Open_Args));
		fargs.memory_base = (unsigned char *)font->font_mem;
		fargs.memory_size = font->font_mem_size;
		fargs.flags = FT_OPEN_MEMORY;
		fargs.stream = &stream;
		error = FT_Open_Face(library, &fargs, 0, &face);

	} else {
		ERR_EXPLAIN("DynamicFont uninitialized");
		ERR_FAIL_V(ERR_UNCONFIGURED);
	}

	//error = FT_New_Face( library, src_path.utf8().get_data(),0,&face );

	if (error == FT_Err_Unknown_File_Format) {
		ERR_EXPLAIN(TTR("Unknown font format."));
		FT_Done_FreeType(library);

	} else if (error) {

		ERR_EXPLAIN(TTR("Error loading font."));
		FT_Done_FreeType(library);
	}

	ERR_FAIL_COND_V(error, ERR_FILE_CANT_OPEN);

	/*error = FT_Set_Char_Size(face,0,64*size,512,512);

	if ( error ) {
		FT_Done_FreeType( library );
		ERR_EXPLAIN(TTR("Invalid font size."));
		ERR_FAIL_COND_V( error, ERR_INVALID_PARAMETER );
	}*/

	error = FT_Set_Pixel_Sizes(face, 0, id.size);

	ascent = face->size->metrics.ascender >> 6;
	descent = -face->size->metrics.descender >> 6;
	linegap = 0;
	texture_flags = 0;
	if (id.mipmaps)
		texture_flags |= Texture::FLAG_MIPMAPS;
	if (id.filter)
		texture_flags |= Texture::FLAG_FILTER;

	//print_line("ASCENT: "+itos(ascent)+" descent "+itos(descent)+" hinted: "+itos(face->face_flags&FT_FACE_FLAG_HINTER));

	valid = true;
	return OK;
}
Exemple #11
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));
		ERR_FAIL_COND_V(!instance,Variant());

		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));
		List<jobject> to_erase;
		for(int i=0;i<p_argcount;i++) {

			jvalret vr = _variant_to_jvalue(env, E->get().argtypes[i], p_args[i]);
			v[i] = vr.val;
			if (vr.obj)
				to_erase.push_back(vr.obj);
		}

		//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;
				env->DeleteLocalRef(o);
			} break;
			case Variant::STRING_ARRAY: {

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

				ret = _jobject_to_variant(env, arr);

				env->DeleteLocalRef(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;
				env->DeleteLocalRef(arr);
			} 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;
				env->DeleteLocalRef(arr);
			} break;

			case Variant::DICTIONARY: {

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

			} break;
			default: {


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

		while (to_erase.size()) {
			env->DeleteLocalRef(to_erase.front()->get());
			to_erase.pop_front();
		}
		//print_line("success");

		return ret;
	}
Exemple #12
0
Error BitmapFont::create_from_fnt(const String &p_file) {
	//fnt format used by angelcode bmfont
	//http://www.angelcode.com/products/bmfont/

	FileAccess *f = FileAccess::open(p_file, FileAccess::READ);

	if (!f) {
		ERR_EXPLAIN("Can't open font: " + p_file);
		ERR_FAIL_V(ERR_FILE_NOT_FOUND);
	}

	clear();

	while (true) {

		String line = f->get_line();

		int delimiter = line.find(" ");
		String type = line.substr(0, delimiter);
		int pos = delimiter + 1;
		Map<String, String> keys;

		while (pos < line.size() && line[pos] == ' ')
			pos++;

		while (pos < line.size()) {

			int eq = line.find("=", pos);
			if (eq == -1)
				break;
			String key = line.substr(pos, eq - pos);
			int end = -1;
			String value;
			if (line[eq + 1] == '"') {
				end = line.find("\"", eq + 2);
				if (end == -1)
					break;
				value = line.substr(eq + 2, end - 1 - eq - 1);
				pos = end + 1;
			} else {
				end = line.find(" ", eq + 1);
				if (end == -1)
					end = line.size();

				value = line.substr(eq + 1, end - eq);

				pos = end;
			}

			while (pos < line.size() && line[pos] == ' ')
				pos++;

			keys[key] = value;
		}

		if (type == "info") {

			if (keys.has("face"))
				set_name(keys["face"]);
			/*
			if (keys.has("size"))
				font->set_height(keys["size"].to_int());
			*/

		} else if (type == "common") {

			if (keys.has("lineHeight"))
				set_height(keys["lineHeight"].to_int());
			if (keys.has("base"))
				set_ascent(keys["base"].to_int());

		} else if (type == "page") {

			if (keys.has("file")) {

				String base_dir = p_file.get_base_dir();
				String file = base_dir.plus_file(keys["file"]);
				Ref<Texture> tex = ResourceLoader::load(file);
				if (tex.is_null()) {
					ERR_PRINT("Can't load font texture!");
				} else {
					add_texture(tex);
				}
			}
		} else if (type == "char") {

			CharType idx = 0;
			if (keys.has("id"))
				idx = keys["id"].to_int();

			Rect2 rect;

			if (keys.has("x"))
				rect.position.x = keys["x"].to_int();
			if (keys.has("y"))
				rect.position.y = keys["y"].to_int();
			if (keys.has("width"))
				rect.size.width = keys["width"].to_int();
			if (keys.has("height"))
				rect.size.height = keys["height"].to_int();

			Point2 ofs;

			if (keys.has("xoffset"))
				ofs.x = keys["xoffset"].to_int();
			if (keys.has("yoffset"))
				ofs.y = keys["yoffset"].to_int();

			int texture = 0;
			if (keys.has("page"))
				texture = keys["page"].to_int();
			int advance = -1;
			if (keys.has("xadvance"))
				advance = keys["xadvance"].to_int();

			add_char(idx, texture, rect, ofs, advance);

		} else if (type == "kerning") {

			CharType first = 0, second = 0;
			int k = 0;

			if (keys.has("first"))
				first = keys["first"].to_int();
			if (keys.has("second"))
				second = keys["second"].to_int();
			if (keys.has("amount"))
				k = keys["amount"].to_int();

			add_kerning_pair(first, second, -k);
		}

		if (f->eof_reached())
			break;
	}

	memdelete(f);

	return OK;
}
Exemple #13
0
Error DirAccessJAndroid::remove(String p_name){

	ERR_FAIL_V(ERR_UNAVAILABLE);
}
Exemple #14
0
Error DirAccessJAndroid::rename(String p_from, String p_to){

	ERR_FAIL_V(ERR_UNAVAILABLE);
}
Exemple #15
0
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;
	List<String> args = OS::get_singleton()->get_cmdline_args();
	for (int i=0;i<args.size();i++) {
		

		if (args[i]=="-doctool" && i <(args.size()-1)) {

			doc_tool=args[i+1];
			i++;
		}else if (args[i]=="-nodocbase") {

			doc_base=false;
		} else if ((args[i]=="-script" || args[i]=="-s") && i <(args.size()-1)) {
		
			script=args[i+1];
			i++;
		} else if ((args[i]=="-level" || args[i]=="-l") && i <(args.size()-1)) {

			OS::get_singleton()->_custom_level=args[i+1];
			i++;
		} else if (args[i]=="-test" && i <(args.size()-1)) {
			test=args[i+1];
			i++;
		} else if (args[i]=="-optimize" && i <(args.size()-1)) {
			optimize=args[i+1];
			i++;
		} else if (args[i]=="-optimize_preset" && i <(args.size()-1)) {
			optimize_preset=args[i+1];
			i++;
		} else if (args[i]=="-export" && i <(args.size()-1)) {
			editor=true; //needs editor
			_export_platform=args[i+1];
			i++;
		} else if (args[i]=="-export_debug" && i <(args.size()-1)) {
			editor=true; //needs editor
			_export_platform=args[i+1];
			export_debug=true;
			i++;
		} else if (args[i]=="-import" && i <(args.size()-1)) {
			editor=true; //needs editor
			_import=args[i+1];
			i++;
		} else if (args[i]=="-import_script" && i <(args.size()-1)) {
			editor=true; //needs editor
			_import_script=args[i+1];
			i++;
		} else if (args[i]=="-noquit" ) {
			noquit=true;
		} else if (args[i]=="-dumpstrings" && i <(args.size()-1)) {
			editor=true; //needs editor
			dumpstrings=args[i+1];
			i++;
		} else if (args[i]=="-editor" || args[i]=="-e") {
			editor=true;
		} else if (args[i]=="-convert_old") {
			convert_old=true;
		} else if (args[i].length() && args[i][0] != '-' && game_path == "") {

			game_path=args[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(script=="" && game_path=="" && !editor && 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>();

#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!="") {

			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();
						}
					}
				}

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

				{
					//autoload
					List<PropertyInfo> props;
					Globals::get_singleton()->get_property_list(&props);
					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);
						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();
							ERR_EXPLAIN("Script does not inherit a Node: "+path);
							ERR_CONTINUE( !ObjectTypeDB::is_type(ibt,"Node") );

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

							ERR_EXPLAIN("Cannot instance node for autoload type: "+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);
						sml->get_root()->add_child(n);
					}

				}

				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 (script=="" && test=="" && game_path=="" && !editor) {

			ProjectManager *pmanager = memnew( ProjectManager );
			sml->get_root()->add_child(pmanager);
		}

#endif
	}

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

	return true;
}
Exemple #16
0
RES ResourceFormatLoaderTheme::load(const String &p_path,const String& p_original_path) {

	Error err;
	FileAccess *f = FileAccess::open(p_path,FileAccess::READ,&err);

	ERR_EXPLAIN("Unable to open theme file: "+p_path);
	ERR_FAIL_COND_V(err,RES());
	String base_path = p_path.get_base_dir();
	Ref<Theme> theme( memnew( Theme ) );
	Map<StringName,Variant> library;

	bool reading_library=false;
	int line=0;

	while(!f->eof_reached()) {

		String l = f->get_line().strip_edges();
		line++;

		int comment = l.find(";");
		if (comment!=-1)
			l=l.substr(0,comment);
		if (l=="")
			continue;

		if (l.begins_with("[")) {
			if (l=="[library]") {
				reading_library=true;
			}  else if (l=="[theme]") {
				reading_library=false;
			} else {
				memdelete(f);
				ERR_EXPLAIN(p_path+":"+itos(line)+": Unknown section type: '"+l+"'.");
				ERR_FAIL_V(RES());
			}
			continue;
		}

		int eqpos = l.find("=");
		if (eqpos==-1) {
			memdelete(f);
			ERR_EXPLAIN(p_path+":"+itos(line)+": Expected '='.");
			ERR_FAIL_V(RES());
		}


		String right=l.substr(eqpos+1,l.length()).strip_edges();
		if (right=="") {
			memdelete(f);
			ERR_EXPLAIN(p_path+":"+itos(line)+": Expected value after '='.");
			ERR_FAIL_V(RES());
		}

		Variant value;

		if (right.is_valid_integer()) {
			//is number
			value = right.to_int();
		} else if (right.is_valid_html_color()) {
			//is html color
			value = Color::html(right);
		} else if (right.begins_with("@")) { //reference

			String reference = right.substr(1,right.length());
			if (!library.has(reference)) {
				memdelete(f);
				ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid reference to '"+reference+"'.");
				ERR_FAIL_V(RES());

			}

			value=library[reference];

		} else if (right.begins_with("default")) { //use default
			//do none
		} else {
			//attempt to parse a constructor
			int popenpos = right.find("(");

			if (popenpos==-1) {
				memdelete(f);
				ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid constructor syntax: "+right);
				ERR_FAIL_V(RES());
			}

			int pclosepos = right.find_last(")");

			if (pclosepos==-1) {
				ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid constructor parameter syntax: "+right);
				ERR_FAIL_V(RES());

			}

			String type = right.substr(0,popenpos);
			String param = right.substr(popenpos+1,pclosepos-popenpos-1);



			if (type=="icon") {

				String path;

				if (param.is_abs_path())
					path=param;
				else
					path=base_path+"/"+param;

				Ref<Texture> texture = ResourceLoader::load(path);
				if (!texture.is_valid()) {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Couldn't find icon at path: "+path);
					ERR_FAIL_V(RES());
				}

				value=texture;

			} else if (type=="sbox") {

				String path;

				if (param.is_abs_path())
					path=param;
				else
					path=base_path+"/"+param;

				Ref<StyleBox> stylebox = ResourceLoader::load(path);
				if (!stylebox.is_valid()) {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Couldn't find stylebox at path: "+path);
					ERR_FAIL_V(RES());
				}

				value=stylebox;

			} else if (type=="sboxt") {

				Vector<String> params = param.split(",");
				if (params.size()!=5 && params.size()!=9) {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid param count for sboxt(): '"+right+"'.");
					ERR_FAIL_V(RES());

				}

				String path=params[0];

				if (!param.is_abs_path())
					path=base_path+"/"+path;

				Ref<Texture> tex = ResourceLoader::load(path);
				if (tex.is_null()) {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Could not open texture for sboxt at path: '"+params[0]+"'.");
					ERR_FAIL_V(RES());

				}

				Ref<StyleBoxTexture> sbtex( memnew(StyleBoxTexture) );

				sbtex->set_texture(tex);

				for(int i=0;i<4;i++) {
					if (!params[i+1].is_valid_integer()) {

						memdelete(f);
						ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid expand margin parameter for sboxt #"+itos(i+1) +", expected integer constant, got: '"+params[i+1]+"'.");
						ERR_FAIL_V(RES());
					}

					int margin = params[i+1].to_int();
					sbtex->set_expand_margin_size(Margin(i),margin);
				}

				if (params.size()==9) {

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

						if (!params[i+5].is_valid_integer()) {
							memdelete(f);
							ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid expand margin parameter for sboxt #"+itos(i+5) +", expected integer constant, got: '"+params[i+5]+"'.");
							ERR_FAIL_V(RES());
						}

						int margin = params[i+5].to_int();
						sbtex->set_margin_size(Margin(i),margin);
					}
				}

				value = sbtex;
			} else if (type=="sboxf") {

				Vector<String> params = param.split(",");
				if (params.size()<2) {

					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid param count for sboxf(): '"+right+"'.");
					ERR_FAIL_V(RES());

				}

				Ref<StyleBoxFlat> sbflat( memnew(StyleBoxFlat) );

				if (!params[0].is_valid_integer()) {

					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Expected integer numeric constant for parameter 0 (border size).");
					ERR_FAIL_V(RES());

				}

				sbflat->set_border_size(params[0].to_int());

				if (!params[0].is_valid_integer()) {

					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Expected integer numeric constant for parameter 0 (border size).");
					ERR_FAIL_V(RES());

				}


				int left = MIN( params.size()-1, 3 );

				int ccodes=0;

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

					if (params[i+1].is_valid_html_color())
						ccodes++;
					else
						break;
				}

				Color normal;
				Color bright;
				Color dark;

				if (ccodes<1) {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Expected at least 1, 2 or 3 html color codes.");
					ERR_FAIL_V(RES());
				} else if (ccodes==1) {

					normal=Color::html(params[1]);
					bright=Color::html(params[1]);
					dark=Color::html(params[1]);
				} else if (ccodes==2) {

					normal=Color::html(params[1]);
					bright=Color::html(params[2]);
					dark=Color::html(params[2]);
				} else {

					normal=Color::html(params[1]);
					bright=Color::html(params[2]);
					dark=Color::html(params[3]);
				}

				sbflat->set_dark_color(dark);
				sbflat->set_light_color(bright);
				sbflat->set_bg_color(normal);

				if (params.size()==ccodes+5) {
					//margins
					for(int i=0;i<4;i++) {

						if (!params[i+ccodes+1].is_valid_integer()) {
							memdelete(f);
							ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid expand margin parameter for sboxf #"+itos(i+ccodes+1) +", expected integer constant, got: '"+params[i+ccodes+1]+"'.");
							ERR_FAIL_V(RES());
						}

//						int margin = params[i+ccodes+1].to_int();
						//sbflat->set_margin_size(Margin(i),margin);
					}
				} else if (params.size()!=ccodes+1) {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid amount of margin parameters for sboxt.");
					ERR_FAIL_V(RES());

				}


				value=sbflat;

			} else {
				memdelete(f);
				ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid constructor type: '"+type+"'.");
				ERR_FAIL_V(RES());

			}

		}


		//parse left and do something with it
		String left= l.substr(0,eqpos);

		if (reading_library) {

			left=left.strip_edges();
			if (!left.is_valid_identifier()) {
				memdelete(f);
				ERR_EXPLAIN(p_path+":"+itos(line)+": <LibraryItem> is not a valid identifier.");
				ERR_FAIL_V(RES());
			}
			if (library.has(left)) {
				memdelete(f);
				ERR_EXPLAIN(p_path+":"+itos(line)+": Already in library: '"+left+"'.");
				ERR_FAIL_V(RES());
			}

			library[left]=value;
		} else {

			int pointpos = left.find(".");
			if (pointpos==-1) {
				memdelete(f);
				ERR_EXPLAIN(p_path+":"+itos(line)+": Expected 'control.item=..' assign syntax.");
				ERR_FAIL_V(RES());
			}

			String control=left.substr(0,pointpos).strip_edges();
			if (!control.is_valid_identifier()) {
				memdelete(f);
				ERR_EXPLAIN(p_path+":"+itos(line)+": <Control> is not a valid identifier.");
				ERR_FAIL_V(RES());
			}
			String item=left.substr(pointpos+1,left.size()).strip_edges();
			if (!item.is_valid_identifier()) {
				memdelete(f);
				ERR_EXPLAIN(p_path+":"+itos(line)+": <Item> is not a valid identifier.");
				ERR_FAIL_V(RES());
			}

			if (value.get_type()==Variant::NIL) {
				//try to use exiting
				if (Theme::get_default()->has_stylebox(item,control))
					value=Theme::get_default()->get_stylebox(item,control);
				else if (Theme::get_default()->has_font(item,control))
					value=Theme::get_default()->get_font(item,control);
				else if (Theme::get_default()->has_icon(item,control))
					value=Theme::get_default()->get_icon(item,control);
				else if (Theme::get_default()->has_color(item,control))
					value=Theme::get_default()->get_color(item,control);
				else if (Theme::get_default()->has_constant(item,control))
					value=Theme::get_default()->get_constant(item,control);
				else {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Default not present for: '"+control+"."+item+"'.");
					ERR_FAIL_V(RES());
				}

			}

			if (value.get_type()==Variant::OBJECT) {

				Ref<Resource> res = value;
				if (!res.is_valid()) {

					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid resource (NULL).");
					ERR_FAIL_V(RES());
				}

				if (res->cast_to<StyleBox>()) {

					theme->set_stylebox(item,control,res);
				} else if (res->cast_to<Font>()) {
					theme->set_font(item,control,res);
				} else if (res->cast_to<Font>()) {
					theme->set_font(item,control,res);
				} else if (res->cast_to<Texture>()) {
					theme->set_icon(item,control,res);
				} else {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid resource type.");
					ERR_FAIL_V(RES());
				}
			} else if (value.get_type()==Variant::COLOR) {

				theme->set_color(item,control,value);

			} else if (value.get_type()==Variant::INT) {

				theme->set_constant(item,control,value);

			} else {

				memdelete(f);
				ERR_EXPLAIN(p_path+":"+itos(line)+": Couldn't even determine what this setting is! what did you do!?");
				ERR_FAIL_V(RES());
			}

		}


	}

	f->close();
	memdelete(f);

	return theme;
}
Exemple #17
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

}
Exemple #18
0
MethodBind *ClassDB::bind_methodfi(uint32_t p_flags, MethodBind *p_bind, const MethodDefinition &method_name, const Variant **p_defs, int p_defcount) {
	StringName mdname = method_name.name;
#else
MethodBind *ClassDB::bind_methodfi(uint32_t p_flags, MethodBind *p_bind, const char *method_name, const Variant **p_defs, int p_defcount) {
	StringName mdname = StaticCString::create(method_name);
#endif

	OBJTYPE_WLOCK;
	ERR_FAIL_COND_V(!p_bind, NULL);
	p_bind->set_name(mdname);

	String instance_type = p_bind->get_instance_class();

#ifdef DEBUG_ENABLED

	if (has_method(instance_type, mdname)) {
		ERR_EXPLAIN("Class " + String(instance_type) + " already has a method " + String(mdname));
		ERR_FAIL_V(NULL);
	}
#endif

	ClassInfo *type = classes.getptr(instance_type);
	if (!type) {
		ERR_PRINTS("Couldn't bind method '" + mdname + "' for instance: " + instance_type);
		memdelete(p_bind);
		ERR_FAIL_V(NULL);
	}

	if (type->method_map.has(mdname)) {
		memdelete(p_bind);
		// overloading not supported
		ERR_EXPLAIN("Method already bound: " + instance_type + "::" + mdname);
		ERR_FAIL_V(NULL);
	}

#ifdef DEBUG_METHODS_ENABLED

	if (method_name.args.size() > p_bind->get_argument_count()) {
		memdelete(p_bind);
		ERR_EXPLAIN("Method definition provides more arguments than the method actually has: " + instance_type + "::" + mdname);
		ERR_FAIL_V(NULL);
	}

	p_bind->set_argument_names(method_name.args);

	type->method_order.push_back(mdname);
#endif

	type->method_map[mdname] = p_bind;

	Vector<Variant> defvals;

	defvals.resize(p_defcount);
	for (int i = 0; i < p_defcount; i++) {

		defvals.write[i] = *p_defs[p_defcount - i - 1];
	}

	p_bind->set_default_arguments(defvals);
	p_bind->set_hint_flags(p_flags);
	return p_bind;
}
RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error, const String &p_path) {

	enum Status {

		STATUS_NONE,
		STATUS_READING_ID,
		STATUS_READING_STRING,
	};

	Status status = STATUS_NONE;

	String msg_id;
	String msg_str;
	String config;

	if (r_error)
		*r_error = ERR_FILE_CORRUPT;

	Ref<Translation> translation = Ref<Translation>(memnew(Translation));
	int line = 1;
	bool skip_this;
	bool skip_next;

	while (true) {

		String l = f->get_line();

		if (f->eof_reached()) {

			if (status == STATUS_READING_STRING) {

				if (msg_id != "") {
					if (!skip_this)
						translation->add_message(msg_id, msg_str);
				} else if (config == "")
					config = msg_str;
				break;

			} else if (status == STATUS_NONE)
				break;

			memdelete(f);
			ERR_EXPLAIN(p_path + ":" + itos(line) + " Unexpected EOF while reading 'msgid' at file: ");
			ERR_FAIL_V(RES());
		}

		l = l.strip_edges();

		if (l.begins_with("msgid")) {

			if (status == STATUS_READING_ID) {

				memdelete(f);
				ERR_EXPLAIN(p_path + ":" + itos(line) + " Unexpected 'msgid', was expecting 'msgstr' while parsing: ");
				ERR_FAIL_V(RES());
			}

			if (msg_id != "") {
				if (!skip_this)
					translation->add_message(msg_id, msg_str);
			} else if (config == "")
				config = msg_str;

			l = l.substr(5, l.length()).strip_edges();
			status = STATUS_READING_ID;
			msg_id = "";
			msg_str = "";
			skip_this = skip_next;
			skip_next = false;
		}

		if (l.begins_with("msgstr")) {

			if (status != STATUS_READING_ID) {

				memdelete(f);
				ERR_EXPLAIN(p_path + ":" + itos(line) + " Unexpected 'msgstr', was expecting 'msgid' while parsing: ");
				ERR_FAIL_V(RES());
			}

			l = l.substr(6, l.length()).strip_edges();
			status = STATUS_READING_STRING;
		}

		if (l == "" || l.begins_with("#")) {
			if (l.find("fuzzy") != -1) {
				skip_next = true;
			}
			line++;
			continue; //nothing to read or comment
		}

		if (!l.begins_with("\"") || status == STATUS_NONE) {
			//not a string? failure!
			ERR_EXPLAIN(p_path + ":" + itos(line) + " Invalid line '" + l + "' while parsing: ");
			ERR_FAIL_V(RES());
		}

		l = l.substr(1, l.length());
		//find final quote
		int end_pos = -1;
		for (int i = 0; i < l.length(); i++) {

			if (l[i] == '"' && (i == 0 || l[i - 1] != '\\')) {
				end_pos = i;
				break;
			}
		}

		if (end_pos == -1) {
			ERR_EXPLAIN(p_path + ":" + itos(line) + " Expected '\"' at end of message while parsing file: ");
			ERR_FAIL_V(RES());
		}

		l = l.substr(0, end_pos);
		l = l.c_unescape();

		if (status == STATUS_READING_ID)
			msg_id += l;
		else
			msg_str += l;

		line++;
	}

	f->close();
	memdelete(f);

	if (config == "") {
		ERR_EXPLAIN("No config found in file: " + p_path);
		ERR_FAIL_V(RES());
	}

	Vector<String> configs = config.split("\n");
	for (int i = 0; i < configs.size(); i++) {

		String c = configs[i].strip_edges();
		int p = c.find(":");
		if (p == -1)
			continue;
		String prop = c.substr(0, p).strip_edges();
		String value = c.substr(p + 1, c.length()).strip_edges();

		if (prop == "X-Language") {
			translation->set_locale(value);
		}
	}

	if (r_error)
		*r_error = OK;

	return translation;
}
Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v)  {


	uint32_t type = f->get_32();
	print_bl("find property of type: "+itos(type));


	switch(type) {

		case VARIANT_NIL: {

			r_v=Variant();
		} break;
		case VARIANT_BOOL: {

			r_v=bool(f->get_32());
		} break;
		case VARIANT_INT: {

			r_v=int(f->get_32());
		} break;
		case VARIANT_REAL: {

			r_v=f->get_real();
		} break;
		case VARIANT_STRING: {

			r_v=get_unicode_string();
		} break;
		case VARIANT_VECTOR2: {

			Vector2 v;
			v.x=f->get_real();
			v.y=f->get_real();
			r_v=v;

		} break;
		case VARIANT_RECT2: {

			Rect2 v;
			v.pos.x=f->get_real();
			v.pos.y=f->get_real();
			v.size.x=f->get_real();
			v.size.y=f->get_real();
			r_v=v;

		} break;
		case VARIANT_VECTOR3: {

			Vector3 v;
			v.x=f->get_real();
			v.y=f->get_real();
			v.z=f->get_real();
			r_v=v;
		} break;
		case VARIANT_PLANE: {

			Plane v;
			v.normal.x=f->get_real();
			v.normal.y=f->get_real();
			v.normal.z=f->get_real();
			v.d=f->get_real();
			r_v=v;
		} break;
		case VARIANT_QUAT: {
			Quat v;
			v.x=f->get_real();
			v.y=f->get_real();
			v.z=f->get_real();
			v.w=f->get_real();
			r_v=v;

		} break;
		case VARIANT_AABB: {

			AABB v;
			v.pos.x=f->get_real();
			v.pos.y=f->get_real();
			v.pos.z=f->get_real();
			v.size.x=f->get_real();
			v.size.y=f->get_real();
			v.size.z=f->get_real();
			r_v=v;

		} break;
		case VARIANT_MATRIX32: {

			Matrix32 v;
			v.elements[0].x=f->get_real();
			v.elements[0].y=f->get_real();
			v.elements[1].x=f->get_real();
			v.elements[1].y=f->get_real();
			v.elements[2].x=f->get_real();
			v.elements[2].y=f->get_real();
			r_v=v;

		} break;
		case VARIANT_MATRIX3: {

			Matrix3 v;
			v.elements[0].x=f->get_real();
			v.elements[0].y=f->get_real();
			v.elements[0].z=f->get_real();
			v.elements[1].x=f->get_real();
			v.elements[1].y=f->get_real();
			v.elements[1].z=f->get_real();
			v.elements[2].x=f->get_real();
			v.elements[2].y=f->get_real();
			v.elements[2].z=f->get_real();
			r_v=v;

		} break;
		case VARIANT_TRANSFORM: {

			Transform v;
			v.basis.elements[0].x=f->get_real();
			v.basis.elements[0].y=f->get_real();
			v.basis.elements[0].z=f->get_real();
			v.basis.elements[1].x=f->get_real();
			v.basis.elements[1].y=f->get_real();
			v.basis.elements[1].z=f->get_real();
			v.basis.elements[2].x=f->get_real();
			v.basis.elements[2].y=f->get_real();
			v.basis.elements[2].z=f->get_real();
			v.origin.x=f->get_real();
			v.origin.y=f->get_real();
			v.origin.z=f->get_real();
			r_v=v;
		} break;
		case VARIANT_COLOR: {

			Color v;
			v.r=f->get_real();
			v.g=f->get_real();
			v.b=f->get_real();
			v.a=f->get_real();
			r_v=v;

		} break;
		case VARIANT_IMAGE: {


			uint32_t encoding = f->get_32();
			if (encoding==IMAGE_ENCODING_EMPTY) {
				r_v=Variant();
				break;
			} else if (encoding==IMAGE_ENCODING_RAW) {
				uint32_t width = f->get_32();
				uint32_t height = f->get_32();
				uint32_t mipmaps = f->get_32();
				uint32_t format = f->get_32();
				Image::Format fmt;
				switch(format) {

					case IMAGE_FORMAT_GRAYSCALE: { fmt=Image::FORMAT_GRAYSCALE; } break;
					case IMAGE_FORMAT_INTENSITY: { fmt=Image::FORMAT_INTENSITY; } break;
					case IMAGE_FORMAT_GRAYSCALE_ALPHA: { fmt=Image::FORMAT_GRAYSCALE_ALPHA; } break;
					case IMAGE_FORMAT_RGB: { fmt=Image::FORMAT_RGB; } break;
					case IMAGE_FORMAT_RGBA: { fmt=Image::FORMAT_RGBA; } break;
					case IMAGE_FORMAT_INDEXED: { fmt=Image::FORMAT_INDEXED; } break;
					case IMAGE_FORMAT_INDEXED_ALPHA: { fmt=Image::FORMAT_INDEXED_ALPHA; } break;
					case IMAGE_FORMAT_BC1: { fmt=Image::FORMAT_BC1; } break;
					case IMAGE_FORMAT_BC2: { fmt=Image::FORMAT_BC2; } break;
					case IMAGE_FORMAT_BC3: { fmt=Image::FORMAT_BC3; } break;
					case IMAGE_FORMAT_BC4: { fmt=Image::FORMAT_BC4; } break;
					case IMAGE_FORMAT_BC5: { fmt=Image::FORMAT_BC5; } break;
					case IMAGE_FORMAT_PVRTC2: { fmt=Image::FORMAT_PVRTC2; } break;
					case IMAGE_FORMAT_PVRTC2_ALPHA: { fmt=Image::FORMAT_PVRTC2_ALPHA; } break;
					case IMAGE_FORMAT_PVRTC4: { fmt=Image::FORMAT_PVRTC4; } break;
					case IMAGE_FORMAT_PVRTC4_ALPHA: { fmt=Image::FORMAT_PVRTC4_ALPHA; } break;
					case IMAGE_FORMAT_ETC: { fmt=Image::FORMAT_ETC; } break;
					case IMAGE_FORMAT_CUSTOM: { fmt=Image::FORMAT_CUSTOM; } break;
					default: {

						ERR_FAIL_V(ERR_FILE_CORRUPT);
					}

				}


				uint32_t datalen = f->get_32();

				DVector<uint8_t> imgdata;
				imgdata.resize(datalen);
				DVector<uint8_t>::Write w = imgdata.write();
				f->get_buffer(w.ptr(),datalen);
				_advance_padding(datalen);
				w=DVector<uint8_t>::Write();

				r_v=Image(width,height,mipmaps,fmt,imgdata);

			} else {
				//compressed
				DVector<uint8_t> data;
				data.resize(f->get_32());
				DVector<uint8_t>::Write w = data.write();
				f->get_buffer(w.ptr(),data.size());
				w = DVector<uint8_t>::Write();

				Image img;

				if (encoding==IMAGE_ENCODING_LOSSY && Image::lossy_unpacker) {

					img = Image::lossy_unpacker(data);
				} else if (encoding==IMAGE_ENCODING_LOSSLESS && Image::lossless_unpacker) {

					img = Image::lossless_unpacker(data);
				}
				_advance_padding(data.size());


				r_v=img;

			}

		} break;
		case VARIANT_NODE_PATH: {

			Vector<StringName> names;
			Vector<StringName> subnames;
			StringName property;
			bool absolute;

			int name_count = f->get_16();
			uint32_t subname_count = f->get_16();
			absolute=subname_count&0x8000;
			subname_count&=0x7FFF;


			for(int i=0;i<name_count;i++)
				names.push_back(string_map[f->get_32()]);
			for(uint32_t i=0;i<subname_count;i++)
				subnames.push_back(string_map[f->get_32()]);
			property=string_map[f->get_32()];

			NodePath np = NodePath(names,subnames,absolute,property);
			//print_line("got path: "+String(np));

			r_v=np;

		} break;
		case VARIANT_RID: {

			r_v=f->get_32();
		} break;
		case VARIANT_OBJECT: {

			uint32_t type=f->get_32();

			switch(type) {

				case OBJECT_EMPTY: {
					//do none

				} break;
				case OBJECT_INTERNAL_RESOURCE: {
					uint32_t index=f->get_32();
					String path = res_path+"::"+itos(index);
					RES res = ResourceLoader::load(path);
					if (res.is_null()) {
						WARN_PRINT(String("Couldn't load resource: "+path).utf8().get_data());
					}
					r_v=res;

				} break;
				case OBJECT_EXTERNAL_RESOURCE: {

					String type = get_unicode_string();
					String path = get_unicode_string();

					if (path.find("://")==-1 && path.is_rel_path()) {
						// path is relative to file being loaded, so convert to a resource path
						path=Globals::get_singleton()->localize_path(res_path.get_base_dir()+"/"+path);

					}

					RES res=ResourceLoader::load(path,type);

					if (res.is_null()) {
						WARN_PRINT(String("Couldn't load resource: "+path).utf8().get_data());
					}
					r_v=res;

				} break;
				default: {

					ERR_FAIL_V(ERR_FILE_CORRUPT);
				} break;
			}

		} break;
		case VARIANT_INPUT_EVENT: {

		} break;
		case VARIANT_DICTIONARY: {

            uint32_t len=f->get_32();
            Dictionary d(len&0x80000000); //last bit means shared
            len&=0x7FFFFFFF;
            for(uint32_t i=0;i<len;i++) {
				Variant key;
				Error err = parse_variant(key);
				ERR_FAIL_COND_V(err,ERR_FILE_CORRUPT);
				Variant value;
				err = parse_variant(value);
				ERR_FAIL_COND_V(err,ERR_FILE_CORRUPT);
				d[key]=value;
			}
			r_v=d;
		} break;
		case VARIANT_ARRAY: {

            uint32_t len=f->get_32();
            Array a(len&0x80000000); //last bit means shared
            len&=0x7FFFFFFF;
			a.resize(len);
            for(uint32_t i=0;i<len;i++) {
				Variant val;
				Error err = parse_variant(val);
				ERR_FAIL_COND_V(err,ERR_FILE_CORRUPT);
				a[i]=val;
			}
			r_v=a;

		} break;
		case VARIANT_RAW_ARRAY: {

			uint32_t len = f->get_32();

			DVector<uint8_t> array;
			array.resize(len);
			DVector<uint8_t>::Write w = array.write();
			f->get_buffer(w.ptr(),len);
			_advance_padding(len);
			w=DVector<uint8_t>::Write();
			r_v=array;

		} break;
		case VARIANT_INT_ARRAY: {

			uint32_t len = f->get_32();

			DVector<int> array;
			array.resize(len);
			DVector<int>::Write w = array.write();
			f->get_buffer((uint8_t*)w.ptr(),len*4);
#ifdef BIG_ENDIAN_ENABLED
			{
				uint32_t *ptr=(uint32_t*)w.ptr();
				for(int i=0;i<len;i++) {

					ptr[i]=BSWAP32(ptr[i]);
				}
			}

#endif
			w=DVector<int>::Write();
			r_v=array;
		} break;
		case VARIANT_REAL_ARRAY: {

			uint32_t len = f->get_32();

			DVector<real_t> array;
			array.resize(len);
			DVector<real_t>::Write w = array.write();
			f->get_buffer((uint8_t*)w.ptr(),len*sizeof(real_t));
#ifdef BIG_ENDIAN_ENABLED
			{
				uint32_t *ptr=(uint32_t*)w.ptr();
				for(int i=0;i<len;i++) {

					ptr[i]=BSWAP32(ptr[i]);
				}
			}

#endif

			w=DVector<real_t>::Write();
			r_v=array;
		} break;
		case VARIANT_STRING_ARRAY: {

			uint32_t len = f->get_32();
			DVector<String> array;
			array.resize(len);
			DVector<String>::Write w = array.write();
			for(uint32_t i=0;i<len;i++)
				w[i]=get_unicode_string();
			w=DVector<String>::Write();
			r_v=array;


		} break;
		case VARIANT_VECTOR2_ARRAY: {

			uint32_t len = f->get_32();

			DVector<Vector2> array;
			array.resize(len);
			DVector<Vector2>::Write w = array.write();
			if (sizeof(Vector2)==8) {
				f->get_buffer((uint8_t*)w.ptr(),len*sizeof(real_t)*2);
#ifdef BIG_ENDIAN_ENABLED
			{
				uint32_t *ptr=(uint32_t*)w.ptr();
				for(int i=0;i<len*2;i++) {

					ptr[i]=BSWAP32(ptr[i]);
				}
			}

#endif

			} else {
				ERR_EXPLAIN("Vector2 size is NOT 8!");
				ERR_FAIL_V(ERR_UNAVAILABLE);
			}
			w=DVector<Vector2>::Write();
			r_v=array;

		} break;
		case VARIANT_VECTOR3_ARRAY: {

			uint32_t len = f->get_32();

			DVector<Vector3> array;
			array.resize(len);
			DVector<Vector3>::Write w = array.write();
			if (sizeof(Vector3)==12) {
				f->get_buffer((uint8_t*)w.ptr(),len*sizeof(real_t)*3);
#ifdef BIG_ENDIAN_ENABLED
				{
					uint32_t *ptr=(uint32_t*)w.ptr();
					for(int i=0;i<len*3;i++) {

						ptr[i]=BSWAP32(ptr[i]);
					}
				}

#endif

			} else {
				ERR_EXPLAIN("Vector3 size is NOT 12!");
				ERR_FAIL_V(ERR_UNAVAILABLE);
			}
			w=DVector<Vector3>::Write();
			r_v=array;

		} break;
		case VARIANT_COLOR_ARRAY: {

			uint32_t len = f->get_32();

			DVector<Color> array;
			array.resize(len);
			DVector<Color>::Write w = array.write();
			if (sizeof(Color)==16) {
				f->get_buffer((uint8_t*)w.ptr(),len*sizeof(real_t)*4);
#ifdef BIG_ENDIAN_ENABLED
			{
				uint32_t *ptr=(uint32_t*)w.ptr();
				for(int i=0;i<len*4;i++) {

					ptr[i]=BSWAP32(ptr[i]);
				}
			}

#endif

			} else {
				ERR_EXPLAIN("Color size is NOT 16!");
				ERR_FAIL_V(ERR_UNAVAILABLE);
			}
			w=DVector<Color>::Write();
			r_v=array;
		} break;

		default: {
			ERR_FAIL_V(ERR_FILE_CORRUPT);
		} break;
	}



	return OK; //never reach anyway

}
Exemple #21
0
Error PoolAllocator::resize(ID p_mem,int p_new_size) {

	mt_lock();
	Entry *e=get_entry(p_mem);

	if (!e) {
		mt_unlock();
		ERR_FAIL_COND_V(!e,ERR_INVALID_PARAMETER);
	}

	if (needs_locking && e->lock) {
		mt_unlock();
		ERR_FAIL_COND_V(e->lock,ERR_ALREADY_IN_USE);
	}

	int alloc_size = aligned(p_new_size);

	if (aligned(e->len)==alloc_size) {

		e->len=p_new_size;
		mt_unlock();
		return OK;
	} else if (e->len>(uint32_t)p_new_size) {

		free_mem += aligned(e->len);
		free_mem -= alloc_size;
		e->len=p_new_size;
		mt_unlock();
		return OK;
	}

	//p_new_size = align(p_new_size)
	int _total = pool_size; // - static_area_size;
	int _free = free_mem; // - static_area_size;

	if ((_free + aligned(e->len)) - alloc_size < 0) {
		mt_unlock();
		ERR_FAIL_V( ERR_OUT_OF_MEMORY );
	};

	EntryIndicesPos entry_indices_pos;

	bool index_found = find_entry_index(&entry_indices_pos,e);

	if (!index_found) {

		mt_unlock();
		ERR_FAIL_COND_V(!index_found,ERR_BUG);
	}

	//no need to move stuff around, it fits before the next block
	int next_pos;
	if (entry_indices_pos+1 == entry_count) {
		next_pos = pool_size; // - static_area_size;
	} else {
		next_pos = entry_array[entry_indices[entry_indices_pos+1]].pos;
	};

	if ((next_pos - e->pos) > alloc_size) {
		free_mem+=aligned(e->len);
		e->len=p_new_size;
		free_mem-=alloc_size;
		mt_unlock();
		return OK;
	}
	//it doesn't fit, compact around BEFORE current index (make room behind)

	compact(entry_indices_pos+1);


	if ((next_pos - e->pos) > alloc_size) {
		//now fits! hooray!
		free_mem+=aligned(e->len);
		e->len=p_new_size;
		free_mem-=alloc_size;
		mt_unlock();
		if (free_mem<free_mem_peak)
			free_mem_peak=free_mem;
		return OK;
	}

	//STILL doesn't fit, compact around AFTER current index (make room after)

	compact_up(entry_indices_pos+1);

	if ((entry_array[entry_indices[entry_indices_pos+1]].pos - e->pos) > alloc_size) {
		//now fits! hooray!
		free_mem+=aligned(e->len);
		e->len=p_new_size;
		free_mem-=alloc_size;
		mt_unlock();
		if (free_mem<free_mem_peak)
			free_mem_peak=free_mem;
		return OK;
	}

	mt_unlock();
	ERR_FAIL_V(ERR_OUT_OF_MEMORY);

}
Error ResourceInteractiveLoaderBinary::poll(){

	if (error!=OK)
		return error;


	int s = stage;

	if (s<external_resources.size()) {

		RES res = ResourceLoader::load(external_resources[s].path,external_resources[s].type);
		if (res.is_null()) {

			if (!ResourceLoader::get_abort_on_missing_resources()) {

				ResourceLoader::notify_load_error("Resource Not Found: "+external_resources[s].path);
			} else {


				error=ERR_FILE_CORRUPT;
				ERR_EXPLAIN("Can't load dependency: "+external_resources[s].path);
				ERR_FAIL_V(error);
			}

		} else {
			resource_cache.push_back(res);
		}

		stage++;
		return OK;
	}

	s-=external_resources.size();


	if (s>=internal_resources.size()) {

		error=ERR_BUG;
		ERR_FAIL_COND_V(s>=internal_resources.size(),error);
	}

	bool main = s==(internal_resources.size()-1);

	//maybe it is loaded already
	String path;



	if (!main) {

		path=internal_resources[s].path;
		if (path.begins_with("local://"))
			path=path.replace("local://",res_path+"::");



		if (ResourceCache::has(path)) {
			//already loaded, don't do anything
			stage++;
			error=OK;
			return error;
		}
	} else {

		path=res_path;
	}

	uint64_t offset = internal_resources[s].offset;

	f->seek(offset);

	String t = get_unicode_string();

	Object *obj = ObjectTypeDB::instance(t);
	if (!obj) {
		error=ERR_FILE_CORRUPT;
		ERR_EXPLAIN(local_path+":Resource of unrecognized type in file: "+t);
	}
	ERR_FAIL_COND_V(!obj,ERR_FILE_CORRUPT);

	Resource *r = obj->cast_to<Resource>();
	if (!r) {
		error=ERR_FILE_CORRUPT;
		memdelete(obj); //bye
		ERR_EXPLAIN(local_path+":Resoucre type in resource field not a resource, type is: "+obj->get_type());
		ERR_FAIL_COND_V(!r,ERR_FILE_CORRUPT);
	}

	RES res = RES( r );

	r->set_path(path);

	int pc = f->get_32();

	//set properties

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

		uint32_t name_idx = f->get_32();
		if (name_idx>=(uint32_t)string_map.size()) {
			error=ERR_FILE_CORRUPT;
			ERR_FAIL_V(ERR_FILE_CORRUPT);
		}

		Variant value;

		error = parse_variant(value);
		if (error)
			return error;

		res->set(string_map[name_idx],value);
	}
#ifdef TOOLS_ENABLED
	res->set_edited(false);
#endif
	stage++;

	resource_cache.push_back(res);

	if (main) {
		if (importmd_ofs) {

			f->seek(importmd_ofs);
			Ref<ResourceImportMetadata> imd = memnew( ResourceImportMetadata );
			imd->set_editor(get_unicode_string());
			int sc = f->get_32();
			for(int i=0;i<sc;i++) {

				String src = get_unicode_string();
				String md5 = get_unicode_string();
				imd->add_source(src,md5);
			}
			int pc = f->get_32();

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

				String name = get_unicode_string();
				Variant val;
				parse_variant(val);
				imd->set_option(name,val);
			}
			res->set_import_metadata(imd);

		}
		f->close();
		resource=res;
		error=ERR_FILE_EOF;

	} else {
		error=OK;
	}

	return OK;

}
Exemple #23
0
MainLoop* test(TestType p_test) {

	List<String> cmdlargs = OS::get_singleton()->get_cmdline_args();

	if (cmdlargs.empty()) {
		//try editor!
		return NULL;
	}

	String test = cmdlargs.back()->get();

	FileAccess *fa = FileAccess::open(test,FileAccess::READ);

	if (!fa) {
		ERR_EXPLAIN("Could not open file: "+test);
		ERR_FAIL_V(NULL);
	}


	Vector<uint8_t> buf;
	int flen = fa->get_len();
	buf.resize(fa->get_len()+1);
	fa->get_buffer(&buf[0],flen);
	buf[flen]=0;

	String code;
	code.parse_utf8((const char*)&buf[0]);

	Vector<String> lines;
	int last=0;

	for(int i=0;i<=code.length();i++) {

		if (code[i]=='\n' || code[i]==0) {

			lines.push_back(code.substr(last,i-last));
			last=i+1;
		}
	}


	if (p_test==TEST_TOKENIZER) {

		GDTokenizerText tk;
		tk.set_code(code);
		int line=-1;
		while(tk.get_token()!=GDTokenizer::TK_EOF) {


			String text;
			if (tk.get_token()==GDTokenizer::TK_IDENTIFIER)
				text="'"+tk.get_token_identifier()+"' (identifier)";
			else if (tk.get_token()==GDTokenizer::TK_CONSTANT) {
				Variant c= tk.get_token_constant();
				if (c.get_type()==Variant::STRING)
					text="\""+String(c)+"\"";
				else
					text=c;

				text=text+" ("+Variant::get_type_name(c.get_type())+" constant)";
			} else if (tk.get_token()==GDTokenizer::TK_ERROR)
				text="ERROR: "+tk.get_token_error();
			else if (tk.get_token()==GDTokenizer::TK_NEWLINE)
				text="newline ("+itos(tk.get_token_line())+") + indent: "+itos(tk.get_token_line_indent());
			else if (tk.get_token()==GDTokenizer::TK_BUILT_IN_FUNC)
				text="'"+String(GDFunctions::get_func_name(tk.get_token_built_in_func()))+"' (built-in function)";
			else
				text=tk.get_token_name(tk.get_token());


			if (tk.get_token_line()!=line) {
				int from=line+1;
				line = tk.get_token_line();;

				for(int i=from;i<=line;i++) {
					int l=i-1;
					if (l>=0 && l<lines.size()) {
						print_line("\n"+itos(i)+": "+lines[l]+"\n");
					}
				}
			}
			print_line("\t("+itos(tk.get_token_column())+"): "+text);
			tk.advance();

		}
	}

	if (p_test==TEST_PARSER) {


		GDParser parser;
		Error err = parser.parse(code);
		if (err) {
			print_line("Parse Error:\n"+itos(parser.get_error_line())+":"+itos(parser.get_error_column())+":"+parser.get_error());
			memdelete(fa);
			return NULL;

		}

		const GDParser::Node* root = parser.get_parse_tree();
		ERR_FAIL_COND_V(root->type!=GDParser::Node::TYPE_CLASS,NULL);
		const GDParser::ClassNode *cnode=static_cast<const GDParser::ClassNode*>(root);

		_parser_show_class(cnode,0,lines);

	}

	if (p_test==TEST_COMPILER) {


		GDParser parser;

		Error err = parser.parse(code);
		if (err) {
			print_line("Parse Error:\n"+itos(parser.get_error_line())+":"+itos(parser.get_error_column())+":"+parser.get_error());
			memdelete(fa);
			return NULL;

		}

		GDScript *script = memnew( GDScript );

		GDCompiler gdc;
		err = gdc.compile(&parser,script);
		if (err) {

			print_line("Compile Error:\n"+itos(gdc.get_error_line())+":"+itos(gdc.get_error_column())+":"+gdc.get_error());
			memdelete(script);
			return NULL;

		}


		Ref<GDScript> gds =Ref<GDScript>( script );

		Ref<GDScript> current=gds;

		while(current.is_valid()) {

			print_line("** CLASS **");
			_disassemble_class(current,lines);

			current=current->get_base();
		}




	} else if (p_test==TEST_BYTECODE) {

		Vector<uint8_t> buf = GDTokenizerBuffer::parse_code_string(code);
		String dst = test.basename()+".gdc";
		FileAccess *fw = FileAccess::open(dst,FileAccess::WRITE);
		fw->store_buffer(buf.ptr(),buf.size());
		memdelete(fw);
	}


#if 0
	Parser parser;
	Error err = parser.parse(code);
	if (err) {
		print_line("error:"+itos(parser.get_error_line())+":"+itos(parser.get_error_column())+":"+parser.get_error());
	} else {
		print_line("Parse O-K!");
	}
#endif



	memdelete(fa);

	return NULL;
}
void ResourceInteractiveLoaderBinary::open(FileAccess *p_f) {


	error=OK;

	f=p_f;
	uint8_t header[4];
	f->get_buffer(header,4);
	if (header[0]=='R' && header[1]=='S' && header[2]=='C' && header[3]=='C') {
		//compressed
		FileAccessCompressed *fac = memnew( FileAccessCompressed );
		fac->open_after_magic(f);
		f=fac;

	} else if (header[0]!='R' || header[1]!='S' || header[2]!='R' || header[3]!='C') {
		//not normal

		error=ERR_FILE_UNRECOGNIZED;
		ERR_EXPLAIN("Unrecognized binary resource file: "+local_path);
		ERR_FAIL_V();
	}

	bool big_endian = f->get_32();
#ifdef BIG_ENDIAN_ENABLED
	endian_swap = !big_endian;
#else
	bool endian_swap = big_endian;
#endif

	bool use_real64 = f->get_32();

	f->set_endian_swap(big_endian!=0); //read big endian if saved as big endian

	uint32_t ver_major=f->get_32();
	uint32_t ver_minor=f->get_32();
	uint32_t ver_format=f->get_32();

	print_bl("big endian: "+itos(big_endian));
	print_bl("endian swap: "+itos(endian_swap));
	print_bl("real64: "+itos(use_real64));
	print_bl("major: "+itos(ver_major));
	print_bl("minor: "+itos(ver_minor));
	print_bl("format: "+itos(ver_format));

	if (ver_format<FORMAT_VERSION ||  ver_major>VERSION_MAJOR || (ver_major==VERSION_MAJOR && ver_minor>VERSION_MINOR)) {

		f->close();
		ERR_EXPLAIN("File Format '"+itos(FORMAT_VERSION)+"."+itos(ver_major)+"."+itos(ver_minor)+"' is too new! Please upgrade to a a new engine version: "+local_path);
		ERR_FAIL();

	}

	type=get_unicode_string();

	print_bl("type: "+type);

	importmd_ofs = f->get_64();
	for(int i=0;i<14;i++)
		f->get_32(); //skip a few reserved fields

	uint32_t string_table_size=f->get_32();
	string_map.resize(string_table_size);
	for(uint32_t i=0;i<string_table_size;i++) {

		StringName s = get_unicode_string();
		string_map[i]=s;
	}

	print_bl("strings: "+itos(string_table_size));

	uint32_t ext_resources_size=f->get_32();
	for(uint32_t i=0;i<ext_resources_size;i++) {

		ExtResoucre er;
		er.type=get_unicode_string();
		er.path=get_unicode_string();
		external_resources.push_back(er);

	}

	print_bl("ext resources: "+itos(ext_resources_size));
	uint32_t int_resources_size=f->get_32();

	for(uint32_t i=0;i<int_resources_size;i++) {

		IntResoucre ir;
		ir.path=get_unicode_string();
		ir.offset=f->get_64();
		internal_resources.push_back(ir);
	}

	print_bl("int resources: "+itos(int_resources_size));


	if (f->eof_reached()) {

		error=ERR_FILE_CORRUPT;
		ERR_EXPLAIN("Premature End Of File: "+local_path);
		ERR_FAIL();
	}

}
Error NetworkedMultiplayerENet::put_packet(const uint8_t *p_buffer,int p_buffer_size){

	ERR_FAIL_COND_V(!active,ERR_UNCONFIGURED);
	ERR_FAIL_COND_V(connection_status!=CONNECTION_CONNECTED,ERR_UNCONFIGURED);

	int packet_flags=0;

	switch(transfer_mode) {
		case TRANSFER_MODE_UNRELIABLE: {
			packet_flags=ENET_PACKET_FLAG_UNSEQUENCED;
		} break;
		case TRANSFER_MODE_UNRELIABLE_ORDERED: {
			packet_flags=0;
		} break;
		case TRANSFER_MODE_RELIABLE: {
			packet_flags=ENET_PACKET_FLAG_RELIABLE;
		} break;
	}

	Map<int,ENetPeer*>::Element *E=NULL;

	if (target_peer!=0) {

		E = peer_map.find(ABS(target_peer));
		if (!E) {
			ERR_EXPLAIN("Invalid Target Peer: "+itos(target_peer));
			ERR_FAIL_V(ERR_INVALID_PARAMETER);
		}
	}

	ENetPacket * packet = enet_packet_create (NULL,p_buffer_size+12,packet_flags);
	encode_uint32(unique_id,&packet->data[0]); //source ID
	encode_uint32(target_peer,&packet->data[4]); //dest ID
	encode_uint32(packet_flags,&packet->data[8]); //dest ID
	copymem(&packet->data[12],p_buffer,p_buffer_size);

	if (server) {

		if (target_peer==0) {
			enet_host_broadcast(host,0,packet);
		} else if (target_peer<0) {
			//send to all but one
			//and make copies for sending

			int exclude=-target_peer;

			for (Map<int,ENetPeer*>::Element *F=peer_map.front();F;F=F->next()) {

				if (F->key()==exclude) // exclude packet
					continue;

				ENetPacket* packet2 = enet_packet_create (packet->data,packet->dataLength,packet_flags);

				enet_peer_send(F->get(),0,packet2);
			}

			enet_packet_destroy(packet); //original packet no longer needed
		} else {
			enet_peer_send (E->get(), 0, packet);

		}
	} else {

		ERR_FAIL_COND_V(!peer_map.has(1),ERR_BUG);
		enet_peer_send (peer_map[1], 0, packet); //send to server for broadcast..

	}

	enet_host_flush(host);

	return OK;
}
Exemple #26
0
Vector<uint8_t> GDTokenizerBuffer::parse_code_string(const String& p_code) {

	Vector<uint8_t> buf;


	Map<StringName,int> identifier_map;
	HashMap<Variant,int,VariantHasher> constant_map;
	Map<uint32_t,int> line_map;
	Vector<uint32_t> token_array;

	GDTokenizerText tt;
	tt.set_code(p_code);
	int line=-1;

	while(true) {

		if (tt.get_token_line()!=line) {

			line=tt.get_token_line();
			line_map[line]=token_array.size();
		}

		uint32_t token=tt.get_token();
		switch(tt.get_token()) {

			case TK_IDENTIFIER: {
				StringName id = tt.get_token_identifier();
				if (!identifier_map.has(id)) {
					int idx = identifier_map.size();
					identifier_map[id]=idx;
				}
				token|=identifier_map[id]<<TOKEN_BITS;
			} break;
			case TK_CONSTANT: {

				Variant c = tt.get_token_constant();
				if (!constant_map.has(c)) {
					int idx = constant_map.size();
					constant_map[c]=idx;
				}
				token|=constant_map[c]<<TOKEN_BITS;
			} break;
			case TK_BUILT_IN_TYPE: {

				token|=tt.get_token_type()<<TOKEN_BITS;
			} break;
			case TK_BUILT_IN_FUNC: {

				token|=tt.get_token_built_in_func()<<TOKEN_BITS;

			} break;
			case TK_NEWLINE: {

				token|=tt.get_token_line_indent()<<TOKEN_BITS;
			} break;
			case TK_ERROR: {

				ERR_FAIL_V(Vector<uint8_t>());
			} break;
			default: {}

		};

		token_array.push_back(token);

		if (tt.get_token()==TK_EOF)
			break;
		tt.advance();

	}

	//reverse maps

	Map<int,StringName> rev_identifier_map;
	for(Map<StringName,int>::Element *E=identifier_map.front();E;E=E->next()) {
		rev_identifier_map[E->get()]=E->key();
	}

	Map<int,Variant> rev_constant_map;
	const Variant *K =NULL;
	while((K=constant_map.next(K))) {
		rev_constant_map[constant_map[*K]]=*K;
	}

	Map<int,uint32_t> rev_line_map;
	for(Map<uint32_t,int>::Element *E=line_map.front();E;E=E->next()) {
		rev_line_map[E->get()]=E->key();
	}

	//save header
	buf.resize(24);
	buf[0]='G';
	buf[1]='D';
	buf[2]='S';
	buf[3]='C';
	encode_uint32(BYTECODE_VERSION,&buf[4]);
	encode_uint32(identifier_map.size(),&buf[8]);
	encode_uint32(constant_map.size(),&buf[12]);
	encode_uint32(line_map.size(),&buf[16]);
	encode_uint32(token_array.size(),&buf[20]);

	//save identifiers

	for(Map<int,StringName>::Element *E=rev_identifier_map.front();E;E=E->next()) {

		CharString cs = String(E->get()).utf8();
		int len = cs.length()+1;
		int extra = 4-(len%4);
		if (extra==4)
			extra=0;

		uint8_t ibuf[4];
		encode_uint32(len+extra,ibuf);
		for(int i=0;i<4;i++) {
			buf.push_back(ibuf[i]);
		}
		for(int i=0;i<len;i++) {
			buf.push_back(cs[i]^0xb6);
		}
		for(int i=0;i<extra;i++) {
			buf.push_back(0^0xb6);
		}
	}

	for(Map<int,Variant>::Element *E=rev_constant_map.front();E;E=E->next()) {

		int len;
		Error err = encode_variant(E->get(),NULL,len);
		ERR_FAIL_COND_V(err!=OK,Vector<uint8_t>());
		int pos=buf.size();
		buf.resize(pos+len);
		encode_variant(E->get(),&buf[pos],len);
	}

	for(Map<int,uint32_t>::Element *E=rev_line_map.front();E;E=E->next()) {

		uint8_t ibuf[8];
		encode_uint32(E->key(),&ibuf[0]);
		encode_uint32(E->get(),&ibuf[4]);
		for(int i=0;i<8;i++)
			buf.push_back(ibuf[i]);
	}

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

		uint32_t token = token_array[i];

		if (token&~TOKEN_MASK) {
			uint8_t buf4[4];
			encode_uint32(token_array[i]|TOKEN_BYTE_MASK,&buf4[0]);
			for(int j=0;j<4;j++) {
				buf.push_back(buf4[j]);
			}
		} else {
			buf.push_back(token);
		}
	}

	return buf;

}
Exemple #27
0
bool HTTPRequest::_update_connection() {

	switch (client->get_status()) {
		case HTTPClient::STATUS_DISCONNECTED: {
			call_deferred("_request_done", RESULT_CANT_CONNECT, 0, PoolStringArray(), PoolByteArray());
			return true; //end it, since it's doing something
		} break;
		case HTTPClient::STATUS_RESOLVING: {
			client->poll();
			//must wait
			return false;
		} break;
		case HTTPClient::STATUS_CANT_RESOLVE: {
			call_deferred("_request_done", RESULT_CANT_RESOLVE, 0, PoolStringArray(), PoolByteArray());
			return true;

		} break;
		case HTTPClient::STATUS_CONNECTING: {
			client->poll();
			//must wait
			return false;
		} break; //connecting to ip
		case HTTPClient::STATUS_CANT_CONNECT: {

			call_deferred("_request_done", RESULT_CANT_CONNECT, 0, PoolStringArray(), PoolByteArray());
			return true;

		} break;
		case HTTPClient::STATUS_CONNECTED: {

			if (request_sent) {

				if (!got_response) {

					//no body

					bool ret_value;

					if (_handle_response(&ret_value))
						return ret_value;

					call_deferred("_request_done", RESULT_SUCCESS, response_code, response_headers, PoolByteArray());
					return true;
				}
				if (got_response && body_len < 0) {
					//chunked transfer is done
					call_deferred("_request_done", RESULT_SUCCESS, response_code, response_headers, body);
					return true;
				}

				call_deferred("_request_done", RESULT_CHUNKED_BODY_SIZE_MISMATCH, response_code, response_headers, PoolByteArray());
				return true;
				//request migh have been done
			} else {
				//did not request yet, do request

				Error err = client->request(method, request_string, headers, request_data);
				if (err != OK) {
					call_deferred("_request_done", RESULT_CONNECTION_ERROR, 0, PoolStringArray(), PoolByteArray());
					return true;
				}

				request_sent = true;
				return false;
			}
		} break; //connected: { } break requests only accepted here
		case HTTPClient::STATUS_REQUESTING: {
			//must wait, it's requesting
			client->poll();
			return false;

		} break; // request in progress
		case HTTPClient::STATUS_BODY: {

			if (!got_response) {

				bool ret_value;

				if (_handle_response(&ret_value))
					return ret_value;

				if (!client->is_response_chunked() && client->get_response_body_length() == 0) {

					call_deferred("_request_done", RESULT_SUCCESS, response_code, response_headers, PoolByteArray());
					return true;
				}

				if (client->is_response_chunked()) {
					body_len = -1; //no body len because chunked, change your webserver configuration if you want body len
				} else {
					body_len = client->get_response_body_length();

					if (body_size_limit >= 0 && body_len > body_size_limit) {
						call_deferred("_request_done", RESULT_BODY_SIZE_LIMIT_EXCEEDED, response_code, response_headers, PoolByteArray());
						return true;
					}
				}

				if (download_to_file != String()) {
					file = FileAccess::open(download_to_file, FileAccess::WRITE);
					if (!file) {

						call_deferred("_request_done", RESULT_DOWNLOAD_FILE_CANT_OPEN, response_code, response_headers, PoolByteArray());
						return true;
					}
				}
			}

			//print_line("BODY: "+itos(body.size()));
			client->poll();

			PoolByteArray chunk = client->read_response_body_chunk();
			downloaded += chunk.size();

			if (file) {
				PoolByteArray::Read r = chunk.read();
				file->store_buffer(r.ptr(), chunk.size());
				if (file->get_error() != OK) {
					call_deferred("_request_done", RESULT_DOWNLOAD_FILE_WRITE_ERROR, response_code, response_headers, PoolByteArray());
					return true;
				}
			} else {
				body.append_array(chunk);
			}

			if (body_size_limit >= 0 && downloaded > body_size_limit) {
				call_deferred("_request_done", RESULT_BODY_SIZE_LIMIT_EXCEEDED, response_code, response_headers, PoolByteArray());
				return true;
			}

			if (body_len >= 0) {

				if (downloaded == body_len) {
					call_deferred("_request_done", RESULT_SUCCESS, response_code, response_headers, body);
					return true;
				}
				/*if (body.size()>=body_len) {
					call_deferred("_request_done",RESULT_BODY_SIZE_MISMATCH,response_code,response_headers,ByteArray());
					return true;
				}*/
			}

			return false;

		} break; // request resulted in body: { } break which must be read
		case HTTPClient::STATUS_CONNECTION_ERROR: {
			call_deferred("_request_done", RESULT_CONNECTION_ERROR, 0, PoolStringArray(), PoolByteArray());
			return true;
		} break;
		case HTTPClient::STATUS_SSL_HANDSHAKE_ERROR: {
			call_deferred("_request_done", RESULT_SSL_HANDSHAKE_ERROR, 0, PoolStringArray(), PoolByteArray());
			return true;
		} break;
	}

	ERR_FAIL_V(false);
}
Exemple #28
0
String GDTokenizerBuffer::get_token_error(int p_offset) const{

	ERR_FAIL_V(String());
}
Exemple #29
0
int VisualServer::shader_get_output_count(ShaderNodeType p_type) {

	switch(p_type) {
		case NODE_IN: return 1;
		case NODE_OUT: return 0;
		case NODE_CONSTANT: return 1;
		case NODE_PARAMETER: return 1;
		case NODE_ADD: return 1;
		case NODE_SUB: return 1;
		case NODE_MUL: return 1;
		case NODE_DIV: return 1;
		case NODE_MOD: return 1;
		case NODE_SIN: return 1;
		case NODE_COS: return 1;
		case NODE_TAN: return 1;
		case NODE_ARCSIN: return 1;
		case NODE_ARCCOS: return 1;
		case NODE_ARCTAN: return 1;
		case NODE_POW: return 1;
		case NODE_LOG: return 1;
		case NODE_MAX: return 1;
		case NODE_MIN: return 1;
		case NODE_COMPARE: return 2;
		case NODE_TEXTURE: return 3;  ///< param  0: texture
		case NODE_TIME: return 1;  ///< param  0: interval length
		case NODE_NOISE: return 1;
		case NODE_PASS: return 1;
		case NODE_VEC_IN: return 1;  ///< param 0: name
		case NODE_VEC_OUT: return 0;  ///< param 0: name
		case NODE_VEC_CONSTANT: return 1;  ///< param  0: value
		case NODE_VEC_PARAMETER: return 1;  ///< param  0: name
		case NODE_VEC_ADD: return 1;
		case NODE_VEC_SUB: return 1;
		case NODE_VEC_MUL: return 1;
		case NODE_VEC_DIV: return 1;
		case NODE_VEC_MOD: return 1;
		case NODE_VEC_CROSS: return 1;
		case NODE_VEC_DOT: return 1;
		case NODE_VEC_POW: return 1;
		case NODE_VEC_NORMALIZE: return 1;
		case NODE_VEC_INTERPOLATE: return 1;
		case NODE_VEC_SCREEN_TO_UV: return 1;
		case NODE_VEC_TRANSFORM3: return 1;
		case NODE_VEC_TRANSFORM4: return 1;
		case NODE_VEC_COMPARE: return 2;
		case NODE_VEC_TEXTURE_2D: return 3;
		case NODE_VEC_TEXTURE_CUBE: return 3;
		case NODE_VEC_NOISE: return 1;
		case NODE_VEC_0: return 1;
		case NODE_VEC_1: return 1;
		case NODE_VEC_2: return 1;
		case NODE_VEC_BUILD: return 1;
		case NODE_VEC_PASS: return 1;
		case NODE_COLOR_CONSTANT: return 2;
		case NODE_COLOR_PARAMETER: return 2;
		case NODE_TEXTURE_PARAMETER:  return 3;
		case NODE_TEXTURE_2D_PARAMETER:  return 3;
		case NODE_TEXTURE_CUBE_PARAMETER:  return 3;
		case NODE_TRANSFORM_CONSTANT: return 1;
		case NODE_TRANSFORM_PARAMETER: return 1;
		case NODE_LABEL: return 0;

		default: {}
	}
	ERR_FAIL_V( 0 );

}
Exemple #30
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 );
		}

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


			switch(E->get().argtypes[i]) {

				case Variant::BOOL: {

					v[i].z=*p_args[i];
				} break;
				case Variant::INT: {

					v[i].i=*p_args[i];
				} break;
				case Variant::REAL: {

					v[i].f=*p_args[i];
				} break;
				case Variant::STRING: {

					String s = *p_args[i];
					jstring jStr = env->NewStringUTF(s.utf8().get_data());
					v[i].l=jStr;
				} break;
				case Variant::STRING_ARRAY: {

					DVector<String> sarray = *p_args[i];
					jobjectArray arr = env->NewObjectArray(sarray.size(),env->FindClass("java/lang/String"),env->NewStringUTF(""));

					for(int j=0;j<sarray.size();j++) {

						env->SetObjectArrayElement(arr,j,env->NewStringUTF( sarray[i].utf8().get_data() ));
					}
					v[i].l=arr;

				} break;
				case Variant::INT_ARRAY: {

					DVector<int> array = *p_args[i];
					jintArray arr = env->NewIntArray(array.size());
					DVector<int>::Read r = array.read();
					env->SetIntArrayRegion(arr,0,array.size(),r.ptr());
					v[i].l=arr;

				} break;
				case Variant::REAL_ARRAY: {

					DVector<float> array = *p_args[i];
					jfloatArray arr = env->NewFloatArray(array.size());
					DVector<float>::Read r = array.read();
					env->SetFloatArrayRegion(arr,0,array.size(),r.ptr());
					v[i].l=arr;

				} break;
				default: {

					ERR_FAIL_V(Variant());
				} break;

			}
		}

		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 singname = env->GetStringUTFChars((jstring)o, NULL );
			} break;
			case Variant::STRING_ARRAY: {

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

				int stringCount = env->GetArrayLength(arr);
				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));
				}

				ret=sarr;

			} 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;
			default: {


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

		print_line("success");

		return ret;
	}