Ejemplo n.º 1
1
 internal RobotCellUR(string name, RobotArm robot, IO io, Plane basePlane, Mesh environment) : base(name, Manufacturers.UR, io, basePlane, environment)
 {
     this.Robot = robot as RobotUR;
     this.DisplayMesh = new Mesh();
     DisplayMesh.Append(robot.DisplayMesh);
     this.DisplayMesh.Transform(this.BasePlane.ToTransform());
 }
Ejemplo n.º 2
0
    void Start ()
    {
        //create vertices and uv array size
        _vertices = new Vector3[24];
        _uv = new Vector2[24];

        //populate hex arrays
        DrawTopAndBottom();
        DrawSides();
        SetTriangles();

        //setup mesh
        Mesh mesh = new Mesh { name = "Hex Mesh" };
        mesh.vertices = _vertices;
        mesh.uv = _uv;
        mesh.triangles = _triangles;
        mesh.normals = _normals;
        GetComponent<MeshFilter>().mesh = mesh;

        //setup collider
        MeshCollider col = GetComponent<MeshCollider>();
        col.sharedMesh = mesh;

        //setup renderer
        Renderer renderer = GetComponent<Renderer>();
        renderer.material.shader = Shader.Find("Diffuse");
        renderer.material.mainTexture = texture;
        _originalColor = renderer.material.color;
        _hoverColor = Color.green;
    }
Ejemplo n.º 3
0
    public void DrawAttkBox(SPoint[] v, string mat, int n, int endN, SPoint p, int pNum,  int t, int poly)
    {
        //specialized manual function for attackboxes
        subMesh [poly] = new Mesh ();
        int vTot = endN - n + 1;
        Vector3[] vertices = new Vector3[vTot];
        Color32[] col = new Color32[vTot];

        //std::stringstream hbName;
        string hbName = "P#" + pNum + "HB-" + t + "-" + poly;

        for (int i = n; i <= endN; i++) {
            vertices [i-n] = new Vector3 (v [i].x + p.x, v [i].y + p.y, 0);
            col [i-n] = new Color32 (0, 250, 20, 150);
        }
        int tTot = (vTot - 2) * 3;
        int[] tri = new int[tTot];
        for (int i = 0; i<(tTot/3);i++) {//triangle fan
            tri[i*3]=0;
            tri[(i*3)+1]=i+1;
            tri[(i*3)+2]=i+2;
        }
        subMesh[poly].vertices=vertices;
        subMesh[poly].triangles = tri;
        subMesh[poly].colors32 = col;
    }
Ejemplo n.º 4
0
 public override void Prepare(Mesh mesh)
 {
   base.Prepare(mesh);
   if (mesh.CustomData == null)
     return;
   this.nextFrameTextureMatrix.Set((Matrix) mesh.CustomData);
 }
	public void Initialize (Mesh mesh, Material[] materials, Color32 color, bool additive, float speed, int sortingLayerID, int sortingOrder) {
		StopAllCoroutines();

		gameObject.SetActive(true);


		meshRenderer.sharedMaterials = materials;
		meshRenderer.sortingLayerID = sortingLayerID;
		meshRenderer.sortingOrder = sortingOrder;

		meshFilter.sharedMesh = (Mesh)Instantiate(mesh);

		colors = meshFilter.sharedMesh.colors32;

		if ((color.a + color.r + color.g + color.b) > 0) {
			for (int i = 0; i < colors.Length; i++) {
				colors[i] = color;
			}
		}

		fadeSpeed = speed;

		if (additive)
			StartCoroutine(FadeAdditive());
		else
			StartCoroutine(Fade());
	}
Ejemplo n.º 6
0
    private void Start()
    {
        mesh = new Mesh();
        GetComponent<MeshFilter>().mesh = mesh;

        CreateMesh();
    }
        public void getCenter(Mesh m)
        {
            double minX=9999, minY=9999, maxX=-9999, maxY=-9999;
            foreach (Zone z in m.Zones)
            {
                foreach (Face f in z.Faces)
                {
                    foreach (uint _edge in f.Edges)
                    {
                        Edge __edge = z.Edges[_edge];
                        if (z.Vertices[__edge.Start].Position.x < minX)
                        {
                            minX = z.Vertices[__edge.Start].Position.x;
                        }
                        if (z.Vertices[__edge.Start].Position.x > maxX)
                        {
                            maxX = z.Vertices[__edge.Start].Position.x;
                        }
                        if (z.Vertices[__edge.Start].Position.y < minY)
                        {
                            minY = z.Vertices[__edge.Start].Position.y;
                        }
                        if (z.Vertices[__edge.Start].Position.y > maxY)
                        {
                            maxY = z.Vertices[__edge.Start].Position.y;
                        }
                    }
                }
            }
            centerX = (maxX + minX) / 2;
            centerY = (maxY + minY) / 2;

        }
    public virtual void Reset()
    {
        if (meshFilter != null) meshFilter.sharedMesh = null;
        if (mesh != null) DestroyImmediate(mesh);
        if (renderer != null) renderer.sharedMaterial = null;
        mesh = null;
        mesh1 = null;
        mesh2 = null;
        lastVertexCount = 0;
        vertices = null;
        colors = null;
        uvs = null;
        sharedMaterials = new Material[0];
        submeshMaterials.Clear();
        submeshes.Clear();
        valid = false;

        if(skeleton==null)
        {
            return;
        }
        valid = true;
        meshFilter = GetComponent<MeshFilter>();
        mesh1 = newMesh();
        mesh2 = newMesh();
        vertices = new Vector3[0];

        if (initialSkinName != null && initialSkinName.Length > 0 && initialSkinName != "default")
            skeleton.SetSkin(initialSkinName);
    }
    public void ManualUpdate(Mesh mesh, Material outerMaterial, float outerScale)
    {
        if (Corona != null)
        {
            if (MeshFilter == null) MeshFilter = gameObject.AddComponent<MeshFilter>();

            if (MeshRenderer == null) MeshRenderer = gameObject.AddComponent<MeshRenderer>();

            if (MeshFilter.sharedMesh != mesh)
            {
                SgtHelper.BeginStealthSet(MeshFilter);
                {
                    MeshFilter.sharedMesh = mesh;
                }
                SgtHelper.EndStealthSet();
            }

            if (MeshRenderer.sharedMaterial != outerMaterial)
            {
                SgtHelper.BeginStealthSet(MeshRenderer);
                {
                    MeshRenderer.sharedMaterial = outerMaterial;
                }
                SgtHelper.EndStealthSet();
            }

            SgtHelper.SetLocalScale(transform, outerScale);
        }
    }
Ejemplo n.º 10
0
    public void BakePatternDesign()
    {
        List<InstanceData> positions = GeneratePositions();

        lastCount = positions.Count;
        var lastBuiltMesh = BakeMesh(positions.ToArray());

        #if UNITY_EDITOR
        string assetPath;

        if (generatedBakedMesh != null)
        {
            assetPath = UnityEditor.AssetDatabase.GetAssetPath(generatedBakedMesh);
        }
        else
        {
            assetPath = UnityEditor.AssetDatabase.GenerateUniqueAssetPath("Assets/AsteroidBelt.asset");
        }

        UnityEditor.AssetDatabase.CreateAsset(lastBuiltMesh, assetPath);
        UnityEditor.AssetDatabase.Refresh(UnityEditor.ImportAssetOptions.Default);
        UnityEditor.AssetDatabase.SaveAssets();

        generatedBakedMesh = UnityEditor.AssetDatabase.LoadAssetAtPath<Mesh>(assetPath);
        #endif
    }
Ejemplo n.º 11
0
 public override void Prepare(Mesh mesh)
 {
   base.Prepare(mesh);
   this.material.Diffuse = mesh.Material.Diffuse;
   this.material.Opacity = mesh.Material.Opacity;
   this.texture.Set((Texture) mesh.Texture);
 }
Ejemplo n.º 12
0
 public void Setup(Mesh m)
 {
     for (int index = 0; index < m.SubMeshes.Count; index++)
     {
         addSubMeshFunc(m.SubMeshes[index]);
     }
 }
Ejemplo n.º 13
0
  public void OnTriggerEnter(Collider c)
  {
    if (c.tag == "Player")
    {
      Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
      float playAreaDistance;
      playArea.Raycast(ray, out playAreaDistance);
      enterPoint = ray.GetPoint(playAreaDistance);

      SkinnedMeshRenderer skinnedMeshRenderer = GetComponent<SkinnedMeshRenderer>();
      if (skinnedMeshRenderer != null)
      {
        Mesh mesh = new Mesh();
        skinnedMeshRenderer.BakeMesh(mesh);
        Destroy(skinnedMeshRenderer);
        Destroy(GetComponent<Animator>());

        MeshRenderer renderer = gameObject.AddComponent<MeshRenderer>();
        MeshFilter meshFilter = gameObject.AddComponent<MeshFilter>();
        meshFilter.sharedMesh = mesh;
        renderer.material = bloodMaterial;
        transform.localScale = new Vector3(1, 1, 1);
      }
    }
  }
Ejemplo n.º 14
0
        /// <summary>
        /// Gets the permutation vector for the Reverse Cuthill-McKee numbering.
        /// </summary>
        /// <param name="mesh">The mesh.</param>
        /// <returns>Permutation vector.</returns>
        public int[] Renumber(Mesh mesh)
        {
            // Algorithm needs linear numbering of the nodes.
            mesh.Renumber(NodeNumbering.Linear);

            return Renumber(new AdjacencyMatrix(mesh));
        }
    private Mesh Generate()
    {
        Debug.Assert(starCount < 65536, "Number of stars must less than 65536");

        var random = new System.Random(seed);

        var mesh = new Mesh();
        var vertices = new Vector3[starCount];
        var indices = new int[starCount];
        var colors = new Color[starCount];

        for (var i = 0; i < starCount; ++i)
        {
            vertices[i] = random.OnUnitSphere();

            indices[i] = i;

            colors[i] = starColors[random.Next(starColors.Length)];
            colors[i].a = (0.2f + 0.8f * MathUtils.NextFloat(random)) * (1 - (Mathf.Abs(vertices[i].y)));
        }

        mesh.vertices = vertices;
        mesh.colors = colors;
        mesh.SetIndices(indices, MeshTopology.Points, 0);

        return mesh;
    }
Ejemplo n.º 16
0
 public override void Prepare(Mesh mesh)
 {
   base.Prepare(mesh);
   this.randomSeed.Set(new Vector3(RandomHelper.Unit(), RandomHelper.Unit(), RandomHelper.Unit()));
   this.material.Diffuse = mesh.Material.Diffuse;
   this.material.Opacity = mesh.Material.Opacity;
 }
Ejemplo n.º 17
0
	// Generate the mesh surface according to the correct dimensions
	private void Generate()
	{
		GetComponent<MeshFilter>().mesh = waveMesh = new Mesh ();
		waveMesh.name = "Ocean Surface";

		vertices = new Vector3[(xSize + 1) * (zSize + 1)];

		for (int i = 0, y = 0; i <= xSize; i++) 
		{
			for (int j = 0; j <= zSize; j++, y++) 
			{
				vertices [y] = new Vector3 (j, 0, i);
			}
		}

		waveMesh.vertices = vertices;

		int[] triangles = new int[xSize * zSize * 6];
		for(int ti = 0, ve = 0, z = 0; z < zSize; z++, ve++){
			for(int x = 0; x < xSize; x++, ti+=6, ve++){
				triangles [ti] = ve;
				triangles [ti+1] = triangles[ti+4] = ve+ xSize+1;
				triangles [ti+2] = triangles[ti+3] = ve+ 1;
				triangles [ti+5] = ve + xSize + 2;
				waveMesh.triangles = triangles;
				waveMesh.RecalculateNormals ();
			}
		}
	} // end Generate
Ejemplo n.º 18
0
        /// <summary>
        /// Generate the Voronoi diagram from given triangle mesh..
        /// </summary>
        /// <param name="mesh"></param>
        /// <param name="bounded"></param>
        protected void Generate(Mesh mesh)
        {
            mesh.Renumber();

            base.edges = new List<HalfEdge>();
            this.rays = new List<HalfEdge>();

            // Allocate space for Voronoi diagram.
            var vertices = new Vertex[mesh.triangles.Count + mesh.hullsize];
            var faces = new Face[mesh.vertices.Count];

            if (factory == null)
            {
                factory = new DefaultVoronoiFactory();
            }

            factory.Initialize(vertices.Length, 2 * mesh.NumberOfEdges, faces.Length);

            // Compute triangles circumcenters.
            var map = ComputeVertices(mesh, vertices);

            // Create all Voronoi faces.
            foreach (var vertex in mesh.vertices.Values)
            {
                faces[vertex.id] = factory.CreateFace(vertex);
            }

            ComputeEdges(mesh, vertices, faces, map);

            // At this point all edges are computed, but the (edge.next) pointers aren't set.
            ConnectEdges(map);

            base.vertices = new List<Vertex>(vertices);
            base.faces = new List<Face>(faces);
        }
Ejemplo n.º 19
0
		public void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material)
		{
			MaterialPropertyBlock properties = null;
			int shaderPass = -1;
			int submeshIndex = 0;
			CommandBuffer.INTERNAL_CALL_DrawMesh(this, mesh, ref matrix, material, submeshIndex, shaderPass, properties);
		}
Ejemplo n.º 20
0
    void Awake()
    {
        gradientLayer = Mathf.Clamp(gradientLayer, 0, 31);
        if (!camera)
        {
            Debug.LogError("Must attach GradientBackground script to the camera");
            return;
        }

        camera.clearFlags = CameraClearFlags.Depth;
        camera.cullingMask = camera.cullingMask & ~(1 << gradientLayer);
        Camera gradientCam = new GameObject("Gradient Cam", typeof(Camera)).camera;
        gradientCam.depth = camera.depth - 1;
        gradientCam.cullingMask = 1 << gradientLayer;

        Mesh mesh = new Mesh();
        mesh.vertices = new Vector3[4] { new Vector3(-100f, .577f, 1f), new Vector3(100f, .577f, 1f), new Vector3(-100f, -.577f, 1f), new Vector3(100f, -.577f, 1f) };

        mesh.colors = new Color[4] { topColor, topColor, bottomColor, bottomColor };

        mesh.triangles = new int[6] { 0, 1, 2, 1, 3, 2 };

        Material mat = new Material("Shader \"Vertex Color Only\"{Subshader{BindChannels{Bind \"vertex\", vertex Bind \"color\", color}Pass{}}}");
        GameObject gradientPlane = new GameObject("Gradient Plane", typeof(MeshFilter), typeof(MeshRenderer));

        ((MeshFilter)gradientPlane.GetComponent(typeof(MeshFilter))).mesh = mesh;
        gradientPlane.renderer.material = mat;
        gradientPlane.layer = gradientLayer;
    }
Ejemplo n.º 21
0
 private static void GenerateMesh(Mesh mesh)
 {
     int num = 1;
     Vector3[] array = new Vector3[4 * num];
     Vector2[] array2 = new Vector2[4 * num];
     int[] array3 = new int[6 * num];
     for (int i = 0; i < num; i++)
     {
         Vector3 zero = Vector3.zero;
         int num2 = 4 * i;
         array[num2] = zero;
         array[num2 + 1] = zero;
         array[num2 + 2] = zero;
         array[num2 + 3] = zero;
         array2[num2] = new Vector2(0f, 0f);
         array2[num2 + 1] = new Vector2(0f, 1f);
         array2[num2 + 2] = new Vector2(1f, 0f);
         array2[num2 + 3] = new Vector2(1f, 1f);
         int num3 = 6 * i;
         array3[num3] = 0 + num2;
         array3[num3 + 1] = 1 + num2;
         array3[num3 + 2] = 2 + num2;
         array3[num3 + 3] = 2 + num2;
         array3[num3 + 4] = 1 + num2;
         array3[num3 + 5] = 3 + num2;
     }
     mesh.vertices = array;
     mesh.uv = array2;
     mesh.triangles = array3;
     mesh.RecalculateNormals();
     mesh.bounds = new Bounds(Vector3.zero, Vector3.one);
     mesh.Optimize();
 }
Ejemplo n.º 22
0
    public void Rebuild()
    {
        MeshFilter mf = GetComponent<MeshFilter>();

        if ( mf != null )
        {
            Mesh mesh = mf.sharedMesh;	//Utils.GetMesh(gameObject);

            if ( mesh == null )
            {
                mesh = new Mesh();
                mf.sharedMesh = mesh;
            }

            if ( mesh != null )
            {
                BuildMesh(mesh);
                MegaModifyObject mo = GetComponent<MegaModifyObject>();
                if ( mo != null )
                {
                    mo.MeshUpdated();
                }
            }
        }
    }
Ejemplo n.º 23
0
 void OnGUI()
 {
     if(obj) {
         if(mesh) {
             p.x = EditorGUILayout.Slider("X", p.x, -1.0f, 1.0f);
             p.y = EditorGUILayout.Slider("Y", p.y, -1.0f, 1.0f);
             p.z = EditorGUILayout.Slider("Z", p.z, -1.0f, 1.0f);
             if(p != last_p) { //Detects user input on any of the three sliders
                 //Only create instance of mesh when user changes pivot
                 if(pivotUnchanged) mesh = meshFilter.mesh; pivotUnchanged = false;
                 UpdatePivot();
                 last_p = p;
             }
             if(GUILayout.Button("Center")) { //Set pivot to the center of the mesh bounds
                 //Only create instance of mesh when user changes pivot
                 if(pivotUnchanged) mesh = meshFilter.mesh; pivotUnchanged = false;
                 p = Vector3.zero;
                 UpdatePivot();
                 last_p = p;
             }
             GUILayout.Label("Bounds " + mesh.bounds.ToString());
         } else {
             GUILayout.Label("Selected object does not have a Mesh specified.");
         }
     } else {
         GUILayout.Label("No object selected in Hierarchy.");
     }
 }
    void Start()
    {
        // Create Vector2 vertices
        Vector3[] vertices3D = new Vector3[] {
            new Vector3(5, 10, 0),
            new Vector3(10, -5, 0),
            new Vector3(-7, -3, 0),
            new Vector3(-2, -8, 0),
            new Vector3(9, -10, 0),
        };

        // Use the triangulator to get indices for creating triangles
        MidpointTriangulator tr = new MidpointTriangulator(vertices3D);

        Vector3[] vertices = tr.Triangulate().ToArray();
        int[] indices = new int[vertices.Length];

        // Create the Vector3 vertices
        for (int i = 0; i < vertices.Length; i++)
        {
          indices[i] = i;
        }

        // Create the mesh
        Mesh msh = new Mesh();
        msh.vertices = vertices;
        msh.triangles = indices;
        msh.RecalculateNormals();
        msh.RecalculateBounds();

        // Set up game object with mesh;
        MeshFilter filter = gameObject.AddComponent(typeof(MeshFilter)) as MeshFilter;
        filter.mesh = msh;
    }
Ejemplo n.º 25
0
    static void CreateQuad(Mesh mesh, float W, float H)
    {
        Vector3[] verts = new Vector3[4];
        Vector2[] uvs = new Vector2[4];

        verts[0] = new Vector3(-W/2, H/2, 0);
        verts[1] = new Vector3(W/2, H/2, 0);
        verts[2] = new Vector3(W/2, -H/2, 0);
        verts[3] = new Vector3(-W/2, -H/2, 0);

        uvs[0] = new Vector2(0, 1);
        uvs[1] = new Vector2(1, 1);
        uvs[2] = new Vector3(1, 0);
        uvs[3] = new Vector3(0, 0);

        int[] triangles = new int[6];
        triangles[0] = 0;
        triangles[1] = 1;
        triangles[2] = 3;
        triangles[3] = 3;
        triangles[4] = 1;
        triangles[5] = 2;

        mesh.Clear();
        mesh.vertices = verts;
        mesh.uv = uvs;
        mesh.triangles = triangles;
    }
Ejemplo n.º 26
0
        public virtual void encode(Mesh m, CtmOutputStream output)
        {
            int vc = m.getVertexCount();

            output.writeLittleInt(MeshDecoder.INDX);
            writeIndicies(m.indices, output);

            output.writeLittleInt(MeshDecoder.VERT);
            writeFloatArray(m.vertices, output, vc * 3, 1);

            // Write normals
            if (m.normals != null) {
                output.writeLittleInt(MeshDecoder.NORM);
                writeFloatArray(m.normals, output, vc, 3);
            }

            foreach (AttributeData ad in m.texcoordinates) {
                output.writeLittleInt(MeshDecoder.TEXC);
                output.writeString(ad.name);
                output.writeString(ad.materialName);
                writeFloatArray(ad.values, output, vc, 2);
            }

            foreach (AttributeData ad in m.attributs) {
                output.writeLittleInt(MeshDecoder.ATTR);
                output.writeString(ad.name);
                writeFloatArray(ad.values, output, vc, 4);
            }
        }
Ejemplo n.º 27
0
    public void createCylinder(float radius, float height, int slices, GameObject go, Matrix4x4 matrix)
    {
        Mesh cylinderMesh = new Mesh();
        vertices = new Vector3[(slices+1) * 4];
        Vector3[] cylPoints1 = createCylinderPoints(radius, height, slices, true);
        Vector3[] cylPoints2 = createCylinderPoints(radius, height, slices, false);
        for (int i = 0; i <cylPoints1.Length; i++) {
            vertices[i] = cylPoints1[i];
        }
        for (int k = 0; k < cylPoints2.Length; k++) {
            vertices[k + cylPoints1.Length] = cylPoints2[k];
        }

        createCylinderNormals(vertices, radius);
        for (int j = 0; j < vertices.Length; j++) {
            vertices[j] = matrix.MultiplyPoint(vertices[j]);
            normals[j] = matrix.MultiplyPoint(normals[j]);
        }

        trianglesIndex = 0;
        createCylinderTriangles(slices+1);

        cylinderMesh.vertices = vertices;
        cylinderMesh.triangles = triangles;
        cylinderMesh.normals = normals;
        cylinderMesh.uv = uvs;

        MeshFilter filter = (MeshFilter)go.GetComponent("MeshFilter");
        filter.mesh = cylinderMesh;
    }
Ejemplo n.º 28
0
 public void MakeCircle(int numOfPoints)
 {
     //Debug.Log(numOfPoints + " --- " + AudioToWave.currentValue);
     float angleStep = 360.0f / (float)numOfPoints;
     List<Vector3> vertexList = new List<Vector3>();
     List<int> triangleList = new List<int>();
     Quaternion quaternion = Quaternion.Euler(0.0f, 0.0f, angleStep);
     // Make first triangle.
     vertexList.Add(new Vector3(0.0f, 0.0f, 10f));  // 1. Circle center.
     vertexList.Add(new Vector3(0.0f, 0.5f, 10f));  // 2. First vertex on circle outline (radius = 0.5f)
     vertexList.Add(quaternion * vertexList[1]);     // 3. First vertex on circle outline rotated by angle)
                                                     // Add triangle indices.
     triangleList.Add(0);
     triangleList.Add(1);
     triangleList.Add(2);
     for (int i = 0; i < numOfPoints - 1; i++)
     {
         triangleList.Add(0);                      // Index of circle center.
         triangleList.Add(vertexList.Count - 1);
         triangleList.Add(vertexList.Count);
         vertexList.Add(quaternion * vertexList[vertexList.Count - 1]);
     }
     Mesh mesh = new Mesh();
     mesh.vertices = vertexList.ToArray();
     mesh.triangles = triangleList.ToArray();
     mf.mesh = mesh;
 }
Ejemplo n.º 29
0
    // Use this for initialization
    void Start()
    {
        theTarget = building1;

        initialMesh = building1.GetComponent<MeshFilter>().mesh;
        swapMesh = building1alt.GetComponent<MeshFilter>().mesh;
    }
Ejemplo n.º 30
0
    void Awake()
    {
        if (mesh == null)
            mesh = new Mesh();
        mf.sharedMesh = mesh;
        mr.sharedMaterial = material;
        var verts = new Vector3[4];
        var tris = new int[] {0, 1, 2, 0, 2, 3};
        var uvs = new Vector2[4];
        verts[0] = targetPosition - size;
        verts[1] = targetPosition + Vector3.up * size.y - Vector3.right * size.x;
        verts[2] = targetPosition + size;
        verts[3] = targetPosition - Vector3.up * size.y + Vector3.right * size.x;

        uvs[0] = new Vector2(0, 0);
        uvs[1] = new Vector2(0, size.y);
        uvs[2] = new Vector2(size.x, size.y);
        uvs[3] = new Vector2(size.x, 0);

        mesh.vertices = verts;
        mesh.triangles = tris;
        mesh.uv = uvs;

        if (!underGround) {
            var bc = gameObject.GetComponent<BoxCollider2D>();
            bc.size = size * 2f;
        }
    }
Ejemplo n.º 31
0
        private void createFrustum(float width, float height, float distance)
        {
            MeshCollider collider = this.gameObject.AddComponent <MeshCollider>();

            collider.convex    = true;
            collider.isTrigger = true;

            Mesh colliderMesh;

            colliderMesh      = new Mesh();
            colliderMesh.name = "Frustum Mesh";

            Vector3[] frustumOriginPlane = new Vector3[4];
            frustumOriginPlane[0] = new Vector3(-width * 0.1f, height * 0.1f, 0);
            frustumOriginPlane[1] = new Vector3(width * 0.1f, height * 0.1f, 0);
            frustumOriginPlane[2] = new Vector3(-width * 0.1f, -height * 0.1f, 0);
            frustumOriginPlane[3] = new Vector3(width * 0.1f, -height * 0.1f, 0);

            Vector3[] frustumDistantPlane = new Vector3[4];
            frustumDistantPlane[0] = new Vector3(-width, height, distance);
            frustumDistantPlane[1] = new Vector3(width, height, distance);
            frustumDistantPlane[2] = new Vector3(-width, -height, distance);
            frustumDistantPlane[3] = new Vector3(width, -height, distance);

            colliderMesh.vertices = new Vector3[]
            {
                // bottom plane
                frustumDistantPlane[2], frustumDistantPlane[3], frustumOriginPlane[3], frustumOriginPlane[2],
                // left plane
                frustumOriginPlane[0], frustumDistantPlane[0], frustumDistantPlane[2], frustumOriginPlane[2],
                // front  plane - Distant
                frustumDistantPlane[0], frustumDistantPlane[1], frustumDistantPlane[3], frustumDistantPlane[2],
                // back  plane - Origin
                frustumOriginPlane[1], frustumOriginPlane[0], frustumOriginPlane[2], frustumOriginPlane[3],
                // right plane
                frustumDistantPlane[1], frustumOriginPlane[1], frustumOriginPlane[3], frustumDistantPlane[3],
                // top plane
                frustumOriginPlane[0], frustumOriginPlane[1], frustumDistantPlane[1], frustumDistantPlane[0]
            };

            colliderMesh.triangles = new int[]
            {
                // Bottom
                3, 1, 0,
                3, 2, 1,

                // Left
                3 + 4 * 1, 1 + 4 * 1, 0 + 4 * 1,
                3 + 4 * 1, 2 + 4 * 1, 1 + 4 * 1,

                // Front
                3 + 4 * 2, 1 + 4 * 2, 0 + 4 * 2,
                3 + 4 * 2, 2 + 4 * 2, 1 + 4 * 2,

                // Back
                3 + 4 * 3, 1 + 4 * 3, 0 + 4 * 3,
                3 + 4 * 3, 2 + 4 * 3, 1 + 4 * 3,

                // Right
                3 + 4 * 4, 1 + 4 * 4, 0 + 4 * 4,
                3 + 4 * 4, 2 + 4 * 4, 1 + 4 * 4,

                // Top
                3 + 4 * 5, 1 + 4 * 5, 0 + 4 * 5,
                3 + 4 * 5, 2 + 4 * 5, 1 + 4 * 5,
            };

            collider.sharedMesh = colliderMesh;
        }
Ejemplo n.º 32
0
    static Mesh GenIcosahedron(string name, VertexAttributeDescriptor[] attribs, bool multiSubmeshes, bool linesTopology)
    {
        var m = new Mesh();
        m.name = "Ico" + name;
        var t = (1f + Mathf.Sqrt(5f)) / 2f;
        var verts = new[]
        {
            new Vector3(-1,+t,0),
            new Vector3(+1,+t,0),
            new Vector3(-1,-t,0),
            new Vector3(+1,-t,0),
            
            new Vector3(0,-1,+t),
            new Vector3(0,+1,+t),
            new Vector3(0,-1,-t),
            new Vector3(0,+1,-t),
            
            new Vector3(+t,0,-1),
            new Vector3(+t,0,+1),
            new Vector3(-t,0,-1),
            new Vector3(-t,0,+1),
        };
        var indices = new[] {
            0, 11, 5,
            0, 5, 1,
            0, 1, 7,
            0, 7, 10,
            0, 10, 11,
            1, 5, 9,
            5, 11, 4,
            11, 10, 2,
            10, 7, 6,
            7, 1, 8,
            3, 9, 4,
            3, 4, 2,
            3, 2, 6,
            3, 6, 8,
            3, 8, 9,
            4, 9, 5,
            2, 4, 11,
            6, 2, 10,
            8, 6, 7,
            9, 8, 1,
        };
        m.vertices = verts;
        m.triangles = indices;

        if (multiSubmeshes)
        {
            m.subMeshCount = 4;
            m.SetTriangles(indices.Skip(0).Take(15).ToArray(), 0);
            m.SetTriangles(indices.Skip(15).Take(15).ToArray(), 1);
            m.SetTriangles(indices.Skip(30).Take(15).ToArray(), 2);
            m.SetTriangles(indices.Skip(45).Take(15).ToArray(), 3);
        }
        if (attribs.Any(e => e.attribute == VertexAttribute.TexCoord0))
            m.uv = verts.Select(v => new Vector2(v.x*0.5f, v.y*0.5f)).ToArray();
        if (attribs.Any(e => e.attribute == VertexAttribute.TexCoord1))
            m.uv2 = verts.Select(v => new Vector2(v.x*0.3f, v.z*0.3f)).ToArray();
        m.RecalculateNormals();
        m.RecalculateTangents();
        if (attribs.Any(e => e.attribute == VertexAttribute.Color))
            m.colors = m.normals.Select(v => new Color(-v.x*0.5f+0.5f, Mathf.Cos(v.y*7f)*0.5f+0.5f, Mathf.Sin(v.z*5f)*0.5f+0.5f, 0.5f)).ToArray();
        
        m.SetVertexBufferParams(m.vertexCount, attribs);

        if (linesTopology)
        {
            var lines = new List<int>();
            for (var i = 0; i < indices.Length; i += 3)
            {
                var i0 = indices[i + 0];
                var i1 = indices[i + 1];
                var i2 = indices[i + 2];
                lines.AddRange(new[]{i0,i1, i1,i2, i2,i0});
            }
            m.SetIndices(lines, MeshTopology.Lines, 0);
        }
        return m;
    }
Ejemplo n.º 33
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            System.Reflection.Assembly         assembly = System.Reflection.Assembly.GetExecutingAssembly();
            System.Diagnostics.FileVersionInfo fvi      = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location);
            string version = fvi.FileVersion;

            Rhino.RhinoApp.WriteLine("Minimal surface component, version " + version);
            Rhino.RhinoApp.WriteLine("GPLv3 licensed, source: https://github.com/Mathias-Fuchs/MinimalSurface");
            Rhino.RhinoApp.WriteLine("Copyright Mathias Fuchs 2020 - 2021, https://mathiasfuchs.com");

            Curve  tc = null;
            int    nrBoundaryVertices = 0;
            int    degree             = 0;
            double angle = 0;

            DA.GetData(0, ref tc);
            DA.GetData(1, ref nrBoundaryVertices);
            DA.GetData(2, ref degree);
            DA.GetData(3, ref angle);

            if (tc == null || !tc.IsValid || !tc.IsClosed)
            {
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Input curve is either unvalid or not closed!"); return;
            }

            Curve _targetCurve = tc;

            // number of control points, tells about the complexity of the curve
            int nrCont = _targetCurve.ToNurbsCurve().Points.Count;
            int crDeg  = _targetCurve.Degree;

            // if degree isn't specified, use this heuristic
            // computationally, 25 is always doable, and more than 300 doesn't usually make sense
            if (degree == 0)
            {
                degree = Math.Min(Math.Max(25, nrCont * crDeg), 300);
            }

            //  number of boundary subdivisions for computation of the polynomials
            int _n = 23 * degree;

            double[] t             = _targetCurve.DivideByCount(_n, true);
            var      _targetPoints = Enumerable.Range(0, _n).Select(i => _targetCurve.PointAt(t[(i + (int)(angle / Math.PI / 2.0 * _n)) % _n])).ToList();

            // now, do the actual work and compute the three complex polynomials
            // ok, let's get the coefficients
            List <double> xs1 = _targetPoints.Select(o => o.X).ToList(); // 1 ms
            LaplaceData   kx  = new LaplaceData(xs1, degree);

            List <double> ys1 = _targetPoints.Select(o => o.Y).ToList(); // 1 ms
            LaplaceData   ky  = new LaplaceData(ys1, degree);

            List <double> zs1 = _targetPoints.Select(o => o.Z).ToList(); // 1 ms
            LaplaceData   kkz = new LaplaceData(zs1, degree);

            var c  = new Circle(1.0);
            var kk = MeshingParameters.Default;

            kk.MinimumEdgeLength = 2 * Math.PI / (double)nrBoundaryVertices;
            kk.MaximumEdgeLength = 2 * Math.PI / (double)nrBoundaryVertices * 2;
            var MM = Mesh.CreateFromPlanarBoundary(c.ToNurbsCurve(), kk, DocumentTolerance());

            var MMM = new Mesh();
            var mvl = MM.Vertices.Select(pp =>
            {
                var p = new Point2d(pp.X, pp.Y);
                return(new Point3d(kx.eval(p), ky.eval(p), kkz.eval(p)));
            }
                                         );

            // bottleneck
            MMM.Vertices.Capacity = MM.Vertices.Count;
            MMM.Vertices.AddVertices(mvl);
            MMM.Faces.Capacity = MM.Faces.Count;
            MMM.Faces.AddFaces(MM.Faces);

            if (MMM.Faces.GetClashingFacePairs(1).Any())
            {
                this.AddRuntimeMessage(
                    GH_RuntimeMessageLevel.Warning,
                    "The resulting mesh has self-intersections. Modifying the rotation angle input parameter can solve this.");
            }
            DA.SetData(0, MMM);
        }
Ejemplo n.º 34
0
	public void UpdateModel()
	{
		this.fovLeft = Mathf.Clamp(this.fovLeft, 1f, 89f);
		this.fovRight = Mathf.Clamp(this.fovRight, 1f, 89f);
		this.fovTop = Mathf.Clamp(this.fovTop, 1f, 89f);
		this.fovBottom = Mathf.Clamp(this.fovBottom, 1f, 89f);
		this.farZ = Mathf.Max(this.farZ, this.nearZ + 0.01f);
		this.nearZ = Mathf.Clamp(this.nearZ, 0.01f, this.farZ - 0.01f);
		float num = Mathf.Sin(-this.fovLeft * 0.0174532924f);
		float num2 = Mathf.Sin(this.fovRight * 0.0174532924f);
		float num3 = Mathf.Sin(this.fovTop * 0.0174532924f);
		float num4 = Mathf.Sin(-this.fovBottom * 0.0174532924f);
		float num5 = Mathf.Cos(-this.fovLeft * 0.0174532924f);
		float num6 = Mathf.Cos(this.fovRight * 0.0174532924f);
		float num7 = Mathf.Cos(this.fovTop * 0.0174532924f);
		float num8 = Mathf.Cos(-this.fovBottom * 0.0174532924f);
		Vector3[] array = new Vector3[]
		{
			new Vector3(num * this.nearZ / num5, num3 * this.nearZ / num7, this.nearZ),
			new Vector3(num2 * this.nearZ / num6, num3 * this.nearZ / num7, this.nearZ),
			new Vector3(num2 * this.nearZ / num6, num4 * this.nearZ / num8, this.nearZ),
			new Vector3(num * this.nearZ / num5, num4 * this.nearZ / num8, this.nearZ),
			new Vector3(num * this.farZ / num5, num3 * this.farZ / num7, this.farZ),
			new Vector3(num2 * this.farZ / num6, num3 * this.farZ / num7, this.farZ),
			new Vector3(num2 * this.farZ / num6, num4 * this.farZ / num8, this.farZ),
			new Vector3(num * this.farZ / num5, num4 * this.farZ / num8, this.farZ)
		};
		int[] array2 = new int[]
		{
			0,
			4,
			7,
			0,
			7,
			3,
			0,
			7,
			4,
			0,
			3,
			7,
			1,
			5,
			6,
			1,
			6,
			2,
			1,
			6,
			5,
			1,
			2,
			6,
			0,
			4,
			5,
			0,
			5,
			1,
			0,
			5,
			4,
			0,
			1,
			5,
			2,
			3,
			7,
			2,
			7,
			6,
			2,
			7,
			3,
			2,
			6,
			7
		};
		int num9 = 0;
		Vector3[] array3 = new Vector3[array2.Length];
		Vector3[] array4 = new Vector3[array2.Length];
		for (int i = 0; i < array2.Length / 3; i++)
		{
			Vector3 vector = array[array2[i * 3]];
			Vector3 vector2 = array[array2[i * 3 + 1]];
			Vector3 vector3 = array[array2[i * 3 + 2]];
			Vector3 normalized = Vector3.Cross(vector2 - vector, vector3 - vector).normalized;
			array4[i * 3] = normalized;
			array4[i * 3 + 1] = normalized;
			array4[i * 3 + 2] = normalized;
			array3[i * 3] = vector;
			array3[i * 3 + 1] = vector2;
			array3[i * 3 + 2] = vector3;
			array2[i * 3] = num9++;
			array2[i * 3 + 1] = num9++;
			array2[i * 3 + 2] = num9++;
		}
		Mesh mesh = new Mesh();
		mesh.vertices = array3;
		mesh.normals = array4;
		mesh.triangles = array2;
		base.GetComponent<MeshFilter>().mesh = mesh;
	}
Ejemplo n.º 35
0
    private void LateUpdate()
    {
        Mesh Vollider = gameObject.GetComponent <MeshCollider>().sharedMesh;

        Vollider.vertices = vertices;
    }
Ejemplo n.º 36
0
    private void GenerateRoadParts(Vector2[] points)
    {
        if (points.Length < 2)
        {
            return;
        }

        if (_roadMesh == null || _roadMesh.vertices.Length != Path.EvenlySpacedPoints.Count * 2)
        {
            _roadMesh                         = new Mesh();
            _roadsidesMesh                    = new Mesh();
            _roadMesh.name                    = "Road_Mesh";
            _roadsidesMesh.name               = "Roadsides_Mesh";
            Road.transform.localPosition      = new Vector3(0, 0, 0);
            Road.transform.localScale         = new Vector3(1, 1, 1);
            Roadsides.transform.localPosition = new Vector3(0, 0, 0);
            Roadsides.transform.localScale    = new Vector3(1, 1, 1);
            Road.mesh                         = _roadMesh;
            RoadCollision.sharedMesh          = _roadMesh;
            Roadsides.mesh                    = _roadsidesMesh;
            Initialized                       = true;
        }

        Vector2 startForward = Vector2.up, endForward = Vector2.up;

        Vector3[] verts          = new Vector3[points.Length * 2];
        Vector3[] vertsRoad      = new Vector3[points.Length * 2];
        Vector3[] vertsRoadsides = new Vector3[points.Length * 2];
        Vector2[] uvs            = new Vector2[verts.Length];
        Vector3[] normals        = new Vector3[verts.Length];
        int[]     tris           = new int[2 * (points.Length - 1) * 3];
        int       vertIndex      = 0;
        int       triIndex       = 0;

        for (int i = 0; i < points.Length; i++)
        {
            Vector2 forward = Vector2.zero;
            if (i > 1)
            {
                if (i < points.Length - 1)
                {
                    forward += points[i] - points[i - 1];
                    forward += points[i + 1] - points[i];
                }
                else
                {
                    forward = endForward;
                }
            }
            else
            {
                forward = startForward;
            }

            forward.Normalize();
            Vector2 left = new Vector2(-forward.y, forward.x);

            vertsRoad[vertIndex]          = points[i] + left * RoadWidth;
            vertsRoad[vertIndex + 1]      = points[i] - left * RoadWidth;
            vertsRoadsides[vertIndex]     = points[i] + left * RoadsideWidth;
            vertsRoadsides[vertIndex + 1] = points[i] - left * RoadsideWidth;

            float completionPercent = i / (float)(points.Length - 1);
            uvs[vertIndex]     = new Vector2(0, completionPercent);
            uvs[vertIndex + 1] = new Vector2(1, completionPercent);

            normals[vertIndex]     = Vector3.back;
            normals[vertIndex + 1] = Vector3.back;

            if (i < points.Length - 1)
            {
                tris[triIndex]     = vertIndex;
                tris[triIndex + 1] = vertIndex + 2;
                tris[triIndex + 2] = vertIndex + 1;

                tris[triIndex + 3] = vertIndex + 1;
                tris[triIndex + 4] = vertIndex + 2;
                tris[triIndex + 5] = vertIndex + 3;
            }

            vertIndex += 2;
            triIndex  += 6;
        }

        _roadMesh.vertices  = vertsRoad;
        _roadMesh.triangles = tris;
        _roadMesh.uv        = uvs;
        _roadMesh.normals   = normals;
        //roadMesh.RecalculateBounds();

        _roadsidesMesh.vertices  = vertsRoadsides;
        _roadsidesMesh.triangles = tris;
        _roadsidesMesh.uv        = uvs;
        _roadsidesMesh.normals   = normals;
        //roadsidesMesh.RecalculateBounds();

        Calculate = false;
        Setted    = true;
    }
Ejemplo n.º 37
0
    private Mesh CreateSmoothedMeshAsset(SelectedMesh originalMesh)
    {
        //Check if we are ok to overwrite
        var overwrite = true;

        var rootPath = mCustomDirectory ? Application.dataPath + "/" + mCustomDirectoryPath + "/" : TCP2_Utils.FindReadmePath() + OUTPUT_FOLDER;

        if (!Directory.Exists(rootPath))
        {
            Directory.CreateDirectory(rootPath);
        }

#if UNITY_EDITOR_WIN
        rootPath = rootPath.Replace(mCustomDirectory ? Application.dataPath : TCP2_Utils.UnityToSystemPath(Application.dataPath), "").Replace(@"\", "/");
#else
        rootPath = rootPath.Replace(Application.dataPath, "");
#endif

        var originalMeshName = GetSafeFilename(originalMesh.name);
        var assetPath        = "Assets" + rootPath;
        var newAssetName     = originalMeshName + " " + MESH_SUFFIX + ".asset";
        if (originalMeshName.Contains(MESH_SUFFIX))
        {
            newAssetName = originalMeshName + ".asset";
        }
        assetPath += newAssetName;
        var existingAsset = AssetDatabase.LoadAssetAtPath(assetPath, typeof(Mesh)) as Mesh;
        var assetExists   = (existingAsset != null) && originalMesh.isAsset;
        if (assetExists)
        {
            if (!mAlwaysOverwrite)
            {
                overwrite = EditorUtility.DisplayDialog("TCP2 : Smoothed Mesh", "The following smoothed mesh already exists:\n\n" + newAssetName + "\n\nOverwrite?", "Yes", "No");
            }

            if (!overwrite)
            {
                return(null);
            }

            originalMesh.mesh = existingAsset;
            originalMesh.name = existingAsset.name;
        }

        Mesh newMesh = null;
        if (originalMesh.isSkinned)
        {
            newMesh = TCP2_Utils.CreateSmoothedMesh(originalMesh.mesh, mFormat, false, true, false, !originalMesh.isAsset || (originalMesh.isAsset && assetExists));
        }
        else
        {
            newMesh = TCP2_Utils.CreateSmoothedMesh(originalMesh.mesh, mFormat, mVColors, mTangents, mUV2, !originalMesh.isAsset || (originalMesh.isAsset && assetExists));
        }

        if (newMesh == null)
        {
            ShowNotification(new GUIContent("Couldn't generate the mesh for:\n" + originalMesh.name));
        }
        else
        {
            if (originalMesh.associatedObjects != null)
            {
                Undo.RecordObjects(originalMesh.associatedObjects, "Assign TCP2 Smoothed Mesh to Selection");

                foreach (var o in originalMesh.associatedObjects)
                {
                    if (o is SkinnedMeshRenderer)
                    {
                        (o as SkinnedMeshRenderer).sharedMesh = newMesh;
                    }
                    else if (o is MeshFilter)
                    {
                        (o as MeshFilter).sharedMesh = newMesh;
                    }
                    else
                    {
                        Debug.LogWarning("[TCP2 Smoothed Normals Utility] Unrecognized AssociatedObject: " + o + "\nType: " + o.GetType());
                    }
                    EditorUtility.SetDirty(o);
                }
            }

            if (originalMesh.isAsset)
            {
                if (overwrite && !assetExists)
                {
                    AssetDatabase.CreateAsset(newMesh, assetPath);
                }
            }
            else
            {
                return(null);
            }
        }

        return(newMesh);
    }
Ejemplo n.º 38
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            ///input parameters
            Mesh Rhino_mesh = new Mesh();

            /// initialise parameters
            double        T_N = 0.0, T_C = 0.0, D = 0.0, M = 0.0, O = 0.0;
            List <double> Rhino_indices = new List <double>();

            ///import data
            if (!DA.GetData("Mesh", ref Rhino_mesh))
            {
                return;
            }
            if (!DA.GetData("ThresValN", ref T_N))
            {
                return;
            }
            if (!DA.GetData("ThresValC", ref T_C))
            {
                return;
            }
            if (!DA.GetData("MaxDist", ref D))
            {
                return;
            }
            if (!DA.GetData("Minsize", ref M))
            {
                return;
            }
            if (!DA.GetData("Offset", ref O))
            {
                return;
            }

            ///get mesh data to Matlab
            /// 1. decompose mesh into face centroids/normals (rhinocommon => .NET)
            /// 1a. compute normals if not present
            /// 2. create appropriete matlab arrays (.NET => Matlab)
            /// 3. run matlab function (Matlab)
            /// 4. convert function output (list with indices) to .Net array (Matlab => .Net)
            /// 5. convert array to rhinocommon list. (.Net => Rhinocommon)
            /// 6. output data

            /// 1.
            var Rhino_c = new Point3f();
            var Rhino_n = new Vector3f();
            var C_xyz   = new float[Rhino_mesh.Faces.Count * 3];
            var C_n     = new float[Rhino_mesh.Faces.Count * 3];

            ///1a. check if normals are present
            if (Rhino_mesh.FaceNormals.Count == 0)
            {
                Rhino_mesh.FaceNormals.ComputeFaceNormals();
            }

            /// 2.
            for (int i = 0; i < Rhino_mesh.Faces.Count; i++)
            {
                Rhino_c          = (Point3f)Rhino_mesh.Faces.GetFaceCenter(i);
                C_xyz[i * 3]     = Rhino_c.X;
                C_xyz[i * 3 + 1] = Rhino_c.Y;
                C_xyz[i * 3 + 2] = Rhino_c.Z;

                Rhino_n        = Rhino_mesh.FaceNormals[i];
                C_n[i * 3]     = Rhino_n.X;
                C_n[i * 3 + 1] = Rhino_n.Y;
                C_n[i * 3 + 2] = Rhino_n.Z;
            }

            var Matlab_xyz = new MWNumericArray(Rhino_mesh.Faces.Count, 3, C_xyz);
            var Matlab_n   = new MWNumericArray(Rhino_mesh.Faces.Count, 3, C_n);

            /// 3.
            Scan2BIM_Matlab.Segmentation segmentation = new Scan2BIM_Matlab.Segmentation();

            MWArray cluster = new MWNumericArray();

            cluster = segmentation.S2B_RegionGrowing_2(Matlab_xyz, Matlab_n, T_N, T_C, D, M, O);

            /// 4.
            MWNumericArray na = (MWNumericArray)cluster;

            double[] dc = (double[])na.ToVector(0);

            /// 5.
            Rhino_indices = new List <double>(dc);

            /// 6.
            DA.SetDataList(0, Rhino_indices);
        }
Ejemplo n.º 39
0
        public static void RecalculateTangents(Mesh theMesh)
        {
            Int32 vertexCount = theMesh.vertexCount;

            Vector3[] vertices      = theMesh.vertices;
            Vector3[] normals       = theMesh.normals;
            Vector2[] uv            = theMesh.uv;
            Int32[]   triangles     = theMesh.triangles;
            Int32     triangleCount = triangles.Length / 3;

            Vector4[] tangents = new Vector4[vertexCount];
            Vector3[] tan1     = new Vector3[vertexCount];
            Vector3[] tan2     = new Vector3[vertexCount];

            Int32 tri = 0;

            for (Int32 i = 0; i < triangleCount; i++)
            {
                Int32 i1 = triangles[tri];
                Int32 i2 = triangles[tri + 1];
                Int32 i3 = triangles[tri + 2];

                Vector3 v1 = vertices[i1];
                Vector3 v2 = vertices[i2];
                Vector3 v3 = vertices[i3];

                Vector2 w1 = uv[i1];
                Vector2 w2 = uv[i2];
                Vector2 w3 = uv[i3];

                Single x1 = v2.x - v1.x;
                Single x2 = v3.x - v1.x;
                Single y1 = v2.y - v1.y;
                Single y2 = v3.y - v1.y;
                Single z1 = v2.z - v1.z;
                Single z2 = v3.z - v1.z;

                Single s1 = w2.x - w1.x;
                Single s2 = w3.x - w1.x;
                Single t1 = w2.y - w1.y;
                Single t2 = w3.y - w1.y;

                Single  r    = 1.0f / (s1 * t2 - s2 * t1);
                Vector3 sdir = new Vector3((t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r, (t2 * z1 - t1 * z2) * r);
                Vector3 tdir = new Vector3((s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r, (s1 * z2 - s2 * z1) * r);

                tan1[i1] += sdir;
                tan1[i2] += sdir;
                tan1[i3] += sdir;

                tan2[i1] += tdir;
                tan2[i2] += tdir;
                tan2[i3] += tdir;

                tri += 3;
            }
            for (Int32 i = 0; i < vertexCount; i++)
            {
                Vector3 n = normals[i];
                Vector3 t = tan1[i];

                Vector3.OrthoNormalize(ref n, ref t);

                tangents[i].x = t.x;
                tangents[i].y = t.y;
                tangents[i].z = t.z;

                // Calculate handedness
                tangents[i].w = Vector3.Dot(Vector3.Cross(n, t), tan2[i]) < 0.0f ? -1.0f : 1.0f;
            }
            theMesh.tangents = tangents;
        }
Ejemplo n.º 40
0
 /// <summary>
 /// The Unity Awake() method.
 /// </summary>
 public void Awake()
 {
     m_Mesh         = GetComponent <MeshFilter>().mesh;
     m_MeshRenderer = GetComponent <UnityEngine.MeshRenderer>();
 }
Ejemplo n.º 41
0
    public void Start()
    {
        //TODO generate a random heightmap
        Vertices  = new Vector3[gridSize * gridSize];
        UV        = new Vector2[Vertices.Length];
        colors    = new Color[Vertices.Length];
        triangles = new int[Vertices.Length * 9];
        int seed = Random.Range(0, 100);

        for (int y = 0; y < gridSize; y++)
        {
            for (int x = 0; x < gridSize; x++)
            {
                float newY = 0;
                if (x == 0 || x == gridSize - 1 || y == 0 || y == gridSize - 1)
                {
                    newY = 0;
                }
                else
                {
                    newY  = Noise(x + seed, y + seed, 10, 3, 2);
                    newY += Noise(x + seed, y + seed, 2, 1, 1);
                    newY += Random.Range(-0.5f, 0.5f);
                    if (x < gridSize / 2)
                    {
                        newY *= (float)x / (float)gridSize;
                    }
                    else
                    {
                        newY *= 1 - (float)x / (float)gridSize;
                    }
                    if (y < gridSize / 2)
                    {
                        newY *= (float)y / (float)gridSize;
                    }
                    else
                    {
                        newY *= 1 - (float)y / (float)gridSize;
                    }
                    newY *= height;
                }
                if (newY > snowLevel)
                {
                    colors[y * gridSize + x] = snowColor;
                }
                else if (newY > rockLevel)
                {
                    colors[y * gridSize + x] = rockColor;
                }
                else if (newY < sandLevel)
                {
                    colors[y * gridSize + x] = sandColor;
                }
                else
                {
                    colors[y * gridSize + x] = grassColor;
                }

                Vertices[y * gridSize + x] = new Vector3(x, newY, y);
                UV[y * gridSize + x]       = new Vector2((float)x / (float)(gridSize - 1), (float)y / (float)(gridSize - 1));
            }
        }

        for (int y = 0; y < gridSize - 1; y++)
        {
            for (int x = 0; x < gridSize - 1; x++)
            {
                //create the triangles
                triangles[6 * (y * gridSize + x)]     = y * gridSize + x;
                triangles[6 * (y * gridSize + x) + 1] = y * gridSize + x + gridSize;
                triangles[6 * (y * gridSize + x) + 2] = y * gridSize + x + 1;
                triangles[6 * (y * gridSize + x) + 3] = y * gridSize + x + 1 + gridSize;
                triangles[6 * (y * gridSize + x) + 4] = y * gridSize + x + 1;
                triangles[6 * (y * gridSize + x) + 5] = y * gridSize + x + gridSize;
            }
        }
        gameObject.AddComponent <MeshFilter> ();
        gameObject.AddComponent <MeshRenderer> ();
        gameObject.renderer.material = partMaterial;

        partMesh           = new Mesh();
        partMesh.vertices  = Vertices;
        partMesh.colors    = colors;
        partMesh.uv        = UV;
        partMesh.triangles = triangles;
        partMesh           = MeshHelper.FlatShading(partMesh, 1);

        gameObject.transform.GetComponent <MeshFilter> ().mesh = partMesh;
        MeshCollider collider = gameObject.AddComponent <MeshCollider> ();

        transform.position = new Vector3(-gridSize / 2, 0, -gridSize / 2);

        //Create water
        GameObject Water = new GameObject("Water");

        Water.transform.parent = transform;
        water = Water.AddComponent <Water>();
        water.partMaterial = waterMaterial;
        Water.AddComponent <MeshFilter> ();
        Water.AddComponent <MeshRenderer> ();
        water.speed      = 1;
        water.waveHeight = 1;
        water.Init(seaLevel, gridSize);

        GameObject DeepWater = new GameObject("DeepWater");

        DeepWater.transform.parent = transform;
        water = DeepWater.AddComponent <Water>();
        water.partMaterial = waterMaterial;
        DeepWater.AddComponent <MeshFilter> ();
        DeepWater.AddComponent <MeshRenderer> ();
        water.speed      = 1;
        water.waveHeight = 1;
        water.Init(seaLevel - 0.25f, gridSize);
    }
Ejemplo n.º 42
0
        public static Mesh DeserializeMesh(String path)
        {
            FileStream   inputStream = new FileStream(path, FileMode.Open, FileAccess.Read);
            BinaryReader reader      = new BinaryReader(inputStream);
            Mesh         m;

            // Check if the file is bin v1 or v2
            Int32   first = reader.ReadInt32();
            Boolean v2    = first == -2;

            // Parse a v1 mesh
            if (!v2)
            {
                // Get the vertices
                Int32     count    = first;
                Vector3[] vertices = new Vector3[count];
                for (Int32 i = 0; i < count; i++)
                {
                    Vector3 vertex;
                    vertex.x    = reader.ReadSingle();
                    vertex.y    = reader.ReadSingle();
                    vertex.z    = reader.ReadSingle();
                    vertices[i] = vertex;
                }

                // Get the uvs
                Int32     uvCount = reader.ReadInt32();
                Vector2[] uvs     = new Vector2[uvCount];
                for (Int32 i = 0; i < uvCount; i++)
                {
                    Vector2 uv;
                    uv.x   = reader.ReadSingle();
                    uv.y   = reader.ReadSingle();
                    uvs[i] = uv;
                }

                // Get the triangles
                Int32   trisCount = reader.ReadInt32();
                Int32[] triangles = new Int32[trisCount];
                for (Int32 i = 0; i < trisCount; i++)
                {
                    triangles[i] = reader.ReadInt32();
                }

                // Create the mesh
                m = new Mesh
                {
                    vertices  = vertices,
                    triangles = triangles,
                    uv        = uvs
                };
                m.RecalculateNormals();
                RecalculateTangents(m);
            }
            else
            {
                // Get the vertices
                Int32     count    = reader.ReadInt32();
                Vector3[] vertices = new Vector3[count];
                for (Int32 i = 0; i < count; i++)
                {
                    Vector3 vertex;
                    vertex.x    = reader.ReadSingle();
                    vertex.y    = reader.ReadSingle();
                    vertex.z    = reader.ReadSingle();
                    vertices[i] = vertex;
                }

                // Get the uvs
                Int32     uvCount = reader.ReadInt32();
                Vector2[] uvs     = new Vector2[uvCount];
                for (Int32 i = 0; i < uvCount; i++)
                {
                    Vector2 uv;
                    uv.x   = reader.ReadSingle();
                    uv.y   = reader.ReadSingle();
                    uvs[i] = uv;
                }

                // Get the triangles
                Int32   trisCount = reader.ReadInt32();
                Int32[] triangles = new Int32[trisCount];
                for (Int32 i = 0; i < trisCount; i++)
                {
                    triangles[i] = reader.ReadInt32();
                }

                // Get the uv2s
                Int32 uv2Count = reader.ReadInt32();
                // ReSharper disable once InconsistentNaming
                Vector2[] uv2s = new Vector2[uv2Count];
                for (Int32 i = 0; i < uv2Count; i++)
                {
                    Vector2 uv2;
                    uv2.x   = reader.ReadSingle();
                    uv2.y   = reader.ReadSingle();
                    uv2s[i] = uv2;
                }

                // Get the normals
                Int32     normalCount = reader.ReadInt32();
                Vector3[] normals     = new Vector3[normalCount];
                for (Int32 i = 0; i < normalCount; i++)
                {
                    Vector3 normal;
                    normal.x   = reader.ReadSingle();
                    normal.y   = reader.ReadSingle();
                    normal.z   = reader.ReadSingle();
                    normals[i] = normal;
                }

                // Get the tangents
                Int32     tangentCount = reader.ReadInt32();
                Vector4[] tangents     = new Vector4[tangentCount];
                for (Int32 i = 0; i < tangentCount; i++)
                {
                    Vector4 tangent;
                    tangent.x   = reader.ReadSingle();
                    tangent.y   = reader.ReadSingle();
                    tangent.z   = reader.ReadSingle();
                    tangent.w   = reader.ReadSingle();
                    tangents[i] = tangent;
                }

                // Create the mesh
                m = new Mesh
                {
                    vertices  = vertices,
                    triangles = triangles,
                    uv        = uvs,
                    uv2       = uv2s,
                    normals   = normals,
                    tangents  = tangents
                };
            }

            // Close
            reader.Close();
            inputStream.Close();

            return(m);
        }
Ejemplo n.º 43
0
        /// <summary>
        /// Initialize the small multiple from point field data
        /// </summary>
        /// <param name="parser">The VTK Parser</param>
        /// <param name="mesh">The mesh to display</param>
        /// <param name="uvID">The ID where to put the color data</param>
        /// <param name="valueID">The ID of the VTKFieldPointValue</param>
        /// <param name="offset">The offset along each axis to apply : pos = x*offset.x + y*offset.y + z*offset.z</param>
        /// <param name="density">The density in use</param>
        /// <param name="mask">The mask to apply along each point</param>
        /// <returns></returns>
        public unsafe bool InitFromPointField(VTKParser parser, Mesh mesh, Int32 uvID, Int32 valueID, Vector3Int offset, Vector3Int density, byte *mask)
        {
            m_material = new Material(ColorMaterial);
            m_values   = new float[density.x * density.y * density.z];

            //Check the ID
            if (uvID > 7)
            {
                Debug.Log("The uvID must be between 0 to 7. This is a limitation of Unity for working within a common mesh...");
                return(false);
            }
            m_mesh = mesh;

            VTKStructuredPoints descPts = parser.GetStructuredPointsDescriptor();

            //Determine the maximum and minimum positions
            Vector3 minModelPos = new Vector3((float)(-descPts.Size[0] / 2.0 * descPts.Spacing[0]),
                                              (float)(-descPts.Size[1] / 2.0 * descPts.Spacing[1]),
                                              (float)(-descPts.Size[2] / 2.0 * descPts.Spacing[2]));
            Vector3 maxModelPos = -minModelPos;

            //The value buffer
            List <VTKFieldValue> fieldDesc = parser.GetPointFieldValueDescriptors();

            if (fieldDesc.Count < valueID)
            {
                Debug.Log("No value to display");
                return(false);
            }
            VTKValue       val    = parser.ParseAllFieldValues(fieldDesc[valueID]);
            List <Vector4> colors = new List <Vector4>((int)(density.x * density.y * density.z));

            //Determine the minimum and maximum value and their position
            m_maxVal = float.MinValue;
            m_minVal = float.MaxValue;
            Vector3 minLoc = new Vector3();
            Vector3 maxLoc = new Vector3();

            for (UInt32 i = 0; i < val.NbValues; i++)
            {
                if (mask != null && mask[i] == 0)
                {
                    continue;
                }
                float v = (float)val.ReadAsDouble(i * fieldDesc[valueID].NbValuesPerTuple);
                if (m_maxVal < v)
                {
                    m_maxVal = v;
                    maxLoc   = new Vector3(i % descPts.Size[0], (i / descPts.Size[0]) % descPts.Size[1], i / (descPts.Size[0] * descPts.Size[1]));
                }
                if (m_minVal > v)
                {
                    m_minVal = v;
                    minLoc   = new Vector3(i % descPts.Size[0], (i / descPts.Size[0]) % descPts.Size[1], i / (descPts.Size[0] * descPts.Size[1]));
                }
            }

            //Normalize the location (between 0.0 and 1.0 for the most "long" axis)
            Vector3[] vec = new Vector3[2] {
                maxLoc, minLoc
            };
            Vector3 modelDist    = maxModelPos - minModelPos;
            float   maxModelDist = Math.Max(modelDist.x, Math.Max(modelDist.y, modelDist.z));

            for (int i = 0; i < vec.Length; i++)
            {
                Vector3 l = vec[i];
                l = (new Vector3((float)(l.x * descPts.Spacing[0]),
                                 (float)(l.y * descPts.Spacing[1]),
                                 (float)(l.z * descPts.Spacing[2])) + minModelPos) / maxModelDist;
                vec[i] = l;
            }

            Debug.Log($"Min : {m_minVal} Max : {m_maxVal}");

            //Fill the color array
            maxLoc = vec[0];
            minLoc = vec[1];
            UInt64 colorValueOff = 0;

            for (UInt32 k = 0; k < density.z; k++)
            {
                for (UInt32 j = 0; j < density.y; j++)
                {
                    for (UInt32 i = 0; i < density.x; i++, colorValueOff++)
                    {
                        UInt64 fieldOff = (UInt64)(i * offset.x + j * offset.y + k * offset.z);
                        //Check the mask
                        if (mask != null && *(mask + fieldOff) == 0)
                        {
                            colors.Add(new Vector4(0.0f, 0.0f, 0.0f, 0.0f));
                            m_values[colorValueOff] = m_minVal;
                            continue;
                        }
                        float c = val.ReadAsFloat(fieldOff * fieldDesc[valueID].NbValuesPerTuple);
                        m_values[colorValueOff] = c;
                        c = (float)((c - m_minVal) / (m_maxVal - m_minVal));

                        //LAB color space (warm - cold)
                        Color?col = null;
                        if (c < 0.5)
                        {
                            col = LABColor.Lerp(coldColor, whiteColor, 2.0f * c).ToXYZ().ToRGB();
                        }
                        else
                        {
                            col = LABColor.Lerp(whiteColor, warmColor, 2.0f * (c - 0.5f)).ToXYZ().ToRGB();
                        }
                        colors.Add(new Vector4(col.Value.r, col.Value.g, col.Value.b, 1.0f));
                    }
                }
            }

            //Update the mesh / material
            m_mesh.SetUVs(uvID, colors);
            m_mesh.UploadMeshData(false);
            m_colorID = uvID;

            for (int i = 0; i < 8; i++)
            {
                if (i != m_colorID)
                {
                    m_material.DisableKeyword($"TEXCOORD{i}_ON");
                }
            }
            m_material.EnableKeyword($"TEXCOORD{m_colorID}_ON");
            PlaneEnabled  = false;
            SphereEnabled = false;

            CreateGameObjects(vec);

            return(true);
        }
Ejemplo n.º 44
0
        public static Mesh ComputeScaledSpaceMesh(CelestialBody body, PQS pqs)
        {
            // We need to get the body for Jool (to steal it's mesh)
            const Double R_SCALED_JOOL        = 1000.0f;
            Double       rMetersToScaledUnits = (Single)(R_SCALED_JOOL / body.Radius);

            // Generate a duplicate of the Jool mesh
            Mesh mesh = DuplicateMesh(Templates.ReferenceGeosphere);

            Logger.Active.Log(body);
            Logger.Active.Log(pqs);
            Logger.Active.Log(body.pqsController);

            // If this body has a PQS, we can create a more detailed object, otherwise just return the generic mesh
            if (pqs == null)
            {
                return(mesh);
            }

            // first we enable all maps
            OnDemandStorage.EnableBody(body.bodyName);

            // In order to generate the scaled space we have to enable the mods.  Since this is
            // a prefab they don't get disabled as kill game performance.  To resolve this we
            // clone the PQS, use it, and then delete it when done. At runtime we can simply use
            // the PQS that is active
            GameObject pqsVersionGameObject =
                Injector.IsInPrefab ? Instantiate(pqs.gameObject) : pqs.gameObject;
            PQS pqsVersion = pqsVersionGameObject.GetComponent <PQS>();

            // Deactivate blacklisted Mods
            PQSMod[] mods = pqsVersion.GetComponentsInChildren <PQSMod>(true).OrderBy(m => m.order).ToArray();
            for (Int32 i = 0; i < mods.Length; i++)
            {
                // Disable mods that don't belong to us
                if (mods[i].transform.parent != pqsVersion.transform)
                {
                    mods[i].modEnabled = false;
                    continue;
                }

                switch (mods[i])
                {
                // Disable the OnDemand notifier
                case PQSMod_OnDemandHandler _:
                    mods[i].modEnabled = false;
                    continue;

                case PQSMod_FlattenArea _:
                    typeof(PQSMod_FlattenArea).GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
                    .First(f => f.FieldType == typeof(Boolean)).SetValue(mods[i], true);
                    break;
                }
            }

            pqsVersion.StartUpSphere();
            pqsVersion.isBuildingMaps = true;

            // If we were able to find PQS mods
            if (mods.Length > 0)
            {
                // Generate the PQS modifications
                Vector3[] vertices = mesh.vertices;
                for (Int32 i = 0; i < mesh.vertexCount; i++)
                {
                    // Get the UV coordinate of this vertex
                    Vector2 uv = mesh.uv[i];

                    // Since this is a geosphere, normalizing the vertex gives the direction from center center
                    Vector3 direction = vertices[i];
                    direction.Normalize();

                    // Build the vertex data object for the PQS mods
                    PQS.VertexBuildData vertex = new PQS.VertexBuildData
                    {
                        directionFromCenter = direction,
                        vertHeight          = body.Radius,
                        u = uv.x,
                        v = uv.y
                    };

                    // Build from the PQS
                    for (Int32 m = 0; m < mods.Length; m++)
                    {
                        // Don't build disabled mods
                        if (!mods[m].modEnabled)
                        {
                            continue;
                        }

                        // Don't build mods that don't belong to us
                        if (mods[m].transform.parent != pqsVersion.transform)
                        {
                            continue;
                        }

                        mods[m].OnVertexBuildHeight(vertex);
                    }

                    // Check for sea level
                    if (pqsVersion.mapOcean)
                    {
                        vertex.vertHeight = Math.Max(vertex.vertHeight, body.Radius);
                    }

                    // Adjust the displacement
                    vertices[i] = direction * (Single)(vertex.vertHeight * rMetersToScaledUnits);
                }
                mesh.vertices = vertices;
                mesh.RecalculateNormals();
                mesh.RecalculateBounds();
                RecalculateTangents(mesh);
            }

            // Cleanup
            pqsVersion.isBuildingMaps = false;
            pqsVersion.DeactivateSphere();

            // If we are working with a copied PQS, clean it up
            if (Injector.IsInPrefab)
            {
                UnityEngine.Object.Destroy(pqsVersionGameObject);
            }
            OnDemandStorage.DisableBody(body.bodyName);

            // Return the generated scaled space mesh
            return(mesh);
        }
Ejemplo n.º 45
0
    void Update()
    {
        if (source)
        {
            int fc = 0;

            switch (source.datasource)
            {
            case MegaCacheData.Mesh: fc = source.meshes.Count - 1; break;

            case MegaCacheData.File: fc = source.framecount - 1; break;

            case MegaCacheData.Image:
                if (source.cacheimage && source.cacheimage.frames != null)
                {
                    fc = source.cacheimage.frames.Count - 1;
                }
                break;
            }

            if (fc > 0)
            {
                if (animate)
                {
                    looptime = fc / fps;
                    if (Application.isPlaying)
                    {
                        time += Time.deltaTime * speed;
                    }

                    float at = time;

                    switch (loopmode)
                    {
                    case MegaCacheRepeatMode.Loop:
                        at = Mathf.Repeat(time, Mathf.Abs(looptime));
                        if (looptime < 0.0f)
                        {
                            at = looptime - at;
                        }
                        break;

                    case MegaCacheRepeatMode.PingPong: at = Mathf.PingPong(time, looptime); break;

                    case MegaCacheRepeatMode.Clamp: at = Mathf.Clamp(time, 0.0f, looptime); break;
                    }

                    frame = (int)((at / looptime) * fc);
                }

                frame = Mathf.Clamp(frame, 0, fc);

                if (frame != currentframe)
                {
                    currentframe = frame;
                    if (source.datasource == MegaCacheData.Image && source.cacheimage)
                    {
                        if (imagemesh == null)
                        {
                            imagemesh = new Mesh();
                        }

                        if (mf.sharedMesh != imagemesh)
                        {
                            mf.sharedMesh = imagemesh;
                        }

                        source.cacheimage.GetMeshRef(imagemesh, frame, source);
                    }

                    if (source.datasource == MegaCacheData.File)
                    {
                        if (imagemesh == null)
                        {
                            imagemesh = new Mesh();
                        }

                        if (mf.sharedMesh != imagemesh)
                        {
                            mf.sharedMesh = imagemesh;
                        }

                        source.GetFrameRef(frame, imagemesh);
                    }

                    if (source.datasource == MegaCacheData.Mesh)
                    {
                        if (mf && source.meshes.Count > 0)
                        {
                            if (mf.sharedMesh != source.meshes[frame])
                            {
                                mf.sharedMesh = source.meshes[frame];
                            }
                        }
                    }

                    if (updatecollider)
                    {
                        if (meshCol == null)
                        {
                            meshCol = GetComponent <MeshCollider>();
                        }

                        if (meshCol != null)
                        {
                            meshCol.sharedMesh = null;
                            meshCol.sharedMesh = mf.sharedMesh;
                        }
                    }
                }
            }
        }
    }
Ejemplo n.º 46
0
        private void CombineMesh(Mesh[] pShape_r)
        {
            StructShapeCache[] _Cache_r;

            if (pShape_r == null || pShape_r.Length <= 0)
            {
                // Default shape
                _Cache_r = new StructShapeCache[] {
                    new StructShapeCache(null)
                };
            }
            else
            {
                _Cache_r = new StructShapeCache[pShape_r.Length];
                for (int i = 0; i < pShape_r.Length; i++)
                {
                    _Cache_r[i] = new StructShapeCache(pShape_r[i]);
                }
            }

            int _CountVertex = 0, _CountIndex = 0;

            foreach (StructShapeCache _Cache in _Cache_r)
            {
                _CountVertex += _Cache.CountVertex;
            }
            if (_CountVertex <= 0)
            {
                return;
            }

            // コピー数を決定
            _CountVertex = 0;
            for (this.m_CountCopy = 0; this.m_CountCopy < this.m_CountCopyMax; this.m_CountCopy++)
            {
                StructShapeCache _Cache = _Cache_r[this.CountCopy % _Cache_r.Length];
                if (65535 < _CountVertex + _Cache.CountVertex)
                {
                    break;
                }

                _CountVertex += _Cache.CountVertex;
                _CountIndex  += _Cache.CountIndex;
            }

            // バーテックス配列生成
            Vector3[] _Vertex_r  = new Vector3[_CountVertex];
            Vector3[] _Normal_r  = new Vector3[_CountVertex];
            Vector4[] _Tangent_r = new Vector4[_CountVertex];
            Vector2[] _UV1_r     = new Vector2[_CountVertex];
            Vector2[] _UV2_r     = new Vector2[_CountVertex];
            int[]     _Index_r   = new int[_CountIndex];
            for (int iVertex = 0, iIndex = 0, iElm = 0; iVertex < _CountVertex; iElm++)
            {
                StructShapeCache _Cache = _Cache_r[iElm % _Cache_r.Length];

                _Cache.CopyVertexTo(_Vertex_r, iVertex);
                _Cache.CopyNormalTo(_Normal_r, iVertex);
                _Cache.CopyTangentTo(_Tangent_r, iVertex);
                _Cache.CopyUVTo(_UV1_r, iVertex);
                _Cache.CopyIndexTo(_Index_r, iIndex, iVertex);

                Vector2 _Coord = new Vector2((float)iElm / this.CountCopy, 0.0f);
                for (int i = 0; i < _Cache.CountVertex; i++)
                {
                    _UV2_r[iVertex + i] = _Coord;
                }

                iVertex += _Cache.CountVertex;
                iIndex  += _Cache.CountIndex;
            }

            // メッシュオブジェクト生成
            this.m_Mesh          = new Mesh();
            this.m_Mesh.vertices = _Vertex_r;
            this.m_Mesh.normals  = _Normal_r;
            this.m_Mesh.tangents = _Tangent_r;
            this.m_Mesh.uv       = _UV1_r;
            this.m_Mesh.uv2      = _UV2_r;
            this.m_Mesh.SetIndices(_Index_r, MeshTopology.Triangles, 0);

            this.m_Mesh.hideFlags = HideFlags.DontSave;                           // 一時使用のため保存しない
            this.m_Mesh.bounds    = new Bounds(Vector3.zero, Vector3.one * 1000); // 淘汰されないよう制御
        }
Ejemplo n.º 47
0
        private void CreateUVSphere()
        {
            #region Setup

            MeshFilter filter = GetComponent<MeshFilter>();
            Mesh mesh = filter.sharedMesh;
            if (mesh == null)
            {
                mesh = filter.sharedMesh = new Mesh();
                mesh.name = gameObject.name + "_Mesh";
            }
            mesh.Clear();

            int latitudeCount = 10 * Detail;
            int longitudeCount = 15 * Detail;

            #endregion Setup

            #region Vertices
            Vector3[] vertices = new Vector3[(longitudeCount + 1) * latitudeCount + 2];
            float _pi = Mathf.PI;
            float _2pi = _pi * 2f;

            vertices[0] = Vector3.up * Radius;
            for (int lat = 0; lat < latitudeCount; lat++)
            {
                float a1 = _pi * (float)(lat + 1) / (latitudeCount + 1);
                float sin1 = Mathf.Sin(a1);
                float cos1 = Mathf.Cos(a1);

                for (int lon = 0; lon <= longitudeCount; lon++)
                {
                    float a2 = _2pi * (float)(lon == longitudeCount ? 0 : lon) / longitudeCount;
                    float sin2 = Mathf.Sin(a2);
                    float cos2 = Mathf.Cos(a2);

                    vertices[lon + lat * (longitudeCount + 1) + 1] = new Vector3(sin1 * cos2, cos1, sin1 * sin2) * Radius;
                }
            }
            vertices[vertices.Length - 1] = Vector3.up * -Radius;
            #endregion

            #region Normales		
            Vector3[] normales = new Vector3[vertices.Length];
            for (int n = 0; n < vertices.Length; n++)
                normales[n] = vertices[n].normalized;
            #endregion

            #region UVs
            Vector2[] uvs = new Vector2[vertices.Length];
            uvs[0] = Vector2.up;
            uvs[uvs.Length - 1] = Vector2.zero;
            for (int lat = 0; lat < latitudeCount; lat++)
                for (int lon = 0; lon <= longitudeCount; lon++)
                    uvs[lon + lat * (longitudeCount + 1) + 1] = new Vector2((float)lon / longitudeCount, 1f - (float)(lat + 1) / (latitudeCount + 1));
            #endregion

            #region Triangles
            int nbFaces = vertices.Length;
            int nbTriangles = nbFaces * 2;
            int nbIndexes = nbTriangles * 3;
            int[] triangles = new int[nbIndexes];

            //Top Cap
            int i = 0;
            for (int lon = 0; lon < longitudeCount; lon++)
            {
                triangles[i++] = lon + 2;
                triangles[i++] = lon + 1;
                triangles[i++] = 0;
            }

            //Middle
            for (int lat = 0; lat < latitudeCount - 1; lat++)
            {
                for (int lon = 0; lon < longitudeCount; lon++)
                {
                    int current = lon + lat * (longitudeCount + 1) + 1;
                    int next = current + longitudeCount + 1;

                    triangles[i++] = current;
                    triangles[i++] = current + 1;
                    triangles[i++] = next + 1;

                    triangles[i++] = current;
                    triangles[i++] = next + 1;
                    triangles[i++] = next;
                }
            }

            //Bottom Cap
            for (int lon = 0; lon < longitudeCount; lon++)
            {
                triangles[i++] = vertices.Length - 1;
                triangles[i++] = vertices.Length - (lon + 2) - 1;
                triangles[i++] = vertices.Length - (lon + 1) - 1;
            }
            #endregion

            #region Finish Up

            mesh.vertices = vertices;
            mesh.normals = normales;
            mesh.uv = uvs;
            mesh.triangles = triangles;
            mesh.RecalculateBounds();
            ;

            #endregion Finish Up
        }
Ejemplo n.º 48
0
    public void Set(BetterList <Vector3> verts, BetterList <Vector3> norms, BetterList <Vector4> tans, BetterList <Vector2> uvs, BetterList <Color32> cols)
    {
        int size = verts.size;

        if (size > 0 && size == uvs.size && size == cols.size && size % 4 == 0)
        {
            if (mFilter == null)
            {
                mFilter = base.gameObject.GetComponent <MeshFilter>();
            }
            if (mFilter == null)
            {
                mFilter = base.gameObject.AddComponent <MeshFilter>();
            }
            if (mRen == null)
            {
                mRen = base.gameObject.GetComponent <MeshRenderer>();
            }
            if (mRen == null)
            {
                mRen = base.gameObject.AddComponent <MeshRenderer>();
                UpdateMaterials();
            }
            else if (mClippedMat != null && mClippedMat.mainTexture != mSharedMat.mainTexture)
            {
                UpdateMaterials();
            }
            if (verts.size < 65000)
            {
                int  num            = (size >> 1) * 3;
                bool rebuildIndices = mIndices == null || mIndices.Length != num;
                if (rebuildIndices)
                {
                    mIndices = new int[num];
                    int num2 = 0;
                    for (int i = 0; i < size; i += 4)
                    {
                        mIndices[num2++] = i;
                        mIndices[num2++] = i + 1;
                        mIndices[num2++] = i + 2;
                        mIndices[num2++] = i + 2;
                        mIndices[num2++] = i + 3;
                        mIndices[num2++] = i;
                    }
                }
                Mesh mesh = GetMesh(ref rebuildIndices, verts.size);
                mesh.vertices = verts.ToArray();
                if (norms != null)
                {
                    mesh.normals = norms.ToArray();
                }
                if (tans != null)
                {
                    mesh.tangents = tans.ToArray();
                }
                mesh.uv       = uvs.ToArray();
                mesh.colors32 = cols.ToArray();
                if (rebuildIndices)
                {
                    mesh.triangles = mIndices;
                }
                mesh.RecalculateBounds();
                mFilter.mesh = mesh;
            }
            else
            {
                if (mFilter.mesh != null)
                {
                    mFilter.mesh.Clear();
                }
                Debug.LogError("Too many vertices on one panel: " + verts.size);
            }
        }
        else
        {
            if (mFilter.mesh != null)
            {
                mFilter.mesh.Clear();
            }
            Debug.LogError("UIWidgets must fill the buffer with 4 vertices per quad. Found " + size);
        }
    }
        public static void DrawQuads(Vector3[] verts, float width)
        {
            //65000 limit divided by 4
            if (verts.Length >= 16250)
            {
                Vector3[] verts2 = new Vector3[verts.Length - 16250];

                for (int i = 16250; i < verts.Length; i++)
                {
                    verts2[i - 16250] = verts[i];
                }

                Vector3[] verts3 = new Vector3[16250];

                for (int i = 0; i < 16250; i++)
                {
                    verts3[i] = verts[i];
                }
                DrawQuads(verts2, width);
                verts = verts3;
            }

            width /= 2F;

            Vector3[] vertices = new Vector3[verts.Length * 4];
            int[]     tris     = new int[verts.Length * 6];

            for (int i = 0; i < verts.Length; i++)
            {
                Vector3 p = verts[i];

                int vIndex = i * 4;
                vertices[vIndex]     = p + new Vector3(-width, 0, -width);
                vertices[vIndex + 1] = p + new Vector3(-width, 0, width);
                vertices[vIndex + 2] = p + new Vector3(width, 0, width);
                vertices[vIndex + 3] = p + new Vector3(width, 0, -width);

                int tIndex = i * 6;
                tris[tIndex]     = vIndex;
                tris[tIndex + 1] = vIndex + 1;
                tris[tIndex + 2] = vIndex + 2;

                tris[tIndex + 3] = vIndex;
                tris[tIndex + 4] = vIndex + 2;
                tris[tIndex + 5] = vIndex + 3;
            }

            Mesh mesh = new Mesh();

            mesh.vertices  = vertices;
            mesh.triangles = tris;

            mesh.RecalculateNormals();
            mesh.RecalculateBounds();

            GameObject   go   = new GameObject("DebugMesh");
            MeshRenderer rend = go.AddComponent(typeof(MeshRenderer)) as MeshRenderer;

            rend.material = active.defaultMaterial;
            (go.AddComponent(typeof(MeshFilter)) as MeshFilter).mesh = mesh;
        }
Ejemplo n.º 50
0
        public void CreateIcoSphere()
        {
            MeshFilter filter = GetComponent<MeshFilter>();
            Mesh mesh = filter.sharedMesh;
            if (mesh == null)
            {
                mesh = filter.sharedMesh = new Mesh();
                mesh.name = gameObject.name + "_Mesh";
            }
            mesh.Clear();

            Dictionary<MiddlePointCacheKey, int> middlePointIndexCache = new Dictionary<MiddlePointCacheKey, int>();
            List<Vector3> vertList = new List<Vector3>();
            List<int> triList = new List<int>();
            List<Vector3> normals = new List<Vector3>();
            List<Vector2> uvs = new List<Vector2>();

            // create 12 vertices of a icosahedron
            float t = (1f + Mathf.Sqrt(5f)) / 2f;

            vertList.Add(new Vector3(-1f, t, 0f).normalized * Radius);
            vertList.Add(new Vector3(1f, t, 0f).normalized * Radius);
            vertList.Add(new Vector3(-1f, -t, 0f).normalized * Radius);
            vertList.Add(new Vector3(1f, -t, 0f).normalized * Radius);

            vertList.Add(new Vector3(0f, -1f, t).normalized * Radius);
            vertList.Add(new Vector3(0f, 1f, t).normalized * Radius);
            vertList.Add(new Vector3(0f, -1f, -t).normalized * Radius);
            vertList.Add(new Vector3(0f, 1f, -t).normalized * Radius);

            vertList.Add(new Vector3(t, 0f, -1f).normalized * Radius);
            vertList.Add(new Vector3(t, 0f, 1f).normalized * Radius);
            vertList.Add(new Vector3(-t, 0f, -1f).normalized * Radius);
            vertList.Add(new Vector3(-t, 0f, 1f).normalized * Radius);

            // create 20 triangles of the icosahedron
            List<TriangleIndices> faces = new List<TriangleIndices>();

            // 5 faces around point 0
            faces.Add(new TriangleIndices(0, 11, 5));
            faces.Add(new TriangleIndices(0, 5, 1));
            faces.Add(new TriangleIndices(0, 1, 7));
            faces.Add(new TriangleIndices(0, 7, 10));
            faces.Add(new TriangleIndices(0, 10, 11));

            // 5 adjacent faces 
            faces.Add(new TriangleIndices(1, 5, 9));
            faces.Add(new TriangleIndices(5, 11, 4));
            faces.Add(new TriangleIndices(11, 10, 2));
            faces.Add(new TriangleIndices(10, 7, 6));
            faces.Add(new TriangleIndices(7, 1, 8));

            // 5 faces around point 3
            faces.Add(new TriangleIndices(3, 9, 4));
            faces.Add(new TriangleIndices(3, 4, 2));
            faces.Add(new TriangleIndices(3, 2, 6));
            faces.Add(new TriangleIndices(3, 6, 8));
            faces.Add(new TriangleIndices(3, 8, 9));

            // 5 adjacent faces 
            faces.Add(new TriangleIndices(4, 9, 5));
            faces.Add(new TriangleIndices(2, 4, 11));
            faces.Add(new TriangleIndices(6, 2, 10));
            faces.Add(new TriangleIndices(8, 6, 7));
            faces.Add(new TriangleIndices(9, 8, 1));

            // refine triangles
            for (int i = 0; i < Detail; i++)
            {
                List<TriangleIndices> faces2 = new List<TriangleIndices>();
                foreach (var tri in faces)
                {
                    // replace triangle by 4 triangles
                    int a = GetMiddlePoint(tri.v1, tri.v2, vertList, middlePointIndexCache);
                    int b = GetMiddlePoint(tri.v2, tri.v3, vertList, middlePointIndexCache);
                    int c = GetMiddlePoint(tri.v3, tri.v1, vertList, middlePointIndexCache);

                    faces2.Add(new TriangleIndices(tri.v1, a, c));
                    faces2.Add(new TriangleIndices(tri.v2, b, a));
                    faces2.Add(new TriangleIndices(tri.v3, c, b));
                    faces2.Add(new TriangleIndices(a, b, c));
                }
                faces = faces2;
            }

            for (int i = 0; i < vertList.Count; i++)
            {
                Vector3 n = vertList[i].normalized;
                normals.Add(n);
                float u = 0.5f - (0.5f * Mathf.Atan2(n.x, n.z) / Mathf.PI);
                float v = 1.0f - Mathf.Acos(n.y) / Mathf.PI;
                uvs.Add(new Vector2(u, v));
            }

            for (int i = 0; i < faces.Count; i++)
            {
                triList.Add(faces[i].v1);
                triList.Add(faces[i].v2);
                triList.Add(faces[i].v3);
            }

            System.Action<int, Vector2> fixVertex = (int i, Vector2 uv) =>
            {
                int index = triList[i];
                triList[i] = vertList.Count;
                vertList.Add(vertList[index]);
                normals.Add(normals[index]);
                uvs.Add(uv);
            };

            // fix texture seams
            for (int i = 0; i < triList.Count; i += 3)
            {
                Vector2 uv0 = uvs[triList[i]];
                Vector2 uv1 = uvs[triList[i + 1]];
                Vector2 uv2 = uvs[triList[i + 2]];
                float d1 = uv1.x - uv0.x;
                float d2 = uv2.x - uv0.x;
                if (Mathf.Abs(d1) > 0.5f)
                {
                    if (Mathf.Abs(d2) > 0.5f)
                    {
                        fixVertex(i, uv0 + new Vector2((d1 > 0.0f) ? 1.0f : -1.0f, 0.0f));
                    }
                    else
                    {
                        fixVertex(i + 1, uv1 + new Vector2((d1 < 0.0f) ? 1.0f : -1.0f, 0.0f));
                    }
                }
                else if (Mathf.Abs(d2) > 0.5f)
                {
                    fixVertex(i + 2, uv2 + new Vector2((d2 < 0.0f) ? 1.0f : -1.0f, 0.0f));
                }
            }

            mesh.SetVertices(vertList);
            mesh.SetUVs(0, uvs);
            mesh.SetNormals(normals);
            mesh.SetTriangles(triList, 0);
            mesh.RecalculateBounds();
            ;

            middlePointIndexCache.Clear();
        }
Ejemplo n.º 51
0
        /**
         * ProBuilderize in-place function.  You must call ToMesh() and Refresh() after
         * returning from this function, as this only creates the pb_Object and sets its
         * fields.  This allows you to record the mesh and gameObject for Undo operations.
         */
        public static bool ResetPbObjectWithMeshFilter(pb_Object pb, bool preserveFaces)
        {
            MeshFilter mf = pb.gameObject.GetComponent <MeshFilter>();

            if (mf == null || mf.sharedMesh == null)
            {
                Debug.Log(pb.name + " does not have a mesh or Mesh Filter component.");
                return(false);
            }

            Mesh m = mf.sharedMesh;

            int vertexCount = m.vertexCount;

            Vector3[] m_vertices = m.vertices;
            Color[]   m_colors   = m.colors != null && m.colors.Length == vertexCount ? m.colors : new Color[vertexCount];
            Vector2[] m_uvs      = m.uv;

            List <Vector3> verts = preserveFaces ? new List <Vector3>(m.vertices) : new List <Vector3>();
            List <Color>   cols  = preserveFaces ? new List <Color>(m.colors) : new List <Color>();
            List <Vector2> uvs   = preserveFaces ? new List <Vector2>(m.uv) : new List <Vector2>();
            List <pb_Face> faces = new List <pb_Face>();

            MeshRenderer mr = pb.gameObject.GetComponent <MeshRenderer>();

            if (mr == null)
            {
                mr = pb.gameObject.AddComponent <MeshRenderer>();
            }

            Material[] sharedMaterials = mr.sharedMaterials;
            int        mat_length      = sharedMaterials.Length;

            for (int n = 0; n < m.subMeshCount; n++)
            {
                int[] tris = m.GetTriangles(n);
                for (int i = 0; i < tris.Length; i += 3)
                {
                    int index = -1;
                    if (preserveFaces)
                    {
                        for (int j = 0; j < faces.Count; j++)
                        {
                            if (faces[j].distinctIndices.Contains(tris[i + 0]) ||
                                faces[j].distinctIndices.Contains(tris[i + 1]) ||
                                faces[j].distinctIndices.Contains(tris[i + 2]))
                            {
                                index = j;
                                break;
                            }
                        }
                    }

                    if (index > -1 && preserveFaces)
                    {
                        int   len = faces[index].indices.Length;
                        int[] arr = new int[len + 3];
                        System.Array.Copy(faces[index].indices, 0, arr, 0, len);
                        arr[len + 0] = tris[i + 0];
                        arr[len + 1] = tris[i + 1];
                        arr[len + 2] = tris[i + 2];
                        faces[index].SetIndices(arr);
                        faces[index].RebuildCaches();
                    }
                    else
                    {
                        int[] faceTris;

                        if (preserveFaces)
                        {
                            faceTris = new int[3]
                            {
                                tris[i + 0],
                                tris[i + 1],
                                tris[i + 2]
                            };
                        }
                        else
                        {
                            verts.Add(m_vertices[tris[i + 0]]);
                            verts.Add(m_vertices[tris[i + 1]]);
                            verts.Add(m_vertices[tris[i + 2]]);

                            cols.Add(m_colors != null && m_colors.Length == vertexCount ? m_colors[tris[i + 0]] : Color.white);
                            cols.Add(m_colors != null && m_colors.Length == vertexCount ? m_colors[tris[i + 1]] : Color.white);
                            cols.Add(m_colors != null && m_colors.Length == vertexCount ? m_colors[tris[i + 2]] : Color.white);

                            uvs.Add(m_uvs[tris[i + 0]]);
                            uvs.Add(m_uvs[tris[i + 1]]);
                            uvs.Add(m_uvs[tris[i + 2]]);

                            faceTris = new int[3] {
                                i + 0, i + 1, i + 2
                            };
                        }

                        faces.Add(
                            new pb_Face(
                                faceTris,
                                sharedMaterials[n >= mat_length ? mat_length - 1 : n],
                                new pb_UV(),
                                0,                              // smoothing group
                                -1,                             // texture group
                                -1,                             // element group
                                true                            // manualUV
                                ));
                    }
                }
            }

            pb.SetVertices(verts.ToArray());
            pb.SetUV(uvs.ToArray());
            pb.SetFaces(faces.ToArray());
            pb.SetSharedIndices(pb_IntArrayUtility.ExtractSharedIndices(verts.ToArray()));
            pb.SetColors(cols.ToArray());

            return(true);
        }
        public static void DrawCubes(Vector3[] topVerts, Vector3[] bottomVerts, Color[] vertexColors, float width)
        {
            if (active == null)
            {
                active = GameObject.FindObjectOfType(typeof(DebugUtility)) as DebugUtility;
            }
            if (active == null)
            {
                throw new System.NullReferenceException();
            }

            if (topVerts.Length != bottomVerts.Length || topVerts.Length != vertexColors.Length)
            {
                Debug.LogError("Array Lengths are not the same");
                return;
            }

            //65000 limit divided by 4*6 = 24
            if (topVerts.Length > 2708)
            {
                Vector3[] topVerts2     = new Vector3[topVerts.Length - 2708];
                Vector3[] bottomVerts2  = new Vector3[topVerts.Length - 2708];
                Color[]   vertexColors2 = new Color[topVerts.Length - 2708];

                for (int i = 2708; i < topVerts.Length; i++)
                {
                    topVerts2[i - 2708]     = topVerts[i];
                    bottomVerts2[i - 2708]  = bottomVerts[i];
                    vertexColors2[i - 2708] = vertexColors[i];
                }

                Vector3[] topVerts3     = new Vector3[2708];
                Vector3[] bottomVerts3  = new Vector3[2708];
                Color[]   vertexColors3 = new Color[2708];

                for (int i = 0; i < 2708; i++)
                {
                    topVerts3[i]     = topVerts[i];
                    bottomVerts3[i]  = bottomVerts[i];
                    vertexColors3[i] = vertexColors[i];
                }

                DrawCubes(topVerts2, bottomVerts2, vertexColors2, width);
                topVerts     = topVerts3;
                bottomVerts  = bottomVerts3;
                vertexColors = vertexColors3;
            }

            width /= 2F;

            Vector3[] vertices = new Vector3[topVerts.Length * 4 * 6];
            int[]     tris     = new int[topVerts.Length * 6 * 6];
            Color[]   colors   = new Color[topVerts.Length * 4 * 6];

            for (int i = 0; i < topVerts.Length; i++)
            {
                Vector3 top    = topVerts[i] + new Vector3(0, active.offset, 0);
                Vector3 bottom = bottomVerts[i] - new Vector3(0, active.offset, 0);;

                Vector3 top1    = top + new Vector3(-width, 0, -width);
                Vector3 top2    = top + new Vector3(width, 0, -width);
                Vector3 top3    = top + new Vector3(width, 0, width);
                Vector3 top4    = top + new Vector3(-width, 0, width);
                Vector3 bottom1 = bottom + new Vector3(-width, 0, -width);
                Vector3 bottom2 = bottom + new Vector3(width, 0, -width);
                Vector3 bottom3 = bottom + new Vector3(width, 0, width);
                Vector3 bottom4 = bottom + new Vector3(-width, 0, width);

                int vIndex = i * 4 * 6;

                Color col = vertexColors[i];
                //Color.Lerp (Color.green,Color.red,topVerts[i].y*0.06F);
                //

                for (int c = vIndex; c < vIndex + 24; c++)
                {
                    colors[c] = col;
                }

                //Top

                vertices[vIndex]     = top1;
                vertices[vIndex + 1] = top4;
                vertices[vIndex + 2] = top3;
                vertices[vIndex + 3] = top2;

                int tIndex = i * 6 * 6;
                tris[tIndex]     = vIndex;
                tris[tIndex + 1] = vIndex + 1;
                tris[tIndex + 2] = vIndex + 2;

                tris[tIndex + 3] = vIndex;
                tris[tIndex + 4] = vIndex + 2;
                tris[tIndex + 5] = vIndex + 3;

                //Bottom
                vIndex += 4;
                vertices[vIndex + 3] = bottom1;
                vertices[vIndex + 2] = bottom4;
                vertices[vIndex + 1] = bottom3;
                vertices[vIndex]     = bottom2;

                tIndex          += 6;
                tris[tIndex]     = vIndex;
                tris[tIndex + 1] = vIndex + 1;
                tris[tIndex + 2] = vIndex + 2;

                tris[tIndex + 3] = vIndex;
                tris[tIndex + 4] = vIndex + 2;
                tris[tIndex + 5] = vIndex + 3;

                //Right
                vIndex              += 4;
                vertices[vIndex]     = bottom2;
                vertices[vIndex + 1] = top2;
                vertices[vIndex + 2] = top3;
                vertices[vIndex + 3] = bottom3;

                tIndex          += 6;
                tris[tIndex]     = vIndex;
                tris[tIndex + 1] = vIndex + 1;
                tris[tIndex + 2] = vIndex + 2;

                tris[tIndex + 3] = vIndex;
                tris[tIndex + 4] = vIndex + 2;
                tris[tIndex + 5] = vIndex + 3;

                //Left
                vIndex += 4;
                vertices[vIndex + 3] = bottom1;
                vertices[vIndex + 2] = top1;
                vertices[vIndex + 1] = top4;
                vertices[vIndex]     = bottom4;

                tIndex          += 6;
                tris[tIndex]     = vIndex;
                tris[tIndex + 1] = vIndex + 1;
                tris[tIndex + 2] = vIndex + 2;

                tris[tIndex + 3] = vIndex;
                tris[tIndex + 4] = vIndex + 2;
                tris[tIndex + 5] = vIndex + 3;

                //Forward
                vIndex += 4;
                vertices[vIndex + 3] = bottom3;
                vertices[vIndex + 2] = bottom4;
                vertices[vIndex + 1] = top4;
                vertices[vIndex]     = top3;

                tIndex          += 6;
                tris[tIndex]     = vIndex;
                tris[tIndex + 1] = vIndex + 1;
                tris[tIndex + 2] = vIndex + 2;

                tris[tIndex + 3] = vIndex;
                tris[tIndex + 4] = vIndex + 2;
                tris[tIndex + 5] = vIndex + 3;

                //Back
                vIndex              += 4;
                vertices[vIndex]     = bottom2;
                vertices[vIndex + 1] = bottom1;
                vertices[vIndex + 2] = top1;
                vertices[vIndex + 3] = top2;

                tIndex          += 6;
                tris[tIndex]     = vIndex;
                tris[tIndex + 1] = vIndex + 1;
                tris[tIndex + 2] = vIndex + 2;

                tris[tIndex + 3] = vIndex;
                tris[tIndex + 4] = vIndex + 2;
                tris[tIndex + 5] = vIndex + 3;
            }


            Mesh mesh = new Mesh();

            mesh.vertices  = vertices;
            mesh.triangles = tris;
            mesh.colors    = colors;

            mesh.name = "VoxelMesh";

            mesh.RecalculateNormals();
            mesh.RecalculateBounds();

            if (active.optimizeMeshes)
            {
                mesh.Optimize();
            }

            GameObject   go   = new GameObject("DebugMesh");
            MeshRenderer rend = go.AddComponent(typeof(MeshRenderer)) as MeshRenderer;

            rend.material = active.defaultMaterial;
            (go.AddComponent(typeof(MeshFilter)) as MeshFilter).mesh = mesh;
        }
Ejemplo n.º 53
0
 public static void GenerateSecondaryUVSet(Mesh src, UnwrapParam settings)
 {
     MeshUtility.SetPerTriangleUV2(src, Unwrapping.GeneratePerTriangleUV(src, settings));
 }
Ejemplo n.º 54
0
        /**
         * "ProBuilder-ize function"
         */
        public static pb_Object CreatePbObjectWithTransform(Transform t, bool preserveFaces)
        {
            Mesh m = t.GetComponent <MeshFilter>().sharedMesh;

            Vector3[] m_vertices = m.vertices;
            Color[]   m_colors   = m.colors ?? new Color[m_vertices.Length];
            Vector2[] m_uvs      = m.uv;

            List <Vector3> verts = preserveFaces ? new List <Vector3>(m.vertices) : new List <Vector3>();
            List <Color>   cols  = preserveFaces ? new List <Color>(m.colors) : new List <Color>();
            List <Vector2> uvs   = preserveFaces ? new List <Vector2>(m.uv) : new List <Vector2>();
            List <pb_Face> faces = new List <pb_Face>();

            for (int n = 0; n < m.subMeshCount; n++)
            {
                int[] tris = m.GetTriangles(n);
                for (int i = 0; i < tris.Length; i += 3)
                {
                    int index = -1;
                    if (preserveFaces)
                    {
                        for (int j = 0; j < faces.Count; j++)
                        {
                            if (faces[j].distinctIndices.Contains(tris[i + 0]) ||
                                faces[j].distinctIndices.Contains(tris[i + 1]) ||
                                faces[j].distinctIndices.Contains(tris[i + 2]))
                            {
                                index = j;
                                break;
                            }
                        }
                    }

                    if (index > -1 && preserveFaces)
                    {
                        int   len = faces[index].indices.Length;
                        int[] arr = new int[len + 3];
                        System.Array.Copy(faces[index].indices, 0, arr, 0, len);
                        arr[len + 0] = tris[i + 0];
                        arr[len + 1] = tris[i + 1];
                        arr[len + 2] = tris[i + 2];
                        faces[index].SetIndices(arr);
                        faces[index].RebuildCaches();
                    }
                    else
                    {
                        int[] faceTris;

                        if (preserveFaces)
                        {
                            faceTris = new int[3]
                            {
                                tris[i + 0],
                                tris[i + 1],
                                tris[i + 2]
                            };
                        }
                        else
                        {
                            verts.Add(m_vertices[tris[i + 0]]);
                            verts.Add(m_vertices[tris[i + 1]]);
                            verts.Add(m_vertices[tris[i + 2]]);

                            cols.Add(m_colors != null ? m_colors[tris[i + 0]] : Color.white);
                            cols.Add(m_colors != null ? m_colors[tris[i + 1]] : Color.white);
                            cols.Add(m_colors != null ? m_colors[tris[i + 2]] : Color.white);

                            uvs.Add(m_uvs[tris[i + 0]]);
                            uvs.Add(m_uvs[tris[i + 1]]);
                            uvs.Add(m_uvs[tris[i + 2]]);

                            faceTris = new int[3] {
                                i + 0, i + 1, i + 2
                            };
                        }

                        faces.Add(
                            new pb_Face(
                                faceTris,
                                t.GetComponent <MeshRenderer>().sharedMaterials[n],
                                new pb_UV(),
                                0,                              // smoothing group
                                -1,                             // texture group
                                -1,                             // element group
                                true                            // manualUV
                                ));
                    }
                }
            }

            GameObject go = (GameObject)GameObject.Instantiate(t.gameObject);

            go.GetComponent <MeshFilter>().sharedMesh = null;

            pb_Object pb = go.AddComponent <pb_Object>();

            pb.GeometryWithVerticesFaces(verts.ToArray(), faces.ToArray());

            pb.SetColors(cols.ToArray());
            pb.SetUV(uvs.ToArray());

            pb.SetName(t.name);

            go.transform.position      = t.position;
            go.transform.localRotation = t.localRotation;
            go.transform.localScale    = t.localScale;

            pb.CenterPivot(null);

            return(pb);
        }
Ejemplo n.º 55
0
 internal static Vector2[] GeneratePerTriangleUVImpl(Mesh src, UnwrapParam settings)
 {
     return(Unwrapping.INTERNAL_CALL_GeneratePerTriangleUVImpl(src, ref settings));
 }
Ejemplo n.º 56
0
    /// <summary>
    /// Set the draw call's geometry.
    /// </summary>

    public void Set(BetterList <Vector3> verts, BetterList <Vector3> norms, BetterList <Vector4> tans, BetterList <Vector2> uvs, BetterList <Color32> cols)
    {
        int count = verts.size;

        // Safety check to ensure we get valid values
        if (count > 0 && (count == uvs.size && count == cols.size) && (count % 4) == 0)
        {
            // Cache all components
            if (mFilter == null)
            {
                mFilter = gameObject.GetComponent <MeshFilter>();
            }
            if (mFilter == null)
            {
                mFilter = gameObject.AddComponent <MeshFilter>();
            }

            if (verts.size < 65000)
            {
                // Populate the index buffer
                int  indexCount = (count >> 1) * 3;
                bool setIndices = (mIndices == null || mIndices.Length != indexCount);

                // Create the mesh
                if (mMesh == null)
                {
                    mMesh           = new Mesh();
                    mMesh.hideFlags = HideFlags.DontSave;
                    mMesh.name      = (mMaterial != null) ? mMaterial.name : "Mesh";
#if !UNITY_3_5
                    mMesh.MarkDynamic();
#endif
                    setIndices = true;
                }
#if !UNITY_FLASH
                // If the buffer length doesn't match, we need to trim all buffers
                bool trim = (uvs.buffer.Length != verts.buffer.Length) ||
                            (cols.buffer.Length != verts.buffer.Length) ||
                            (norms != null && norms.buffer.Length != verts.buffer.Length) ||
                            (tans != null && tans.buffer.Length != verts.buffer.Length);

                mTriangles = (verts.size >> 1);

                if (trim || verts.buffer.Length > 65000)
                {
                    if (trim || mMesh.vertexCount != verts.size)
                    {
                        mMesh.Clear();
                        setIndices = true;
                    }

                    mMesh.vertices = verts.ToArray();
                    mMesh.uv       = uvs.ToArray();
                    mMesh.colors32 = cols.ToArray();

                    if (norms != null)
                    {
                        mMesh.normals = norms.ToArray();
                    }
                    if (tans != null)
                    {
                        mMesh.tangents = tans.ToArray();
                    }
                }
                else
                {
                    if (mMesh.vertexCount != verts.buffer.Length)
                    {
                        mMesh.Clear();
                        setIndices = true;
                    }

                    mMesh.vertices = verts.buffer;
                    mMesh.uv       = uvs.buffer;
                    mMesh.colors32 = cols.buffer;

                    if (norms != null)
                    {
                        mMesh.normals = norms.buffer;
                    }
                    if (tans != null)
                    {
                        mMesh.tangents = tans.buffer;
                    }
                }
#else
                mTriangles = (verts.size >> 1);

                if (mMesh.vertexCount != verts.size)
                {
                    mMesh.Clear();
                    setIndices = true;
                }

                mMesh.vertices = verts.ToArray();
                mMesh.uv       = uvs.ToArray();
                mMesh.colors32 = cols.ToArray();

                if (norms != null)
                {
                    mMesh.normals = norms.ToArray();
                }
                if (tans != null)
                {
                    mMesh.tangents = tans.ToArray();
                }
#endif
                if (setIndices)
                {
                    mIndices        = GenerateCachedIndexBuffer(count, indexCount);
                    mMesh.triangles = mIndices;
                }
                if (!alwaysOnScreen)
                {
                    mMesh.RecalculateBounds();
                }
                mFilter.mesh = mMesh;
            }
            else
            {
                mTriangles = 0;
                if (mFilter.mesh != null)
                {
                    mFilter.mesh.Clear();
                }
                Debug.LogError("Too many vertices on one panel: " + verts.size);
            }

            if (mRenderer == null)
            {
                mRenderer = gameObject.GetComponent <MeshRenderer>();
            }

            if (mRenderer == null)
            {
                mRenderer = gameObject.AddComponent <MeshRenderer>();
#if UNITY_EDITOR
                mRenderer.enabled = isActive;
#endif
            }
            UpdateMaterials();
        }
        else
        {
            if (mFilter.mesh != null)
            {
                mFilter.mesh.Clear();
            }
            Debug.LogError("UIWidgets must fill the buffer with 4 vertices per quad. Found " + count);
        }
    }
Ejemplo n.º 57
0
 public Job_BuildCollisionMesh(VoxelChunk Chunk, Mesh Target) : base(Chunk)
 {
     mTarget = Target;
 }
Ejemplo n.º 58
0
 private static extern Vector2[] INTERNAL_CALL_GeneratePerTriangleUVImpl(Mesh src, ref UnwrapParam settings);
    void OnWizardCreate()
    {
        GameObject newCone = new GameObject("Cone");

        if (openingAngle > 0 && openingAngle < 180)
        {
            radiusTop    = 0;
            radiusBottom = length * Mathf.Tan(openingAngle * Mathf.Deg2Rad / 2);
        }
        string meshName       = newCone.name + numVertices + "v" + radiusTop + "t" + radiusBottom + "b" + length + "l" + length + (outside?"o":"") + (inside?"i":"");
        string meshPrefabPath = "Assets/Editor/" + meshName + ".asset";
        Mesh   mesh           = (Mesh)AssetDatabase.LoadAssetAtPath(meshPrefabPath, typeof(Mesh));

        if (mesh == null)
        {
            mesh      = new Mesh();
            mesh.name = meshName;
            // can't access Camera.current
            //newCone.transform.position = Camera.current.transform.position + Camera.current.transform.forward * 5.0f;
            int       multiplier = (outside?1:0) + (inside?1:0);
            int       offset     = (outside && inside?2 * numVertices:0);
            Vector3[] vertices   = new Vector3[2 * multiplier * numVertices]; // 0..n-1: top, n..2n-1: bottom
            Vector3[] normals    = new Vector3[2 * multiplier * numVertices];
            Vector2[] uvs        = new Vector2[2 * multiplier * numVertices];
            int[]     tris;
            float     slope    = Mathf.Atan((radiusBottom - radiusTop) / length); // (rad difference)/height
            float     slopeSin = Mathf.Sin(slope);
            float     slopeCos = Mathf.Cos(slope);
            int       i;

            for (i = 0; i < numVertices; i++)
            {
                float angle        = 2 * Mathf.PI * i / numVertices;
                float angleSin     = Mathf.Sin(angle);
                float angleCos     = Mathf.Cos(angle);
                float angleHalf    = 2 * Mathf.PI * (i + 0.5f) / numVertices; // for degenerated normals at cone tips
                float angleHalfSin = Mathf.Sin(angleHalf);
                float angleHalfCos = Mathf.Cos(angleHalf);

                vertices[i] = new Vector3(radiusTop * angleCos, radiusTop * angleSin, 0);
                vertices[i + numVertices] = new Vector3(radiusBottom * angleCos, radiusBottom * angleSin, length);

                if (radiusTop == 0)
                {
                    normals[i] = new Vector3(angleHalfCos * slopeCos, angleHalfSin * slopeCos, -slopeSin);
                }
                else
                {
                    normals[i] = new Vector3(angleCos * slopeCos, angleSin * slopeCos, -slopeSin);
                }
                if (radiusBottom == 0)
                {
                    normals[i + numVertices] = new Vector3(angleHalfCos * slopeCos, angleHalfSin * slopeCos, -slopeSin);
                }
                else
                {
                    normals[i + numVertices] = new Vector3(angleCos * slopeCos, angleSin * slopeCos, -slopeSin);
                }

                uvs[i] = new Vector2(1.0f * i / numVertices, 1);
                uvs[i + numVertices] = new Vector2(1.0f * i / numVertices, 0);

                if (outside && inside)
                {
                    // vertices and uvs are identical on inside and outside, so just copy
                    vertices[i + 2 * numVertices] = vertices[i];
                    vertices[i + 3 * numVertices] = vertices[i + numVertices];
                    uvs[i + 2 * numVertices]      = uvs[i];
                    uvs[i + 3 * numVertices]      = uvs[i + numVertices];
                }
                if (inside)
                {
                    // invert normals
                    normals[i + offset] = -normals[i];
                    normals[i + numVertices + offset] = -normals[i + numVertices];
                }
            }
            mesh.vertices = vertices;
            mesh.normals  = normals;
            mesh.uv       = uvs;

            // create triangles
            // here we need to take care of point order, depending on inside and outside
            int cnt = 0;
            if (radiusTop == 0)
            {
                // top cone
                tris = new int[numVertices * 3 * multiplier];
                if (outside)
                {
                    for (i = 0; i < numVertices; i++)
                    {
                        tris[cnt++] = i + numVertices;
                        tris[cnt++] = i;
                        if (i == numVertices - 1)
                        {
                            tris[cnt++] = numVertices;
                        }
                        else
                        {
                            tris[cnt++] = i + 1 + numVertices;
                        }
                    }
                }
                if (inside)
                {
                    for (i = offset; i < numVertices + offset; i++)
                    {
                        tris[cnt++] = i;
                        tris[cnt++] = i + numVertices;
                        if (i == numVertices - 1 + offset)
                        {
                            tris[cnt++] = numVertices + offset;
                        }
                        else
                        {
                            tris[cnt++] = i + 1 + numVertices;
                        }
                    }
                }
            }
            else if (radiusBottom == 0)
            {
                // bottom cone
                tris = new int[numVertices * 3 * multiplier];
                if (outside)
                {
                    for (i = 0; i < numVertices; i++)
                    {
                        tris[cnt++] = i;
                        if (i == numVertices - 1)
                        {
                            tris[cnt++] = 0;
                        }
                        else
                        {
                            tris[cnt++] = i + 1;
                        }
                        tris[cnt++] = i + numVertices;
                    }
                }
                if (inside)
                {
                    for (i = offset; i < numVertices + offset; i++)
                    {
                        if (i == numVertices - 1 + offset)
                        {
                            tris[cnt++] = offset;
                        }
                        else
                        {
                            tris[cnt++] = i + 1;
                        }
                        tris[cnt++] = i;
                        tris[cnt++] = i + numVertices;
                    }
                }
            }
            else
            {
                // truncated cone
                tris = new int[numVertices * 6 * multiplier];
                if (outside)
                {
                    for (i = 0; i < numVertices; i++)
                    {
                        int ip1 = i + 1;
                        if (ip1 == numVertices)
                        {
                            ip1 = 0;
                        }

                        tris[cnt++] = i;
                        tris[cnt++] = ip1;
                        tris[cnt++] = i + numVertices;

                        tris[cnt++] = ip1 + numVertices;
                        tris[cnt++] = i + numVertices;
                        tris[cnt++] = ip1;
                    }
                }
                if (inside)
                {
                    for (i = offset; i < numVertices + offset; i++)
                    {
                        int ip1 = i + 1;
                        if (ip1 == numVertices + offset)
                        {
                            ip1 = offset;
                        }

                        tris[cnt++] = ip1;
                        tris[cnt++] = i;
                        tris[cnt++] = i + numVertices;

                        tris[cnt++] = i + numVertices;
                        tris[cnt++] = ip1 + numVertices;
                        tris[cnt++] = ip1;
                    }
                }
            }
            mesh.triangles = tris;
            AssetDatabase.CreateAsset(mesh, meshPrefabPath);
            AssetDatabase.SaveAssets();
        }

        MeshFilter mf = newCone.AddComponent <MeshFilter>();

        mf.mesh = mesh;

        newCone.AddComponent <MeshRenderer>();

        if (addCollider)
        {
            MeshCollider mc = newCone.AddComponent <MeshCollider>();
            mc.sharedMesh = mf.sharedMesh;
        }

        Selection.activeObject = newCone;
    }
Ejemplo n.º 60
0
 public static Vector2[] GeneratePerTriangleUV(Mesh src, UnwrapParam settings)
 {
     return(Unwrapping.GeneratePerTriangleUVImpl(src, settings));
 }