static Error _parse_obj(const String &p_path, List<Ref<Mesh> > &r_meshes, bool p_single_mesh, bool p_generate_tangents, Vector3 p_scale_mesh, List<String> *r_missing_deps) {

	FileAccessRef f = FileAccess::open(p_path, FileAccess::READ);

	ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);

	Ref<ArrayMesh> mesh;
	mesh.instance();

	bool generate_tangents = p_generate_tangents;
	Vector3 scale_mesh = p_scale_mesh;
	bool flip_faces = false;
	//bool flip_faces = p_options["force/flip_faces"];
	//bool force_smooth = p_options["force/smooth_shading"];
	//bool weld_vertices = p_options["force/weld_vertices"];
	//float weld_tolerance = p_options["force/weld_tolerance"];

	Vector<Vector3> vertices;
	Vector<Vector3> normals;
	Vector<Vector2> uvs;
	String name;

	Map<String, Map<String, Ref<SpatialMaterial> > > material_map;

	Ref<SurfaceTool> surf_tool = memnew(SurfaceTool);
	surf_tool->begin(Mesh::PRIMITIVE_TRIANGLES);

	String current_material_library;
	String current_material;
	String current_group;

	while (true) {

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

		if (l.begins_with("v ")) {
			//vertex
			Vector<String> v = l.split(" ", false);
			ERR_FAIL_COND_V(v.size() < 4, ERR_FILE_CORRUPT);
			Vector3 vtx;
			vtx.x = v[1].to_float() * scale_mesh.x;
			vtx.y = v[2].to_float() * scale_mesh.y;
			vtx.z = v[3].to_float() * scale_mesh.z;
			vertices.push_back(vtx);
		} else if (l.begins_with("vt ")) {
			//uv
			Vector<String> v = l.split(" ", false);
			ERR_FAIL_COND_V(v.size() < 3, ERR_FILE_CORRUPT);
			Vector2 uv;
			uv.x = v[1].to_float();
			uv.y = 1.0 - v[2].to_float();
			uvs.push_back(uv);

		} else if (l.begins_with("vn ")) {
			//normal
			Vector<String> v = l.split(" ", false);
			ERR_FAIL_COND_V(v.size() < 4, ERR_FILE_CORRUPT);
			Vector3 nrm;
			nrm.x = v[1].to_float();
			nrm.y = v[2].to_float();
			nrm.z = v[3].to_float();
			normals.push_back(nrm);
		} else if (l.begins_with("f ")) {
			//vertex

			Vector<String> v = l.split(" ", false);
			ERR_FAIL_COND_V(v.size() < 4, ERR_FILE_CORRUPT);

			//not very fast, could be sped up

			Vector<String> face[3];
			face[0] = v[1].split("/");
			face[1] = v[2].split("/");
			ERR_FAIL_COND_V(face[0].size() == 0, ERR_FILE_CORRUPT);
			ERR_FAIL_COND_V(face[0].size() != face[1].size(), ERR_FILE_CORRUPT);
			for (int i = 2; i < v.size() - 1; i++) {

				face[2] = v[i + 1].split("/");
				ERR_FAIL_COND_V(face[0].size() != face[2].size(), ERR_FILE_CORRUPT);
				for (int j = 0; j < 3; j++) {

					int idx = j;

					if (!flip_faces && idx < 2) {
						idx = 1 ^ idx;
					}

					if (face[idx].size() == 3) {
						int norm = face[idx][2].to_int() - 1;
						if (norm < 0)
							norm += normals.size() + 1;
						ERR_FAIL_INDEX_V(norm, normals.size(), ERR_FILE_CORRUPT);
						surf_tool->add_normal(normals[norm]);
					}

					if (face[idx].size() >= 2 && face[idx][1] != String()) {
						int uv = face[idx][1].to_int() - 1;
						if (uv < 0)
							uv += uvs.size() + 1;
						ERR_FAIL_INDEX_V(uv, uvs.size(), ERR_FILE_CORRUPT);
						surf_tool->add_uv(uvs[uv]);
					}

					int vtx = face[idx][0].to_int() - 1;
					if (vtx < 0)
						vtx += vertices.size() + 1;
					ERR_FAIL_INDEX_V(vtx, vertices.size(), ERR_FILE_CORRUPT);

					Vector3 vertex = vertices[vtx];
					//if (weld_vertices)
					//	vertex.snap(Vector3(weld_tolerance, weld_tolerance, weld_tolerance));
					surf_tool->add_vertex(vertex);
				}

				face[1] = face[2];
			}
		} else if (l.begins_with("s ")) { //smoothing
			String what = l.substr(2, l.length()).strip_edges();
			if (what == "off")
				surf_tool->add_smooth_group(false);
			else
				surf_tool->add_smooth_group(true);
		} else if (/*l.begins_with("g ") ||*/ l.begins_with("usemtl ") || (l.begins_with("o ") || f->eof_reached())) { //commit group to mesh
			//groups are too annoying
			if (surf_tool->get_vertex_array().size()) {
				//another group going on, commit it
				if (normals.size() == 0) {
					surf_tool->generate_normals();
				}

				if (generate_tangents && uvs.size()) {
					surf_tool->generate_tangents();
				}

				surf_tool->index();

				print_line("current material library " + current_material_library + " has " + itos(material_map.has(current_material_library)));
				print_line("current material " + current_material + " has " + itos(material_map.has(current_material_library) && material_map[current_material_library].has(current_material)));

				if (material_map.has(current_material_library) && material_map[current_material_library].has(current_material)) {
					surf_tool->set_material(material_map[current_material_library][current_material]);
				}

				mesh = surf_tool->commit(mesh);

				if (current_material != String()) {
					mesh->surface_set_name(mesh->get_surface_count() - 1, current_material.get_basename());
				} else if (current_group != String()) {
					mesh->surface_set_name(mesh->get_surface_count() - 1, current_group);
				}

				print_line("Added surface :" + mesh->surface_get_name(mesh->get_surface_count() - 1));
				surf_tool->clear();
				surf_tool->begin(Mesh::PRIMITIVE_TRIANGLES);
			}

			if (l.begins_with("o ") || f->eof_reached()) {

				if (!p_single_mesh) {
					mesh->set_name(name);
					r_meshes.push_back(mesh);
					mesh.instance();
					current_group = "";
					current_material = "";
				}
			}

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

			if (l.begins_with("o ")) {
				name = l.substr(2, l.length()).strip_edges();
			}

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

				current_material = l.replace("usemtl", "").strip_edges();
			}

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

				current_group = l.substr(2, l.length()).strip_edges();
			}

		} else if (l.begins_with("mtllib ")) { //parse material

			current_material_library = l.replace("mtllib", "").strip_edges();
			if (!material_map.has(current_material_library)) {
				Map<String, Ref<SpatialMaterial> > lib;
				Error err = _parse_material_library(current_material_library, lib, r_missing_deps);
				if (err == ERR_CANT_OPEN) {
					String dir = p_path.get_base_dir();
					err = _parse_material_library(dir.plus_file(current_material_library), lib, r_missing_deps);
				}
				if (err == OK) {
					material_map[current_material_library] = lib;
				}
			}
		}
	}

	if (p_single_mesh) {

		r_meshes.push_back(mesh);
	}

	return OK;
}
void AnimatedSprite::_notification(int p_what) {

	switch(p_what) {
		case NOTIFICATION_PROCESS: {

			if (frames.is_null())
				return;
			if (!frames->has_animation(animation))
				return;
			if (frame<0)
				return;

			float speed = frames->get_animation_speed(animation);
			if (speed==0)
				return; //do nothing

			float remaining = get_process_delta_time();

			while(remaining) {

				if (timeout<=0) {

					timeout=1.0/speed;

					int fc = frames->get_frame_count(animation);
					if (frame>=fc-1) {
						if (frames->get_animation_loop(animation)) {
							frame=0;
						} else {
							frame=fc-1;
						}
					} else {
						frame++;
					}

					update();
					_change_notify("frame");
				}

				float to_process = MIN(timeout,remaining);
				remaining-=to_process;
				timeout-=to_process;
			}
		} break;

		case NOTIFICATION_DRAW: {

			if (frames.is_null()) {
				print_line("no draw no faemos");
				return;
			}

			if (frame<0) {
				print_line("no draw frame <0");
				return;
			}

			if (!frames->has_animation(animation)) {
				print_line("no draw no anim: "+String(animation));
				return;
			}



			Ref<Texture> texture = frames->get_frame(animation,frame);
			if (texture.is_null()) {
				print_line("no draw texture is null");
				return;
			}

			//print_line("DECIDED TO DRAW");

			RID ci = get_canvas_item();

			/*
			texture->draw(ci,Point2());
			break;
			*/

			Size2i s;
			s = texture->get_size();
			Point2 ofs=offset;
			if (centered)
				ofs-=s/2;

			if (OS::get_singleton()->get_use_pixel_snap()) {
				ofs=ofs.floor();
			}
			Rect2 dst_rect(ofs,s);

			if (hflip)
				dst_rect.size.x=-dst_rect.size.x;
			if (vflip)
				dst_rect.size.y=-dst_rect.size.y;

			//texture->draw_rect(ci,dst_rect,false,modulate);
			texture->draw_rect_region(ci,dst_rect,Rect2(Vector2(),texture->get_size()),modulate);
//			VisualServer::get_singleton()->canvas_item_add_texture_rect_region(ci,dst_rect,texture->get_rid(),src_rect,modulate);

		} break;
	}

}
	void insertData(float* data, int nSamples) {

		stream->input(data, nSamples);
	};
示例#4
0
  void OpenGLRenderer::renderFrame(const Ref<Camera>& camera, const Ref<BackendScene>& scene,  Ref<Film>& film)
  {
    /*! render frame */
    double t = getSeconds();
    this->camera = camera;
    this->scene = scene;
    this->film = film;

    /*! precompute some values */
    
    if (!OpenGLRenderer::is_initialized){
      OpenGLRenderer::initGL(scene);
    }

    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, OpenGLRenderer::fbo_render);
    glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,
                              GL_TEXTURE_2D,OpenGLRenderer::img_render, 0);
                                  
    glEnable(GL_DEPTH_TEST);
    glDisable(GL_LIGHTING);
    glEnable(GL_CULL_FACE);
    glClearColor(0.0,0.0,0.0,0.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    if (linedrawing) glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
    else glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);

    glViewport(0,0,fb_size_w,fb_size_h);

    PinholeCamera* cam = dynamic_cast<PinholeCamera*>(camera.ptr);
    if (!cam) {
      std::cerr<<"OpenGL Renderer use only pinehole camera ! "<<std::endl;
      exit(1);
    }
    AffineSpace worldToCam = rcp(cam->localToWorld);

    float mat[16];
    worldToCam.to4x4ArrayMatrix(mat);

    glMatrixMode( GL_PROJECTION );
    glPushMatrix();
    glLoadIdentity();
    //std::cerr<<"Far plane ..."<<std::endl;
    gluPerspective(cam->angle,cam->aspectRatio,cam->focalDistance,1000.0*cam->focalDistance);
    glMatrixMode( GL_MODELVIEW );
    glPushMatrix();
    glLoadMatrixf(mat);
    //glMultMatrixf(mat);

    //! Handle lights
    if (scene->allLights.size()>0) {
      glEnable(GL_LIGHTING);
      uint ind_lght = 0;
      std::vector< Ref< Light > > lights = scene->allLights;
      for(std::vector< Ref< Light > >::iterator it = lights.begin();it != lights.end();it++) {
        handleLight(ind_lght++,*it);
      }
    }

    glColor3f(1.0,0.0,0.0);
    std::vector< Ref< Instance > > geom = scene->geometry;
    Ref<Shape> one_shape;
    uint ind_mesh = 0;
    
    for(std::vector< Ref< Instance > >::iterator it = geom.begin();it != geom.end();it++) {
      one_shape = (*it)->shape;
      handleMaterial((*it)->material);
      if (TriangleMesh* tm = dynamic_cast<TriangleMesh*>(one_shape.ptr)) {
        drawTriangleMesh(ind_mesh++,tm);
      }
      else if (Triangle* tr = dynamic_cast<Triangle*>(one_shape.ptr)) {
        drawTriangle(tr);
      }
      //! Handle here all other cases
      else if (TriangleMeshWithNormals* trn = dynamic_cast<TriangleMeshWithNormals*>(one_shape.ptr)) {
        drawTriangleMeshNormals(ind_mesh++,trn);
      }
      else {
        //std::cerr<<" Is a "<<typeid(*one_shape).name()<<std::endl;
      }
    }

    glPopMatrix();
    glMatrixMode( GL_PROJECTION );
    glPopMatrix();
    glMatrixMode( GL_MODELVIEW );
    glFinish();
    //! Copy of the GPU framebuffer to the CPU color buffer...
    glReadPixels(0,0,OpenGLRenderer::fb_size_w,OpenGLRenderer::fb_size_h,GL_RGB,
                  GL_UNSIGNED_BYTE,OpenGLRenderer::color_buffer);
    glFinish();
    glDisable(GL_DEPTH_TEST);
    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
    glDisable(GL_DEPTH_TEST);
    //! Copy of the CPU color buffer to the film...
    Col3f colcour;
    for(uint i=0;i<fb_size_w;i++) {
      for(uint j=0;j<fb_size_h;j++) {
        colcour.r = OpenGLRenderer::color_buffer[(fb_size_h-1-j)*3*fb_size_w+3*i]/255.0;
        colcour.g = OpenGLRenderer::color_buffer[(fb_size_h-1-j)*3*fb_size_w+3*i+1]/255.0;
        colcour.b = OpenGLRenderer::color_buffer[(fb_size_h-1-j)*3*fb_size_w+3*i+2]/255.0;
        film->set(i,j,colcour);
      }
    }
    this->camera = null;
    this->scene = null;
    this->film = null;
    double dt = getSeconds()-t;

    /*! print framerate */
    std::cout << "\r" << 1.0f/dt << " fps, " << dt*1000.0f << " ms" ;//<< std::endl;
  }
示例#5
0
void SampleEditor::generate_preview_texture(const Ref<Sample>& p_sample,Ref<ImageTexture> &p_texture) {


	DVector<uint8_t> data = p_sample->get_data();

	DVector<uint8_t> img;
	int w = p_texture->get_width();
	int h = p_texture->get_height();
	img.resize(w*h*3);
	DVector<uint8_t>::Write imgdata = img.write();
	uint8_t * imgw = imgdata.ptr();
	DVector<uint8_t>::Read sampledata = data.read();
	const uint8_t *sdata=sampledata.ptr();

	bool stereo = p_sample->is_stereo();
	bool _16=p_sample->get_format()==Sample::FORMAT_PCM16;
	int len = p_sample->get_length();

	if (len<1)
		return;

	for(int i=0;i<w;i++) {
		// i trust gcc will optimize this loop
		float max[2]={-1e10,-1e10};
		float min[2]={1e10,1e10};
		int c=stereo?2:1;
		int from = i*len/w;
		int to = (i+1)*len/w;
		if (to>=len)
			to=len-1;

		if (_16) {
			const int16_t*src =(const int16_t*)sdata;

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

				for(int k=from;k<=to;k++) {

					float v = src[k*c+j]/32768.0;
					if (v>max[j])
						max[j]=v;
					if (v<min[j])
						min[j]=v;
				}

			}
		} else {

			const int8_t*src =(const int8_t*)sdata;

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

				for(int k=from;k<=to;k++) {

					float v = src[k*c+j]/128.0;
					if (v>max[j])
						max[j]=v;
					if (v<min[j])
						min[j]=v;
				}

			}
		}

		if (!stereo) {
			for(int j=0;j<h;j++) {
				float v = (j/(float)h) * 2.0 - 1.0;
				uint8_t* imgofs = &imgw[(j*w+i)*3];
				if (v>min[0] && v<max[0]) {
					imgofs[0]=255;
					imgofs[1]=150;
					imgofs[2]=80;
				} else {
					imgofs[0]=0;
					imgofs[1]=0;
					imgofs[2]=0;
				}
			}
		} else {

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

				int half,ofs;
				float v;
				if (j<(h/2)) {
					half=0;
					ofs=0;
					v = (j/(float)(h/2)) * 2.0 - 1.0;
				} else {
					half=1;
					ofs=h/2;
					v = ((j-(h/2))/(float)(h/2)) * 2.0 - 1.0;
				}

				uint8_t* imgofs = &imgw[(j*w+i)*3];
				if (v>min[half] && v<max[half]) {
					imgofs[0]=255;
					imgofs[1]=150;
					imgofs[2]=80;
				} else {
					imgofs[0]=0;
					imgofs[1]=0;
					imgofs[2]=0;
				}
			}

		}

	}

	imgdata = DVector<uint8_t>::Write();


	p_texture->set_data(Image(w,h,0,Image::FORMAT_RGB,img));

}
WKArrayRef WKUserContentControllerCopyUserScripts(WKUserContentControllerRef userContentControllerRef)
{
    Ref<API::Array> userScripts = toImpl(userContentControllerRef)->userScripts().copy();
    return toAPI(&userScripts.leakRef());
}
void AuthLoop(CONNECT_INFO* cfg, Ref< UsersPool > OnlineUsers, Ref< CrossThreadQueue< string > > OutputQueue) {
	RakPeerInterface* rakServer = RakNetworkFactory::GetRakPeerInterface();

	PacketFileLogger* msgFileHandler = NULL;
	if (cfg->logFile) {
		msgFileHandler = new PacketFileLogger();
		rakServer->AttachPlugin(msgFileHandler);
	}

	InitSecurity(rakServer, cfg->useEncryption);
	SocketDescriptor socketDescriptor(cfg->listenPort, 0);

	if (rakServer->Startup(8, 30, &socketDescriptor, 1)) {
		stringstream s;
		s << "auth started! Listening on: " << cfg->listenPort << "\n";
		OutputQueue->Insert(s.str());
	} else QuitError("auth server init error!");
	rakServer->SetMaximumIncomingConnections(8);

	if (msgFileHandler != NULL) msgFileHandler->StartLog(".\\logs\\auth");

	Packet* packet;

	while (!LUNIterminate) {
		RakSleep(30);	// This sleep keeps RakNet responsive
		packet = rakServer->Receive();
		if (packet == NULL) continue;
		PrintPacketInfo(packet, msgFileHandler);

		switch (packet->data[0]) {
			case ID_LEGO_PACKET:

				switch (packet->data[1]) {
					case LUNI_INITAW:
						if (packet->data[3] == 0) {	// thats just a formality so far since no other numbers occured for this case
							// response: 00, 00
							auto v = OpenPacket(".\\auth\\init_aw.bin");
							// bytes 8-10 is the game version (same numbers are mentioned in the game log)
							// the client expects it to be the same that he sent (otherwise he displays "server is being updated" and disconnects)
							ServerSendPacket(rakServer, v, packet->systemAddress);
						}
						break;

					case LUNI_LOGIN: //user logging into server
						{
							auto usr = HandleUserLogin(rakServer, packet, cfg, OnlineUsers);
							if( usr != NULL ) OutputQueue->Insert("\n" + usr->GetUsername() + " Logged-in\n");
						#ifdef DEBUG
							else OutputQueue->Insert("\n Login failed!\n");
						#endif
						}
						break;

					default:
						stringstream s;
						s << "\nauth received unknow pakcet: " << RawDataToString(packet->data, packet->length) << endl;
						OutputQueue->Insert(s.str());
				}

				break;

			case ID_NEW_INCOMING_CONNECTION:
#			ifdef DEBUG
				OutputQueue->Insert("\n Auth is receiving a new connection...\n");
			#endif
				break;

			case ID_DISCONNECTION_NOTIFICATION: // do nothing
				break;

			default:
				stringstream s;
				s << "\nauth received unknow pakcet: " << RawDataToString(packet->data, packet->length) << endl;
				OutputQueue->Insert(s.str());
		}

		rakServer->DeallocatePacket(packet);
	}

	stringstream s;
	s << "Quitting auth\n";
	OutputQueue->Insert(s.str());

	rakServer->Shutdown(0);
	RakNetworkFactory::DestroyRakPeerInterface(rakServer);
}
示例#8
0
static bool _parse_completion_class(const String& p_base_path,const GDParser::ClassNode *p_class,int p_line,List<String>* r_options,List<String>::Element *p_indices) {


	static const char*_type_names[Variant::VARIANT_MAX]={
		"null","bool","int","float","String","Vector2","Rect2","Vector3","Matrix32","Plane","Quat","AABB","Matrix3","Trasnform",
		"Color","Image","NodePath","RID","Object","InputEvent","Dictionary","Array","RawArray","IntArray","FloatArray","StringArray",
		"Vector2Array","Vector3Array","ColorArray"};

	if (p_indices && !p_indices->next()) {
		for(int i=0;i<Variant::VARIANT_MAX;i++) {

			if (p_indices->get()==_type_names[i]) {

				List<StringName> ic;

				Variant::get_numeric_constants_for_type(Variant::Type(i),&ic);
				for(List<StringName>::Element *E=ic.front();E;E=E->next()) {
					r_options->push_back(E->get());
				}
				return true;
			}
		}
	}



	for(int i=0;i<p_class->subclasses.size();i++) {

		if (p_line>=p_class->subclasses[i]->line && (p_line<=p_class->subclasses[i]->end_line || p_class->subclasses[i]->end_line==-1)) {

			if (_parse_completion_class(p_base_path,p_class->subclasses[i],p_line,r_options,p_indices))
				return true;
		}
	}

	bool in_static_func=false;

	for(int i=0;i<p_class->functions.size();i++) {

		const GDParser::FunctionNode *fu = p_class->functions[i];

		if (p_line>=fu->body->line && (p_line<=fu->body->end_line || fu->body->end_line==-1)) {
			//if in function, first block stuff from outer to inner
			if (_parse_completion_block(fu->body,p_line,r_options,p_indices))
				return true;
			//then function arguments
			if (!p_indices) {
				for(int j=0;j<fu->arguments.size();j++) {

					r_options->push_back(fu->arguments[j]);
				}
			}
		}

	}

	for(int i=0;i<p_class->static_functions.size();i++) {

		const GDParser::FunctionNode *fu = p_class->static_functions[i];

		if (p_line>=fu->body->line && (p_line<=fu->body->end_line || fu->body->end_line==-1)) {

			//if in function, first block stuff from outer to inne
			if (_parse_completion_block(fu->body,p_line,r_options,p_indices))
				return true;
			//then function arguments
			if (!p_indices) {
				for(int j=0;j<fu->arguments.size();j++) {

					r_options->push_back(fu->arguments[j]);
				}
			}

			in_static_func=true;
		}

	}


	//add all local names
	if (!p_indices) {

		if (!in_static_func) {

			for(int i=0;i<p_class->variables.size();i++) {

				r_options->push_back(p_class->variables[i].identifier);
			}
		}

		for(int i=0;i<p_class->constant_expressions.size();i++) {

			r_options->push_back(p_class->constant_expressions[i].identifier);
		}

		if (!in_static_func) {
			for(int i=0;i<p_class->functions.size();i++) {

				r_options->push_back(p_class->functions[i]->name);
			}
		}

		for(int i=0;i<p_class->static_functions.size();i++) {

			r_options->push_back(p_class->static_functions[i]->name);
		}
	}


	if (p_class->extends_used) {
		//do inheritance
		String path = p_class->extends_file;

		Ref<GDScript> script;
		Ref<GDNativeClass> native;

		if (path!="") {
			//path (and optionally subclasses)

			script = ResourceLoader::load(path);
			if (script.is_null()) {
				return false;
			}

			if (p_class->extends_class.size()) {

				for(int i=0;i<p_class->extends_class.size();i++) {

					String sub = p_class->extends_class[i];
					if (script->get_subclasses().has(sub)) {

						script=script->get_subclasses()[sub];
					} else {

						return false;
					}
				}
			}

		} else {

			ERR_FAIL_COND_V(p_class->extends_class.size()==0,false);
			//look around for the subclasses

			String base=p_class->extends_class[0];
			Ref<GDScript> base_class;
#if 0
			while(p) {

				if (p->subclasses.has(base)) {

					base_class=p->subclasses[base];
					break;
				}
				p=p->_owner;
			}

			if (base_class.is_valid()) {

				for(int i=1;i<p_class->extends_class.size();i++) {

					String subclass=p_class->extends_class[i];

					if (base_class->subclasses.has(subclass)) {

						base_class=base_class->subclasses[subclass];
					} else {

						_set_error("Could not find subclass: "+subclass,p_class);
						return ERR_FILE_NOT_FOUND;
					}
				}


			} else {
#endif
				if (p_class->extends_class.size()>1) {

					return false;

				}
				//if not found, try engine classes
				if (!GDScriptLanguage::get_singleton()->get_global_map().has(base)) {
					return false;
				}

				int base_idx = GDScriptLanguage::get_singleton()->get_global_map()[base];
				native = GDScriptLanguage::get_singleton()->get_global_array()[base_idx];
				if (!native.is_valid()) {
					return false;
				}
#if 0
			}
#endif

		}

		if (script.is_valid()) {
			if (_parse_script_symbols(script,in_static_func,r_options,p_indices))
				return true;

		} else if (native.is_valid() && !p_indices) {

			_parse_native_symbols(native->get_name(),in_static_func,r_options);
		}
	}

	return false;

}
示例#9
0
int main(int argc, char** argv)
{
	if (argc == 2)
		return echo(argc, argv);
	
	{
		class TestFactory: public ProcessFactory
		{
		public:
			int incarnate() {
				print("Good morning %%.\n", User(Process::realUserId()).fullName());
				return 7;
			}
		};
		
		print("(1) Worker clone\n\n");
		
		Ref<ProcessFactory, Owner> factory = new TestFactory;
		Ref<Process, Owner> worker = factory->produce();
		int ret = worker->wait();
		print("ret = %%\n", ret);
		print("\n");
	}
	
	{
		print("(2) I/O Redirection, passing of arguments and environment variables\n\n");
		
		Ref<ProcessFactory, Owner> factory = new ProcessFactory;
		factory->setExecPath(argv[0]);
		factory->setIoPolicy(Process::ForwardInput | Process::ForwardOutput);
		factory->options()->append("--echo 123");
		factory->envMap()->define("Hello", "World!");
		
		Ref<Process, Owner> process = factory->produce();
		
		print("Created child process with pid = %%\n", unsigned(process->id()));

		const char* message =
			"Hello, world!\n"
			"exit\n";
		process->rawInput()->write(message, str::len(message));
		process->rawInput()->close();
		
		const int bufSize = 16;
		uint8_t buf[bufSize];
		while (true) {
			int bufFill = process->rawOutput()->readAvail(buf, bufSize);
			if (bufFill == 0) break;
			rawOutput()->write(buf, bufFill);
		}
		
		print("Waiting for child process to finish...\n");
		
		int ret = process->wait();
		print("ret = %%\n", ret);
		print("\n");
	}
	
	{
		print("(3) Current process\n\n");
		print("Process::cwd() = %%\n", Process::cwd());
		print("Process::execPath() = %%\n", Process::execPath());
		print("Process::isSuperUser() = %%\n", Process::isSuperUser());
		print("\n");
	}
	
	return 0;
}
示例#10
0
 Ref<BVH2<Triangle4> > BVH2Builder::build(const BuildTriangle* triangles, size_t numTriangles)
 {
   Ref<BVH2<Triangle4> > bvh = new BVH2<Triangle4>;
   double t0 = getSeconds();
   BVH2Builder builder(triangles,numTriangles,bvh);
   double t1 = getSeconds();
   size_t bytesNodes = bvh->getNumNodes()*sizeof(BVH2<Triangle4>::Node);
   size_t bytesTris = bvh->getNumPrimBlocks()*sizeof(BVH2<Triangle4>::Triangle);
   std::ostringstream stream;
   stream << "triangles = " << numTriangles << std::endl;
   stream.setf(std::ios::fixed, std::ios::floatfield);
   stream.precision(0);
   stream << "build time = " << (t1-t0)*1000.0f << " ms" << std::endl;
   stream.setf(std::ios::scientific, std::ios::floatfield);
   stream.precision(2);
   stream << "sah = " << bvh->getSAH() << std::endl;
   stream.setf(std::ios::fixed, std::ios::floatfield);
   stream.precision(1);
   stream << "size = " << (bytesNodes+bytesTris)/1048576.0f << " MB" << std::endl;
   stream << "nodes = " << bvh->getNumNodes() << " "
          << "(" << bytesNodes/1048576.0f << " MB) "
          << "(" << 100.0f*(bvh->getNumNodes()-1+bvh->getNumLeaves())/(2.0*bvh->getNumNodes()) << " %)"
          << std::endl;
   stream << "leaves = " << bvh->getNumLeaves() << " "
          << "(" << bytesTris/1048576.0f  << " MB) "
          << "(" << 100.0f*bvh->getNumPrims()/(4.0*bvh->getNumPrimBlocks()) << " %)"
          << std::endl;
   std::cout << stream.str();
   return bvh;
 }
void GenericMultipleBarcodeReader::doDecodeMultiple(Ref<BinaryBitmap> image, 
                                                    DecodeHints hints, std::vector<Ref<Result> >& results, int xOffset, int yOffset)
{
    Ref<Result> result;
    try {
        result = delegate_.decode(image, hints);
    } catch (ReaderException& re) {
        return;
    }
    bool alreadyFound = false;
    for (unsigned int i = 0; i < results.size(); i++) {
        Ref<Result> existingResult = results[i];
        if (existingResult->getText()->getText() == result->getText()->getText()) {
            alreadyFound = true;
            break;
        }
    }
    if (alreadyFound) {
        return;
    }

    results.push_back(translateResultPoints(result, xOffset, yOffset));
    const std::vector<Ref<ResultPoint> > resultPoints = result->getResultPoints();
    if (resultPoints.empty()) {
        return;
    }

    int width = image->getWidth();
    int height = image->getHeight();
    float minX = width;
    float minY = height;
    float maxX = 0.0f;
    float maxY = 0.0f;
    for (unsigned int i = 0; i < resultPoints.size(); i++) {
        Ref<ResultPoint> point = resultPoints[i];
        float x = point->getX();
        float y = point->getY();
        if (x < minX) {
            minX = x;
        }
        if (y < minY) {
            minY = y;
        }
        if (x > maxX) {
            maxX = x;
        }
        if (y > maxY) {
            maxY = y;
        }
    }

    // Decode left of barcode
    if (minX > MIN_DIMENSION_TO_RECUR) {
        doDecodeMultiple(image->crop(0, 0, (int) minX, height),
                         hints, results, xOffset, yOffset);
    }
    // Decode above barcode
    if (minY > MIN_DIMENSION_TO_RECUR) {
        doDecodeMultiple(image->crop(0, 0, width, (int) minY),
                         hints, results, xOffset, yOffset);
    }
    // Decode right of barcode
    if (maxX < width - MIN_DIMENSION_TO_RECUR) {
        doDecodeMultiple(image->crop((int) maxX, 0, width - (int) maxX, height),
                         hints, results, xOffset + (int) maxX, yOffset);
    }
    // Decode below barcode
    if (maxY < height - MIN_DIMENSION_TO_RECUR) {
        doDecodeMultiple(image->crop(0, (int) maxY, width, height - (int) maxY),
                         hints, results, xOffset, yOffset + (int) maxY);
    }
}
示例#12
0
文件: QPCommon.cpp 项目: hpropp/drake
VectorXd velocityReference(NewQPControllerData *pdata, double t, const Ref<VectorXd> &q, const Ref<VectorXd> &qd, const Ref<VectorXd> &qdd, bool foot_contact[2], VRefIntegratorParams *params, RobotPropertyCache *rpc) {
  // Integrate expected accelerations to determine a target feed-forward velocity, which we can pass in to Atlas
  int i;
  assert(qdd.size() == pdata->r->num_velocities);

  double dt = 0;
  if (pdata->state.t_prev != 0) {
    dt = t - pdata->state.t_prev;
  }

  VectorXd qdd_limited = qdd;
  // Do not wind the vref integrator up against the joint limits for the legs
  for (i=0; i < rpc->position_indices.at("r_leg").size(); i++) {
    int pos_ind = rpc->position_indices.at("r_leg")(i);
    if (q(pos_ind) <= pdata->r->joint_limit_min(pos_ind) + LEG_INTEGRATOR_DEACTIVATION_MARGIN) {
      qdd_limited(pos_ind) = std::max(qdd(pos_ind), 0.0);
    } else if (q(pos_ind) >= pdata->r->joint_limit_max(pos_ind) - LEG_INTEGRATOR_DEACTIVATION_MARGIN) {
      qdd_limited(pos_ind) = std::min(qdd(pos_ind), 0.0);
    }
  }
  for (i=0; i < rpc->position_indices.at("l_leg").size(); i++) {
    int pos_ind = rpc->position_indices.at("l_leg")(i);
    if (q(pos_ind) <= pdata->r->joint_limit_min(pos_ind) + LEG_INTEGRATOR_DEACTIVATION_MARGIN) {
      qdd_limited(pos_ind) = std::max(qdd(pos_ind), 0.0);
    } else if (q(pos_ind) >= pdata->r->joint_limit_max(pos_ind) - LEG_INTEGRATOR_DEACTIVATION_MARGIN) {
      qdd_limited(pos_ind) = std::min(qdd(pos_ind), 0.0);
    }
  }

  pdata->state.vref_integrator_state = (1-params->eta)*pdata->state.vref_integrator_state + params->eta*qd + qdd_limited*dt;

  if (params->zero_ankles_on_contact && foot_contact[0] == 1) {
    for (i=0; i < rpc->position_indices.at("l_leg_ak").size(); i++) {
      pdata->state.vref_integrator_state(rpc->position_indices.at("l_leg_ak")(i)) = 0;
    }
  }
  if (params->zero_ankles_on_contact && foot_contact[1] == 1) {
    for (i=0; i < rpc->position_indices.at("r_leg_ak").size(); i++) {
      pdata->state.vref_integrator_state(rpc->position_indices.at("r_leg_ak")(i)) = 0;
    }
  }
  if (pdata->state.foot_contact_prev[0] != foot_contact[0]) {
    // contact state changed, reset integrated velocities
    for (i=0; i < rpc->position_indices.at("l_leg").size(); i++) {
      pdata->state.vref_integrator_state(rpc->position_indices.at("l_leg")(i)) = qd(rpc->position_indices.at("l_leg")(i));
    }
  }
  if (pdata->state.foot_contact_prev[1] != foot_contact[1]) {
    // contact state changed, reset integrated velocities
    for (i=0; i < rpc->position_indices.at("r_leg").size(); i++) {
      pdata->state.vref_integrator_state(rpc->position_indices.at("r_leg")(i)) = qd(rpc->position_indices.at("r_leg")(i));
    }
  }

  pdata->state.foot_contact_prev[0] = foot_contact[0];
  pdata->state.foot_contact_prev[1] = foot_contact[1];

  VectorXd qd_err = pdata->state.vref_integrator_state - qd;

  // do not velocity control ankles when in contact
  if (params->zero_ankles_on_contact && foot_contact[0] == 1) {
    for (i=0; i < rpc->position_indices.at("l_leg_ak").size(); i++) {
      qd_err(rpc->position_indices.at("l_leg_ak")(i)) = 0;
    }
  }
  if (params->zero_ankles_on_contact && foot_contact[1] == 1) {
    for (i=0; i < rpc->position_indices.at("r_leg_ak").size(); i++) {
      qd_err(rpc->position_indices.at("r_leg_ak")(i)) = 0;
    }
  }

  VectorXd qd_ref = qd_err.array().max(-params->delta_max);
  qd_ref = qd_ref.array().min(params->delta_max);
  return qd_ref;
}
示例#13
0
void ConsoleMessage::addToFrontend(ConsoleFrontendDispatcher* consoleFrontendDispatcher, InjectedScriptManager* injectedScriptManager, bool generatePreview)
{
    Ref<Inspector::Protocol::Console::ConsoleMessage> jsonObj = Inspector::Protocol::Console::ConsoleMessage::create()
        .setSource(messageSourceValue(m_source))
        .setLevel(messageLevelValue(m_level))
        .setText(m_message)
        .release();

    // FIXME: only send out type for ConsoleAPI source messages.
    jsonObj->setType(messageTypeValue(m_type));
    jsonObj->setLine(static_cast<int>(m_line));
    jsonObj->setColumn(static_cast<int>(m_column));
    jsonObj->setUrl(m_url);
    jsonObj->setRepeatCount(static_cast<int>(m_repeatCount));

    if (m_source == MessageSource::Network && !m_requestId.isEmpty())
        jsonObj->setNetworkRequestId(m_requestId);

    if (m_arguments && m_arguments->argumentCount()) {
        InjectedScript injectedScript = injectedScriptManager->injectedScriptFor(m_arguments->globalState());
        if (!injectedScript.hasNoValue()) {
            Ref<Inspector::Protocol::Array<Inspector::Protocol::Runtime::RemoteObject>> jsonArgs = Inspector::Protocol::Array<Inspector::Protocol::Runtime::RemoteObject>::create();
            if (m_type == MessageType::Table && generatePreview && m_arguments->argumentCount()) {
                Deprecated::ScriptValue table = m_arguments->argumentAt(0);
                Deprecated::ScriptValue columns = m_arguments->argumentCount() > 1 ? m_arguments->argumentAt(1) : Deprecated::ScriptValue();
                RefPtr<Inspector::Protocol::Runtime::RemoteObject> inspectorValue = injectedScript.wrapTable(table, columns);
                if (!inspectorValue) {
                    ASSERT_NOT_REACHED();
                    return;
                }
                jsonArgs->addItem(inspectorValue.copyRef());
                if (m_arguments->argumentCount() > 1)
                    jsonArgs->addItem(injectedScript.wrapObject(columns, ASCIILiteral("console"), true));
            } else {
                for (unsigned i = 0; i < m_arguments->argumentCount(); ++i) {
                    RefPtr<Inspector::Protocol::Runtime::RemoteObject> inspectorValue = injectedScript.wrapObject(m_arguments->argumentAt(i), ASCIILiteral("console"), generatePreview);
                    if (!inspectorValue) {
                        ASSERT_NOT_REACHED();
                        return;
                    }
                    jsonArgs->addItem(inspectorValue.copyRef());
                }
            }
            jsonObj->setParameters(WTF::move(jsonArgs));
        }
    }

    if (m_callStack)
        jsonObj->setStackTrace(m_callStack->buildInspectorArray());

    consoleFrontendDispatcher->messageAdded(WTF::move(jsonObj));
}
示例#14
0
static Error _parse_material_library(const String &p_path, Map<String, Ref<SpatialMaterial> > &material_map, List<String> *r_missing_deps) {

	FileAccessRef f = FileAccess::open(p_path, FileAccess::READ);
	ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);

	Ref<SpatialMaterial> current;
	String current_name;
	String base_path = p_path.get_base_dir();
	while (true) {

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

		if (l.begins_with("newmtl ")) {
			//vertex

			current_name = l.replace("newmtl", "").strip_edges();
			current.instance();
			current->set_name(current_name);
			material_map[current_name] = current;
		} else if (l.begins_with("Ka ")) {
			//uv
			print_line("Warning: Ambient light for material '" + current_name + "' is ignored in PBR");

		} else if (l.begins_with("Kd ")) {
			//normal
			ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
			Vector<String> v = l.split(" ", false);
			ERR_FAIL_COND_V(v.size() < 4, ERR_INVALID_DATA);
			Color c = current->get_albedo();
			c.r = v[1].to_float();
			c.g = v[2].to_float();
			c.b = v[3].to_float();
			current->set_albedo(c);
		} else if (l.begins_with("Ks ")) {
			//normal
			ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
			Vector<String> v = l.split(" ", false);
			ERR_FAIL_COND_V(v.size() < 4, ERR_INVALID_DATA);
			float r = v[1].to_float();
			float g = v[2].to_float();
			float b = v[3].to_float();
			float metalness = MAX(r, MAX(g, b));
			current->set_metallic(metalness);
		} else if (l.begins_with("Ns ")) {
			//normal
			ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
			Vector<String> v = l.split(" ", false);
			ERR_FAIL_COND_V(v.size() != 2, ERR_INVALID_DATA);
			float s = v[1].to_float();
			current->set_metallic((1000.0 - s) / 1000.0);
		} else if (l.begins_with("d ")) {
			//normal
			ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
			Vector<String> v = l.split(" ", false);
			ERR_FAIL_COND_V(v.size() != 2, ERR_INVALID_DATA);
			float d = v[1].to_float();
			Color c = current->get_albedo();
			c.a = d;
			current->set_albedo(c);
			if (c.a < 0.99) {
				current->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
			}
		} else if (l.begins_with("Tr ")) {
			//normal
			ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
			Vector<String> v = l.split(" ", false);
			ERR_FAIL_COND_V(v.size() != 2, ERR_INVALID_DATA);
			float d = v[1].to_float();
			Color c = current->get_albedo();
			c.a = 1.0 - d;
			current->set_albedo(c);
			if (c.a < 0.99) {
				current->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
			}

		} else if (l.begins_with("map_Ka ")) {
			//uv
			print_line("Warning: Ambient light texture for material '" + current_name + "' is ignored in PBR");

		} else if (l.begins_with("map_Kd ")) {
			//normal
			ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);

			String p = l.replace("map_Kd", "").replace("\\", "/").strip_edges();
			String path = base_path.plus_file(p);

			Ref<Texture> texture = ResourceLoader::load(path);

			if (texture.is_valid()) {
				current->set_texture(SpatialMaterial::TEXTURE_ALBEDO, texture);
			} else if (r_missing_deps) {
				r_missing_deps->push_back(path);
			}

		} else if (l.begins_with("map_Ks ")) {
			//normal
			ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);

			String p = l.replace("map_Ks", "").replace("\\", "/").strip_edges();
			String path = base_path.plus_file(p);

			Ref<Texture> texture = ResourceLoader::load(path);

			if (texture.is_valid()) {
				current->set_texture(SpatialMaterial::TEXTURE_METALLIC, texture);
			} else if (r_missing_deps) {
				r_missing_deps->push_back(path);
			}

		} else if (l.begins_with("map_Ns ")) {
			//normal
			ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);

			String p = l.replace("map_Ns", "").replace("\\", "/").strip_edges();
			String path = base_path.plus_file(p);

			Ref<Texture> texture = ResourceLoader::load(path);

			if (texture.is_valid()) {
				current->set_texture(SpatialMaterial::TEXTURE_ROUGHNESS, texture);
			} else if (r_missing_deps) {
				r_missing_deps->push_back(path);
			}
		} else if (l.begins_with("map_bump ")) {
			//normal
			ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);

			String p = l.replace("map_bump", "").replace("\\", "/").strip_edges();
			String path = base_path.plus_file(p);

			Ref<Texture> texture = ResourceLoader::load(path);

			if (texture.is_valid()) {
				current->set_feature(SpatialMaterial::FEATURE_NORMAL_MAPPING, true);
				current->set_texture(SpatialMaterial::TEXTURE_NORMAL, texture);
			} else if (r_missing_deps) {
				r_missing_deps->push_back(path);
			}
		} else if (f->eof_reached()) {
			break;
		}
	}

	return OK;
}
示例#15
0
Ref<Result> OneDReader::doDecode(Ref<BinaryBitmap> image, DecodeHints hints) {
  int width = image->getWidth();
  int height = image->getHeight();
  Ref<BitArray> row(new BitArray(width));

  int middle = height >> 1;
  bool tryHarder = hints.getTryHarder();
  int rowStep = std::max(1, height >> (tryHarder ? 8 : 5));
  using namespace std;
  // cerr << "rS " << rowStep << " " << height << " " << tryHarder << endl;
  int maxLines;
  if (tryHarder) {
    maxLines = height; // Look at the whole image, not just the center
  } else {
    maxLines = 15; // 15 rows spaced 1/32 apart is roughly the middle half of the image
  }

  for (int x = 0; x < maxLines; x++) {

    // Scanning from the middle out. Determine which row we're looking at next:
    int rowStepsAboveOrBelow = (x + 1) >> 1;
    bool isAbove = (x & 0x01) == 0; // i.e. is x even?
    int rowNumber = middle + rowStep * (isAbove ? rowStepsAboveOrBelow : -rowStepsAboveOrBelow);
    if (false) {
      std::cerr << "rN "
                << rowNumber << " "
                << height << " "
                << middle << " "
                << rowStep << " "
                << isAbove << " "
                << rowStepsAboveOrBelow
                << std::endl;
    }
    if (rowNumber < 0 || rowNumber >= height) {
      // Oops, if we run off the top or bottom, stop
      break;
    }

    // Estimate black point for this row and load it:
    try {
      row = image->getBlackRow(rowNumber, row);
    } catch (NotFoundException const& ignored) {
      (void)ignored;
      continue;
    }

    // While we have the image data in a BitArray, it's fairly cheap to reverse it in place to
    // handle decoding upside down barcodes.
    for (int attempt = 0; attempt < 2; attempt++) {
      if (attempt == 1) {
        row->reverse(); // reverse the row and continue
      }

      // Java hints stuff missing

      try {
        // Look for a barcode
        // std::cerr << "rn " << rowNumber << " " << typeid(*this).name() << std::endl;
        Ref<Result> result = decodeRow(rowNumber, row);
        // We found our barcode
        if (attempt == 1) {
          // But it was upside down, so note that
          // result.putMetadata(ResultMetadataType.ORIENTATION, new Integer(180));
          // And remember to flip the result points horizontally.
          ArrayRef< Ref<ResultPoint> > points(result->getResultPoints());
          if (points) {
            points[0] = Ref<ResultPoint>(new OneDResultPoint(width - points[0]->getX() - 1,
                                                             points[0]->getY()));
            points[1] = Ref<ResultPoint>(new OneDResultPoint(width - points[1]->getX() - 1,
                                                             points[1]->getY()));
            
          }
        }
        return result;
      } catch (ReaderException const& re) {
        (void)re;
        continue;
      }
    }
  }
  throw NotFoundException();
}
示例#16
0
bool Path2DEditor::forward_input_event(const InputEvent& p_event) {

	if (!node)
		return false;

	if (!node->is_visible())
		return false;

	if (!node->get_curve().is_valid())
		return false;

	switch(p_event.type) {

		case InputEvent::MOUSE_BUTTON: {

			const InputEventMouseButton &mb=p_event.mouse_button;

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

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

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



			// Test move point!!

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

				Ref<Curve2D> curve = node->get_curve();

				for(int i=0;i<curve->get_point_count();i++) {

					bool pointunder=false;

					{
						Point2 p = xform.xform( curve->get_point_pos(i) );
						if (gpoint.distance_to(p) < grab_treshold ) {

							if (!mb.mod.shift) {

								action=ACTION_MOVING_POINT;
								action_point=i;
								moving_from=curve->get_point_pos(i);
								moving_screen_from=gpoint;
								return true;
							} else
								pointunder=true;
						}
					}

					if (i<(curve->get_point_count()-1)) {
						Point2 p = xform.xform( curve->get_point_pos(i)+curve->get_point_out(i) );
						if (gpoint.distance_to(p) < grab_treshold ) {

							action=ACTION_MOVING_OUT;
							action_point=i;
							moving_from=curve->get_point_out(i);
							moving_screen_from=gpoint;
							return true;
						}
					}

					if (i>0) {
						Point2 p = xform.xform( curve->get_point_pos(i)+curve->get_point_in(i) );
						if (gpoint.distance_to(p) < grab_treshold ) {

							action=ACTION_MOVING_IN;
							action_point=i;
							moving_from=curve->get_point_in(i);
							moving_screen_from=gpoint;
							return true;
						}
					}

					if (pointunder)
						return true;

				}

			}

			// Test add point in empty space!

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

				Ref<Curve2D> curve = node->get_curve();

				undo_redo->create_action("Add Point to Curve");
				undo_redo->add_do_method(curve.ptr(),"add_point",cpoint);
				undo_redo->add_undo_method(curve.ptr(),"remove_point",curve->get_point_count());
				undo_redo->add_do_method(canvas_item_editor,"update");
				undo_redo->add_undo_method(canvas_item_editor,"update");
				undo_redo->commit_action();

				action=ACTION_MOVING_POINT;
				action_point=curve->get_point_count()-1;
				moving_from=curve->get_point_pos(action_point);
				moving_screen_from=gpoint;

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

				return true;
			}

			if ( !mb.pressed && mb.button_index==BUTTON_LEFT && action!=ACTION_NONE) {


				Ref<Curve2D> curve = node->get_curve();

				Vector2 new_pos = moving_from + xform.basis_xform( gpoint - moving_screen_from );
				switch(action) {

					case ACTION_MOVING_POINT: {


						undo_redo->create_action("Move Point in Curve");
						undo_redo->add_do_method(curve.ptr(),"set_point_pos",action_point,cpoint);
						undo_redo->add_undo_method(curve.ptr(),"set_point_pos",action_point,moving_from);
						undo_redo->add_do_method(canvas_item_editor,"update");
						undo_redo->add_undo_method(canvas_item_editor,"update");
						undo_redo->commit_action();

					} break;
					case ACTION_MOVING_IN: {

						undo_redo->create_action("Move In-Control in Curve");
						undo_redo->add_do_method(curve.ptr(),"set_point_in",action_point,new_pos);
						undo_redo->add_undo_method(curve.ptr(),"set_point_in",action_point,moving_from);
						undo_redo->add_do_method(canvas_item_editor,"update");
						undo_redo->add_undo_method(canvas_item_editor,"update");
						undo_redo->commit_action();

					} break;
					case ACTION_MOVING_OUT: {

						undo_redo->create_action("Move Out-Control in Curve");
						undo_redo->add_do_method(curve.ptr(),"set_point_out",action_point,new_pos);
						undo_redo->add_undo_method(curve.ptr(),"set_point_out",action_point,moving_from);
						undo_redo->add_do_method(canvas_item_editor,"update");
						undo_redo->add_undo_method(canvas_item_editor,"update");
						undo_redo->commit_action();

					} break;

				}

				action=ACTION_NONE;

				return true;
			}


#if 0
			switch(mode) {


				case MODE_CREATE: {

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


						if (!wip_active) {

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

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

								return true;
							} else {

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

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



				} break;

				case MODE_EDIT: {

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

							if (mb.mod.control) {


								if (poly.size() < 3) {

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

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

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

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

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


								}

								if (closest_idx>=0) {

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

								//look for points to move

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

									Vector2 cp =xform.xform(poly[i]);

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

								}

								if (closest_idx>=0) {

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

							if (edited_point!=-1) {

								//apply

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

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



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

							Vector2 cp =xform.xform(poly[i]);

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

						}

						if (closest_idx>=0) {


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

					}



				} break;
			}


#endif
		} break;
		case InputEvent::MOUSE_MOTION: {

			const InputEventMouseMotion &mm=p_event.mouse_motion;


			if ( action!=ACTION_NONE) {

				Matrix32 xform = canvas_item_editor->get_canvas_transform() * node->get_global_transform();
				Vector2 gpoint = Point2(mm.x,mm.y);
				Vector2 cpoint = !mm.mod.alt? snap_point(xform.affine_inverse().xform(gpoint))
											: node->get_global_transform().affine_inverse().xform( snap_point(canvas_item_editor->get_canvas_transform().affine_inverse().xform(gpoint)) );

				Ref<Curve2D> curve = node->get_curve();

				Vector2 new_pos = moving_from + xform.basis_xform( gpoint - moving_screen_from );

				switch(action) {

					case ACTION_MOVING_POINT: {

						curve->set_point_pos(action_point,cpoint);
					} break;
					case ACTION_MOVING_IN: {

						curve->set_point_in(action_point,new_pos);

					} break;
					case ACTION_MOVING_OUT: {

						curve->set_point_out(action_point,new_pos);

					} break;
				}


				canvas_item_editor->get_viewport_control()->update();
				return true;
			}

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


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

				Vector2 gpoint = Point2(mm.x,mm.y);
				edited_point_pos = snap_point(xform.affine_inverse().xform(gpoint));
				canvas_item_editor->update();

			}
#endif
		} break;
	}

	return false;
}
Ref<InspectorObject> TimelineRecordFactory::createConsoleProfileData(const String& title) {
    Ref<InspectorObject> data = InspectorObject::create();
    data->setString("title", title);
    return WTF::move(data);
}
示例#18
0
void TileMapEditor::_canvas_draw() {

	if (!node)
		return;

	Size2 cell_size=node->get_cell_size();
	Matrix32 cell_xf = node->get_cell_transform();

	Matrix32 xform = CanvasItemEditor::get_singleton()->get_canvas_transform() * node->get_global_transform();
	Matrix32 xform_inv = xform.affine_inverse();


	Size2 screen_size=canvas_item_editor->get_size();
	{
		Rect2 aabb;
		aabb.pos=node->world_to_map(xform_inv.xform(Vector2()));
		aabb.expand_to(node->world_to_map(xform_inv.xform(Vector2(0,screen_size.height))));
		aabb.expand_to(node->world_to_map(xform_inv.xform(Vector2(screen_size.width,0))));
		aabb.expand_to(node->world_to_map(xform_inv.xform(screen_size)));
		Rect2i si=aabb.grow(1.0);

		if (node->get_half_offset()!=TileMap::HALF_OFFSET_X) {

			for(int i=(si.pos.x)-1;i<=(si.pos.x+si.size.x);i++) {

				Vector2 from = xform.xform(node->map_to_world(Vector2(i,si.pos.y)));
				Vector2 to = xform.xform(node->map_to_world(Vector2(i,si.pos.y+si.size.y+1)));

				Color col=i==0?Color(1,0.8,0.2,0.5):Color(1,0.3,0.1,0.2);
				canvas_item_editor->draw_line(from,to,col,1);

			}
		} else {


			for(int i=(si.pos.x)-1;i<=(si.pos.x+si.size.x);i++) {

				for(int j=(si.pos.y)-1;j<=(si.pos.y+si.size.y);j++) {

					Vector2 ofs;
					if (ABS(j)&1) {
						ofs=cell_xf[0]*0.5;
					}

					Vector2 from = xform.xform(node->map_to_world(Vector2(i,j),true)+ofs);
					Vector2 to = xform.xform(node->map_to_world(Vector2(i,j+1),true)+ofs);
					Color col=i==0?Color(1,0.8,0.2,0.5):Color(1,0.3,0.1,0.2);
					canvas_item_editor->draw_line(from,to,col,1);
				}

			}
		}

		if (node->get_half_offset()!=TileMap::HALF_OFFSET_Y) {

			for(int i=(si.pos.y)-1;i<=(si.pos.y+si.size.y);i++) {

				Vector2 from = xform.xform(node->map_to_world(Vector2(si.pos.x,i)));
				Vector2 to = xform.xform(node->map_to_world(Vector2(si.pos.x+si.size.x+1,i)));

				Color col=i==0?Color(1,0.8,0.2,0.5):Color(1,0.3,0.1,0.2);
				canvas_item_editor->draw_line(from,to,col,1);

			}
		} else {


			for(int i=(si.pos.y)-1;i<=(si.pos.y+si.size.y);i++) {

				for(int j=(si.pos.x)-1;j<=(si.pos.x+si.size.x);j++) {

					Vector2 ofs;
					if (ABS(j)&1) {
						ofs=cell_xf[1]*0.5;
					}

					Vector2 from = xform.xform(node->map_to_world(Vector2(j,i),true)+ofs);
					Vector2 to = xform.xform(node->map_to_world(Vector2(j+1,i),true)+ofs);
					Color col=i==0?Color(1,0.8,0.2,0.5):Color(1,0.3,0.1,0.2);
					canvas_item_editor->draw_line(from,to,col,1);
				}

			}



		}
/*
	for(int i=(si.pos.y/cell_size.y)-1;i<=(si.pos.y+si.size.y)/cell_size.y;i++) {

		int ofs = i*cell_size.y;
		Color col=i==0?Color(1,0.8,0.2,0.5):Color(1,0.3,0.1,0.2);
		canvas_item_editor->draw_line(xform.xform(Point2(si.pos.x,ofs)),xform.xform(Point2(si.pos.x+si.size.x,ofs)),col,1);*/
	}


	if (selection_active) {

		Vector<Vector2> points;
		points.push_back( xform.xform( node->map_to_world(( selection.pos ) )));
		points.push_back( xform.xform( node->map_to_world((selection.pos+Point2(selection.size.x+1,0)) ) ));
		points.push_back( xform.xform( node->map_to_world((selection.pos+Point2(selection.size.x+1,selection.size.y+1)) ) ));
		points.push_back( xform.xform( node->map_to_world((selection.pos+Point2(0,selection.size.y+1)) ) ));
		Color col=Color(0.2,0.8,1,0.4);

		canvas_item_editor->draw_colored_polygon(points,col);
	}


	if (mouse_over){

		Vector2 endpoints[4]={

			( node->map_to_world(over_tile,true) ) ,
			( node->map_to_world((over_tile+Point2(1,0)),true ) ),
			( node->map_to_world((over_tile+Point2(1,1)),true ) ),
			( node->map_to_world((over_tile+Point2(0,1)),true ) )

		};

		for(int i=0;i<4;i++) {
			if (node->get_half_offset()==TileMap::HALF_OFFSET_X && ABS(over_tile.y)&1)
				endpoints[i]+=cell_xf[0]*0.5;
			if (node->get_half_offset()==TileMap::HALF_OFFSET_Y && ABS(over_tile.x)&1)
				endpoints[i]+=cell_xf[1]*0.5;
			endpoints[i]=xform.xform(endpoints[i]);
		}
		Color col;
		if (node->get_cell(over_tile.x,over_tile.y)!=TileMap::INVALID_CELL)
			col=Color(0.2,0.8,1.0,0.8);
		else
			col=Color(1.0,0.4,0.2,0.8);

		for(int i=0;i<4;i++)
			canvas_item_editor->draw_line(endpoints[i],endpoints[(i+1)%4],col,2);



		if (tool==TOOL_DUPLICATING) {

			Rect2i duplicate=selection;
			duplicate.pos=over_tile;


			Vector<Vector2> points;
			points.push_back( xform.xform( node->map_to_world(duplicate.pos ) ));
			points.push_back( xform.xform( node->map_to_world((duplicate.pos+Point2(duplicate.size.x+1,0)) ) ));
			points.push_back( xform.xform( node->map_to_world((duplicate.pos+Point2(duplicate.size.x+1,duplicate.size.y+1))) ));
			points.push_back( xform.xform( node->map_to_world((duplicate.pos+Point2(0,duplicate.size.y+1))) ));
			Color col=Color(0.2,1.0,0.8,0.4);

			canvas_item_editor->draw_colored_polygon(points,col);

		} else {

			Ref<TileSet> ts = node->get_tileset();


			if (ts.is_valid()) {

				int st = get_selected_tile();
				if (ts->has_tile(st)) {

					Ref<Texture> t = ts->tile_get_texture(st);
					if (t.is_valid()) {
						Vector2 from = xform.xform(ts->tile_get_texture_offset(st)+node->map_to_world(over_tile)+node->get_cell_draw_offset());
						Rect2 r = ts->tile_get_region(st);												
						Size2 sc = xform.get_scale();
						if (mirror_x->is_pressed())
							sc.x*=-1.0;
						if (mirror_y->is_pressed())
							sc.y*=-1.0;
						if (r==Rect2()) {

							canvas_item_editor->draw_texture_rect(t,Rect2(from,t->get_size()*sc),false,Color(1,1,1,0.5));
						} else {

							canvas_item_editor->draw_texture_rect_region(t,Rect2(from,r.get_size()*sc),r,Color(1,1,1,0.5));
						}
					}
				}
			}

		}
	}



}
示例#19
0
  static void parseCommandLine(Ref<ParseStream> cin, const FileName& path)
  {
    while (true)
    {
      std::string tag = cin->getString();
      if (tag == "") return;

      /* parse command line parameters from a file */
      else if (tag == "-c") {
        FileName file = path + cin->getFileName();
        parseCommandLine(new ParseStream(new LineCommentFilter(file, "#")), file.path());
      }

      /* load OBJ model*/
      else if (tag == "-i") {
        filename = path + cin->getFileName();
      }

      /* parse camera parameters */
      else if (tag == "-vp") g_camera.from = cin->getVec3fa();
      else if (tag == "-vi") g_camera.to = cin->getVec3fa();
      else if (tag == "-vd") g_camera.to = g_camera.from + cin->getVec3fa();
      else if (tag == "-vu") g_camera.up = cin->getVec3fa();
      else if (tag == "-fov") g_camera.fov = cin->getFloat();

      /* frame buffer size */
      else if (tag == "-size") {
        g_width = cin->getInt();
        g_height = cin->getInt();
      }

      /* full screen mode */
      else if (tag == "-fullscreen") 
        g_fullscreen = true;

      /* output filename */
      else if (tag == "-o") {
        outFilename = cin->getFileName();
	g_interactive = false;
      }

      /* number of frames to render in benchmark mode */
      else if (tag == "-benchmark") {
        g_skipBenchmarkFrames = cin->getInt();
        g_numBenchmarkFrames  = cin->getInt();
	g_interactive = false;
      }

      /* rtcore configuration */
      else if (tag == "-rtcore")
        g_rtcore = cin->getString();

      /* number of threads to use */
      else if (tag == "-threads")
        g_numThreads = cin->getInt();

       /* ambient light source */
      else if (tag == "-ambientlight") 
      {
        const Vec3fa L = cin->getVec3fa();
        g_obj_scene.ambientLights.push_back(OBJScene::AmbientLight(L));
      }

      /* point light source */
      else if (tag == "-pointlight") 
      {
        const Vec3fa P = cin->getVec3fa();
        const Vec3fa I = cin->getVec3fa();
        g_obj_scene.pointLights.push_back(OBJScene::PointLight(P,I));
      }

      /* directional light source */
      else if (tag == "-directionallight" || tag == "-dirlight") 
      {
        const Vec3fa D = cin->getVec3fa();
        const Vec3fa E = cin->getVec3fa();
        g_obj_scene.directionalLights.push_back(OBJScene::DirectionalLight(D,E));
      }

      /* distant light source */
      else if (tag == "-distantlight") 
      {
        const Vec3fa D = cin->getVec3fa();
        const Vec3fa L = cin->getVec3fa();
        const float halfAngle = cin->getFloat();
        g_obj_scene.distantLights.push_back(OBJScene::DistantLight(D,L,halfAngle));
      }

      /* skip unknown command line parameter */
      else {
        std::cerr << "unknown command line parameter: " << tag << " ";
        while (cin->peek() != "" && cin->peek()[0] != '-') std::cerr << cin->getString() << " ";
        std::cerr << std::endl;
      }
    }
  }
示例#20
0
文件: Ref.hpp 项目: giftnuss/libftl
	Ref(const Ref& b) { this->set(b.get()); }
示例#21
0
void OS_Android::process_touch(int p_what, int p_pointer, const Vector<TouchPos> &p_points) {

	//print_line("ev: "+itos(p_what)+" pnt: "+itos(p_pointer)+" pointc: "+itos(p_points.size()));

	switch (p_what) {
		case 0: { //gesture begin

			if (touch.size()) {
				//end all if exist
				{
					Ref<InputEventMouseButton> ev;
					ev.instance();
					ev->set_button_index(BUTTON_LEFT);
					ev->set_button_mask(BUTTON_MASK_LEFT);
					ev->set_pressed(false);
					ev->set_position(touch[0].pos);
					ev->set_global_position(touch[0].pos);
					input->parse_input_event(ev);
				}

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

					Ref<InputEventScreenTouch> ev;
					ev.instance();
					ev->set_index(touch[i].id);
					ev->set_pressed(false);
					ev->set_position(touch[i].pos);
					input->parse_input_event(ev);
				}
			}

			touch.resize(p_points.size());
			for (int i = 0; i < p_points.size(); i++) {
				touch[i].id = p_points[i].id;
				touch[i].pos = p_points[i].pos;
			}

			{
				//send mouse
				Ref<InputEventMouseButton> ev;
				ev.instance();
				// ev.type = Ref<InputEvent>::MOUSE_BUTTON;
				ev->set_button_index(BUTTON_LEFT);
				ev->set_button_mask(BUTTON_MASK_LEFT);
				ev->set_pressed(true);
				ev->set_position(touch[0].pos);
				ev->set_global_position(touch[0].pos);
				input->set_mouse_position(Point2(touch[0].pos.x, touch[0].pos.y));
				last_mouse = touch[0].pos;
				input->parse_input_event(ev);
			}

			//send touch
			for (int i = 0; i < touch.size(); i++) {

				Ref<InputEventScreenTouch> ev;
				ev.instance();
				ev->set_index(touch[i].id);
				ev->set_pressed(true);
				ev->set_position(touch[i].pos);
				input->parse_input_event(ev);
			}

		} break;
		case 1: { //motion

			if (p_points.size()) {
				//send mouse, should look for point 0?
				Ref<InputEventMouseMotion> ev;
				ev.instance();
				ev->set_button_mask(BUTTON_MASK_LEFT);
				ev->set_position(p_points[0].pos);
				input->set_mouse_position(Point2(ev->get_position().x, ev->get_position().y));
				ev->set_speed(input->get_last_mouse_speed());
				ev->set_relative(p_points[0].pos - last_mouse);
				last_mouse = p_points[0].pos;
				input->parse_input_event(ev);
			}

			ERR_FAIL_COND(touch.size() != p_points.size());

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

				int idx = -1;
				for (int j = 0; j < p_points.size(); j++) {

					if (touch[i].id == p_points[j].id) {
						idx = j;
						break;
					}
				}

				ERR_CONTINUE(idx == -1);

				if (touch[i].pos == p_points[idx].pos)
					continue; //no move unncesearily

				Ref<InputEventScreenDrag> ev;
				ev.instance();
				ev->set_index(touch[i].id);
				ev->set_position(p_points[idx].pos);
				ev->set_relative(p_points[idx].pos - touch[i].pos);
				input->parse_input_event(ev);
				touch[i].pos = p_points[idx].pos;
			}

		} break;
		case 2: { //release

			if (touch.size()) {
				//end all if exist
				Ref<InputEventMouseButton> ev;
				ev.instance();
				ev->set_button_index(BUTTON_LEFT);
				ev->set_button_mask(BUTTON_MASK_LEFT);
				ev->set_pressed(false);
				ev->set_position(touch[0].pos);
				ev->set_global_position(touch[0].pos);
				input->set_mouse_position(Point2(touch[0].pos.x, touch[0].pos.y));
				input->parse_input_event(ev);

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

					Ref<InputEventScreenTouch> ev;
					ev.instance();
					ev->set_index(touch[i].id);
					ev->set_pressed(false);
					ev->set_position(touch[i].pos);
					input->parse_input_event(ev);
				}
				touch.clear();
			}

		} break;
		case 3: { // add tuchi

			ERR_FAIL_INDEX(p_pointer, p_points.size());

			TouchPos tp = p_points[p_pointer];
			touch.push_back(tp);

			Ref<InputEventScreenTouch> ev;
			ev.instance();

			ev->set_index(tp.id);
			ev->set_pressed(true);
			ev->set_position(tp.pos);
			input->parse_input_event(ev);

		} break;
		case 4: {

			for (int i = 0; i < touch.size(); i++) {
				if (touch[i].id == p_pointer) {

					Ref<InputEventScreenTouch> ev;
					ev.instance();
					ev->set_index(touch[i].id);
					ev->set_pressed(false);
					ev->set_position(touch[i].pos);
					input->parse_input_event(ev);
					touch.remove(i);
					i--;
				}
			}

		} break;
	}
}
示例#22
0
文件: Ref.hpp 项目: giftnuss/libftl
	explicit Ref(const Ref<T, GetAndSetPolicy2>& b) { this->set(b.get()); }
示例#23
0
void OutputStrings::_notification(int p_what) {

	switch (p_what) {

		case NOTIFICATION_DRAW: {

			if (following) {

				updating = true;
				v_scroll->set_value(v_scroll->get_max() - v_scroll->get_page());
				updating = false;
			}

			RID ci = get_canvas_item();
			Size2 size = get_size();

			Ref<Font> font = get_font("font", "Tree");
			Ref<StyleBox> tree_st = get_stylebox("bg", "Tree");
			tree_st->draw(ci, Rect2(Point2(), size));
			Color color = get_color("font_color", "Tree");
			Ref<Texture> icon_error = get_icon("Error", "EditorIcons");
			Ref<Texture> icon_warning = get_icon("Warning", "EditorIcons");

			//int lines = (size_height-(int)margin.y) / font_height;
			Point2 ofs = tree_st->get_offset();

			LineMap::Element *E = line_map.find(v_scroll->get_value());
			float h_ofs = (int)h_scroll->get_value();
			Point2 icon_ofs = Point2(0, (font_height - (int)icon_error->get_height()) / 2);

			while (E && ofs.y < (size_height - (int)margin.y)) {

				String str = E->get().text;
				Point2 line_ofs = ofs;

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

					case LINE_WARNING: {
						icon_warning->draw(ci, line_ofs + icon_ofs);

					} break;
					case LINE_ERROR: {
						icon_error->draw(ci, line_ofs + icon_ofs);
					} break;
					case LINE_LINK: {

					} break;
					default: {}
				}

				line_ofs.y += font->get_ascent();
				line_ofs.x += icon_error->get_width() + 4;

				for (int i = 0; i < str.length(); i++) {
					if (line_ofs.x - h_ofs < 0) {
						line_ofs.x += font->get_char_size(str[i], str[i + 1]).width;
					} else if (line_ofs.x - h_ofs > size.width - margin.width) {
						break;
					} else {
						line_ofs.x += font->draw_char(ci, Point2(line_ofs.x - h_ofs, line_ofs.y), str[i], str[i + 1], color);
					}
				}

				ofs.y += font_height;
				E = E->next();
			}

		} break;

		case NOTIFICATION_ENTER_TREE:
		case NOTIFICATION_RESIZED: {

			font_height = get_font("font", "Tree")->get_height();
			size_height = get_size().height;
			update_scrollbars();
		} break;
	}
}
示例#24
0
文件: Ref.hpp 项目: giftnuss/libftl
	explicit Ref(const Ref<T2, GetAndSetPolicy2>& b) { this->set(FTL_CAST_FROM_TO(T2, T, b.get())); }
示例#25
0
	virtual void init() {
	
		SceneTree::init();


#if 0


		Viewport *vp = memnew( Viewport );
		vp->set_world( Ref<World>( memnew( World )));
		get_root()->add_child(vp);

		vp->set_rect(Rect2(0,0,256,256));
		vp->set_as_render_target(true);
		vp->set_render_target_update_mode(Viewport::RENDER_TARGET_UPDATE_ALWAYS);


		Camera *camera = memnew( Camera );
		vp->add_child(camera);
		camera->make_current();

		TestCube *testcube = memnew( TestCube );
		vp->add_child(testcube);
		testcube->set_transform(Transform( Matrix3().rotated(Vector3(0,1,0),Math_PI*0.25), Vector3(0,0,-8)));

		Sprite *sp = memnew( Sprite );
		sp->set_texture( vp->get_render_target_texture() );
//		sp->set_texture( ResourceLoader::load("res://ball.png") );
		sp->set_pos(Point2(300,300));
		get_root()->add_child(sp);


		return;
#endif

		Panel * frame = memnew( Panel );
		frame->set_anchor( MARGIN_RIGHT, Control::ANCHOR_END );
		frame->set_anchor( MARGIN_BOTTOM, Control::ANCHOR_END );
		frame->set_end( Point2(0,0) );

		Ref<Theme> t = memnew( Theme );
		frame->set_theme(t);
		
		get_root()->add_child( frame );

		Label *label = memnew( Label );

		label->set_pos( Point2( 80,90 ) );
		label->set_size( Point2( 170,80 ) );
		label->set_align( Label::ALIGN_FILL );
		//label->set_text("There");
		label->set_text("There was once upon a time a beautiful unicorn that loved to play with little girls...");

		frame->add_child(label);

		Button *button = memnew( Button );

		button->set_pos( Point2( 20,20 ) );
		button->set_size( Point2( 1,1 ) );
		button->set_text("This is a biggie button");


		frame->add_child( button );


#if 0
		Sprite *tf = memnew( Sprite );
		frame->add_child(tf);
		Image img;
		ImageLoader::load_image("LarvoClub.png",&img);

		img.resize(512,512);
		img.generate_mipmaps();
		img.compress(Image::COMPRESS_PVRTC4);
		Ref<ImageTexture> tt = memnew( ImageTexture );
		tt->create_from_image(img);
		tf->set_texture(tt);
		tf->set_pos(Point2(50,50));
		//tf->set_scale(Point2(0.3,0.3));


		return;
#endif

		Tree * tree = memnew( Tree );
		tree->set_columns(2);

		tree->set_pos( Point2( 230,210 ) );
		tree->set_size( Point2( 150,250 ) );


		TreeItem *item = tree->create_item();
		item->set_editable(0,true);
		item->set_text(0,"root");
		item = tree->create_item( tree->get_root() );
		item->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
		item->set_editable(0,true);
		item->set_text(0,"check");
		item->set_cell_mode(1, TreeItem::CELL_MODE_CHECK);
		item->set_editable(1,true);
		item->set_text(1,"check2");
		item = tree->create_item( tree->get_root() );
		item->set_cell_mode(0, TreeItem::CELL_MODE_RANGE);
		item->set_editable(0,true);
		item->set_range_config(0,0,20,0.1);
		item->set_range(0,2);
		item->add_button(0,Theme::get_default()->get_icon("folder","FileDialog"));
		item->set_cell_mode(1, TreeItem::CELL_MODE_RANGE);
		item->set_editable(1,true);
		item->set_range_config(1,0,20,0.1);
		item->set_range(1,3);

		item = tree->create_item( tree->get_root() );
		item->set_cell_mode(0, TreeItem::CELL_MODE_RANGE);
		item->set_editable(0,true);
		item->set_text(0,"Have,Many,Several,Options!");
		item->set_range(0,2);

		item = tree->create_item( item );
		item->set_editable(0,true);
		item->set_text(0,"Gershwin!");

		frame->add_child(tree);

		//control = memnew( Control );
		//root->add_child( control );


		
		LineEdit *line_edit = memnew( LineEdit );
		
		line_edit->set_pos( Point2( 30,190 ) );
		line_edit->set_size( Point2( 180,1 ) );
		
		frame->add_child(line_edit);
		
		HScrollBar *hscroll = memnew( HScrollBar );
		
		hscroll->set_pos( Point2( 30,290 ) );
		hscroll->set_size( Point2( 180,1 ) );
		hscroll->set_max(10);
		hscroll->set_page(4);
		
		frame->add_child(hscroll);



		SpinBox *spin = memnew( SpinBox );

		spin->set_pos( Point2( 30,260 ) );
		spin->set_size( Point2( 120,1 ) );

		frame->add_child(spin);
		hscroll->share(spin);

		ProgressBar *progress = memnew( ProgressBar );

		progress->set_pos( Point2( 30,330 ) );
		progress->set_size( Point2( 120,1 ) );

		frame->add_child(progress);
		hscroll->share(progress);

		MenuButton *menu_button = memnew( MenuButton );
		
		menu_button->set_text("I'm a menu!");
		menu_button->set_pos( Point2( 30,380 ) );
		menu_button->set_size( Point2( 1,1 ) );
		
		frame->add_child(menu_button);		
		
		PopupMenu *popup = menu_button->get_popup();
		
		popup->add_item("Hello, testing");
		popup->add_item("My Dearest");
		popup->add_separator();
		popup->add_item("Popup");
		popup->add_check_item("Check Popup");
		popup->set_item_checked(4,true);		
				
		OptionButton *options = memnew( OptionButton );
		
		options->add_item("Hello, testing");
		options->add_item("My Dearest");
		
		options->set_pos( Point2( 230,180 ) );
		options->set_size( Point2( 1,1 ) );
		
		frame->add_child(options);		

		/*
		Tree * tree = memnew( Tree );
		tree->set_columns(2);
		
		tree->set_pos( Point2( 230,210 ) );
		tree->set_size( Point2( 150,250 ) );


		TreeItem *item = tree->create_item();
		item->set_editable(0,true);
		item->set_text(0,"root");
		item = tree->create_item( tree->get_root() );
		item->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
		item->set_editable(0,true);
		item->set_text(0,"check");
		item = tree->create_item( tree->get_root() );
		item->set_cell_mode(0, TreeItem::CELL_MODE_RANGE);
		item->set_editable(0,true);
		item->set_range_config(0,0,20,0.1);
		item->set_range(0,2);
		item->add_button(0,Theme::get_default()->get_icon("folder","FileDialog"));
		item = tree->create_item( tree->get_root() );
		item->set_cell_mode(0, TreeItem::CELL_MODE_RANGE);
		item->set_editable(0,true);
		item->set_text(0,"Have,Many,Several,Options!");
		item->set_range(0,2);
		
		frame->add_child(tree);
*/


		RichTextLabel *richtext = memnew( RichTextLabel );

		richtext->set_pos( Point2( 600,210 ) );
		richtext->set_size( Point2( 180,250 ) );
		richtext->set_anchor_and_margin(MARGIN_RIGHT,Control::ANCHOR_END,20);

		frame->add_child(richtext);


		richtext->add_text("Hello, My Friends!\n\nWelcome to the amazing world of ");

		richtext->add_newline();
		richtext->add_newline();

		richtext->push_color(Color(1,0.5,0.5));
		richtext->add_text("leprechauns");
		richtext->pop();

		richtext->add_text(" and ");
		richtext->push_color(Color(0,1.0,0.5));
		richtext->add_text("faeries.\n");
		richtext->pop();
		richtext->add_text("In this new episode, we will attemp to ");
		richtext->push_font(richtext->get_font("mono_font","Fonts"));
		richtext->push_color(Color(0.7,0.5,1.0));
		richtext->add_text("deliver something nice");
		richtext->pop();
		richtext->pop();
		richtext->add_text(" to all the viewers! Unfortunately, I need to ");
		richtext->push_underline();
		richtext->add_text("keep writing a lot of text");
		richtext->pop();
		richtext->add_text(" so the label control overflows and the scrollbar appears.\n");
		//richtext->push_indent(1);
		//richtext->add_text("By the way, testing indent levels! Yohohoho! Everything should appear to the right sightly here!\n");
		//richtext->pop();
		richtext->push_meta("http://www.scrollingcapabilities.xz");
		richtext->add_text("This allows to test for the scrolling capabilities ");
		richtext->pop();
		richtext->add_text("of the rich text label for huge text (not like this text will really be huge but, you know).\nAs long as it is so long that it will work nicely for a test/demo, then it's welcomed in my book...\nChanging subject, the day is cloudy today and I'm wondering if I'll get che chance to travel somewhere nice. Sometimes, watching the clouds from satellite images may give a nice insight about how pressure zones in our planet work, althogh it also makes it pretty obvious to see why most weather forecasts get it wrong so often.\nClouds are so difficult to predict!\nBut it's pretty cool how our civilization has adapted to having water falling from the sky each time it rains...");
		//richtext->add_text("Hello!\nGorgeous..");


		//richtext->push_meta("http://www.scrollingcapabilities.xz");
		///richtext->add_text("Hello!\n");
		//richtext->pop();

		richtext->set_anchor(MARGIN_RIGHT,Control::ANCHOR_END);


		TabContainer * tabc = memnew( TabContainer );

		Control *ctl= memnew( Control );
		ctl->set_name("tab 1");
		tabc->add_child(ctl);

		ctl= memnew( Control );
		ctl->set_name("tab 2");
		tabc->add_child(ctl);
		label = memnew( Label );
		label->set_text("Some Label");
		label->set_pos( Point2(20,20) );
		ctl->add_child(label);;

		ctl= memnew( Control );
		ctl->set_name("tab 3");
		button = memnew( Button );
		button->set_text("Some Button");
		button->set_pos( Point2(30,50) );
		ctl->add_child(button);;

		tabc->add_child(ctl);

		frame->add_child(tabc);
		
		tabc->set_pos( Point2( 400,210 ) );
		tabc->set_size( Point2( 180,250 ) );

		
		Ref<ImageTexture> text = memnew( ImageTexture );
		text->load("test_data/concave.png");

		Sprite* sprite = memnew(Sprite);
		sprite->set_texture(text);
		sprite->set_pos(Point2(300, 300));
		frame->add_child(sprite);
		sprite->show();

		Sprite* sprite2 = memnew(Sprite);
		sprite->set_texture(text);
		sprite->add_child(sprite2);
		sprite2->set_pos(Point2(50, 50));
		sprite2->show();
	}
示例#26
0
文件: Ref.hpp 项目: giftnuss/libftl
	inline bool operator<(const Ref& b) const { return *(this->saveGet()) < *(b.saveGet()); }
示例#27
0
void EditorResourcePreview::_thread() {

	//print_line("begin thread");
	while (!exit) {

		//print_line("wait for semaphore");
		preview_sem->wait();
		preview_mutex->lock();

		//print_line("blue team go");

		if (queue.size()) {

			QueueItem item = queue.front()->get();
			queue.pop_front();

			if (cache.has(item.path)) {
				//already has it because someone loaded it, just let it know it's ready
				String path = item.path;
				if (item.resource.is_valid()) {
					path += ":" + itos(cache[item.path].last_hash); //keep last hash (see description of what this is in condition below)
				}

				print_line("cached: " + item.path);
				_preview_ready(path, cache[item.path].preview, item.id, item.function, item.userdata);

				preview_mutex->unlock();
			} else {
				preview_mutex->unlock();

				Ref<ImageTexture> texture;

				//print_line("pop from queue "+item.path);

				int thumbnail_size = EditorSettings::get_singleton()->get("filesystem/file_dialog/thumbnail_size");
				thumbnail_size *= EDSCALE;

				if (item.resource.is_valid()) {

					print_line("generated: " + item.path);

					texture = _generate_preview(item, String());
					//adding hash to the end of path (should be ID:<objid>:<hash>) because of 5 argument limit to call_deferred
					_preview_ready(item.path + ":" + itos(item.resource->hash_edited_version()), texture, item.id, item.function, item.userdata);

				} else {

					print_line("from file: " + item.path);

					String temp_path = EditorSettings::get_singleton()->get_settings_path().plus_file("tmp");
					String cache_base = ProjectSettings::get_singleton()->globalize_path(item.path).md5_text();
					cache_base = temp_path.plus_file("resthumb-" + cache_base);

					//does not have it, try to load a cached thumbnail

					String file = cache_base + ".txt";
					//print_line("cachetxt at "+file);
					FileAccess *f = FileAccess::open(file, FileAccess::READ);
					if (!f) {

						//print_line("generate because not cached");

						//generate
						texture = _generate_preview(item, cache_base);
					} else {

						uint64_t modtime = FileAccess::get_modified_time(item.path);
						int tsize = f->get_line().to_int64();
						uint64_t last_modtime = f->get_line().to_int64();

						bool cache_valid = true;

						if (tsize != thumbnail_size) {

							cache_valid = false;
							memdelete(f);
						} else if (last_modtime != modtime) {

							String last_md5 = f->get_line();
							String md5 = FileAccess::get_md5(item.path);
							memdelete(f);

							if (last_md5 != md5) {

								cache_valid = false;

							} else {
								//update modified time

								f = FileAccess::open(file, FileAccess::WRITE);
								f->store_line(itos(modtime));
								f->store_line(md5);
								memdelete(f);
							}
						} else {
							memdelete(f);
						}

						//cache_valid = false;

						if (cache_valid) {

							Ref<Image> img;
							img.instance();

							if (img->load(cache_base + ".png") != OK) {
								//well f**k
								cache_valid = false;
							} else {

								texture.instance();
								texture->create_from_image(img, Texture::FLAG_FILTER);
							}
						}

						if (!cache_valid) {

							texture = _generate_preview(item, cache_base);
						}
					}

					//print_line("notify of preview ready");
					_preview_ready(item.path, texture, item.id, item.function, item.userdata);
				}
			}

		} else {
			preview_mutex->unlock();
		}
	}
}
示例#28
0
Error ResourceInteractiveLoaderBinary::poll(){

	if (error!=OK)
		return error;


	int s = stage;

	if (s<external_resources.size()) {

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

			if (!ResourceLoader::get_abort_on_missing_resources()) {

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


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

		} else {
			resource_cache.push_back(res);
		}

		stage++;
		return error;
	}

	s-=external_resources.size();


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

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

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

	//maybe it is loaded already
	String path;
	int subindex=0;



	if (!main) {

		path=internal_resources[s].path;
		if (path.begins_with("local://")) {
			path=path.replace_first("local://","");
			subindex = path.to_int();
			path=res_path+"::"+path;
		}



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

		path=res_path;
	}

	uint64_t offset = internal_resources[s].offset;

	f->seek(offset);

	String t = get_unicode_string();

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

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

	RES res = RES( r );

	r->set_path(path);
	r->set_subindex(subindex);

	int pc = f->get_32();

	//set properties

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

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

		Variant value;

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

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

	resource_cache.push_back(res);

	if (main) {
		if (importmd_ofs) {

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

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

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

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

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

	} else {
		error=OK;
	}

	return OK;

}
	void stop() {

		stream->stop();
	};
示例#30
0
RES ResourceFormatLoaderTheme::load(const String &p_path,const String& p_original_path) {

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

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

	bool reading_library=false;
	int line=0;

	while(!f->eof_reached()) {

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

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

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

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


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

		Variant value;

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

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

			}

			value=library[reference];

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

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

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

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

			}

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



			if (type=="icon") {

				String path;

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

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

				value=texture;

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

				String path;

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

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

				value=stylebox;

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

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

				}

				String path=params[0];

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

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

				}

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

				sbtex->set_texture(tex);

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

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

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

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

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

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

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

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

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

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

				}

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

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

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

				}

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

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

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

				}


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

				int ccodes=0;

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

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

				Color normal;
				Color bright;
				Color dark;

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

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

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

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

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

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

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

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

				}


				value=sbflat;

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

			}

		}


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

		if (reading_library) {

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

			library[left]=value;
		} else {

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

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

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

			}

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

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

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

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

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

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

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

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

			} else {

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

		}


	}

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

	return theme;
}