virtual Vector<uint8_t> custom_export(String& p_path,const Ref<EditorExportPlatform> &p_platform) {
		//compile gdscript to bytecode

		if (EditorImportExport::get_singleton()->script_get_action()!=EditorImportExport::SCRIPT_ACTION_NONE) {

			if (p_path.ends_with(".gd")) {
				Vector<uint8_t> file = FileAccess::get_file_as_array(p_path);
				if (file.empty())
					return file;
				String txt;
				txt.parse_utf8((const char*)file.ptr(),file.size());
				file = GDTokenizerBuffer::parse_code_string(txt);

				if (!file.empty()) {

					if (EditorImportExport::get_singleton()->script_get_action()==EditorImportExport::SCRIPT_ACTION_ENCRYPT) {

						String tmp_path=EditorSettings::get_singleton()->get_settings_path().plus_file("tmp/script.gde");
						FileAccess *fa = FileAccess::open(tmp_path,FileAccess::WRITE);
						String skey=EditorImportExport::get_singleton()->script_get_encryption_key().to_lower();
						Vector<uint8_t> key;
						key.resize(32);
						for(int i=0;i<32;i++) {
							int v=0;
							if (i*2<skey.length()) {
								CharType ct = skey[i*2];
								if (ct>='0' && ct<='9')
									ct=ct-'0';
								else if (ct>='a' && ct<='f')
									ct=10+ct-'a';
								v|=ct<<4;
							}

							if (i*2+1<skey.length()) {
								CharType ct = skey[i*2+1];
								if (ct>='0' && ct<='9')
									ct=ct-'0';
								else if (ct>='a' && ct<='f')
									ct=10+ct-'a';
								v|=ct;
							}
							key[i]=v;
						}
						FileAccessEncrypted *fae=memnew(FileAccessEncrypted);
						Error err = fae->open_and_parse(fa,key,FileAccessEncrypted::MODE_WRITE_AES256);
						if (err==OK) {

							fae->store_buffer(file.ptr(),file.size());
							p_path=p_path.basename()+".gde";
						}

						memdelete(fae);

						file=FileAccess::get_file_as_array(tmp_path);
						return file;


					} else {

						p_path=p_path.basename()+".gdc";
						return file;
					}
				}

			}
		}

		return Vector<uint8_t>();
	}
Example #2
0
MainLoop *test(TestType p_type) {

	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.ptrw(), flen);
	buf.write[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_type == TEST_TOKENIZER) {

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

			String text;
			if (tk.get_token() == GDScriptTokenizer::TK_IDENTIFIER)
				text = "'" + tk.get_token_identifier() + "' (identifier)";
			else if (tk.get_token() == GDScriptTokenizer::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() == GDScriptTokenizer::TK_ERROR)
				text = "ERROR: " + tk.get_token_error();
			else if (tk.get_token() == GDScriptTokenizer::TK_NEWLINE)
				text = "newline (" + itos(tk.get_token_line()) + ") + indent: " + itos(tk.get_token_line_indent());
			else if (tk.get_token() == GDScriptTokenizer::TK_BUILT_IN_FUNC)
				text = "'" + String(GDScriptFunctions::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_type == TEST_PARSER) {

		GDScriptParser 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 GDScriptParser::Node *root = parser.get_parse_tree();
		ERR_FAIL_COND_V(root->type != GDScriptParser::Node::TYPE_CLASS, NULL);
		const GDScriptParser::ClassNode *cnode = static_cast<const GDScriptParser::ClassNode *>(root);

		_parser_show_class(cnode, 0, lines);
	}

	if (p_type == TEST_COMPILER) {

		GDScriptParser 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);

		GDScriptCompiler 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_type == TEST_BYTECODE) {

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

	memdelete(fa);

	return NULL;
}
Example #3
0
void OS_X11::set_icon(const Image& p_icon) {

	//does not work, if anyone knows why, please fix
	if (!p_icon.empty()) {

		Image img=p_icon;
		img.convert(Image::FORMAT_RGBA);


		int w = img.get_width();
		int h = img.get_height();

		Vector<long> pd;

		pd.resize((2+w*h)*sizeof(long));

		print_line("***** SET ICON ***** "+itos(w)+"  "+itos(h));

		pd[0]=w;
		pd[1]=h;

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

		long *wr=(long*)&pd[2];

		for(int i=0;i<w*h;i++) {

			uint32_t v=0;
			v|=r[i*4+3];
			v<<=8;
			v|=r[i*4+0];
			v<<=8;
			v|=r[i*4+1];
			v<<=8;
			v|=r[i*4+2];
			wr[i]=v;
		}

		XChangeProperty(x11_display, x11_window, net_wm_icon, XA_CARDINAL,	32, PropModeReplace, (unsigned char *) pd.ptr(),
				(2+w*h));
	} else {
	    XDeleteProperty(x11_display, x11_window, net_wm_icon);
	}
	XFlush(x11_display);

}
Example #4
0
Error EditorExportPlatformBB10::export_project(const String& p_path, bool p_debug, int p_flags) {


	EditorProgress ep("export","Exporting for BlackBerry 10",104);

	String src_template=custom_package;

	if (src_template=="") {
		String err;
		src_template = find_export_template("bb10.zip", &err);
		if (src_template=="") {
			EditorNode::add_io_error(err);
			return ERR_FILE_NOT_FOUND;
		}
	}

	FileAccess *src_f=NULL;
	zlib_filefunc_def io = zipio_create_io_from_file(&src_f);

	ep.step("Creating FileSystem for BAR",0);

	unzFile pkg = unzOpen2(src_template.utf8().get_data(), &io);
	if (!pkg) {

		EditorNode::add_io_error("Could not find template zip to export:\n"+src_template);
		return ERR_FILE_NOT_FOUND;
	}

	DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
	da->change_dir(EditorSettings::get_singleton()->get_settings_path());


	if (da->change_dir("tmp")!=OK) {
		da->make_dir("tmp");
		if (da->change_dir("tmp")!=OK)
			return ERR_CANT_CREATE;
	}

	if (da->change_dir("bb10_export")!=OK) {
		da->make_dir("bb10_export");
		if (da->change_dir("bb10_export")!=OK) {
			return ERR_CANT_CREATE;
		}
	}


	String bar_dir = da->get_current_dir();
	if (bar_dir.ends_with("/")) {
		bar_dir=bar_dir.substr(0,bar_dir.length()-1);
	}

	//THIS IS SUPER, SUPER DANGEROUS!!!!
	//CAREFUL WITH THIS CODE, MIGHT DELETE USERS HARD DRIVE OR HOME DIR
	//EXTRA CHECKS ARE IN PLACE EVERYWERE TO MAKE SURE NOTHING BAD HAPPENS BUT STILL....
	//BE SUPER CAREFUL WITH THIS PLEASE!!!
	//BLACKBERRY THIS IS YOUR FAULT FOR NOT MAKING A BETTER WAY!!

	bool berr = bar_dir.ends_with("bb10_export");
	if (berr) {
		if (da->list_dir_begin()) {
			EditorNode::add_io_error("Can't ensure that dir is empty:\n"+bar_dir);
			ERR_FAIL_COND_V(berr,FAILED);
		};

		String f = da->get_next();
		while (f != "") {

			if (f == "." || f == "..") {
				f = da->get_next();
				continue;
			};
			Error err = da->remove(bar_dir + "/" + f);
			if (err != OK) {
				EditorNode::add_io_error("Can't ensure that dir is empty:\n"+bar_dir);
				ERR_FAIL_COND_V(err!=OK,err);
			};
			f = da->get_next();
		};

		da->list_dir_end();

	} else {
		print_line("ARE YOU CRAZY??? THIS IS A SERIOUS BUG HERE!!!");
		ERR_FAIL_V(ERR_OMFG_THIS_IS_VERY_VERY_BAD);
	}


	ERR_FAIL_COND_V(!pkg, ERR_CANT_OPEN);
	int ret = unzGoToFirstFile(pkg);



	while(ret==UNZ_OK) {

		//get filename
		unz_file_info info;
		char fname[16384];
		ret = unzGetCurrentFileInfo(pkg,&info,fname,16384,NULL,0,NULL,0);

		String file=fname;

		Vector<uint8_t> data;
		data.resize(info.uncompressed_size);

		//read
		unzOpenCurrentFile(pkg);
		unzReadCurrentFile(pkg,data.ptr(),data.size());
		unzCloseCurrentFile(pkg);

		//write

		if (file=="bar-descriptor.xml") {

			_fix_descriptor(data);
		}

		if (file=="icon.png") {
			bool found=false;

			if (this->icon!="" && this->icon.ends_with(".png")) {

				FileAccess *f = FileAccess::open(this->icon,FileAccess::READ);
				if (f) {

					data.resize(f->get_len());
					f->get_buffer(data.ptr(),data.size());
					memdelete(f);
					found=true;
				}

			}

			if (!found) {

				String appicon = Globals::get_singleton()->get("application/icon");
				if (appicon!="" && appicon.ends_with(".png")) {
					FileAccess*f = FileAccess::open(appicon,FileAccess::READ);
					if (f) {
						data.resize(f->get_len());
						f->get_buffer(data.ptr(),data.size());
						memdelete(f);
					}
				}
			}
		}


		if (file.find("/")) {

			da->make_dir_recursive(file.get_base_dir());
		}

		FileAccessRef wf = FileAccess::open(bar_dir.plus_file(file),FileAccess::WRITE);
		wf->store_buffer(data.ptr(),data.size());

		ret = unzGoToNextFile(pkg);
	}

	ep.step("Adding Files..",2);

	FileAccess* dst = FileAccess::open(bar_dir+"/data.pck", FileAccess::WRITE);
	if (!dst) {
		EditorNode::add_io_error("Can't copy executable file to:\n "+p_path);
		return ERR_FILE_CANT_WRITE;
	}
	save_pack(dst, false, 1024);
	dst->close();
	memdelete(dst);

	ep.step("Creating BAR Package..",104);

	String bb_packager=EditorSettings::get_singleton()->get("blackberry/host_tools");
	bb_packager=bb_packager.plus_file("blackberry-nativepackager");
	if (OS::get_singleton()->get_name()=="Windows")
		bb_packager+=".bat";


	if (!FileAccess::exists(bb_packager)) {
		EditorNode::add_io_error("Can't find packager:\n"+bb_packager);
		return ERR_CANT_OPEN;
	}

	List<String> args;
	args.push_back("-package");
	args.push_back(p_path);
	if (p_debug) {

		String debug_token=EditorSettings::get_singleton()->get("blackberry/debug_token");
		if (!FileAccess::exists(debug_token)) {
			EditorNode::add_io_error("Debug token not found!");
		} else {
			args.push_back("-debugToken");
			args.push_back(debug_token);
		}
		args.push_back("-devMode");
		args.push_back("-configuration");
		args.push_back("Device-Debug");
	} else {

		args.push_back("-configuration");
		args.push_back("Device-Release");
	}
	args.push_back(bar_dir.plus_file("bar-descriptor.xml"));

	int ec;

	Error err = OS::get_singleton()->execute(bb_packager,args,true,NULL,NULL,&ec);

	if (err!=OK)
		return err;
	if (ec!=0)
		return ERR_CANT_CREATE;

	return OK;

}
Example #5
0
void Navigation::_navmesh_link(int p_id) {

	ERR_FAIL_COND(!navmesh_map.has(p_id));
	NavMesh &nm=navmesh_map[p_id];
	ERR_FAIL_COND(nm.linked);

	print_line("LINK");

	PoolVector<Vector3> vertices=nm.navmesh->get_vertices();
	int len = vertices.size();
	if (len==0)
		return;

	PoolVector<Vector3>::Read r=vertices.read();

	for(int i=0;i<nm.navmesh->get_polygon_count();i++) {

		//build

		List<Polygon>::Element *P=nm.polygons.push_back(Polygon());
		Polygon &p=P->get();
		p.owner=&nm;

		Vector<int> poly = nm.navmesh->get_polygon(i);
		int plen=poly.size();
		const int *indices=poly.ptr();
		bool valid=true;
		p.edges.resize(plen);

		Vector3 center;
		float sum=0;

		for(int j=0;j<plen;j++) {

			int idx = indices[j];
			if (idx<0 || idx>=len) {
				valid=false;
				break;
			}

			Polygon::Edge e;
			Vector3 ep=nm.xform.xform(r[idx]);
			center+=ep;
			e.point=_get_point(ep);
			p.edges[j]=e;

			if (j>=2) {
				Vector3 epa = nm.xform.xform(r[indices[j-2]]);
				Vector3 epb = nm.xform.xform(r[indices[j-1]]);

				sum+=up.dot((epb-epa).cross(ep-epa));

			}

		}

		p.clockwise=sum>0;

		if (!valid) {
			nm.polygons.pop_back();
			ERR_CONTINUE(!valid);
			continue;
		}

		p.center = center;
		if( plen != 0 ) {
			p.center /= plen;
		}


		//connect

		for(int j=0;j<plen;j++) {

			int next = (j+1)%plen;
			EdgeKey ek(p.edges[j].point,p.edges[next].point);

			Map<EdgeKey,Connection>::Element *C=connections.find(ek);
			if (!C) {

				Connection c;
				c.A=&p;
				c.A_edge=j;
				c.B=NULL;
				c.B_edge=-1;
				connections[ek]=c;
			} else {

				if (C->get().B!=NULL) {
					ConnectionPending pending;
					pending.polygon=&p;
					pending.edge=j;
					p.edges[j].P=C->get().pending.push_back(pending);
					continue;
					//print_line(String()+_get_vertex(ek.a)+" -> "+_get_vertex(ek.b));
				}
				//ERR_CONTINUE(C->get().B!=NULL); //wut

				C->get().B=&p;
				C->get().B_edge=j;
				C->get().A->edges[C->get().A_edge].C=&p;
				C->get().A->edges[C->get().A_edge].C_edge=j;
				p.edges[j].C=C->get().A;
				p.edges[j].C_edge=C->get().A_edge;
				//connection successful.
			}
		}
	}

	nm.linked=true;

}
Example #6
0
Array Physics2DDirectSpaceState::_collide_shape(const Ref<Physics2DShapeQueryParameters> &p_shape_query, int p_max_results) {

	Vector<Vector2> ret;
	ret.resize(p_max_results * 2);
	int rc = 0;
	bool res = collide_shape(p_shape_query->shape, p_shape_query->transform, p_shape_query->motion, p_shape_query->margin, ret.ptr(), p_max_results, rc, p_shape_query->exclude, p_shape_query->collision_layer, p_shape_query->object_type_mask);
	if (!res)
		return Array();
	Array r;
	r.resize(rc * 2);
	for (int i = 0; i < rc * 2; i++)
		r[i] = ret[i];
	return r;
}
Example #7
0
void Polygon2D::_notification(int p_what) {

	switch (p_what) {

		case NOTIFICATION_DRAW: {

			if (polygon.size() < 3)
				return;

			Skeleton2D *skeleton_node = NULL;
			if (has_node(skeleton)) {
				skeleton_node = Object::cast_to<Skeleton2D>(get_node(skeleton));
			}

			ObjectID new_skeleton_id = 0;

			if (skeleton_node) {
				VS::get_singleton()->canvas_item_attach_skeleton(get_canvas_item(), skeleton_node->get_skeleton());
				new_skeleton_id = skeleton_node->get_instance_id();
			} else {
				VS::get_singleton()->canvas_item_attach_skeleton(get_canvas_item(), RID());
			}

			if (new_skeleton_id != current_skeleton_id) {
				Object *old_skeleton = ObjectDB::get_instance(current_skeleton_id);
				if (old_skeleton) {
					old_skeleton->disconnect("bone_setup_changed", this, "_skeleton_bone_setup_changed");
				}

				if (skeleton_node) {
					skeleton_node->connect("bone_setup_changed", this, "_skeleton_bone_setup_changed");
				}

				current_skeleton_id = new_skeleton_id;
			}

			Vector<Vector2> points;
			Vector<Vector2> uvs;
			Vector<int> bones;
			Vector<float> weights;

			int len = polygon.size();
			if ((invert || polygons.size() == 0) && internal_vertices > 0) {
				//if no polygons are around, internal vertices must not be drawn, else let them be
				len -= internal_vertices;
			}

			if (len <= 0) {
				return;
			}
			points.resize(len);

			{

				PoolVector<Vector2>::Read polyr = polygon.read();
				for (int i = 0; i < len; i++) {
					points.write[i] = polyr[i] + offset;
				}
			}

			if (invert) {

				Rect2 bounds;
				int highest_idx = -1;
				float highest_y = -1e20;
				float sum = 0;

				for (int i = 0; i < len; i++) {
					if (i == 0)
						bounds.position = points[i];
					else
						bounds.expand_to(points[i]);
					if (points[i].y > highest_y) {
						highest_idx = i;
						highest_y = points[i].y;
					}
					int ni = (i + 1) % len;
					sum += (points[ni].x - points[i].x) * (points[ni].y + points[i].y);
				}

				bounds = bounds.grow(invert_border);

				Vector2 ep[7] = {
					Vector2(points[highest_idx].x, points[highest_idx].y + invert_border),
					Vector2(bounds.position + bounds.size),
					Vector2(bounds.position + Vector2(bounds.size.x, 0)),
					Vector2(bounds.position),
					Vector2(bounds.position + Vector2(0, bounds.size.y)),
					Vector2(points[highest_idx].x - CMP_EPSILON, points[highest_idx].y + invert_border),
					Vector2(points[highest_idx].x - CMP_EPSILON, points[highest_idx].y),
				};

				if (sum > 0) {
					SWAP(ep[1], ep[4]);
					SWAP(ep[2], ep[3]);
					SWAP(ep[5], ep[0]);
					SWAP(ep[6], points.write[highest_idx]);
				}

				points.resize(points.size() + 7);
				for (int i = points.size() - 1; i >= highest_idx + 7; i--) {

					points.write[i] = points[i - 7];
				}

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

					points.write[highest_idx + i + 1] = ep[i];
				}

				len = points.size();
			}

			if (texture.is_valid()) {

				Transform2D texmat(tex_rot, tex_ofs);
				texmat.scale(tex_scale);
				Size2 tex_size = texture->get_size();

				uvs.resize(len);

				if (points.size() == uv.size()) {

					PoolVector<Vector2>::Read uvr = uv.read();

					for (int i = 0; i < len; i++) {
						uvs.write[i] = texmat.xform(uvr[i]) / tex_size;
					}

				} else {
					for (int i = 0; i < len; i++) {
						uvs.write[i] = texmat.xform(points[i]) / tex_size;
					}
				}
			}

			if (skeleton_node && !invert && bone_weights.size()) {
				//a skeleton is set! fill indices and weights
				int vc = len;
				bones.resize(vc * 4);
				weights.resize(vc * 4);

				int *bonesw = bones.ptrw();
				float *weightsw = weights.ptrw();

				for (int i = 0; i < vc * 4; i++) {
					bonesw[i] = 0;
					weightsw[i] = 0;
				}

				for (int i = 0; i < bone_weights.size(); i++) {
					if (bone_weights[i].weights.size() != points.size()) {
						continue; //different number of vertices, sorry not using.
					}
					if (!skeleton_node->has_node(bone_weights[i].path)) {
						continue; //node does not exist
					}
					Bone2D *bone = Object::cast_to<Bone2D>(skeleton_node->get_node(bone_weights[i].path));
					if (!bone) {
						continue;
					}

					int bone_index = bone->get_index_in_skeleton();
					PoolVector<float>::Read r = bone_weights[i].weights.read();
					for (int j = 0; j < vc; j++) {
						if (r[j] == 0.0)
							continue; //weight is unpainted, skip
						//find an index with a weight
						for (int k = 0; k < 4; k++) {
							if (weightsw[j * 4 + k] < r[j]) {
								//this is less than this weight, insert weight!
								for (int l = 3; l > k; l--) {
									weightsw[j * 4 + l] = weightsw[j * 4 + l - 1];
									bonesw[j * 4 + l] = bonesw[j * 4 + l - 1];
								}
								weightsw[j * 4 + k] = r[j];
								bonesw[j * 4 + k] = bone_index;
								break;
							}
						}
					}
				}

				//normalize the weights
				for (int i = 0; i < vc; i++) {
					float tw = 0;
					for (int j = 0; j < 4; j++) {
						tw += weightsw[i * 4 + j];
					}
					if (tw == 0)
						continue; //unpainted, do nothing

					//normalize
					for (int j = 0; j < 4; j++) {
						weightsw[i * 4 + j] /= tw;
					}
				}
			}

			Vector<Color> colors;
			if (vertex_colors.size() == points.size()) {
				colors.resize(len);
				PoolVector<Color>::Read color_r = vertex_colors.read();
				for (int i = 0; i < len; i++) {
					colors.write[i] = color_r[i];
				}
			} else {
				colors.push_back(color);
			}

			//			Vector<int> indices = Geometry::triangulate_polygon(points);
			//			VS::get_singleton()->canvas_item_add_triangle_array(get_canvas_item(), indices, points, colors, uvs, texture.is_valid() ? texture->get_rid() : RID());

			if (invert || polygons.size() == 0) {
				Vector<int> indices = Geometry::triangulate_polygon(points);
				VS::get_singleton()->canvas_item_add_triangle_array(get_canvas_item(), indices, points, colors, uvs, bones, weights, texture.is_valid() ? texture->get_rid() : RID());
			} else {
				//draw individual polygons
				Vector<int> total_indices;
				for (int i = 0; i < polygons.size(); i++) {
					PoolVector<int> src_indices = polygons[i];
					int ic = src_indices.size();
					if (ic < 3)
						continue;
					PoolVector<int>::Read r = src_indices.read();

					Vector<Vector2> tmp_points;
					tmp_points.resize(ic);

					for (int j = 0; j < ic; j++) {
						int idx = r[j];
						ERR_CONTINUE(idx < 0 || idx >= points.size());
						tmp_points.write[j] = points[r[j]];
					}
					Vector<int> indices = Geometry::triangulate_polygon(tmp_points);
					int ic2 = indices.size();
					const int *r2 = indices.ptr();

					int bic = total_indices.size();
					total_indices.resize(bic + ic2);
					int *w2 = total_indices.ptrw();

					for (int j = 0; j < ic2; j++) {
						w2[j + bic] = r[r2[j]];
					}
				}

				if (total_indices.size()) {
					VS::get_singleton()->canvas_item_add_triangle_array(get_canvas_item(), total_indices, points, colors, uvs, bones, weights, texture.is_valid() ? texture->get_rid() : RID());
				}

#if 0
				//use splits
				Vector<int> loop;
				int sc = splits.size();
				PoolVector<int>::Read r = splits.read();


				print_line("has splits, amount " + itos(splits.size()));
				Vector<Vector<int> > loops;

				// find a point that can be used to begin, must not be in a split, and have to the left and right the same one
				// like this one -> x---o
				//                   \ / \ .
				//                    o---o
				int base_point = -1;
				{
					int current_point = -1;
					int base_point_prev_split = -1;


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

						//find if this point is in a split
						int split_index = -1;
						bool has_prev_split = false;
						int min_dist_to_end = 0x7FFFFFFF;

						for (int j = 0; j < sc; j += 2) {

							int split_pos = -1;
							int split_end = -1;

							if (r[j + 0] == i) { //found split in first point
								split_pos = r[j + 0];
								split_end = r[j + 1];
							} else if (r[j + 1] == i) { //found split in second point
								split_pos = r[j + 1];
								split_end = r[j + 0];
							}

							if (split_pos == split_end) {
								continue; //either nothing found or begin == end, this not a split in either case
							}

							if (j == base_point_prev_split) {
								has_prev_split = true;
							}

							//compute distance from split pos to split end in current traversal direction
							int dist_to_end = split_end > split_pos ? split_end - split_pos : (last - split_pos + split_end);

							if (dist_to_end < min_dist_to_end) {
								//always keep the valid split with the least distance to the loop
								min_dist_to_end = dist_to_end;
								split_index = j;
							}
						}

						if (split_index == -1) {
							current_point = i; //no split here, we are testing this point
						} else if (has_prev_split) {
							base_point = current_point; // there is a split and it contains the previous visited split, success
							break;
						} else {
							//invalidate current point and keep split
							current_point = -1;
							base_point_prev_split = split_index;
						}
					}
				}

				print_line("found base point: " + itos(base_point));

				if (base_point != -1) {

					int point = base_point;
					int last = base_point;
					//go through all the points, find splits
					do {

						int split;
						int last_dist_to_end = -1; //maximum valid distance to end

						do {

							loop.push_back(point); //push current point

							split = -1;
							int end = -1;

							int max_dist_to_end = 0;

							//find if this point is in a split
							for (int j = 0; j < sc; j += 2) {

								int split_pos = -1;
								int split_end = -1;

								if (r[j + 0] == point) { //match first split index
									split_pos = r[j + 0];
									split_end = r[j + 1];
								} else if (r[j + 1] == point) { //match second split index
									split_pos = r[j + 1];
									split_end = r[j + 0];
								}

								if (split_pos == split_end) {
									continue; //either nothing found or begin == end, this not a split in either case
								}

								//compute distance from split pos to split end
								int dist_to_end = split_end > split_pos ? split_end - split_pos : (points.size() - split_pos + split_end);

								if (last_dist_to_end != -1 && dist_to_end >= last_dist_to_end) {
									//distance must be shorter than in last iteration, means we've tested this before so ignore
									continue;
								} else if (dist_to_end > max_dist_to_end) {
									//always keep the valid point with the most distance (as long as it's valid)
									max_dist_to_end = dist_to_end;
									split = split_pos;
									end = split_end;
								}
							}

							if (split != -1) {
								//found a split!
								int from = end;

								//add points until last is reached
								while (true) {
									//find if point is in a split
									loop.push_back(from);

									if (from == last) {
										break;
									}

									from++;
									if (from >= points.size()) { //wrap if reached end
										from = 0;
									}

									if (from == loop[0]) {
										break; //end because we reached split source
									}
								}

								loops.push_back(loop); //done with this loop
								loop.clear();

								last_dist_to_end = max_dist_to_end;
								last = end; //algorithm can safely finish in this split point
							}

						} while (split != -1);

					} while (point != last);
				}

				if (loop.size() >=2 ) { //points remained
					//points remain
					loop.push_back(last); //no splits found, use last
					loops.push_back(loop);
				}

				print_line("total loops: " + itos(loops.size()));

				if (loops.size()) { //loops found
					Vector<int> indices;

					for (int i = 0; i < loops.size(); i++) {
						Vector<int> loop = loops[i];
						Vector<Vector2> vertices;
						vertices.resize(loop.size());
						for (int j = 0; j < vertices.size(); j++) {
							vertices.write[j] = points[loop[j]];
						}
						Vector<int> sub_indices = Geometry::triangulate_polygon(vertices);
						int from = indices.size();
						indices.resize(from + sub_indices.size());
						for (int j = 0; j < sub_indices.size(); j++) {
							indices.write[from + j] = loop[sub_indices[j]];
						}
					}

					VS::get_singleton()->canvas_item_add_triangle_array(get_canvas_item(), indices, points, colors, uvs, bones, weights, texture.is_valid() ? texture->get_rid() : RID());
				}
#endif
			}

		} break;
	}
}
Example #8
0
bool SparseMatrix::solveSAMG (Vector& B)
{
  int ierr = 1;
  if (!factored) this->optimiseSAMG();

#ifdef HAS_SAMG
  // Setting up additional parameters
  int nnu = this->rows(); // number of solution components (variables)
  int nna = this->size(); // number of nonzero entries in system matrix
  int nsys = 1; // one unknown - scalar system
  int iu = 1; // dummy - since nsys = 1;
  int ndiu = 1; // dummy - since nsys = 1;
  int ip = 1; // dummy - since nsys = 1 and no point-based approach used
  int ndip = 1; // dummy - since nsys = 1 and no point-based approach used
  int matrix = 120; // symmetric, NO zero rowsum, NO modification of matrix
  int iscale = 1; // dummy - since nsys = 1;
  Real res_in, res_out; // output parameters
  int ncyc_done; // output parameters
  int nsolve = 2; // default solution strategy
                  // (this parameter can quickly become complicated to set)
  int ifirst = 1; // no initial solution guess
  Real eps = -1.0e-16; // stopping criterion
  int ncyc = 110200; // define the cycling and accelleration strategy
  int iswitch = !factored ? 4140 : 1140; // No memory release in first run,
  // assuming identical coefficent matrix in all subsequent runs
  Real a_cmplx = 0.0; // l
  Real g_cmplx = 0.0; //  l  specifies preallocation of memory, etc.
  Real p_cmplx = 0.0; //  /
  Real w_avrge = 0.0; // /
  Real chktol = 0.0; // standard checking for logical correctness
                     // @@ set this to negative value for production run
  int iout = -2; // minimal output on results and timings
  int idump = -2; // printout of coarsening history

  int mode_mess = -2;
  SAMG_SET_MODE_MESS(&mode_mess);

  Vector X(B.size());

  SAMG(&nnu, &nna, &nsys,
       &IA.front(), &JA.front(), &A.front(), B.ptr(), X.ptr(),
       &iu, &ndiu, &ip, &ndip, &matrix, &iscale,
       &res_in, &res_out, &ncyc_done, &ierr,
       &nsolve, &ifirst, &eps, &ncyc, &iswitch,
       &a_cmplx, &g_cmplx, &p_cmplx, &w_avrge,
       &chktol, &idump, &iout);

  B.swap(X);

  if (ierr > 0)
    std::cerr <<"SAMG Failure "<< ierr << std::endl;
  else
  {
    factored = true;
    if (ierr < 0)
      std::cerr <<"SAMG warning "<< -ierr << std::endl;
  }
#else
  std::cerr <<"SparseMatrix::solve: SAMG solver not available"<< std::endl;
#endif
  return ierr <= 0;
}
Example #9
0
bool SparseMatrix::solveSLU (Vector& B)
{
  int ierr = ncol+1;
  if (!factored) this->optimiseSLU();

#ifdef HAS_SUPERLU_MT
  if (!slu) {
    // Create a new SuperLU matrix
    slu = new SuperLUdata;
    slu->perm_c = new int[ncol];
    slu->perm_r = new int[nrow];
    dCreate_CompCol_Matrix(&slu->A, nrow, ncol, this->size(),
                           &A.front(), &JA.front(), &IA.front(),
                           SLU_NC, SLU_D, SLU_GE);
  }
  else {
    Destroy_SuperMatrix_Store(&slu->A);
    Destroy_SuperNode_Matrix(&slu->L);
    Destroy_CompCol_Matrix(&slu->U);
    dCreate_CompCol_Matrix(&slu->A, nrow, ncol, this->size(),
                           &A.front(), &JA.front(), &IA.front(),
                           SLU_NC, SLU_D, SLU_GE);
  }

  // Get column permutation vector perm_c[], according to permc_spec:
  //   permc_spec = 0: natural ordering
  //   permc_spec = 1: minimum degree ordering on structure of A'*A
  //   permc_spec = 2: minimum degree ordering on structure of A'+A
  //   permc_spec = 3: approximate minimum degree for unsymmetric matrices
  int permc_spec = 1;
  get_perm_c(permc_spec, &slu->A, slu->perm_c);

  // Create right-hand-side/solution vector(s)
  size_t nrhs = B.size() / nrow;
  SuperMatrix Bmat;
  dCreate_Dense_Matrix(&Bmat, nrow, nrhs, B.ptr(), nrow,
                       SLU_DN, SLU_D, SLU_GE);

  // Invoke the simple driver
  pdgssv(numThreads, &slu->A, slu->perm_c, slu->perm_r,
         &slu->L, &slu->U, &Bmat, &ierr);

  if (ierr > 0)
    std::cerr <<"SuperLU_MT Failure "<< ierr << std::endl;

  Destroy_SuperMatrix_Store(&Bmat);

#elif defined(HAS_SUPERLU)
  if (!slu) {
    // Create a new SuperLU matrix
    slu = new SuperLUdata(1);
    slu->perm_c = new int[ncol];
    slu->perm_r = new int[nrow];
    dCreate_CompCol_Matrix(&slu->A, nrow, ncol, this->size(),
                           &A.front(), &JA.front(), &IA.front(),
                           SLU_NC, SLU_D, SLU_GE);
  }
  else if (factored)
    slu->opts->Fact = FACTORED; // Re-use previous factorization
  else {
    Destroy_SuperMatrix_Store(&slu->A);
    Destroy_SuperNode_Matrix(&slu->L);
    Destroy_CompCol_Matrix(&slu->U);
    dCreate_CompCol_Matrix(&slu->A, nrow, ncol, this->size(),
                           &A.front(), &JA.front(), &IA.front(),
                           SLU_NC, SLU_D, SLU_GE);
  }

  // Create right-hand-side/solution vector(s)
  size_t nrhs = B.size() / nrow;
  SuperMatrix Bmat;
  dCreate_Dense_Matrix(&Bmat, nrow, nrhs, B.ptr(), nrow,
                       SLU_DN, SLU_D, SLU_GE);

  SuperLUStat_t stat;
  StatInit(&stat);

  // Invoke the simple driver
  dgssv(slu->opts, &slu->A, slu->perm_c, slu->perm_r,
        &slu->L, &slu->U, &Bmat, &stat, &ierr);

  if (ierr > 0)
    std::cerr <<"SuperLU Failure "<< ierr << std::endl;
  else
    factored = true;

  if (printSLUstat)
    StatPrint(&stat);
  StatFree(&stat);

  Destroy_SuperMatrix_Store(&Bmat);
#else
  std::cerr <<"SparseMatrix::solve: SuperLU solver not available"<< std::endl;
#endif
  return ierr == 0;
}
Example #10
0
void raw_copy_to(PoolVector<T> &to, const Vector<T> &from) {
	to.resize(from.size());
	typename PoolVector<T>::Write w = to.write();
	memcpy(w.ptr(), from.ptr(), from.size() * sizeof(T));
}
Example #11
0
bool SparseMatrix::solveSLUx (Vector& B, Real* rcond)
{
  int ierr = ncol+1;
  if (!factored) this->optimiseSLU();

#ifdef HAS_SUPERLU_MT
  if (!slu) {
    // Create a new SuperLU matrix
    slu = new SuperLUdata(numThreads);
    slu->equed = NOEQUIL;
    slu->perm_c = new int[ncol];
    slu->perm_r = new int[nrow];
    slu->C = new Real[ncol];
    slu->R = new Real[nrow];
    slu->opts->etree = new int[ncol];
    slu->opts->colcnt_h = new int[ncol];
    slu->opts->part_super_h = new int[ncol];
    memset(slu->opts->colcnt_h, 0, ncol*sizeof(int));
    memset(slu->opts->part_super_h, 0, ncol*sizeof(int));
    memset(slu->opts->etree, 0, ncol*sizeof(int));
    dCreate_CompCol_Matrix(&slu->A, nrow, ncol, this->size(),
                           &A.front(), &JA.front(), &IA.front(),
                           SLU_NC, SLU_D, SLU_GE);

    // Get column permutation vector perm_c[], according to permc_spec:
    //   permc_spec = 0: natural ordering
    //   permc_spec = 1: minimum degree ordering on structure of A'*A
    //   permc_spec = 2: minimum degree ordering on structure of A'+A
    //   permc_spec = 3: approximate minimum degree for unsymmetric matrices
    int permc_spec = 1;
    get_perm_c(permc_spec, &slu->A, slu->perm_c);
  }
  else if (factored)
    slu->opts->fact = FACTORED; // Re-use previous factorization
  else
    slu->opts->refact = YES; // Re-use previous ordering

  // Create right-hand-side and solution vector(s)
  Vector      X(B.size());
  SuperMatrix Bmat, Xmat;
  const size_t nrhs = B.size() / nrow;
  dCreate_Dense_Matrix(&Bmat, nrow, nrhs, B.ptr(), nrow,
                       SLU_DN, SLU_D, SLU_GE);
  dCreate_Dense_Matrix(&Xmat, nrow, nrhs, X.ptr(), nrow,
                       SLU_DN, SLU_D, SLU_GE);

  Real ferr[nrhs], berr[nrhs];
  superlu_memusage_t mem_usage;

  // Invoke the expert driver
  pdgssvx(numThreads, slu->opts, &slu->A, slu->perm_c, slu->perm_r,
          &slu->equed, slu->R, slu->C, &slu->L, &slu->U, &Bmat, &Xmat,
          &slu->rpg, &slu->rcond, ferr, berr, &mem_usage, &ierr);

  B.swap(X);

  if (ierr > 0)
    std::cerr <<"SuperLU_MT Failure "<< ierr << std::endl;
  else if (!factored)
  {
    factored = true;
    if (rcond)
      *rcond = slu->rcond;
  }

  Destroy_SuperMatrix_Store(&Bmat);
  Destroy_SuperMatrix_Store(&Xmat);

#elif defined(HAS_SUPERLU)
  if (!slu) {
    // Create a new SuperLU matrix
    slu = new SuperLUdata(1);
    slu->perm_c = new int[ncol];
    slu->perm_r = new int[nrow];
    slu->etree = new int[ncol];
    slu->C = new Real[ncol];
    slu->R = new Real[nrow];
    dCreate_CompCol_Matrix(&slu->A, nrow, ncol, this->size(),
                           &A.front(), &JA.front(), &IA.front(),
                           SLU_NC, SLU_D, SLU_GE);
  }
  else if (factored)
    slu->opts->Fact = FACTORED; // Re-use previous factorization
  else {
    Destroy_SuperMatrix_Store(&slu->A);
    Destroy_SuperNode_Matrix(&slu->L);
    Destroy_CompCol_Matrix(&slu->U);
    dCreate_CompCol_Matrix(&slu->A, nrow, ncol, this->size(),
                           &A.front(), &JA.front(), &IA.front(),
                           SLU_NC, SLU_D, SLU_GE);
  }

  // Create right-hand-side vector and solution vector
  Vector      X(B.size());
  SuperMatrix Bmat, Xmat;
  const  size_t nrhs = B.size() / nrow;
  dCreate_Dense_Matrix(&Bmat, nrow, nrhs, B.ptr(), nrow,
                       SLU_DN, SLU_D, SLU_GE);
  dCreate_Dense_Matrix(&Xmat, nrow, nrhs, X.ptr(), nrow,
                       SLU_DN, SLU_D, SLU_GE);

  slu->opts->ConditionNumber = printSLUstat || rcond ? YES : NO;
  slu->opts->PivotGrowth = printSLUstat ? YES : NO;

  void* work = 0;
  int  lwork = 0;
  Real ferr[nrhs], berr[nrhs];
  mem_usage_t mem_usage;

  SuperLUStat_t stat;
  StatInit(&stat);

  // Invoke the expert driver
#if SUPERLU_VERSION == 5
  GlobalLU_t Glu;
  dgssvx(slu->opts, &slu->A, slu->perm_c, slu->perm_r, slu->etree, slu->equed,
         slu->R, slu->C, &slu->L, &slu->U, work, lwork, &Bmat, &Xmat,
         &slu->rpg, &slu->rcond, ferr, berr, &Glu, &mem_usage, &stat, &ierr);
#else
  dgssvx(slu->opts, &slu->A, slu->perm_c, slu->perm_r, slu->etree, slu->equed,
         slu->R, slu->C, &slu->L, &slu->U, work, lwork, &Bmat, &Xmat,
         &slu->rpg, &slu->rcond, ferr, berr, &mem_usage, &stat, &ierr);
#endif

  B.swap(X);

  if (ierr > 0)
    std::cerr <<"SuperLU Failure "<< ierr << std::endl;
  else if (!factored)
  {
    factored = true;
    if (rcond)
      *rcond = slu->rcond;
  }

  if (printSLUstat)
  {
    StatPrint(&stat);
    IFEM::cout <<"Reciprocal condition number = "<< slu->rcond
               <<"\nReciprocal pivot growth = "<< slu->rpg << std::endl;
  }
  StatFree(&stat);

  Destroy_SuperMatrix_Store(&Bmat);
  Destroy_SuperMatrix_Store(&Xmat);
#else
  std::cerr <<"SparseMatrix::solve: SuperLU solver not available"<< std::endl;
#endif
  return ierr == 0;
}
Example #12
0
void EditorProfiler::_update_plot() {

	int w = graph->get_size().width;
	int h = graph->get_size().height;

	bool reset_texture=false;

	int desired_len = w * h * 4;

	if (graph_image.size()!=desired_len) {
		reset_texture=true;
		graph_image.resize(desired_len);
	}


	DVector<uint8_t>::Write wr = graph_image.write();



	//clear
	for(int i=0;i<desired_len;i+=4) {
		wr[i+0]=0;
		wr[i+1]=0;
		wr[i+2]=0;
		wr[i+3]=255;
	}


	//find highest value

	bool use_self = display_time->get_selected()==DISPLAY_SELF_TIME;
	float highest=0;

	for(int i=0;i<frame_metrics.size();i++) {
		Metric &m = frame_metrics[i];
		if (!m.valid)
			continue;

		for (Set<StringName>::Element *E=plot_sigs.front();E;E=E->next()) {

			Map<StringName,Metric::Category*>::Element *F=m.category_ptrs.find(E->get());
			if (F) {
				highest=MAX(F->get()->total_time,highest);
			}

			Map<StringName,Metric::Category::Item*>::Element *G=m.item_ptrs.find(E->get());
			if (G) {
				if (use_self) {
					highest=MAX(G->get()->self,highest);
				} else {
					highest=MAX(G->get()->total,highest);
				}
			}
		}
	}

	if (highest>0) {
		//means some data exists..
		highest*=1.2; //leave some upper room
		graph_height=highest;

		Vector<int> columnv;
		columnv.resize(h*4);

		int *column = columnv.ptr();

		Map<StringName,int> plot_prev;
		//Map<StringName,int> plot_max;

		uint64_t time = OS::get_singleton()->get_ticks_usec();

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


			for(int j=0;j<h*4;j++) {
				column[j]=0;
			}

			int current = i*frame_metrics.size()/w;
			int next = (i+1)*frame_metrics.size()/w;
			if (next>frame_metrics.size()) {
				next=frame_metrics.size();
			}
			if (next==current)
				next=current+1; //just because for loop must work

			for (Set<StringName>::Element *E=plot_sigs.front();E;E=E->next()) {

				int plot_pos=-1;

				for(int j=current;j<next;j++) {

					//wrap
					int idx = last_metric+1+j;
					while( idx >= frame_metrics.size() ) {
						idx-=frame_metrics.size();
					}

					//get
					Metric &m = frame_metrics[idx];
					if (m.valid==false)
						continue; //skip because invalid


					float value=0;

					Map<StringName,Metric::Category*>::Element *F=m.category_ptrs.find(E->get());
					if (F) {
						value=F->get()->total_time;
					}

					Map<StringName,Metric::Category::Item*>::Element *G=m.item_ptrs.find(E->get());
					if (G) {
						if (use_self) {
							value=G->get()->self;
						} else {
							value=G->get()->total;
						}
					}


					plot_pos = MAX( CLAMP(int(value*h/highest),0,h-1), plot_pos );


				}

				int prev_plot=plot_pos;
				Map<StringName,int>::Element *H=plot_prev.find(E->get());
				if (H) {
					prev_plot=H->get();
					H->get()=plot_pos;
				} else {
					plot_prev[E->get()]=plot_pos;
				}

				if (plot_pos==-1 && prev_plot==-1) {
					//don't bother drawing
					continue;
				}

				if (prev_plot!=-1 && plot_pos==-1) {

					plot_pos=prev_plot;
				}

				if (prev_plot==-1 && plot_pos!=-1) {
					prev_plot=plot_pos;
				}

				plot_pos = h- plot_pos -1;
				prev_plot = h- prev_plot -1;

				if (prev_plot > plot_pos) {
					SWAP(prev_plot,plot_pos);
				}

				Color col = _get_color_from_signature(E->get());

				for(int j=prev_plot;j<=plot_pos;j++) {

					column[j*4+0]+=Math::fast_ftoi(CLAMP(col.r*255,0,255));
					column[j*4+1]+=Math::fast_ftoi(CLAMP(col.g*255,0,255));
					column[j*4+2]+=Math::fast_ftoi(CLAMP(col.b*255,0,255));
					column[j*4+3]+=1;

				}
			}


			for(int j=0;j<h*4;j+=4) {

				int a = column[j+3];
				if (a>0) {
					column[j+0]/=a;
					column[j+1]/=a;
					column[j+2]/=a;

				}

				uint8_t r = uint8_t(column[j+0]);
				uint8_t g = uint8_t(column[j+1]);
				uint8_t b = uint8_t(column[j+2]);

				int widx = ((j>>2)*w+i)*4;
				wr[widx+0]=r;
				wr[widx+1]=g;
				wr[widx+2]=b;
				wr[widx+3]=255;
			}
		}

		time = OS::get_singleton()->get_ticks_usec() - time;
		//print_line("Taken: "+rtos(USEC_TO_SEC(time)));

	}
void FileAccessNetworkClient::_thread_func() {

	client->set_nodelay(true);
	while(!quit) {

		DEBUG_PRINT("SEM WAIT - "+itos(sem->get()));
		Error err = sem->wait();
		DEBUG_TIME("sem_unlock");
		//DEBUG_PRINT("semwait returned "+itos(werr));
		DEBUG_PRINT("MUTEX LOCK "+itos(lockcount));
		DEBUG_PRINT("POPO");
		DEBUG_PRINT("PEPE");
		lock_mutex();
		DEBUG_PRINT("MUTEX PASS");

		blockrequest_mutex->lock();
		while(block_requests.size()) {
			put_32(block_requests.front()->get().id);
			put_32(FileAccessNetwork::COMMAND_READ_BLOCK);
			put_64(block_requests.front()->get().offset);
			put_32(block_requests.front()->get().size);
			block_requests.pop_front();
		}
		blockrequest_mutex->unlock();

		DEBUG_PRINT("THREAD ITER");

		DEBUG_TIME("sem_read");
		int id = get_32();

		int response = get_32();
		DEBUG_PRINT("GET RESPONSE: "+itos(response));

		FileAccessNetwork *fa=NULL;

		if (response!=FileAccessNetwork::RESPONSE_DATA) {
			ERR_FAIL_COND(!accesses.has(id));
		}

		if (accesses.has(id))
			fa=accesses[id];


		switch(response) {

			case FileAccessNetwork::RESPONSE_OPEN: {


				DEBUG_TIME("sem_open");
				int status = get_32();
				if (status!=OK) {
					fa->_respond(0,Error(status));
				} else {
					uint64_t len = get_64();
					fa->_respond(len,Error(status));
				}

				fa->sem->post();


			} break;
			case FileAccessNetwork::RESPONSE_DATA: {

				int64_t offset = get_64();
				uint32_t len = get_32();

				Vector<uint8_t> block;
				block.resize(len);
				client->get_data(block.ptr(),len);

				if (fa) //may have been queued
					fa->_set_block(offset,block);

			} break;
			case FileAccessNetwork::RESPONSE_FILE_EXISTS: {


				int status = get_32();
				fa->exists_modtime=status!=0;
				fa->sem->post();



			} break;
			case FileAccessNetwork::RESPONSE_GET_MODTIME: {


				uint64_t status = get_64();
				fa->exists_modtime=status;
				fa->sem->post();

			} break;

		}


		unlock_mutex();
	}

}
Example #14
0
void UndoRedo::_process_operation_list(List<Operation>::Element *E) {

	for (; E; E = E->next()) {

		Operation &op = E->get();

		Object *obj = ObjectDB::get_instance(op.object);
		if (!obj) //may have been deleted and this is fine
			continue;

		switch (op.type) {

			case Operation::TYPE_METHOD: {

				Vector<const Variant *> argptrs;
				argptrs.resize(VARIANT_ARG_MAX);
				int argc = 0;

				for (int i = 0; i < VARIANT_ARG_MAX; i++) {
					if (op.args[i].get_type() == Variant::NIL) {
						break;
					}
					argptrs.write[i] = &op.args[i];
					argc++;
				}
				argptrs.resize(argc);

				Variant::CallError ce;
				obj->call(op.name, (const Variant **)argptrs.ptr(), argc, ce);
				if (ce.error != Variant::CallError::CALL_OK) {
					ERR_PRINTS("Error calling method from signal '" + String(op.name) + "': " + Variant::get_call_error_text(obj, op.name, (const Variant **)argptrs.ptr(), argc, ce));
				}
#ifdef TOOLS_ENABLED
				Resource *res = Object::cast_to<Resource>(obj);
				if (res)
					res->set_edited(true);

#endif

				if (method_callback) {
					method_callback(method_callbck_ud, obj, op.name, VARIANT_ARGS_FROM_ARRAY(op.args));
				}
			} break;
			case Operation::TYPE_PROPERTY: {

				obj->set(op.name, op.args[0]);
#ifdef TOOLS_ENABLED
				Resource *res = Object::cast_to<Resource>(obj);
				if (res)
					res->set_edited(true);
#endif
				if (property_callback) {
					property_callback(prop_callback_ud, obj, op.name, op.args[0]);
				}
			} break;
			case Operation::TYPE_REFERENCE: {
				//do nothing
			} break;
		}
	}
}
Example #15
0
bool Expression::_execute(const Array &p_inputs, Object *p_instance, Expression::ENode *p_node, Variant &r_ret, String &r_error_str) {

	switch (p_node->type) {
		case Expression::ENode::TYPE_INPUT: {

			const Expression::InputNode *in = static_cast<const Expression::InputNode *>(p_node);
			if (in->index < 0 || in->index >= p_inputs.size()) {
				r_error_str = vformat(RTR("Invalid input %i (not passed) in expression"), in->index);
				return true;
			}
			r_ret = p_inputs[in->index];
		} break;
		case Expression::ENode::TYPE_CONSTANT: {

			const Expression::ConstantNode *c = static_cast<const Expression::ConstantNode *>(p_node);
			r_ret = c->value;

		} break;
		case Expression::ENode::TYPE_SELF: {

			if (!p_instance) {
				r_error_str = RTR("self can't be used because instance is null (not passed)");
				return true;
			}
			r_ret = p_instance;
		} break;
		case Expression::ENode::TYPE_OPERATOR: {

			const Expression::OperatorNode *op = static_cast<const Expression::OperatorNode *>(p_node);

			Variant a;
			bool ret = _execute(p_inputs, p_instance, op->nodes[0], a, r_error_str);
			if (ret)
				return true;

			Variant b;

			if (op->nodes[1]) {
				ret = _execute(p_inputs, p_instance, op->nodes[1], b, r_error_str);
				if (ret)
					return true;
			}

			bool valid = true;
			Variant::evaluate(op->op, a, b, r_ret, valid);
			if (!valid) {
				r_error_str = vformat(RTR("Invalid operands to operator %s, %s and %s."), Variant::get_operator_name(op->op), Variant::get_type_name(a.get_type()), Variant::get_type_name(b.get_type()));
				return true;
			}

		} break;
		case Expression::ENode::TYPE_INDEX: {

			const Expression::IndexNode *index = static_cast<const Expression::IndexNode *>(p_node);

			Variant base;
			bool ret = _execute(p_inputs, p_instance, index->base, base, r_error_str);
			if (ret)
				return true;

			Variant idx;

			ret = _execute(p_inputs, p_instance, index->index, idx, r_error_str);
			if (ret)
				return true;

			bool valid;
			r_ret = base.get(idx, &valid);
			if (!valid) {
				r_error_str = vformat(RTR("Invalid index of type %s for base type %s"), Variant::get_type_name(idx.get_type()), Variant::get_type_name(base.get_type()));
				return true;
			}

		} break;
		case Expression::ENode::TYPE_NAMED_INDEX: {

			const Expression::NamedIndexNode *index = static_cast<const Expression::NamedIndexNode *>(p_node);

			Variant base;
			bool ret = _execute(p_inputs, p_instance, index->base, base, r_error_str);
			if (ret)
				return true;

			bool valid;
			r_ret = base.get_named(index->name, &valid);
			if (!valid) {
				r_error_str = vformat(RTR("Invalid named index '%s' for base type %s"), String(index->name), Variant::get_type_name(base.get_type()));
				return true;
			}

		} break;
		case Expression::ENode::TYPE_ARRAY: {
			const Expression::ArrayNode *array = static_cast<const Expression::ArrayNode *>(p_node);

			Array arr;
			arr.resize(array->array.size());
			for (int i = 0; i < array->array.size(); i++) {

				Variant value;
				bool ret = _execute(p_inputs, p_instance, array->array[i], value, r_error_str);

				if (ret)
					return true;
				arr[i] = value;
			}

			r_ret = arr;

		} break;
		case Expression::ENode::TYPE_DICTIONARY: {
			const Expression::DictionaryNode *dictionary = static_cast<const Expression::DictionaryNode *>(p_node);

			Dictionary d;
			for (int i = 0; i < dictionary->dict.size(); i += 2) {

				Variant key;
				bool ret = _execute(p_inputs, p_instance, dictionary->dict[i + 0], key, r_error_str);

				if (ret)
					return true;

				Variant value;
				ret = _execute(p_inputs, p_instance, dictionary->dict[i + 1], value, r_error_str);
				if (ret)
					return true;

				d[key] = value;
			}

			r_ret = d;
		} break;
		case Expression::ENode::TYPE_CONSTRUCTOR: {

			const Expression::ConstructorNode *constructor = static_cast<const Expression::ConstructorNode *>(p_node);

			Vector<Variant> arr;
			Vector<const Variant *> argp;
			arr.resize(constructor->arguments.size());
			argp.resize(constructor->arguments.size());

			for (int i = 0; i < constructor->arguments.size(); i++) {

				Variant value;
				bool ret = _execute(p_inputs, p_instance, constructor->arguments[i], value, r_error_str);

				if (ret)
					return true;
				arr.write[i] = value;
				argp.write[i] = &arr[i];
			}

			Variant::CallError ce;
			r_ret = Variant::construct(constructor->data_type, (const Variant **)argp.ptr(), argp.size(), ce);

			if (ce.error != Variant::CallError::CALL_OK) {
				r_error_str = vformat(RTR("Invalid arguments to construct '%s'"), Variant::get_type_name(constructor->data_type));
				return true;
			}

		} break;
		case Expression::ENode::TYPE_BUILTIN_FUNC: {

			const Expression::BuiltinFuncNode *bifunc = static_cast<const Expression::BuiltinFuncNode *>(p_node);

			Vector<Variant> arr;
			Vector<const Variant *> argp;
			arr.resize(bifunc->arguments.size());
			argp.resize(bifunc->arguments.size());

			for (int i = 0; i < bifunc->arguments.size(); i++) {

				Variant value;
				bool ret = _execute(p_inputs, p_instance, bifunc->arguments[i], value, r_error_str);
				if (ret)
					return true;
				arr.write[i] = value;
				argp.write[i] = &arr[i];
			}

			Variant::CallError ce;
			exec_func(bifunc->func, (const Variant **)argp.ptr(), &r_ret, ce, r_error_str);

			if (ce.error != Variant::CallError::CALL_OK) {
				r_error_str = "Builtin Call Failed. " + r_error_str;
				return true;
			}

		} break;
		case Expression::ENode::TYPE_CALL: {

			const Expression::CallNode *call = static_cast<const Expression::CallNode *>(p_node);

			Variant base;
			bool ret = _execute(p_inputs, p_instance, call->base, base, r_error_str);

			if (ret)
				return true;

			Vector<Variant> arr;
			Vector<const Variant *> argp;
			arr.resize(call->arguments.size());
			argp.resize(call->arguments.size());

			for (int i = 0; i < call->arguments.size(); i++) {

				Variant value;
				ret = _execute(p_inputs, p_instance, call->arguments[i], value, r_error_str);

				if (ret)
					return true;
				arr.write[i] = value;
				argp.write[i] = &arr[i];
			}

			Variant::CallError ce;
			r_ret = base.call(call->method, (const Variant **)argp.ptr(), argp.size(), ce);

			if (ce.error != Variant::CallError::CALL_OK) {
				r_error_str = vformat(RTR("On call to '%s':"), String(call->method));
				return true;
			}

		} break;
	}
	return false;
}
Example #16
0
void SoftBodyBullet::create_soft_body() {
	if (!space || !soft_body_shape_data) {
		return;
	}
	ERR_FAIL_COND(!space->is_using_soft_world());
	switch (soft_shape_type) {
		case SOFT_SHAPE_TYPE_TRIMESH: {
			TrimeshSoftShapeData *trimesh_data = static_cast<TrimeshSoftShapeData *>(soft_body_shape_data);

			Vector<int> indices;
			Vector<btScalar> vertices;

			int i;
			const int indices_size = trimesh_data->m_triangles_indices.size();
			const int vertices_size = trimesh_data->m_vertices.size();
			indices.resize(indices_size);
			vertices.resize(vertices_size * 3);

			PoolVector<int>::Read i_r = trimesh_data->m_triangles_indices.read();
			for (i = 0; i < indices_size; ++i) {
				indices[i] = i_r[i];
			}
			i_r = PoolVector<int>::Read();

			PoolVector<Vector3>::Read f_r = trimesh_data->m_vertices.read();
			for (int j = i = 0; i < vertices_size; ++i, j += 3) {
				vertices[j + 0] = f_r[i][0];
				vertices[j + 1] = f_r[i][1];
				vertices[j + 2] = f_r[i][2];
			}
			f_r = PoolVector<Vector3>::Read();

			bt_soft_body = btSoftBodyHelpers::CreateFromTriMesh(*space->get_soft_body_world_info(), vertices.ptr(), indices.ptr(), trimesh_data->m_triangles_num);
		} break;
		default:
			ERR_PRINT("Shape type not supported");
			return;
	}

	setupBulletCollisionObject(bt_soft_body);
	bt_soft_body->getCollisionShape()->setMargin(0.001f);
	bt_soft_body->setCollisionFlags(bt_soft_body->getCollisionFlags() & (~(btCollisionObject::CF_KINEMATIC_OBJECT | btCollisionObject::CF_STATIC_OBJECT)));
	mat0 = bt_soft_body->appendMaterial();
}
Example #17
0
Array Physics2DDirectSpaceState::_intersect_shape(const Ref<Physics2DShapeQueryParameters> &p_shape_query, int p_max_results) {

	Vector<ShapeResult> sr;
	sr.resize(p_max_results);
	int rc = intersect_shape(p_shape_query->shape, p_shape_query->transform, p_shape_query->motion, p_shape_query->margin, sr.ptr(), sr.size(), p_shape_query->exclude, p_shape_query->collision_layer, p_shape_query->object_type_mask);
	Array ret;
	ret.resize(rc);
	for (int i = 0; i < rc; i++) {

		Dictionary d;
		d["rid"] = sr[i].rid;
		d["collider_id"] = sr[i].collider_id;
		d["collider"] = sr[i].collider;
		d["shape"] = sr[i].shape;
		d["metadata"] = sr[i].metadata;
		ret[i] = d;
	}

	return ret;
}
Example #18
0
SolverState<double> BelosSolver::solve(const LinearOperator<double>& A, 
  const Vector<double>& rhs, 
  Vector<double>& soln) const
{
  typedef Thyra::MultiVectorBase<double>         MV;
  typedef Thyra::LinearOpBase<double>            OP;
  typedef Belos::LinearProblem<double, MV, OP>   LP;

  TEST_FOR_EXCEPT(!A.ptr().get());
  TEST_FOR_EXCEPT(!rhs.ptr().get());

  /* get Thyra objects */
  RCP<OP> APtr = A.ptr();
  RCP<MV> bPtr = rhs.ptr(); 

  if (!soln.ptr().get()) soln = rhs.copy();

  RCP<MV> ansPtr = soln.ptr();

  
  
  RCP<LP> prob = rcp(new LP(APtr, ansPtr, bPtr));

  TEST_FOR_EXCEPT(!prob->setProblem());

  
  if (pf_.ptr().get())
  {
    Preconditioner<double> P = pf_.createPreconditioner(A);
    if (P.hasLeft())
    {
      prob->setLeftPrec(P.left().ptr());
    }
  
    if (P.hasRight())
    {
      prob->setRightPrec(P.right().ptr());
    }
  }

  ParameterList plist = parameters();

  RCP<ParameterList> belosList = rcp(&plist, false);
  RCP<Belos::SolverManager<double, MV, OP> > solver ;
  std::string solverType = parameters().get<string>("Method");
  
  if (solverType=="GMRES")
  {
    solver=rcp(new Belos::BlockGmresSolMgr<double, MV, OP>(prob, belosList));
  }
  else if (solverType=="CG")
  {
    solver=rcp(new Belos::BlockCGSolMgr<double, MV, OP>(prob, belosList));
  }
  else
  {
    TEST_FOR_EXCEPT(!(solverType=="GMRES" || solverType=="CG"));
  }

  Belos::ReturnType rtn = solver->solve();

  int numIters = solver->getNumIters();
  double resid = -1.0;
  
  SolverStatusCode code = SolveFailedToConverge;
  if (rtn==Belos::Converged) code = SolveConverged;
  SolverState<double> state(code, "Belos solver completed", numIters, resid);
  
  return state;
}
Example #19
0
int main(int argc, char *argv[]) 
{
  typedef Teuchos::ScalarTraits<double> ST;

  try
  {
    GlobalMPISession session(&argc, &argv);

    MPIComm::world().synchronize();

    VectorType<double> type = new EpetraVectorType();


#ifdef HAVE_CONFIG_H
      ParameterXMLFileReader reader(Sundance::searchForFile("SolverParameters/userPrecParams.xml"));
#else
      ParameterXMLFileReader reader("userPrecParams.xml");
#endif

    ParameterList solverParams = reader.getParameters();
    ParameterList innerSolverParams = solverParams.sublist("Inner Solve");
    ParameterList outerSolverParams = solverParams.sublist("Outer Solve");

    /* create the range space  */
    int nLocalRows = solverParams.get<int>("nLocal");

    MatrixLaplacian1D builder(nLocalRows, type);

    LinearOperator<double> A = builder.getOp();

    Vector<double> x = A.domain().createMember();
    int myRank = MPIComm::world().getRank();
    int nProcs = MPIComm::world().getNProc();
      

    Thyra::randomize(-ST::one(),+ST::one(),x.ptr().ptr());
#ifdef TRILINOS_6
    if (myRank==0) x[0] = 0.0;
    if (myRank==nProcs-1) x[nProcs * nLocalRows - 1] = 0.0;
    // need to fix operator[] routine
#else
    if (myRank==0) x.setElement(0, 0);
    if (myRank==nProcs-1) x.setElement(nProcs * nLocalRows - 1, 0.0);
#endif

    cout << "x=" << std::endl;
    x.print(cout);
      
    Vector<double> y = A*x;
    cout << "y=" << std::endl;
    y.print(cout);

    Vector<double> ans = A.range().createMember();

    LinearSolver<double> innerSolver 
      = LinearSolverBuilder::createSolver(innerSolverParams);

    LinearSolver<double> outerSolver 
      = LinearSolverBuilder::createSolver(outerSolverParams);

    /* call the setUserPrec() function to set the operator and solver 
     * to be used for preconditioning */
    outerSolver.setUserPrec(A, innerSolver);

    LinearOperator<double> AInv = inverse(A, outerSolver);
      

    ans = AInv * y;

    //      SolverState<double> state = solver.solve(A, y, ans);
      

      
    //      cout << state << std::endl;

    cout << "answer is " << std::endl;
    ans.print(cout);
      
    double err = (x-ans).norm2();
    cout << "error norm = " << err << std::endl;

    double tol = 1.0e-8;
    if (err > tol)
    {
      cout << "User-defined preconditioner test FAILED" << std::endl;
      return 1;
    }
    else
    {
      cout << "User-defined preconditioner test PASSED" << std::endl;
      return 0;
    }
  }
  catch(std::exception& e)
  {
    cout << "Caught exception: " << e.what() << std::endl;
    return -1;
  }
}
Example #20
0
void EditorAssetInstaller::ok_pressed() {

	FileAccess *src_f=NULL;
	zlib_filefunc_def io = zipio_create_io_from_file(&src_f);

	unzFile pkg = unzOpen2(package_path.utf8().get_data(), &io);
	if (!pkg) {

		error->set_text("Error opening package file, not in zip format.");
		return;
	}

	int ret = unzGoToFirstFile(pkg);

	Vector<String> failed_files;

	ProgressDialog::get_singleton()->add_task("uncompress","Uncompressing Assets",status_map.size());

	int idx=0;
	while(ret==UNZ_OK) {

		//get filename
		unz_file_info info;
		char fname[16384];
		ret = unzGetCurrentFileInfo(pkg,&info,fname,16384,NULL,0,NULL,0);

		String name=fname;

		if (status_map.has(name) && status_map[name]->is_checked(0)) {

			String path = status_map[name]->get_metadata(0);
			if (path==String()) { // a dir

				String dirpath;
				TreeItem *t = status_map[name];
				while(t) {
					dirpath=t->get_text(0)+dirpath;
					t=t->get_parent();
				}

				if (dirpath.ends_with("/")) {
					dirpath=dirpath.substr(0,dirpath.length()-1);
				}

				DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
				da->make_dir(dirpath);
				memdelete(da);

			} else {

				Vector<uint8_t> data;
				data.resize(info.uncompressed_size);

				//read
				unzOpenCurrentFile(pkg);
				unzReadCurrentFile(pkg,data.ptr(),data.size());
				unzCloseCurrentFile(pkg);

				FileAccess *f=FileAccess::open(path,FileAccess::WRITE);
				if (f) {
					f->store_buffer(data.ptr(),data.size());
					memdelete(f);
				} else {
					failed_files.push_back(path);
				}

				ProgressDialog::get_singleton()->task_step("uncompress",path,idx);
			}

		}

		idx++;
		ret = unzGoToNextFile(pkg);
	}

	ProgressDialog::get_singleton()->end_task("uncompress");
	unzClose(pkg);

	if (failed_files.size()) {
		String msg="The following files failed extraction from package:\n\n";
		for(int i=0;i<failed_files.size();i++) {

			if (i>15) {
				msg+="\nAnd "+itos(failed_files.size()-i)+" more files.";
				break;
			}
			msg+=failed_files[i];
		}
		if (EditorNode::get_singleton() != NULL)
			EditorNode::get_singleton()->show_warning(msg);
	} else {
		if (EditorNode::get_singleton() != NULL)
			EditorNode::get_singleton()->show_warning("Package Installed Successfully!","Success!");
	}




}
Example #21
0
void EditorExportPlatformBB10::_fix_descriptor(Vector<uint8_t>& p_descriptor) {

	String fpath =  EditorSettings::get_singleton()->get_settings_path().plus_file("tmp_bar-settings.xml");
	{
		FileAccessRef f = FileAccess::open(fpath,FileAccess::WRITE);
		f->store_buffer(p_descriptor.ptr(),p_descriptor.size());
	}

	Ref<XMLParser> parser = memnew( XMLParser );
	Error err = parser->open(fpath);
	ERR_FAIL_COND(err!=OK);

	String txt;
	err = parser->read();
	Vector<String> depth;

	while(err!=ERR_FILE_EOF) {

		ERR_FAIL_COND(err!=OK);

		switch(parser->get_node_type()) {

			case XMLParser::NODE_NONE: {
				print_line("???");
			} break;
			case XMLParser::NODE_ELEMENT: {
				String e="<";
				e+=parser->get_node_name();
				for(int i=0;i<parser->get_attribute_count();i++) {
					e+=" ";
					e+=parser->get_attribute_name(i)+"=\"";
					e+=parser->get_attribute_value(i)+"\" ";
				}



				if (parser->is_empty()) {
					e+="/";
				} else {
					depth.push_back(parser->get_node_name());
				}

				e+=">";
				txt+=e;

			} break;
			case XMLParser::NODE_ELEMENT_END: {

				txt+="</"+parser->get_node_name()+">";
				if (depth.size() && depth[depth.size()-1]==parser->get_node_name()) {
					depth.resize(depth.size()-1);
				}


			} break;
			case XMLParser::NODE_TEXT: {
				if (depth.size()==2 && depth[0]=="qnx" && depth[1]=="id") {

					txt+=package;
				} else if (depth.size()==2 && depth[0]=="qnx" && depth[1]=="name") {

					String aname;
					if (this->name!="") {
						aname=this->name;
					} else {
						aname = Globals::get_singleton()->get("application/name");

					}

					if (aname=="") {
						aname=_MKSTR(VERSION_NAME);
					}

					txt+=aname;

				} else if (depth.size()==2 && depth[0]=="qnx" && depth[1]=="versionNumber") {
					txt+=itos(version_code);
				} else if (depth.size()==2 && depth[0]=="qnx" && depth[1]=="description") {
					txt+=description;
				} else if (depth.size()==2 && depth[0]=="qnx" && depth[1]=="author") {
					txt+=author_name;
				} else if (depth.size()==2 && depth[0]=="qnx" && depth[1]=="authorId") {
					txt+=author_id;
				} else if (depth.size()==2 && depth[0]=="qnx" && depth[1]=="category") {
					txt+=category;
				} else {
					txt+=parser->get_node_data();
				}
			} break;
			case XMLParser::NODE_COMMENT: {
				txt+="<!--"+parser->get_node_name()+"-->";
			} break;
			case XMLParser::NODE_CDATA: {
				//ignore
				//print_line("cdata");
			} break;
			case XMLParser::NODE_UNKNOWN: {
				//ignore
				txt+="<"+parser->get_node_name()+">";
			} break;
		}

		err = parser->read();
	}


	CharString cs = txt.utf8();
	p_descriptor.resize(cs.length());
	for(int i=0;i<cs.length();i++)
		p_descriptor[i]=cs[i];

}
Example #22
0
void EditorExportPlatformAndroid::_fix_manifest(Vector<uint8_t>& p_manifest,bool p_give_internet) {


	const int CHUNK_AXML_FILE = 0x00080003;
	const int CHUNK_RESOURCEIDS = 0x00080180;
	const int CHUNK_STRINGS = 0x001C0001;
	const int CHUNK_XML_END_NAMESPACE = 0x00100101;
	const int CHUNK_XML_END_TAG = 0x00100103;
	const int CHUNK_XML_START_NAMESPACE = 0x00100100;
	const int CHUNK_XML_START_TAG = 0x00100102;
	const int CHUNK_XML_TEXT = 0x00100104;
	const int UTF8_FLAG = 0x00000100;

	Vector<String> string_table;

	uint32_t ofs=0;


	uint32_t header = decode_uint32(&p_manifest[ofs]);
	uint32_t filesize = decode_uint32(&p_manifest[ofs+4]);
	ofs+=8;

//	print_line("FILESIZE: "+itos(filesize)+" ACTUAL: "+itos(p_manifest.size()));

	uint32_t string_count;
	uint32_t styles_count;
	uint32_t string_flags;
	uint32_t string_data_offset;

	uint32_t styles_offset;
	uint32_t string_table_begins;
	uint32_t string_table_ends;
	Vector<uint8_t> stable_extra;

	while(ofs < p_manifest.size()) {

		uint32_t chunk = decode_uint32(&p_manifest[ofs]);
		uint32_t size = decode_uint32(&p_manifest[ofs+4]);


		switch(chunk) {

			case CHUNK_STRINGS: {


				int iofs=ofs+8;

				string_count=decode_uint32(&p_manifest[iofs]);
				styles_count=decode_uint32(&p_manifest[iofs+4]);
				uint32_t string_flags=decode_uint32(&p_manifest[iofs+8]);
				string_data_offset=decode_uint32(&p_manifest[iofs+12]);
				styles_offset=decode_uint32(&p_manifest[iofs+16]);
/*
				printf("string count: %i\n",string_count);
				printf("flags: %i\n",string_flags);
				printf("sdata ofs: %i\n",string_data_offset);
				printf("styles ofs: %i\n",styles_offset);
*/
				uint32_t st_offset=iofs+20;
				string_table.resize(string_count);
				uint32_t string_end=0;

				string_table_begins=st_offset;


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

					uint32_t string_at = decode_uint32(&p_manifest[st_offset+i*4]);
					string_at+=st_offset+string_count*4;

					ERR_EXPLAIN("Unimplemented, can't read utf8 string table.");
					ERR_FAIL_COND(string_flags&UTF8_FLAG);

					if (string_flags&UTF8_FLAG) {



					} else {
						uint32_t len = decode_uint16(&p_manifest[string_at]);
						Vector<CharType> ucstring;
						ucstring.resize(len+1);
						for(int j=0;j<len;j++) {
							uint16_t c=decode_uint16(&p_manifest[string_at+2+2*j]);
							ucstring[j]=c;
						}
						string_end=MAX(string_at+2+2*len,string_end);
						ucstring[len]=0;
						string_table[i]=ucstring.ptr();
					}


//					print_line("String "+itos(i)+": "+string_table[i]);
				}

				for(int i=string_end;i<(ofs+size);i++) {
					stable_extra.push_back(p_manifest[i]);
				}

//				printf("stable extra: %i\n",int(stable_extra.size()));
				string_table_ends=ofs+size;

//				print_line("STABLE SIZE: "+itos(size)+" ACTUAL: "+itos(string_table_ends));

			} break;
			case CHUNK_XML_START_TAG: {

				int iofs=ofs+8;
				uint32_t line=decode_uint32(&p_manifest[iofs]);
				uint32_t nspace=decode_uint32(&p_manifest[iofs+8]);
				uint32_t name=decode_uint32(&p_manifest[iofs+12]);
				uint32_t check=decode_uint32(&p_manifest[iofs+16]);

				String tname=string_table[name];

//				printf("NSPACE: %i\n",nspace);
				//printf("NAME: %i (%s)\n",name,tname.utf8().get_data());
				//printf("CHECK: %x\n",check);
				uint32_t attrcount=decode_uint32(&p_manifest[iofs+20]);
				iofs+=28;
				//printf("ATTRCOUNT: %x\n",attrcount);
				for(int i=0;i<attrcount;i++) {
					uint32_t attr_nspace=decode_uint32(&p_manifest[iofs]);
					uint32_t attr_name=decode_uint32(&p_manifest[iofs+4]);
					uint32_t attr_value=decode_uint32(&p_manifest[iofs+8]);
					uint32_t attr_flags=decode_uint32(&p_manifest[iofs+12]);
					uint32_t attr_resid=decode_uint32(&p_manifest[iofs+16]);


					String value;
					if (attr_value!=0xFFFFFFFF)
						value=string_table[attr_value];
					else
						value="Res #"+itos(attr_resid);
					String attrname = string_table[attr_name];
					String nspace;
					if (attr_nspace!=0xFFFFFFFF)
						nspace=string_table[attr_nspace];
					else
						nspace="";

					printf("ATTR %i NSPACE: %i\n",i,attr_nspace);
					printf("ATTR %i NAME: %i (%s)\n",i,attr_name,attrname.utf8().get_data());
					printf("ATTR %i VALUE: %i (%s)\n",i,attr_value,value.utf8().get_data());
					printf("ATTR %i FLAGS: %x\n",i,attr_flags);
					printf("ATTR %i RESID: %x\n",i,attr_resid);

					//replace project information
					if (tname=="manifest" && attrname=="package") {

						print_line("FOUND PACKAGE");
						string_table[attr_value]=get_package_name();
					}

					//print_line("tname: "+tname);
					//print_line("nspace: "+nspace);
					//print_line("attrname: "+attrname);
					if (tname=="manifest" && /*nspace=="android" &&*/ attrname=="versionCode") {

						print_line("FOUND versioncode");
						encode_uint32(version_code,&p_manifest[iofs+16]);
					}


					if (tname=="manifest" && /*nspace=="android" &&*/ attrname=="versionName") {

						print_line("FOUND versionname");
						if (attr_value==0xFFFFFFFF) {
							WARN_PRINT("Version name in a resource, should be plaintext")
						} else
							string_table[attr_value]=version_name;
					}

					if (tname=="activity" && /*nspace=="android" &&*/ attrname=="screenOrientation") {

						encode_uint32(orientation==0?0:1,&p_manifest[iofs+16]);
						/*
						print_line("FOUND screen orientation");
						if (attr_value==0xFFFFFFFF) {
							WARN_PRINT("Version name in a resource, should be plaintext")
						} else {
							string_table[attr_value]=(orientation==0?"landscape":"portrait");
						}*/
					}

					if (tname=="uses-permission" && /*nspace=="android" &&*/ attrname=="name") {

						if (value.begins_with("godot.custom")) {

							int which = value.get_slice(".",2).to_int();
							if (which>=0 && which<MAX_USER_PERMISSIONS && user_perms[which].strip_edges()!="") {

								string_table[attr_value]=user_perms[which].strip_edges();
							}

						} else if (value.begins_with("godot.")) {
							String perm = value.get_slice(".",1);
							print_line("PERM: "+perm+" HAS: "+itos(perms.has(perm)));

							if (perms.has(perm) || (p_give_internet && perm=="INTERNET")) {

								string_table[attr_value]="android.permission."+perm;
							}

						}
					}

					if (tname=="supports-screens" ) {

						if (attrname=="smallScreens") {

							encode_uint32(screen_support[SCREEN_SMALL]?0xFFFFFFFF:0,&p_manifest[iofs+16]);

						} else if (attrname=="normalScreens") {

							encode_uint32(screen_support[SCREEN_NORMAL]?0xFFFFFFFF:0,&p_manifest[iofs+16]);

						} else if (attrname=="largeScreens") {

							encode_uint32(screen_support[SCREEN_LARGE]?0xFFFFFFFF:0,&p_manifest[iofs+16]);

						} else if (attrname=="xlargeScreens") {

							encode_uint32(screen_support[SCREEN_XLARGE]?0xFFFFFFFF:0,&p_manifest[iofs+16]);

						}
					}


					iofs+=20;
				}

			} break;
		}
		printf("chunk %x: size: %d\n",chunk,size);

		ofs+=size;
	}
Example #23
0
Error GDTokenizerBuffer::set_code_buffer(const Vector<uint8_t> & p_buffer) {


	const uint8_t *buf=p_buffer.ptr();
	int total_len=p_buffer.size();
	ERR_FAIL_COND_V( p_buffer.size()<24 || p_buffer[0]!='G' || p_buffer[1]!='D' || p_buffer[2]!='S' || p_buffer[3]!='C',ERR_INVALID_DATA);
	
	int version = decode_uint32(&buf[4]);
	if (version>BYTECODE_VERSION) {
		ERR_EXPLAIN("Bytecode is too New! Please use a newer engine version.");
		ERR_FAIL_COND_V(version>BYTECODE_VERSION,ERR_INVALID_DATA);
	}
	int identifier_count = decode_uint32(&buf[8]);
	int constant_count = decode_uint32(&buf[12]);
	int line_count = decode_uint32(&buf[16]);
	int token_count = decode_uint32(&buf[20]);

	const uint8_t *b=buf;
	
	b=&buf[24];
	total_len-=24;
	
	identifiers.resize(identifier_count);
	for(int i=0;i<identifier_count;i++) {
		
		int len = decode_uint32(b);
		ERR_FAIL_COND_V(len>total_len,ERR_INVALID_DATA);
		b+=4;
		Vector<uint8_t> cs;
		cs.resize(len);
		for(int j=0;j<len;j++) {
			cs[j]=b[j]^0xb6;
		}

		cs[cs.size()-1]=0;
		String s;
		s.parse_utf8((const char*)cs.ptr());
		b+=len;
		total_len-=len+4;
		identifiers[i]=s;
	}
	
	constants.resize(constant_count);
	for(int i=0;i<constant_count;i++) {

		Variant v;
		int len;
		Error err = decode_variant(v,b,total_len,&len);
		if (err)
			return err;
		b+=len;
		total_len-=len;
		constants[i]=v;

	}

	ERR_FAIL_COND_V(line_count*8>total_len,ERR_INVALID_DATA);

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

		uint32_t token=decode_uint32(b);
		b+=4;
		uint32_t linecol=decode_uint32(b);
		b+=4;

		lines.insert(token,linecol);
		total_len-=8;
	}

	tokens.resize(token_count);

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

		ERR_FAIL_COND_V( total_len < 1, ERR_INVALID_DATA);

		if ((*b)&TOKEN_BYTE_MASK) { //little endian always
			ERR_FAIL_COND_V( total_len < 4, ERR_INVALID_DATA);

			tokens[i]=decode_uint32(b)&~TOKEN_BYTE_MASK;
			b+=4;
		} else {
			tokens[i]=*b;
			b+=1;
			total_len--;
		}
	}

	token=0;

	return OK;

}
Example #24
0
void ExportTemplateManager::_install_from_file(const String &p_file) {

	FileAccess *fa = NULL;
	zlib_filefunc_def io = zipio_create_io_from_file(&fa);

	unzFile pkg = unzOpen2(p_file.utf8().get_data(), &io);
	if (!pkg) {

		EditorNode::get_singleton()->show_warning(TTR("Can't open export templates zip."));
		return;
	}
	int ret = unzGoToFirstFile(pkg);

	int fc = 0; //count them and find version
	String version;

	while (ret == UNZ_OK) {

		unz_file_info info;
		char fname[16384];
		ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, NULL, 0, NULL, 0);

		String file = fname;

		if (file.ends_with("version.txt")) {

			Vector<uint8_t> data;
			data.resize(info.uncompressed_size);

			//read
			unzOpenCurrentFile(pkg);
			ret = unzReadCurrentFile(pkg, data.ptr(), data.size());
			unzCloseCurrentFile(pkg);

			String data_str;
			data_str.parse_utf8((const char *)data.ptr(), data.size());
			data_str = data_str.strip_edges();

			if (data_str.get_slice_count("-") != 2 || data_str.get_slice_count(".") != 2) {
				EditorNode::get_singleton()->show_warning(TTR("Invalid version.txt format inside templates."));
				unzClose(pkg);
				return;
			}

			String ver = data_str.get_slice("-", 0);

			int major = ver.get_slice(".", 0).to_int();
			int minor = ver.get_slice(".", 1).to_int();
			String rev = data_str.get_slice("-", 1);

			if (!rev.is_valid_identifier()) {
				EditorNode::get_singleton()->show_warning(TTR("Invalid version.txt format inside templates. Revision is not a valid identifier."));
				unzClose(pkg);
				return;
			}

			version = itos(major) + "." + itos(minor) + "-" + rev;
		}

		fc++;
		ret = unzGoToNextFile(pkg);
	}

	if (version == String()) {
		EditorNode::get_singleton()->show_warning(TTR("No version.txt found inside templates."));
		unzClose(pkg);
		return;
	}

	String template_path = EditorSettings::get_singleton()->get_templates_dir().plus_file(version);

	DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
	Error err = d->make_dir_recursive(template_path);
	if (err != OK) {
		EditorNode::get_singleton()->show_warning(TTR("Error creating path for templates:\n") + template_path);
		unzClose(pkg);
		return;
	}

	memdelete(d);

	ret = unzGoToFirstFile(pkg);

	EditorProgress p("ltask", TTR("Extracting Export Templates"), fc);

	fc = 0;

	while (ret == UNZ_OK) {

		//get filename
		unz_file_info info;
		char fname[16384];
		unzGetCurrentFileInfo(pkg, &info, fname, 16384, NULL, 0, NULL, 0);

		String file = fname;

		Vector<uint8_t> data;
		data.resize(info.uncompressed_size);

		//read
		unzOpenCurrentFile(pkg);
		unzReadCurrentFile(pkg, data.ptr(), data.size());
		unzCloseCurrentFile(pkg);

		print_line(fname);
		/*
		for(int i=0;i<512;i++) {
			print_line(itos(data[i]));
		}
		*/

		file = file.get_file();

		p.step(TTR("Importing:") + " " + file, fc);

		FileAccess *f = FileAccess::open(template_path.plus_file(file), FileAccess::WRITE);

		ERR_CONTINUE(!f);
		f->store_buffer(data.ptr(), data.size());

		memdelete(f);

		ret = unzGoToNextFile(pkg);
		fc++;
	}

	unzClose(pkg);

	_update_template_list();
}
Example #25
0
	void ok_pressed() {

		if (!_test_path())
			return;

		String dir;

		if (mode==MODE_IMPORT) {
			dir=project_path->get_text();


		} else {
			DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);

			if (d->change_dir(project_path->get_text())!=OK) {
				error->set_text(TTR("Invalid project path (changed anything?)."));
				memdelete(d);
				return;
			}

			dir=d->get_current_dir();
			memdelete(d);

			if (mode==MODE_NEW) {




				FileAccess *f = FileAccess::open(dir.plus_file("/engine.cfg"),FileAccess::WRITE);
				if (!f) {
					error->set_text(TTR("Couldn't create engine.cfg in project path."));
				} else {

					f->store_line("; Engine configuration file.");
					f->store_line("; It's best edited using the editor UI and not directly,");
					f->store_line("; since the parameters that go here are not all obvious.");
					f->store_line("; ");
					f->store_line("; Format: ");
					f->store_line(";   [section] ; section goes between []");
					f->store_line(";   param=value ; assign values to parameters");
					f->store_line("\n");
					f->store_line("[application]");
					f->store_line("\n");
					f->store_line("name=\""+project_name->get_text()+"\"");
					f->store_line("icon=\"res://icon.png\"");

					memdelete(f);

					ResourceSaver::save(dir.plus_file("/icon.png"),get_icon("DefaultProjectIcon","EditorIcons"));
				}

			} else if (mode==MODE_INSTALL) {


				FileAccess *src_f=NULL;
				zlib_filefunc_def io = zipio_create_io_from_file(&src_f);

				unzFile pkg = unzOpen2(zip_path.utf8().get_data(), &io);
				if (!pkg) {

					dialog_error->set_text("Error opening package file, not in zip format.");
					return;
				}

				int ret = unzGoToFirstFile(pkg);

				Vector<String> failed_files;

				int idx=0;
				while(ret==UNZ_OK) {

					//get filename
					unz_file_info info;
					char fname[16384];
					ret = unzGetCurrentFileInfo(pkg,&info,fname,16384,NULL,0,NULL,0);

					String path=fname;

					int depth=1; //stuff from github comes with tag
					bool skip=false;
					while(depth>0) {
						int pp = path.find("/");
						if (pp==-1) {
							skip=true;
							break;
						}
						path=path.substr(pp+1,path.length());
						depth--;
					}


					if (skip || path==String()) {
						//
					} else if (path.ends_with("/")) { // a dir

						path=path.substr(0,path.length()-1);

						DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
						da->make_dir(dir.plus_file(path));
						memdelete(da);

					} else {

						Vector<uint8_t> data;
						data.resize(info.uncompressed_size);

						//read
						unzOpenCurrentFile(pkg);
						unzReadCurrentFile(pkg,data.ptr(),data.size());
						unzCloseCurrentFile(pkg);

						FileAccess *f=FileAccess::open(dir.plus_file(path),FileAccess::WRITE);

						if (f) {
							f->store_buffer(data.ptr(),data.size());
							memdelete(f);
						} else {
							failed_files.push_back(path);
						}


					}

					idx++;
					ret = unzGoToNextFile(pkg);
				}

				unzClose(pkg);

				if (failed_files.size()) {
					String msg=TTR("The following files failed extraction from package:")+"\n\n";
					for(int i=0;i<failed_files.size();i++) {

						if (i>15) {
							msg+="\nAnd "+itos(failed_files.size()-i)+" more files.";
							break;
						}
						msg+=failed_files[i]+"\n";
					}

					dialog_error->set_text(msg);
					dialog_error->popup_centered_minsize();

				} else {
					dialog_error->set_text(TTR("Package Installed Successfully!"));
					dialog_error->popup_centered_minsize();
				}

			}



		}

		dir=dir.replace("\\","/");
		if (dir.ends_with("/"))
			dir=dir.substr(0,dir.length()-1);
		String proj=dir.replace("/","::");
		EditorSettings::get_singleton()->set("projects/"+proj,dir);
		EditorSettings::get_singleton()->save();



		hide();
		emit_signal("project_created");

	}
Example #26
0
Error EditorExportPlatformOSX::export_project(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags) {

	String src_pkg_name;

	EditorProgress ep("export", "Exporting for OSX", 3);

	if (p_debug)
		src_pkg_name = p_preset->get("custom_package/debug");
	else
		src_pkg_name = p_preset->get("custom_package/release");

	if (src_pkg_name == "") {
		String err;
		src_pkg_name = find_export_template("osx.zip", &err);
		if (src_pkg_name == "") {
			EditorNode::add_io_error(err);
			return ERR_FILE_NOT_FOUND;
		}
	}

	FileAccess *src_f = NULL;
	zlib_filefunc_def io = zipio_create_io_from_file(&src_f);

	ep.step("Creating app", 0);

	unzFile src_pkg_zip = unzOpen2(src_pkg_name.utf8().get_data(), &io);
	if (!src_pkg_zip) {

		EditorNode::add_io_error("Could not find template app to export:\n" + src_pkg_name);
		return ERR_FILE_NOT_FOUND;
	}

	ERR_FAIL_COND_V(!src_pkg_zip, ERR_CANT_OPEN);
	int ret = unzGoToFirstFile(src_pkg_zip);

	String binary_to_use = "godot_osx_" + String(p_debug ? "debug" : "release") + ".";
	int bits_mode = p_preset->get("application/bits_mode");
	binary_to_use += String(bits_mode == 0 ? "fat" : bits_mode == 1 ? "64" : "32");

	print_line("binary: " + binary_to_use);
	String pkg_name;
	if (p_preset->get("application/name") != "")
		pkg_name = p_preset->get("application/name"); // app_name
	else if (String(ProjectSettings::get_singleton()->get("application/config/name")) != "")
		pkg_name = String(ProjectSettings::get_singleton()->get("application/config/name"));
	else
		pkg_name = "Unnamed";

	Error err = OK;
	String tmp_app_path_name = "";
	zlib_filefunc_def io2 = io;
	FileAccess *dst_f = NULL;
	io2.opaque = &dst_f;
	zipFile dst_pkg_zip = NULL;

	if (use_dmg()) {
		// We're on OSX so we can export to DMG, but first we create our application bundle
		tmp_app_path_name = EditorSettings::get_singleton()->get_cache_dir().plus_file(pkg_name + ".app");
		print_line("Exporting to " + tmp_app_path_name);
		DirAccess *tmp_app_path = DirAccess::create_for_path(tmp_app_path_name);
		if (!tmp_app_path) {
			err = ERR_CANT_CREATE;
		}

		// Create our folder structure or rely on unzip?
		if (err == OK) {
			print_line("Creating " + tmp_app_path_name + "/Contents/MacOS");
			err = tmp_app_path->make_dir_recursive(tmp_app_path_name + "/Contents/MacOS");
		}

		if (err == OK) {
			print_line("Creating " + tmp_app_path_name + "/Contents/Resources");
			err = tmp_app_path->make_dir_recursive(tmp_app_path_name + "/Contents/Resources");
		}
	} else {
		// Open our destination zip file
		dst_pkg_zip = zipOpen2(p_path.utf8().get_data(), APPEND_STATUS_CREATE, NULL, &io2);
		if (!dst_pkg_zip) {
			err = ERR_CANT_CREATE;
		}
	}

	// Now process our template
	bool found_binary = false;
	int total_size = 0;

	while (ret == UNZ_OK && err == OK) {
		bool is_execute = false;

		//get filename
		unz_file_info info;
		char fname[16384];
		ret = unzGetCurrentFileInfo(src_pkg_zip, &info, fname, 16384, NULL, 0, NULL, 0);

		String file = fname;

		print_line("READ: " + file);
		Vector<uint8_t> data;
		data.resize(info.uncompressed_size);

		//read
		unzOpenCurrentFile(src_pkg_zip);
		unzReadCurrentFile(src_pkg_zip, data.ptr(), data.size());
		unzCloseCurrentFile(src_pkg_zip);

		//write

		file = file.replace_first("osx_template.app/", "");

		if (file == "Contents/Info.plist") {
			print_line("parse plist");
			_fix_plist(p_preset, data, pkg_name);
		}

		if (file.begins_with("Contents/MacOS/godot_")) {
			if (file != "Contents/MacOS/" + binary_to_use) {
				ret = unzGoToNextFile(src_pkg_zip);
				continue; //ignore!
			}
			found_binary = true;
			is_execute = true;
			file = "Contents/MacOS/" + pkg_name;
		}

		if (file == "Contents/Resources/icon.icns") {
			//see if there is an icon
			String iconpath;
			if (p_preset->get("application/icon") != "")
				iconpath = p_preset->get("application/icon");
			else
				iconpath = ProjectSettings::get_singleton()->get("application/config/icon");
			print_line("icon? " + iconpath);
			if (iconpath != "") {
				Ref<Image> icon;
				icon.instance();
				icon->load(iconpath);
				if (!icon->empty()) {
					print_line("loaded?");
					_make_icon(icon, data);
				}
			}
			//bleh?
		}

		if (data.size() > 0) {
			print_line("ADDING: " + file + " size: " + itos(data.size()));
			total_size += data.size();

			if (use_dmg()) {
				// write it into our application bundle
				file = tmp_app_path_name + "/" + file;

				// write the file, need to add chmod
				FileAccess *f = FileAccess::open(file, FileAccess::WRITE);
				if (f) {
					f->store_buffer(data.ptr(), data.size());
					f->close();
					if (is_execute) {
						// Chmod with 0755 if the file is executable
						f->_chmod(file, 0755);
					}
					memdelete(f);
				} else {
					err = ERR_CANT_CREATE;
				}
			} else {
				// add it to our zip file
				file = pkg_name + ".app/" + file;

				zip_fileinfo fi;
				fi.tmz_date.tm_hour = info.tmu_date.tm_hour;
				fi.tmz_date.tm_min = info.tmu_date.tm_min;
				fi.tmz_date.tm_sec = info.tmu_date.tm_sec;
				fi.tmz_date.tm_mon = info.tmu_date.tm_mon;
				fi.tmz_date.tm_mday = info.tmu_date.tm_mday;
				fi.tmz_date.tm_year = info.tmu_date.tm_year;
				fi.dosDate = info.dosDate;
				fi.internal_fa = info.internal_fa;
				fi.external_fa = info.external_fa;

				int zerr = zipOpenNewFileInZip(dst_pkg_zip,
						file.utf8().get_data(),
						&fi,
						NULL,
						0,
						NULL,
						0,
						NULL,
						Z_DEFLATED,
						Z_DEFAULT_COMPRESSION);

				print_line("OPEN ERR: " + itos(zerr));
				zerr = zipWriteInFileInZip(dst_pkg_zip, data.ptr(), data.size());
				print_line("WRITE ERR: " + itos(zerr));
				zipCloseFileInZip(dst_pkg_zip);
			}
		}

		ret = unzGoToNextFile(src_pkg_zip);
	}

	// we're done with our source zip
	unzClose(src_pkg_zip);

	if (!found_binary) {
		ERR_PRINTS("Requested template binary '" + binary_to_use + "' not found. It might be missing from your template archive.");
		err = ERR_FILE_NOT_FOUND;
	}

	if (err == OK) {
		ep.step("Making PKG", 1);

		if (use_dmg()) {
			String pack_path = tmp_app_path_name + "/Contents/Resources/" + pkg_name + ".pck";
			err = save_pack(p_preset, pack_path);

			// see if we can code sign our new package
			String identity = p_preset->get("codesign/identity");
			if (err == OK && identity != "") {
				ep.step("Code signing bundle", 2);

				// the order in which we code sign is important, this is a bit of a shame or we could do this in our loop that extracts the files from our ZIP

				// start with our application
				err = _code_sign(p_preset, tmp_app_path_name + "/Contents/MacOS/" + pkg_name);

				///@TODO we should check the contents of /Contents/Frameworks for frameworks to sign
			}

			if (err == OK && identity != "") {
				// we should probably loop through all resources and sign them?
				err = _code_sign(p_preset, tmp_app_path_name + "/Contents/Resources/icon.icns");
			}

			if (err == OK && identity != "") {
				err = _code_sign(p_preset, pack_path);
			}

			if (err == OK && identity != "") {
				err = _code_sign(p_preset, tmp_app_path_name + "/Contents/Info.plist");
			}

			// and finally create a DMG
			if (err == OK) {
				ep.step("Making DMG", 3);
				err = _create_dmg(p_path, pkg_name, tmp_app_path_name);
			}

			// Clean up temporary .app dir
			OS::get_singleton()->move_to_trash(tmp_app_path_name);
		} else {

			String pack_path = EditorSettings::get_singleton()->get_cache_dir().plus_file(pkg_name + ".pck");
			Error err = save_pack(p_preset, pack_path);

			if (err == OK) {
				zipOpenNewFileInZip(dst_pkg_zip,
						(pkg_name + ".app/Contents/Resources/" + pkg_name + ".pck").utf8().get_data(),
						NULL,
						NULL,
						0,
						NULL,
						0,
						NULL,
						Z_DEFLATED,
						Z_DEFAULT_COMPRESSION);

				FileAccess *pf = FileAccess::open(pack_path, FileAccess::READ);
				if (pf) {
					const int BSIZE = 16384;
					uint8_t buf[BSIZE];

					while (true) {

						int r = pf->get_buffer(buf, BSIZE);
						if (r <= 0)
							break;
						zipWriteInFileInZip(dst_pkg_zip, buf, r);
					}
					zipCloseFileInZip(dst_pkg_zip);
					memdelete(pf);
				} else {
					err = ERR_CANT_OPEN;
				}
			}
		}
	}

	if (dst_pkg_zip) {
		zipClose(dst_pkg_zip, NULL);
	}

	return OK;
}
Example #27
0
void OS_X11::set_icon(const Image& p_icon) {
	if (!p_icon.empty()) {
		Image img=p_icon;
		img.convert(Image::FORMAT_RGBA);

		int w = img.get_width();
		int h = img.get_height();

		// We're using long to have wordsize (32Bit build -> 32 Bits, 64 Bit build -> 64 Bits
		Vector<long> pd;

		pd.resize(2+w*h);

		print_line("***** SET ICON ***** "+itos(w)+"  "+itos(h));

		pd[0]=w;
		pd[1]=h;

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

		long * wr = &pd[2];
		uint8_t const * pr = r.ptr();

		for(int i=0;i<w*h;i++) {
			long v=0;
			//    A             R             G            B
			v|=pr[3] << 24 | pr[0] << 16 | pr[1] << 8 | pr[2];
			*wr++=v;
			pr += 4;
		}
		XChangeProperty(x11_display, x11_window, net_wm_icon, XA_CARDINAL, 32, PropModeReplace, (unsigned char*) pd.ptr(), pd.size());
	} else {
	    XDeleteProperty(x11_display, x11_window, net_wm_icon);
	}
	XFlush(x11_display);

}
Example #28
0
Error EditorExportPlatformJavaScript::export_project(const String& p_path, bool p_debug, int p_flags) {


	String src_template;

	EditorProgress ep("export","Exporting for javascript",104);

	String template_path = EditorSettings::get_singleton()->get_settings_path()+"/templates/";

	if (p_debug) {

		src_template=custom_debug_package!=""?custom_debug_package:template_path+"javascript_debug.zip";
	} else {

		src_template=custom_release_package!=""?custom_release_package:template_path+"javascript_release.zip";

	}


	FileAccess *src_f=NULL;
	zlib_filefunc_def io = zipio_create_io_from_file(&src_f);

	ep.step("Exporting to HTML5",0);

	ep.step("Finding Files..",1);

	FileAccess *f=FileAccess::open(p_path.get_base_dir()+"/data.pck",FileAccess::WRITE);
	if (!f) {
		EditorNode::add_io_error("Could not create file for writing:\n"+p_path.basename()+"_files.js");
		return ERR_FILE_CANT_WRITE;
	}
	Error err = save_pack(f);
	size_t len = f->get_len();
	memdelete(f);
	if (err)
		return err;


	unzFile pkg = unzOpen2(src_template.utf8().get_data(), &io);
	if (!pkg) {

		EditorNode::add_io_error("Could not find template HTML5 to export:\n"+src_template);
		return ERR_FILE_NOT_FOUND;
	}

	ERR_FAIL_COND_V(!pkg, ERR_CANT_OPEN);
	int ret = unzGoToFirstFile(pkg);


	while(ret==UNZ_OK) {

		//get filename
		unz_file_info info;
		char fname[16384];
		ret = unzGetCurrentFileInfo(pkg,&info,fname,16384,NULL,0,NULL,0);

		String file=fname;

		Vector<uint8_t> data;
		data.resize(info.uncompressed_size);

		//read
		unzOpenCurrentFile(pkg);
		unzReadCurrentFile(pkg,data.ptr(),data.size());
		unzCloseCurrentFile(pkg);

		//write

		if (file=="godot.html") {

			_fix_html(data,p_path.get_file().basename(),1<<(max_memory+5));
			file=p_path.get_file();
		}
		if (file=="godotfs.js") {

			_fix_files(data,len);
			file=p_path.get_file().basename()+"fs.js";
		}
		if (file=="godot.js") {

			//_fix_godot(data);
			file=p_path.get_file().basename()+".js";
		}

		if (file=="godot.mem") {

			//_fix_godot(data);
			file=p_path.get_file().basename()+".mem";
		}

		String dst = p_path.get_base_dir().plus_file(file);
		FileAccess *f=FileAccess::open(dst,FileAccess::WRITE);
		if (!f) {
			EditorNode::add_io_error("Could not create file for writing:\n"+dst);
			unzClose(pkg);
			return ERR_FILE_CANT_WRITE;
		}
		f->store_buffer(data.ptr(),data.size());
		memdelete(f);


		ret = unzGoToNextFile(pkg);
	}



	return OK;

}
void EditorSampleImportPlugin::_compress_ima_adpcm(const Vector<float>& p_data,DVector<uint8_t>& dst_data) {


	/*p_sample_data->data = (void*)malloc(len);
	xm_s8 *dataptr=(xm_s8*)p_sample_data->data;*/

	static const int16_t _ima_adpcm_step_table[89] = {
		7, 8, 9, 10, 11, 12, 13, 14, 16, 17,
		19, 21, 23, 25, 28, 31, 34, 37, 41, 45,
		50, 55, 60, 66, 73, 80, 88, 97, 107, 118,
		130, 143, 157, 173, 190, 209, 230, 253, 279, 307,
		337, 371, 408, 449, 494, 544, 598, 658, 724, 796,
		876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066,
		2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358,
		5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899,
		15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767
	};

	static const int8_t _ima_adpcm_index_table[16] = {
		-1, -1, -1, -1, 2, 4, 6, 8,
		-1, -1, -1, -1, 2, 4, 6, 8
	};


	int datalen = p_data.size();
	int datamax=datalen;
	if (datalen&1)
		datalen++;

	dst_data.resize(datalen/2+4);
	DVector<uint8_t>::Write w = dst_data.write();


	int i,step_idx=0,prev=0;
	uint8_t *out = w.ptr();
	//int16_t xm_prev=0;
	const float *in=p_data.ptr();


	/* initial value is zero */
	*(out++) =0;
	*(out++) =0;
	/* Table index initial value */
	*(out++) =0;
	/* unused */
	*(out++) =0;

	for (i=0;i<datalen;i++) {
		int step,diff,vpdiff,mask;
		uint8_t nibble;
		int16_t xm_sample;

		if (i>=datamax)
			xm_sample=0;
		else {


			xm_sample=CLAMP(in[i]*32767.0,-32768,32767);
			//if (xm_sample==32767 || xm_sample==-32768)
			//	printf("clippy!\n",xm_sample);
		}

	//	xm_sample=xm_sample+xm_prev;
	//	xm_prev=xm_sample;

		diff = (int)xm_sample - prev ;

		nibble=0 ;
		step =  _ima_adpcm_step_table[ step_idx ];
		vpdiff = step >> 3 ;
		if (diff < 0) {
			nibble=8;
			diff=-diff ;
		}
		mask = 4 ;
		while (mask) {

			if (diff >= step) {

				nibble |= mask;
				diff -= step;
				vpdiff += step;
			}

			step >>= 1 ;
			mask >>= 1 ;
		};

		if (nibble&8)
			prev-=vpdiff ;
		else
			prev+=vpdiff ;

		if (prev > 32767) {
			//printf("%i,xms %i, prev %i,diff %i, vpdiff %i, clip up %i\n",i,xm_sample,prev,diff,vpdiff,prev);
			prev=32767;
		} else if (prev < -32768) {
			//printf("%i,xms %i, prev %i,diff %i, vpdiff %i, clip down %i\n",i,xm_sample,prev,diff,vpdiff,prev);
			prev = -32768 ;
		}

		step_idx += _ima_adpcm_index_table[nibble];
		if (step_idx< 0)
			step_idx= 0 ;
		else if (step_idx> 88)
			step_idx= 88 ;


		if (i&1) {
			*out|=nibble<<4;
			out++;
		} else {
			*out=nibble;
		}
		/*dataptr[i]=prev>>8;*/
	}

}
void ExportTemplateManager::_install_from_file(const String &p_file, bool p_use_progress) {

	FileAccess *fa = NULL;
	zlib_filefunc_def io = zipio_create_io_from_file(&fa);

	unzFile pkg = unzOpen2(p_file.utf8().get_data(), &io);
	if (!pkg) {

		EditorNode::get_singleton()->show_warning(TTR("Can't open export templates zip."));
		return;
	}
	int ret = unzGoToFirstFile(pkg);

	int fc = 0; //count them and find version
	String version;

	while (ret == UNZ_OK) {

		unz_file_info info;
		char fname[16384];
		ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, NULL, 0, NULL, 0);

		String file = fname;

		if (file.ends_with("version.txt")) {

			Vector<uint8_t> data;
			data.resize(info.uncompressed_size);

			//read
			unzOpenCurrentFile(pkg);
			ret = unzReadCurrentFile(pkg, data.ptrw(), data.size());
			unzCloseCurrentFile(pkg);

			String data_str;
			data_str.parse_utf8((const char *)data.ptr(), data.size());
			data_str = data_str.strip_edges();

			// Version number should be of the form major.minor[.patch].status[.module_config]
			// so it can in theory have 3 or more slices.
			if (data_str.get_slice_count(".") < 3) {
				EditorNode::get_singleton()->show_warning(vformat(TTR("Invalid version.txt format inside templates: %s."), data_str));
				unzClose(pkg);
				return;
			}

			version = data_str;
		}

		fc++;
		ret = unzGoToNextFile(pkg);
	}

	if (version == String()) {
		EditorNode::get_singleton()->show_warning(TTR("No version.txt found inside templates."));
		unzClose(pkg);
		return;
	}

	String template_path = EditorSettings::get_singleton()->get_templates_dir().plus_file(version);

	DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
	Error err = d->make_dir_recursive(template_path);
	if (err != OK) {
		EditorNode::get_singleton()->show_warning(TTR("Error creating path for templates:") + "\n" + template_path);
		unzClose(pkg);
		return;
	}

	memdelete(d);

	ret = unzGoToFirstFile(pkg);

	EditorProgress *p = NULL;
	if (p_use_progress) {
		p = memnew(EditorProgress("ltask", TTR("Extracting Export Templates"), fc));
	}

	fc = 0;

	while (ret == UNZ_OK) {

		//get filename
		unz_file_info info;
		char fname[16384];
		unzGetCurrentFileInfo(pkg, &info, fname, 16384, NULL, 0, NULL, 0);

		String file = String(fname).get_file();

		Vector<uint8_t> data;
		data.resize(info.uncompressed_size);

		//read
		unzOpenCurrentFile(pkg);
		unzReadCurrentFile(pkg, data.ptrw(), data.size());
		unzCloseCurrentFile(pkg);

		if (p) {
			p->step(TTR("Importing:") + " " + file, fc);
		}

		FileAccess *f = FileAccess::open(template_path.plus_file(file), FileAccess::WRITE);

		if (!f) {
			ret = unzGoToNextFile(pkg);
			fc++;
			ERR_CONTINUE(!f);
		}

		f->store_buffer(data.ptr(), data.size());

		memdelete(f);

		ret = unzGoToNextFile(pkg);
		fc++;
	}

	if (p) {
		memdelete(p);
	}

	unzClose(pkg);

	_update_template_list();
}