Example #1
0
bool D_bjmak::getHashesAndData(int fd, DVector& dataBuffer, DVector& hashBuffer, int blockCount){
    
    string hash;
    hash.reserve(26);
    for(int i = 0; i < blockCount; ++i){
        char buf[bsize_];
        int l = read(fd, buf, bsize_);
        //cout << " read " << l << " i = " << i << "blockCount = " << blockCount << endl;
        
        if (l == -1){
            cout << " read errror " << strerror(errno) << endl;
            return false;
        }
        
        DVector hashstr;
        hash = Hash::sha1(buf, l);
        hashstr.push_back(hash.data(), hash.size());
        hashstr.push_back(int64_to_byte(Hash::crc32(buf, l), 4));
        hashstr.push_back(int64_to_byte(l, 2));
        hashBuffer.push_back(hashstr);
        dataBuffer.push_back(buf, l);
    }
    
    return true;
}
Example #2
0
DVector<Plane> Geometry::build_capsule_planes(float p_radius, float p_height, int p_sides, int p_lats, Vector3::Axis p_axis) {

	DVector<Plane> planes;

	Vector3 axis;
	axis[p_axis] = 1.0;

	Vector3 axis_neg;
	axis_neg[(p_axis + 1) % 3] = 1.0;
	axis_neg[(p_axis + 2) % 3] = 1.0;
	axis_neg[p_axis] = -1.0;

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

		Vector3 normal;
		normal[(p_axis + 1) % 3] = Math::cos(i * (2.0 * Math_PI) / p_sides);
		normal[(p_axis + 2) % 3] = Math::sin(i * (2.0 * Math_PI) / p_sides);

		planes.push_back(Plane(normal, p_radius));

		for (int j = 1; j <= p_lats; j++) {

			Vector3 angle = normal.linear_interpolate(axis, j / (float)p_lats).normalized();
			Vector3 pos = axis * p_height * 0.5 + angle * p_radius;
			planes.push_back(Plane(pos, angle));
			planes.push_back(Plane(pos * axis_neg, angle * axis_neg));
		}
	}

	return planes;
}
Example #3
0
Ref<Mesh> SceneTree::get_debug_contact_mesh() {

	if (debug_contact_mesh.is_valid())
		return debug_contact_mesh;

	debug_contact_mesh = Ref<Mesh>( memnew( Mesh ) );

	Ref<FixedMaterial> mat = memnew( FixedMaterial );
	mat->set_flag(Material::FLAG_UNSHADED,true);
	mat->set_flag(Material::FLAG_DOUBLE_SIDED,true);
	mat->set_fixed_flag(FixedMaterial::FLAG_USE_ALPHA,true);
	mat->set_parameter(FixedMaterial::PARAM_DIFFUSE,get_debug_collision_contact_color());

	Vector3 diamond[6]={
		Vector3(-1, 0, 0),
		Vector3( 1, 0, 0),
		Vector3( 0, -1, 0),
		Vector3( 0, 1, 0),
		Vector3( 0, 0, -1),
		Vector3( 0, 0, 1)
	};

	int diamond_faces[8*3]={
		0,2,4,
		0,3,4,
		1,2,4,
		1,3,4,
		0,2,5,
		0,3,5,
		1,2,5,
		1,3,5,
	};

	DVector<int> indices;
	for(int i=0;i<8*3;i++)
		indices.push_back(diamond_faces[i]);

	DVector<Vector3> vertices;
	for(int i=0;i<6;i++)
		vertices.push_back(diamond[i]*0.1);

	Array arr;
	arr.resize(Mesh::ARRAY_MAX);
	arr[Mesh::ARRAY_VERTEX]=vertices;
	arr[Mesh::ARRAY_INDEX]=indices;


	debug_contact_mesh->add_surface(Mesh::PRIMITIVE_TRIANGLES,arr);
	debug_contact_mesh->surface_set_material(0,mat);

	return debug_contact_mesh;

}
Example #4
0
DVector<int> Font::_get_kernings() const {

	DVector<int> kernings;

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

		kernings.push_back(E->key().A);
		kernings.push_back(E->key().B);
		kernings.push_back(E->get());
	}

	return kernings;
}
void GridMapEditor::_update_areas_display() {


	_clear_areas();
	List<int> areas;
	node->get_area_list(&areas);

	Transform global_xf = node->get_global_transform();

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

		int area = E->get();
		Color color;
		if (node->area_is_exterior_portal(area))
			color=Color(1,1,1,0.2);
		else
			color.set_hsv(Math::fmod(area*0.37,1),Math::fmod(area*0.75,1),1.0,0.2);
		RID material = VisualServer::get_singleton()->fixed_material_create();
		VisualServer::get_singleton()->fixed_material_set_param( material, VS::FIXED_MATERIAL_PARAM_DIFFUSE,color );
		VisualServer::get_singleton()->fixed_material_set_param( material, VS::FIXED_MATERIAL_PARAM_EMISSION,0.5 );
		VisualServer::get_singleton()->fixed_material_set_flag( material, VisualServer::FIXED_MATERIAL_FLAG_USE_ALPHA, true );


		RID mesh = VisualServer::get_singleton()->mesh_create();

		DVector<Plane> planes;
		for(int i=0;i<3;i++) {

			Vector3 axis;
			axis[i]=1.0;
			planes.push_back(Plane(axis,1));
			planes.push_back(Plane(-axis,0));
		}

		VisualServer::get_singleton()->mesh_add_surface_from_planes(mesh,planes);
		VisualServer::get_singleton()->mesh_surface_set_material(mesh,0,material,true);

		AreaDisplay ad;
		ad.mesh=mesh;
		ad.instance = VisualServer::get_singleton()->instance_create2(mesh,node->get_world()->get_scenario());
		Transform xform;
		AABB aabb = node->area_get_bounds(area);
		xform.origin=aabb.pos * node->get_cell_size();
		xform.basis.scale(aabb.size * node->get_cell_size());
		VisualServer::get_singleton()->instance_set_transform(ad.instance,global_xf * xform);
		this->areas.push_back(ad);

	}

}
Example #6
0
DVector<Face3> Portal::get_faces(uint32_t p_usage_flags) const {

	if (!(p_usage_flags&FACES_ENCLOSING))
		return DVector<Face3>();

	Vector<Point2> shape = get_shape();
	if (shape.size()==0)
		return DVector<Face3>();
		
	Vector2 center;
	for (int i=0;i<shape.size();i++) {
	
		center+=shape[i];
		
	}
	
	DVector<Face3> ret;
	center/=shape.size();

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

		int n=(i+1)%shape.size();
		
		Face3 f;
		f.vertex[0]=Vector3( center.x, center.y, 0 );
		f.vertex[1]=Vector3( shape[i].x, shape[i].y, 0 );
		f.vertex[2]=Vector3( shape[n].x, shape[n].y, 0 );
		ret.push_back(f);
	}
	
	return ret;
}
Example #7
0
DVector D_bjmak::getDataBufferFromReply(DVector& reply, DVector& hashBuffer, DVector& dataBuffer){
    int dataPos = 0;
    int blockCount = reply.size();
    char* hashBufferPtr = hashBuffer.data();
    char* dataBufferPtr = dataBuffer.data();
    DVector res;
    res.reserve(blockCount*bsize_);
    
    for(int i = 0; i < blockCount; ++i){
        int dataBlockSize = byte_to_int64((hashBufferPtr+i*(D_LENGTH_OF_HASH+2)+D_LENGTH_OF_HASH), 2);
        
        if (reply[i] == 1){
            //cout << " 1 " << dataBlockSize << endl;
            res.push_back(dataBufferPtr+dataPos, dataBlockSize);
        }else
            //cout << " - " << (int)reply[i] << "  " << dataBuffer.size() << " " << hashBuffer.size()<< " " << dataBlockSize << endl;
            
        
        dataPos += dataBlockSize;
    }
    
    //cout << endl;
    return move(res);
    
}
Example #8
0
void FileDialog::_action_pressed() {
	
	if (mode==MODE_OPEN_FILES) {

		TreeItem *ti=tree->get_next_selected(NULL);
		String fbase=dir_access->get_current_dir();

		DVector<String> files;
		while(ti) {

			files.push_back( fbase.plus_file(ti->get_text(0)) );
			ti=tree->get_next_selected(ti);
		}

		if (files.size()) {
			emit_signal("files_selected",files);
			hide();
		}

		return;
	}

	String f=dir_access->get_current_dir().plus_file(file->get_text());
	                   
	if (mode==MODE_OPEN_FILE && dir_access->file_exists(f)) {
		emit_signal("file_selected",f);
		hide();
	}

	if (mode==MODE_OPEN_DIR) {


		String path=dir_access->get_current_dir();
		/*if (tree->get_selected()) {
			Dictionary d = tree->get_selected()->get_metadata(0);
			if (d["dir"]) {
				path=path+"/"+String(d["name"]);
			}
		}*/
		path=path.replace("\\","/");
		emit_signal("dir_selected",path);
		hide();
	}

	if (mode==MODE_SAVE_FILE) {
		
		if (dir_access->file_exists(f)) {
			confirm_save->set_text("File Exists, Overwrite?");
			confirm_save->popup_centered(Size2(200,80));
		} else {
			
			emit_signal("file_selected",f);
			hide();
		}
	}
}
Example #9
0
DVector<String> SceneState::_get_node_groups(int p_idx) const {

	Vector<StringName> groups = get_node_groups(p_idx);
	DVector<String> ret;

	for(int i=0;i<groups.size();i++)
		ret.push_back(groups[i]);

	return ret;
}
Example #10
0
bool Mesh::_get(const StringName& p_name,Variant &r_ret) const {

	String sname=p_name;

	if (p_name=="morph_target/names") {

		DVector<String> sk;
		for(int i=0;i<morph_targets.size();i++)
			sk.push_back(morph_targets[i]);
		r_ret=sk;
		return true;
	} else if (p_name=="morph_target/mode") {

		r_ret = get_morph_target_mode();
		return true;
	} else if (sname.begins_with("surface_")) {

		int sl=sname.find("/");
		if (sl==-1)
			return false;
		int idx=sname.substr(8,sl-8).to_int()-1;
		String what = sname.get_slice("/",1);
		if (what=="material")
			r_ret=surface_get_material(idx);
		else if (what=="name")
			r_ret=surface_get_name(idx);
		return true;
	} else if (sname=="custom_aabb/custom_aabb") {

		r_ret=custom_aabb;
		return true;

	} else if (!sname.begins_with("surfaces"))
		return false;


	int idx=sname.get_slice("/",1).to_int();
	ERR_FAIL_INDEX_V(idx,surfaces.size(),false);

	Dictionary d;
	d["primitive"]=surface_get_primitive_type(idx);
	d["arrays"]=surface_get_arrays(idx);
	d["morph_arrays"]=surface_get_morph_arrays(idx);
	d["alphasort"]=surface_is_alpha_sorting_enabled(idx);
	Ref<Material> m = surface_get_material(idx);
	if (m.is_valid())
		d["material"]=m;
	String n = surface_get_name(idx);
	if (n!="")
		d["name"]=n;

	r_ret=d;

	return true;
}
Example #11
0
void VisualServer::mesh_add_surface_from_mesh_data( RID p_mesh, const Geometry::MeshData& p_mesh_data) {

#if 1
	DVector<Vector3> vertices;
	DVector<Vector3> normals;
		
	for (int i=0;i<p_mesh_data.faces.size();i++) {
	
		const Geometry::MeshData::Face& f = p_mesh_data.faces[i];
		
		for (int j=2;j<f.indices.size();j++) {
			
#define _ADD_VERTEX(m_idx)\
	vertices.push_back( p_mesh_data.vertices[ f.indices[m_idx] ] );\
	normals.push_back( f.plane.normal );
	
			_ADD_VERTEX( 0 );
			_ADD_VERTEX( j-1 );
			_ADD_VERTEX( j );
		}	
	}
	
	int s = mesh_get_surface_count(p_mesh);
	Array d;
	d.resize(VS::ARRAY_MAX);
	d[ARRAY_VERTEX]=vertices;
	d[ARRAY_NORMAL]=normals;
	mesh_add_surface(p_mesh,PRIMITIVE_TRIANGLES, d);

#else


	DVector<Vector3> vertices;



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

		const Geometry::MeshData::Edge& f = p_mesh_data.edges[i];
		vertices.push_back(p_mesh_data.vertices[ f.a]);
		vertices.push_back(p_mesh_data.vertices[ f.b]);
	}

	Array d;
	d.resize(VS::ARRAY_MAX);
	d[ARRAY_VERTEX]=vertices;
	mesh_add_surface(p_mesh,PRIMITIVE_LINES, d);




#endif
	
}
Example #12
0
DVector<String> _ResourceSaver::get_recognized_extensions(const RES& p_resource) {

    ERR_FAIL_COND_V(p_resource.is_null(),DVector<String>());
    List<String> exts;
    ResourceSaver::get_recognized_extensions(p_resource,&exts);
    DVector<String> ret;
    for(List<String>::Element *E=exts.front(); E; E=E->next()) {

        ret.push_back(E->get());
    }
    return ret;
}
Example #13
0
DVector<String> _ResourceLoader::get_recognized_extensions_for_type(const String& p_type) {

    List<String> exts;
    ResourceLoader::get_recognized_extensions_for_type(p_type,&exts);
    DVector<String> ret;
    for(List<String>::Element *E=exts.front(); E; E=E->next()) {

        ret.push_back(E->get());
    }

    return ret;
}
Example #14
0
DVector<Plane> Geometry::build_cylinder_planes(float p_radius, float p_height, int p_sides, Vector3::Axis p_axis) {

	DVector<Plane> planes;

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

		Vector3 normal;
		normal[(p_axis + 1) % 3] = Math::cos(i * (2.0 * Math_PI) / p_sides);
		normal[(p_axis + 2) % 3] = Math::sin(i * (2.0 * Math_PI) / p_sides);

		planes.push_back(Plane(normal, p_radius));
	}

	Vector3 axis;
	axis[p_axis] = 1.0;

	planes.push_back(Plane(axis, p_height * 0.5));
	planes.push_back(Plane(-axis, p_height * 0.5));

	return planes;
}
Example #15
0
DVector* NextCalculator::MultiplyVectors(std::vector<double> & first, std::vector<double> & second) {
	DVector coeffs_tmp;
	DVector *ret;

	if (first.size() < 1) {
		ret = new DVector(second);
		return ret;
	}

	if (second.size() < 1) {
		ret = new DVector(first);
		return ret;
	}

	if (second.size() != 2)
		throw NextException("Second vector's size is not 2.");

	ret = new DVector();

	for (DVector::iterator first_ite = first.begin(); first_ite != first.end(); ++first_ite)
		for (DVector::iterator second_ite = second.begin(); second_ite != second.end(); ++second_ite)
			coeffs_tmp.push_back(*first_ite * *second_ite);

	ret->push_back(coeffs_tmp.data()[0]);

	double tmp = 0;
	for (int i = 1; i < coeffs_tmp.size()-1; i++) {
		tmp += coeffs_tmp.data()[i];

		if (i % 2 == 0) {
			ret->push_back(tmp);
			tmp = 0;
		}
	}

	ret->push_back(coeffs_tmp.data()[coeffs_tmp.size()-1]);

	return ret;
}
Example #16
0
DVector<Plane> Geometry::build_box_planes(const Vector3 &p_extents) {

	DVector<Plane> planes;

	planes.push_back(Plane(Vector3(1, 0, 0), p_extents.x));
	planes.push_back(Plane(Vector3(-1, 0, 0), p_extents.x));
	planes.push_back(Plane(Vector3(0, 1, 0), p_extents.y));
	planes.push_back(Plane(Vector3(0, -1, 0), p_extents.y));
	planes.push_back(Plane(Vector3(0, 0, 1), p_extents.z));
	planes.push_back(Plane(Vector3(0, 0, -1), p_extents.z));

	return planes;
}
Example #17
0
DVector<String> VisualServer::_shader_get_param_list(RID p_shader) const {

//remove at some point

	DVector<String> pl;


#if 0
	List<StringName> params;
	shader_get_param_list(p_shader,&params);


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

		pl.push_back(E->get());
	}
#endif
	return pl;
}
Example #18
0
DVector<Vector2> TileMapEditor::_bucket_fill(const Point2i& p_start) {

	if (node->get_cell(p_start.x, p_start.y) != TileMap::INVALID_CELL)
		return DVector<Vector2>();

	int id = get_selected_tile();

	if (id == TileMap::INVALID_CELL)
		return DVector<Vector2>();

	Rect2 r = node->get_item_rect();
	r.pos = r.pos/node->get_cell_size();
	r.size = r.size/node->get_cell_size();

	DVector<Vector2> points;

	List<Point2i> queue;
	queue.push_back(p_start);

	while (queue.size()) {

		Point2i n = queue.front()->get();
		queue.pop_front();

		if (!r.has_point(n))
			continue;

		if (node->get_cell(n.x, n.y) == TileMap::INVALID_CELL) {

			node->set_cellv(n, id, flip_h, flip_v, transpose);

			points.push_back(n);

			queue.push_back(n + Point2i(0, 1));
			queue.push_back(n + Point2i(0, -1));
			queue.push_back(n + Point2i(1, 0));
			queue.push_back(n + Point2i(-1, 0));
		}
	}

	return points;
}
Example #19
0
DVector<int> Font::_get_chars() const {

	DVector<int> chars;

	const CharType* key=NULL;

	while((key=char_map.next(key))) {

		const Character *c=char_map.getptr(*key);
		chars.push_back(*key);
		chars.push_back(c->texture_idx);
		chars.push_back(c->rect.pos.x);
		chars.push_back(c->rect.pos.y);

		chars.push_back(c->rect.size.x);
		chars.push_back(c->rect.size.y);
		chars.push_back(c->h_align);
		chars.push_back(c->v_align);
		chars.push_back(c->advance);
	}

	return chars;
}
Example #20
0
void FileDialog::_action_pressed() {
	
	if (mode==MODE_OPEN_FILES) {

		TreeItem *ti=tree->get_next_selected(NULL);
		String fbase=dir_access->get_current_dir();

		DVector<String> files;
		while(ti) {

			files.push_back( fbase.plus_file(ti->get_text(0)) );
			ti=tree->get_next_selected(ti);
		}

		if (files.size()) {
			emit_signal("files_selected",files);
			hide();
		}

		return;
	}

	String f=dir_access->get_current_dir().plus_file(file->get_text());
	                   
	if (mode==MODE_OPEN_FILE && dir_access->file_exists(f)) {
		emit_signal("file_selected",f);
		hide();
	}

	if (mode==MODE_OPEN_DIR) {


		String path=dir_access->get_current_dir();
		/*if (tree->get_selected()) {
			Dictionary d = tree->get_selected()->get_metadata(0);
			if (d["dir"]) {
				path=path+"/"+String(d["name"]);
			}
		}*/
		path=path.replace("\\","/");
		emit_signal("dir_selected",path);
		hide();
	}

	if (mode==MODE_SAVE_FILE) {
		
		bool valid=false;

		if (filter->get_selected()==filter->get_item_count()-1) {
			valid=true; //match none
		} else if (filters.size()>1 && filter->get_selected()==0) {
			// match all filters
			for (int i=0;i<filters.size();i++) {

				String flt=filters[i].get_slice(";",0);
				for (int j=0;j<flt.get_slice_count(",");j++) {

					String str = flt.get_slice(",",j).strip_edges();
					if (f.match(str)) {
						valid=true;
						break;
					}
				}
				if (valid)
					break;
			}
		} else {
			int idx=filter->get_selected();
			if (filters.size()>1)
				idx--;
			if (idx>=0 && idx<filters.size()) {

				String flt=filters[idx].get_slice(";",0);
				int filterSliceCount=flt.get_slice_count(",");
				for (int j=0;j<filterSliceCount;j++) {

					String str = (flt.get_slice(",",j).strip_edges());
					if (f.match(str)) {
						valid=true;
						break;
					}
				}

				if (!valid && filterSliceCount>0) {
					String str = (flt.get_slice(",",0).strip_edges());
					f+=str.substr(1, str.length()-1);
					file->set_text(f.get_file());
					valid=true;
				}
			} else {
				valid=true;
			}
		}


		if (!valid) {

			exterr->popup_centered_minsize(Size2(250,80));
			return;

		}

		if (dir_access->file_exists(f)) {
			confirm_save->set_text("File Exists, Overwrite?");
			confirm_save->popup_centered(Size2(200,80));
		} else {
			

			emit_signal("file_selected",f);
			hide();
		}
	}
}
Example #21
0
	virtual Variant call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error) {

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

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

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

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


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

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

		if (ac>p_argcount) {

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



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

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

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


		jvalue *v=NULL;

		if (p_argcount) {

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

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


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

				case Variant::BOOL: {

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

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

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

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

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

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

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

				} break;
				case Variant::INT_ARRAY: {

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

				} break;
				case Variant::REAL_ARRAY: {

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

				} break;
				default: {

					ERR_FAIL_V(Variant());
				} break;

			}
		}

		print_line("calling method!!");

		Variant ret;

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

			case Variant::NIL: {


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

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

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

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

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

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

				int stringCount = env->GetArrayLength(arr);
				DVector<String> sarr;

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

				ret=sarr;

			} break;
			case Variant::INT_ARRAY: {

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

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

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

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

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

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


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

		print_line("success");

		return ret;
	}
Example #22
0
	void _create_body_shape_data() {
		VisualServer *vs = VisualServer::get_singleton();
		Physics2DServer *ps = Physics2DServer::get_singleton();

		// SEGMENT

		{

			DVector<uint8_t> pixels;
			pixels.resize(32*2*2);
			for(int i=0;i<2;i++) {

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

					pixels.set(i*32*2+j*2+0,(j==0)?255:0);
					pixels.set(i*32*2+j*2+1,255);
				}
			}

			Image image(32,2,0,Image::FORMAT_LA8,pixels);

			body_shape_data[Physics2DServer::SHAPE_SEGMENT].image=vs->texture_create_from_image(image);

			RID segment_shape = ps->shape_create(Physics2DServer::SHAPE_SEGMENT);
			Rect2 sg(Point2(-16,0),Point2(16,0));
			ps->shape_set_data(segment_shape,sg);

			body_shape_data[Physics2DServer::SHAPE_SEGMENT].shape = segment_shape;

		}
		// CIRCLE

		{

			DVector<uint8_t> pixels;
			pixels.resize(32*32*2);
			for(int i=0;i<32;i++) {

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

					bool black=Vector2(i-16,j-16).length_squared() < 16*16;

					pixels.set(i*32*2+j*2+0,(i==16 || j==16)?255:0);
					pixels.set(i*32*2+j*2+1,black?255:0);
				}
			}

			Image image(32,32,0,Image::FORMAT_LA8,pixels);

			body_shape_data[Physics2DServer::SHAPE_CIRCLE].image=vs->texture_create_from_image(image);

			RID circle_shape = ps->shape_create(Physics2DServer::SHAPE_CIRCLE);
			ps->shape_set_data(circle_shape,16);

			body_shape_data[Physics2DServer::SHAPE_CIRCLE].shape = circle_shape;

		}

		// BOX

		{

			DVector<uint8_t> pixels;
			pixels.resize(32*32*2);
			for(int i=0;i<32;i++) {

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

					bool black=i>0 && i<31 && j>0 && j<31;

					pixels.set(i*32*2+j*2+0,black?0:255);
					pixels.set(i*32*2+j*2+1,255);
				}
			}

			Image image(32,32,0,Image::FORMAT_LA8,pixels);

			body_shape_data[Physics2DServer::SHAPE_RECTANGLE].image=vs->texture_create_from_image(image);

			RID rectangle_shape = ps->shape_create(Physics2DServer::SHAPE_RECTANGLE);
			ps->shape_set_data(rectangle_shape,Vector2(16,16));

			body_shape_data[Physics2DServer::SHAPE_RECTANGLE].shape = rectangle_shape;

		}


		// CAPSULE

		{

			DVector<uint8_t> pixels;
			pixels.resize(32*64*2);
			for(int i=0;i<64;i++) {

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


					int si = i>48 ? i - 32 : (i<16 ? i : 16);
					bool black=Vector2(si-16,j-16).length_squared() < 16*16;

					pixels.set(i*32*2+j*2+0,(i==16 || j==16 || i==48)?255:0);
					pixels.set(i*32*2+j*2+1,black?255:0);

				}
			}

			Image image(32,64,0,Image::FORMAT_LA8,pixels);

			body_shape_data[Physics2DServer::SHAPE_CAPSULE].image=vs->texture_create_from_image(image);

			RID capsule_shape = ps->shape_create(Physics2DServer::SHAPE_CAPSULE);
			ps->shape_set_data(capsule_shape,Vector2(16,32));

			body_shape_data[Physics2DServer::SHAPE_CAPSULE].shape = capsule_shape;

		}

		// CONVEX

		{


			Image image(convex_png);

			body_shape_data[Physics2DServer::SHAPE_CUSTOM+1].image=vs->texture_create_from_image(image);

			RID convex_polygon_shape = ps->shape_create(Physics2DServer::SHAPE_CONVEX_POLYGON);

			DVector<Vector2> arr;
			Point2 sb(32,32);
			arr.push_back(Point2(20,3)-sb);
			arr.push_back(Point2(58,23)-sb);
			arr.push_back(Point2(55,54)-sb);
			arr.push_back(Point2(27,60)-sb);
			arr.push_back(Point2(5,56)-sb);
			arr.push_back(Point2(4,20)-sb);
			arr.push_back(Point2(11,7)-sb);
			ps->shape_set_data(convex_polygon_shape,arr);

			body_shape_data[Physics2DServer::SHAPE_CUSTOM+1].shape = convex_polygon_shape;

		}


	}
Example #23
0
Variant _jobject_to_variant(JNIEnv * env, jobject obj) {

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

	print_line("ARGNAME: "+name);
	if (name == "java.lang.String") {

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


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

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

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

		}

		return sarr;
	};

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

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

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

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

	if (name == "[I") {

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

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

	if (name == "[B") {

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

		DVector<uint8_t>::Write w = sarr.write();
		env->GetByteArrayRegion(arr,0,fCount,reinterpret_cast<signed char*>(w.ptr()));
		w = DVector<uint8_t>::Write();
		return sarr;
	};

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

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

	if (name == "[D") {

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

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

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

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

		};
		return sarr;
	};

	if (name == "[F") {

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


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

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

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

		};
		return sarr;
	};


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

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

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

		}

		return varr;
	};

    if (name == "java.util.HashMap" || name == "org.godotengine.godot.Dictionary") {

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

		StringArray keys = _jobject_to_variant(env, arr);
		env->DeleteLocalRef(arr);

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

		Array vals = _jobject_to_variant(env, arr);
		env->DeleteLocalRef(arr);

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

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


		return ret;
	};

	env->DeleteLocalRef(c);

	return Variant();
};
Example #24
0
void CollisionShape::_update_indicator() {

	while (VisualServer::get_singleton()->mesh_get_surface_count(indicator))
		VisualServer::get_singleton()->mesh_remove_surface(indicator,0);

	if (shape.is_null())
		return;

	DVector<Vector3> points;
	DVector<Vector3> normals;

	VS::PrimitiveType pt = VS::PRIMITIVE_TRIANGLES;

	if (shape->cast_to<RayShape>()) {

		RayShape *rs = shape->cast_to<RayShape>();
		points.push_back(Vector3());
		points.push_back(Vector3(0,0,rs->get_length()));
		pt = VS::PRIMITIVE_LINES;
	} else if (shape->cast_to<SphereShape>()) {

//		VisualServer *vs=VisualServer::get_singleton();
		SphereShape *shapeptr=shape->cast_to<SphereShape>();


		Color col(0.4,1.0,1.0,0.5);

		int lats=6;
		int lons=12;
		float size=shapeptr->get_radius();


		for(int i = 1; i <= lats; i++) {
			double lat0 = Math_PI * (-0.5 + (double) (i - 1) / lats);
			double z0  = Math::sin(lat0);
			double zr0 =  Math::cos(lat0);

			double lat1 = Math_PI * (-0.5 + (double) i / lats);
			double z1 = Math::sin(lat1);
			double zr1 = Math::cos(lat1);

			for(int j = lons; j >= 1; j--) {

				double lng0 = 2 * Math_PI * (double) (j - 1) / lons;
				double x0 = Math::cos(lng0);
				double y0 = Math::sin(lng0);

				double lng1 = 2 * Math_PI * (double) (j) / lons;
				double x1 = Math::cos(lng1);
				double y1 = Math::sin(lng1);

				Vector3 v4=Vector3(x0 * zr0, z0, y0 *zr0)*size;
				Vector3 v3=Vector3(x0 * zr1, z1, y0 *zr1)*size;
				Vector3 v2=Vector3(x1 * zr1, z1, y1 *zr1)*size;
				Vector3 v1=Vector3(x1 * zr0, z0, y1 *zr0)*size;

				Vector<Vector3> line;
				line.push_back(v1);
				line.push_back(v2);
				line.push_back(v3);
				line.push_back(v4);


				points.push_back(v1);
				points.push_back(v2);
				points.push_back(v3);

				points.push_back(v1);
				points.push_back(v3);
				points.push_back(v4);

				normals.push_back(v1.normalized());
				normals.push_back(v2.normalized());
				normals.push_back(v3.normalized());

				normals.push_back(v1.normalized());
				normals.push_back(v3.normalized());
				normals.push_back(v4.normalized());

			}
		}
	} else if (shape->cast_to<BoxShape>()) {

		BoxShape *shapeptr=shape->cast_to<BoxShape>();

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


			Vector3 face_points[4];


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

				float v[3];
				v[0]=1.0;
				v[1]=1-2*((j>>1)&1);
				v[2]=v[1]*(1-2*(j&1));

				for (int k=0;k<3;k++) {

					if (i<3)
						face_points[j][(i+k)%3]=v[k]*(i>=3?-1:1);
					else
						face_points[3-j][(i+k)%3]=v[k]*(i>=3?-1:1);
				}
			}
			Vector3 normal;
			normal[i%3]=(i>=3?-1:1);

			for(int j=0;j<4;j++)
				face_points[j]*=shapeptr->get_extents();

			points.push_back(face_points[0]);
			points.push_back(face_points[1]);
			points.push_back(face_points[2]);

			points.push_back(face_points[0]);
			points.push_back(face_points[2]);
			points.push_back(face_points[3]);

			for(int n=0;n<6;n++)
				normals.push_back(normal);

		}

	} else if (shape->cast_to<ConvexPolygonShape>()) {
Example #25
0
static DVector<uint8_t> _lossless_pack_png(const Image& p_image) {


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


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

	png_structp png_ptr;
	png_infop info_ptr;
	png_bytep * row_pointers;


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

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

	info_ptr = png_create_info_struct(png_ptr);

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

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

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

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

	int pngf=0;
	int pngb=8;
	int cs=0;

	switch(img.get_format()) {

		case Image::FORMAT_GRAYSCALE: {

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

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

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

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

			if (img.detect_alpha()) {

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

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

		}
	}

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

	png_write_info(png_ptr, info_ptr);


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


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

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

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

	memfree(row_pointers);

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

		ERR_FAIL_V(DVector<uint8_t>());
	}

	png_write_end(png_ptr, NULL);


	return ret;
}
Example #26
0
static inline void _build_faces(uint8_t ***p_cell_status, int x, int y, int z, int len_x, int len_y, int len_z, DVector<Face3> &p_faces) {

	ERR_FAIL_INDEX(x, len_x);
	ERR_FAIL_INDEX(y, len_y);
	ERR_FAIL_INDEX(z, len_z);

	if (p_cell_status[x][y][z] & _CELL_EXTERIOR)
		return;

/*	static const Vector3 vertices[8]={
		Vector3(0,0,0),
		Vector3(0,0,1),
		Vector3(0,1,0),
		Vector3(0,1,1),
		Vector3(1,0,0),
		Vector3(1,0,1),
		Vector3(1,1,0),
		Vector3(1,1,1),
	};
*/
#define vert(m_idx) Vector3((m_idx & 4) >> 2, (m_idx & 2) >> 1, m_idx & 1)

	static const uint8_t indices[6][4] = {
		{ 7, 6, 4, 5 },
		{ 7, 3, 2, 6 },
		{ 7, 5, 1, 3 },
		{ 0, 2, 3, 1 },
		{ 0, 1, 5, 4 },
		{ 0, 4, 6, 2 },

	};
	/*

		{0,1,2,3},
		{0,1,4,5},
		{0,2,4,6},
		{4,5,6,7},
		{2,3,7,6},
		{1,3,5,7},

		{0,2,3,1},
		{0,1,5,4},
		{0,4,6,2},
		{7,6,4,5},
		{7,3,2,6},
		{7,5,1,3},
*/

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

		Vector3 face_points[4];
		int disp_x = x + ((i % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
		int disp_y = y + (((i - 1) % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
		int disp_z = z + (((i - 2) % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);

		bool plot = false;

		if (disp_x < 0 || disp_x >= len_x)
			plot = true;
		if (disp_y < 0 || disp_y >= len_y)
			plot = true;
		if (disp_z < 0 || disp_z >= len_z)
			plot = true;

		if (!plot && (p_cell_status[disp_x][disp_y][disp_z] & _CELL_EXTERIOR))
			plot = true;

		if (!plot)
			continue;

		for (int j = 0; j < 4; j++)
			face_points[j] = vert(indices[i][j]) + Vector3(x, y, z);

		p_faces.push_back(
				Face3(
						face_points[0],
						face_points[1],
						face_points[2]));

		p_faces.push_back(
				Face3(
						face_points[2],
						face_points[3],
						face_points[0]));
	}
}
Example #27
0
bool D_bjmak::sendBuffer(QVector<FileID>& ids, qint64 bufferSize){
    //QString idsBuffer;
    //QString hashBuffer;
    //QString dataBuffer;
    
    std::cout << "sending buffer of " << ids.size() << std::endl;
    
    server->connectionPtr->sendMsg("NEXT");
    const int hashBufferSize = bufferSize / bsize_;
    DVector hashBuffer;
    hashBuffer.reserve(hashBufferSize);

    DVector dataBuffer;
    hashBuffer.reserve(bufferSize);

    DVector idsBuffer;
    hashBuffer.reserve(3000000);
    
    int blockCount;
    int fd;
    bool isCleared = true;
    for(int i = 0; i < ids.size(); ++i){

        if (!ids[i].isREG()){
            idsBuffer.push_back(ids[i].toString());
            //cout << "added not reg " << ids[i].getFullPath().toStdString() << endl;
            continue;
        }
        
        DVector tmpHashBuffer;
        DVector tmpDataBuffer;
        
        if ( (dataBuffer.size()+ids[i].getSize()) > bufferSize ){
            blockCount = (bufferSize-dataBuffer.size()) / bsize_;
            isCleared = false;
        }
        else{
            blockCount = ids[i].getSize() / bsize_;
            
            if ( (ids[i].getSize() % bsize_) != 0 )
                ++blockCount;
            
        }
        
        fd = open(ids[i].getFullPath().toStdString().c_str(), O_RDONLY);
        
        if (fd == -1){
            cout << "error " << strerror(errno) << endl;
            writeLog.warning() << "Error open file <" << ids[i].getFullPath() 
                    << "> " << strerror(errno) 
                    << DebusLogger::endl;
            continue;
        }
        
        if (!getHashesAndData(fd, tmpDataBuffer, tmpHashBuffer, blockCount)){
            cout << "error " << strerror(errno) << endl;
            writeLog.warning() << "Error read file <" << ids[i].getFullPath() 
                    << "> " << strerror(errno) 
                    << DebusLogger::endl;
            continue;
        }

        
        
        
        idsBuffer.push_back(ids[i].toString());
        //cout << "added reg " << ids[i].getFullPath().toStdString() << endl;
        //idsBuffer.push_back(ids[i].toQString());
        hashBuffer.push_back(tmpHashBuffer);
        dataBuffer.push_back(tmpDataBuffer);
        
        if (isCleared)
            close(fd);
    }

    cout << "Sending idsbuffer " << idsBuffer.size() << endl;
    server->connectionPtr->sendMsg(idsBuffer.data(), idsBuffer.size());
    cout << "Sending hashBuffer " << hashBuffer.size() << endl;
    server->connectionPtr->sendMsg(hashBuffer.data(), hashBuffer.size());
    server->connectionPtr->recvMsg();
    DVector reply;
    reply.push_back(server->connectionPtr->dataToVector());
    cout << "Received reply size " << reply.size() << endl;
    DVector newDataBuffer;
    newDataBuffer = this->getDataBufferFromReply(reply, hashBuffer, dataBuffer);
    cout << "sending data size " << newDataBuffer.size() << endl;
    server->connectionPtr->sendMsg(newDataBuffer.data(), newDataBuffer.size());

    if (!isCleared){
        int clearedBlockCount = blockCount;
        blockCount = ids.last().getSize() / bsize_;
        if ( (ids.last().getSize() % bsize_) != 0 )
            ++blockCount;

        blockCount -= clearedBlockCount;
        
        while(blockCount){
            int i;
            if (blockCount*bsize_ > bufferSize)
                i = bufferSize/bsize_;
            else
                i = blockCount;

            cout <<  "bufferSize " << bufferSize << " "
                    << " i " << i << endl;
            
            dataBuffer.clear();
            hashBuffer.clear();
            getHashesAndData(fd, dataBuffer, hashBuffer, i);
            cout <<  "dataBuffer" << dataBuffer.size() << " "
                    << "hashBuffer" << hashBuffer.size() << endl;
            server->connectionPtr->sendMsg(hashBuffer.data(), hashBuffer.size());
            cout <<  "clearedBlockCount" << clearedBlockCount << " "
                    << "blockCount" << blockCount << endl;
            server->connectionPtr->recvMsg();
            cout <<  "clearedBlockCount" << clearedBlockCount << " "
                    << "blockCount" << blockCount << endl;
            DVector reply;
            reply.push_back(server->connectionPtr->dataToString());
            DVector newDataBuffer;
            newDataBuffer = this->getDataBufferFromReply(reply, hashBuffer, dataBuffer);
            server->connectionPtr->sendMsg(newDataBuffer.data(), newDataBuffer.size());
            
            blockCount -= i;
        }
        close(fd);
    }
        

    cout << "sended block" << endl;
    return true;
}
GridMapEditor::GridMapEditor(EditorNode *p_editor) {


	input_action=INPUT_NONE;
	editor=p_editor;
	undo_redo=p_editor->get_undo_redo();

	int mw = EDITOR_DEF("grid_map/palette_min_width",230);
	Control *ec = memnew( Control);
	ec->set_custom_minimum_size(Size2(mw,0));
	add_child(ec);


	spatial_editor_hb = memnew( HBoxContainer );
	SpatialEditor::get_singleton()->add_control_to_menu_panel(spatial_editor_hb);
	options = memnew( MenuButton );
	spatial_editor_hb->add_child(options);
	spatial_editor_hb->hide();

	options->set_text("Grid");
	options->get_popup()->add_check_item("Snap View",MENU_OPTION_LOCK_VIEW);
	options->get_popup()->add_separator();
	options->get_popup()->add_item("Prev Level ("+keycode_get_string(KEY_MASK_CMD)+"Down Wheel)",MENU_OPTION_PREV_LEVEL);
	options->get_popup()->add_item("Next Level ("+keycode_get_string(KEY_MASK_CMD)+"Up Wheel)",MENU_OPTION_NEXT_LEVEL);
	options->get_popup()->add_separator();
	options->get_popup()->add_check_item("Clip Disabled",MENU_OPTION_CLIP_DISABLED);
	options->get_popup()->set_item_checked( options->get_popup()->get_item_index(MENU_OPTION_CLIP_DISABLED), true );
	options->get_popup()->add_check_item("Clip Above",MENU_OPTION_CLIP_ABOVE);
	options->get_popup()->add_check_item("Clip Below",MENU_OPTION_CLIP_BELOW);
	options->get_popup()->add_separator();
	options->get_popup()->add_check_item("Edit X Axis",MENU_OPTION_X_AXIS,KEY_Z);
	options->get_popup()->add_check_item("Edit Y Axis",MENU_OPTION_Y_AXIS,KEY_X);
	options->get_popup()->add_check_item("Edit Z Axis",MENU_OPTION_Z_AXIS,KEY_C);
	options->get_popup()->set_item_checked( options->get_popup()->get_item_index(MENU_OPTION_Y_AXIS), true );
	options->get_popup()->add_separator();
	options->get_popup()->add_item("Cursor Rotate X",MENU_OPTION_CURSOR_ROTATE_X,KEY_A);
	options->get_popup()->add_item("Cursor Rotate Y",MENU_OPTION_CURSOR_ROTATE_Y,KEY_S);
	options->get_popup()->add_item("Cursor Rotate Z",MENU_OPTION_CURSOR_ROTATE_Z,KEY_D);
	options->get_popup()->add_item("Cursor Back Rotate X",MENU_OPTION_CURSOR_ROTATE_X,KEY_MASK_SHIFT+KEY_A);
	options->get_popup()->add_item("Cursor Back Rotate Y",MENU_OPTION_CURSOR_ROTATE_Y,KEY_MASK_SHIFT+KEY_S);
	options->get_popup()->add_item("Cursor Back Rotate Z",MENU_OPTION_CURSOR_ROTATE_Z,KEY_MASK_SHIFT+KEY_D);
	options->get_popup()->add_item("Cursor Clear Rotation",MENU_OPTION_CURSOR_CLEAR_ROTATION,KEY_W);
	options->get_popup()->add_separator();
	options->get_popup()->add_check_item("Duplicate Selects",MENU_OPTION_DUPLICATE_SELECTS);
	options->get_popup()->add_separator();
	options->get_popup()->add_item("Create Area",MENU_OPTION_SELECTION_MAKE_AREA,KEY_CONTROL+KEY_C);
	options->get_popup()->add_item("Create Exterior Connector",MENU_OPTION_SELECTION_MAKE_EXTERIOR_CONNECTOR);
	options->get_popup()->add_item("Erase Area",MENU_OPTION_REMOVE_AREA);
	options->get_popup()->add_separator();
	options->get_popup()->add_item("Selection -> Clear",MENU_OPTION_SELECTION_CLEAR);
	//options->get_popup()->add_separator();
	//options->get_popup()->add_item("Configure",MENU_OPTION_CONFIGURE);

	clip_mode=CLIP_DISABLED;
	options->get_popup()->connect("item_pressed", this,"_menu_option");


	edit_mode = memnew(OptionButton);
	edit_mode->set_area_as_parent_rect();
	edit_mode->set_anchor_and_margin(MARGIN_BOTTOM,ANCHOR_BEGIN,24);;
	edit_mode->set_anchor_and_margin(MARGIN_RIGHT,ANCHOR_END,14);;
	edit_mode->add_item("Tiles");
	edit_mode->add_item("Areas");
	add_child(edit_mode);

	selected_area=-1;


	theme_pallete = memnew( Tree );
	theme_pallete->set_columns(3);
	add_child(theme_pallete);
	theme_pallete->set_v_size_flags(SIZE_EXPAND_FILL);

	area_list = memnew( Tree );
	add_child(area_list);
	area_list->set_v_size_flags(SIZE_EXPAND_FILL);
	area_list->hide();

	spatial_editor_hb->add_child(memnew(VSeparator));
	Label *fl = memnew(Label);
	fl->set_text("   Floor: ");
	spatial_editor_hb->add_child(fl);

	floor = memnew( SpinBox );
	floor->set_min(-32767);
	floor->set_max(32767);
	floor->set_step(1);
	floor->get_line_edit()->add_constant_override("minimum_spaces",16);

	spatial_editor_hb->add_child(floor);
	floor->connect("value_changed",this,"_floor_changed");


	edit_axis=Vector3::AXIS_Y;
	edit_floor[0]=-1;
	edit_floor[1]=-1;
	edit_floor[2]=-1;

	cursor_visible=false;
	selected_pallete=-1;
	lock_view=false;
	cursor_rot=0;
	last_mouseover=Vector3(-1,-1,-1);

	selection_mesh = VisualServer::get_singleton()->mesh_create();
	duplicate_mesh = VisualServer::get_singleton()->mesh_create();

	{
		//selection mesh create


		DVector<Vector3> lines;
		DVector<Vector3> triangles;

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


			Vector3 face_points[4];

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

				float v[3];
				v[0]=1.0;
				v[1]=1-2*((j>>1)&1);
				v[2]=v[1]*(1-2*(j&1));

				for (int k=0;k<3;k++) {

					if (i<3)
						face_points[j][(i+k)%3]=v[k]*(i>=3?-1:1);
					else
						face_points[3-j][(i+k)%3]=v[k]*(i>=3?-1:1);
				}
			}

			triangles.push_back(face_points[0]*0.5+Vector3(0.5,0.5,0.5));
			triangles.push_back(face_points[1]*0.5+Vector3(0.5,0.5,0.5));
			triangles.push_back(face_points[2]*0.5+Vector3(0.5,0.5,0.5));

			triangles.push_back(face_points[2]*0.5+Vector3(0.5,0.5,0.5));
			triangles.push_back(face_points[3]*0.5+Vector3(0.5,0.5,0.5));
			triangles.push_back(face_points[0]*0.5+Vector3(0.5,0.5,0.5));
		}

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

			AABB base(Vector3(0,0,0),Vector3(1,1,1));
			Vector3 a,b;
			base.get_edge(i,a,b);
			lines.push_back(a);
			lines.push_back(b);
		}

		Array d;
		d.resize(VS::ARRAY_MAX);

		RID inner_mat = VisualServer::get_singleton()->fixed_material_create();
		VisualServer::get_singleton()->fixed_material_set_param(inner_mat,VS::FIXED_MATERIAL_PARAM_DIFFUSE,Color(0.7,0.7,1.0,0.3));
		VisualServer::get_singleton()->material_set_flag(inner_mat,VS::MATERIAL_FLAG_ONTOP,true);
		VisualServer::get_singleton()->material_set_flag(inner_mat,VS::MATERIAL_FLAG_UNSHADED,true);
		VisualServer::get_singleton()->fixed_material_set_flag( inner_mat, VisualServer::FIXED_MATERIAL_FLAG_USE_ALPHA, true );


		d[VS::ARRAY_VERTEX]=triangles;
		VisualServer::get_singleton()->mesh_add_surface(selection_mesh,VS::PRIMITIVE_TRIANGLES,d);
		VisualServer::get_singleton()->mesh_surface_set_material(selection_mesh,0,inner_mat,true);

		RID outer_mat = VisualServer::get_singleton()->fixed_material_create();
		VisualServer::get_singleton()->fixed_material_set_param(outer_mat,VS::FIXED_MATERIAL_PARAM_DIFFUSE,Color(0.7,0.7,1.0,0.8));
		VisualServer::get_singleton()->material_set_line_width(outer_mat,3.0);
		VisualServer::get_singleton()->material_set_flag(outer_mat,VS::MATERIAL_FLAG_ONTOP,true);
		VisualServer::get_singleton()->material_set_flag(outer_mat,VS::MATERIAL_FLAG_UNSHADED,true);
		VisualServer::get_singleton()->fixed_material_set_flag( outer_mat, VisualServer::FIXED_MATERIAL_FLAG_USE_ALPHA, true );


		d[VS::ARRAY_VERTEX]=lines;
		VisualServer::get_singleton()->mesh_add_surface(selection_mesh,VS::PRIMITIVE_LINES,d);
		VisualServer::get_singleton()->mesh_surface_set_material(selection_mesh,1,outer_mat,true);


		RID inner_mat_dup = VisualServer::get_singleton()->fixed_material_create();
		VisualServer::get_singleton()->fixed_material_set_param(inner_mat_dup,VS::FIXED_MATERIAL_PARAM_DIFFUSE,Color(1.0,0.7,0.7,0.3));
		VisualServer::get_singleton()->material_set_flag(inner_mat_dup,VS::MATERIAL_FLAG_ONTOP,true);
		VisualServer::get_singleton()->material_set_flag(inner_mat_dup,VS::MATERIAL_FLAG_UNSHADED,true);
		VisualServer::get_singleton()->fixed_material_set_flag( inner_mat_dup, VisualServer::FIXED_MATERIAL_FLAG_USE_ALPHA, true );


		d[VS::ARRAY_VERTEX]=triangles;
		VisualServer::get_singleton()->mesh_add_surface(duplicate_mesh,VS::PRIMITIVE_TRIANGLES,d);
		VisualServer::get_singleton()->mesh_surface_set_material(duplicate_mesh,0,inner_mat_dup,true);

		RID outer_mat_dup = VisualServer::get_singleton()->fixed_material_create();
		VisualServer::get_singleton()->fixed_material_set_param(outer_mat_dup,VS::FIXED_MATERIAL_PARAM_DIFFUSE,Color(1.0,0.7,0.7,0.8));
		VisualServer::get_singleton()->material_set_line_width(outer_mat_dup,3.0);
		VisualServer::get_singleton()->material_set_flag(outer_mat_dup,VS::MATERIAL_FLAG_ONTOP,true);
		VisualServer::get_singleton()->material_set_flag(outer_mat_dup,VS::MATERIAL_FLAG_UNSHADED,true);
		VisualServer::get_singleton()->fixed_material_set_flag( outer_mat_dup, VisualServer::FIXED_MATERIAL_FLAG_USE_ALPHA, true );


		d[VS::ARRAY_VERTEX]=lines;
		VisualServer::get_singleton()->mesh_add_surface(duplicate_mesh,VS::PRIMITIVE_LINES,d);
		VisualServer::get_singleton()->mesh_surface_set_material(duplicate_mesh,1,outer_mat_dup,true);

	}

	selection.active=false;
	updating=false;

}