Example #1
0
    private void extrude()
    {
        height = heightProperty * Game.heightFactor;

        MeshFilter filter = roof.GetComponent <MeshFilter>() as MeshFilter;
        Mesh       msh    = filter.mesh;

        Matrix4x4 [] extrusionPath = new Matrix4x4 [2];
        extrusionPath[0] = roof.transform.worldToLocalMatrix * Matrix4x4.TRS(roof.transform.position, Quaternion.identity, Vector3.one);
        extrusionPath[1] = roof.transform.worldToLocalMatrix * Matrix4x4.TRS(roof.transform.position + new Vector3(0, 0, height), Quaternion.identity, Vector3.one);

        Mesh extrudedmesh = new Mesh();

//		MeshExtrusion.ExtrudeMesh(msh, GetComponent<MeshFilter>().mesh, extrusionPath, false);
        MeshExtrusion.ExtrudeMesh(msh, extrudedmesh, extrusionPath, false);

        // Add the sides to this gameobject
        MeshFilter sidesMeshFilter = gameObject.AddComponent <MeshFilter> ();

        sidesMeshFilter.mesh = extrudedmesh;
        MeshRenderer sidesMeshRenderer = gameObject.AddComponent <MeshRenderer> ();

        sidesMeshRenderer.material.color = new Color(1f, 0, 0);
        transform.SetParent(this.gameObject.transform);

        transform.localPosition      += bodyPositionWhileRising;
        roof.transform.localPosition -= bodyPositionWhileRising;

        // TODO - Set weight on stadium
        setBuildingWeight();
    }
Example #2
0
    /// <summary>
    /// Called when the "Extrude" button is clicked
    /// </summary>
    private void OnWizardCreate()
    {
        if (this.Extrusion <= 0)
        {
            return;
        }

        try
        {
            Transform[] transforms = Selection.transforms;

            foreach (Transform transform in transforms)
            {
                GameObject go = transform.gameObject;

                if (go == null)
                {
                    continue;
                }

                MeshExtrusion.Extrude(go, this.Extrusion, this.InvertFaces);
            }
        }
        catch (Exception ex)
        {
            Debug.Log(ex);
        }
    }
Example #3
0
    /// <summary>
    /// Called when the "Import" button is clicked
    /// </summary>
    private void OnWizardCreate()
    {
        GameObject parentGameObject = new GameObject();

        parentGameObject.name = this.ParentName;

        try
        {
            FeatureCollection features = GeoJSONObject.Deserialize(this.GeoJSONSource.text);

            MapBounds bounds = features.bbox;
            bounds.ProjectToWebMercator();
            bounds.SetScale(this.HorizontalScale);

            this.UpdateCameraParameters(bounds.Center.ToVector3(), this.HorizontalScale, this.VerticalScale);

            foreach (FeatureObject ftr in features.features)
            {
                MapFeature feature = new MapFeature(ftr.properties[this.ObjectIDFieldName]);

                List <Vertex> vertices = ftr.geometry.AllPositions().ConvertAll((v) => new Vertex(v.latitude, v.longitude, 0.0));

                feature.SetAttributes(ftr.properties);
                feature.SetGeometry(EnumGeometryType.Polygon, vertices);

                if (feature.Geometry.IsEmpty)
                {
                    continue;
                }

                feature.Geometry.ProjectToWebMercator();
                feature.Geometry.SetScale(this.HorizontalScale);

                Vector3 cityOrigin = feature.Geometry.GetCentroid();

                GameObject go = feature.ToGameObject();
                go.transform.position = cityOrigin - bounds.Center.ToVector3();
                go.transform.parent   = parentGameObject.transform;

                Material material = new Material(Shader.Find("Standard"));
                material.color = Color.gray;// UnityEngine.Random.ColorHSV();
                go.GetComponent <Renderer>().material = material;

                if (this.Extrude)
                {
                    float height = feature.Attributes.Get <float>(this.ExtrudeField);

                    if (height > 0)
                    {
                        height = height * this.ExtrudeFactor;
                        MeshExtrusion.Extrude(go, height, this.InvertFaces);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Debug.Log(ex);
        }
    }
Example #4
0
    // Use this for initialization
    void Start()
    {
        // Getting the mesh of THIS object (the plane).
        this.sourceMesh       = GetComponent <MeshFilter>().mesh;
        this.precomputedEdges = MeshExtrusion.BuildManifoldEdges(this.sourceMesh);

        // Defining transformations to extrude the mesh.
        Matrix4x4[] sections = new Matrix4x4[2];

        // Starting point (where the mesh already is, but its needed so the new mesh does not generate with a hole).
        sections[0] = this.transform.localToWorldMatrix;
        // The end point.
        sections[1] = this.transform.worldToLocalMatrix * Matrix4x4.TRS(new Vector3(0, 1, 1), Quaternion.Euler(0, 45, 0), new Vector3(0.75f, 2, 1));

        // Get the mesh again (the script need a different reference to the same mesh for some reason?).
        Mesh mesh = GetComponent <MeshFilter>().mesh;

        // Actually perform the extrusion, the parameter [invertFaces] is extremely important in this case but its kind of hard to programatically tell when it is needed.
        // I would guess you would need to somehow see the direction of the normals before even creating the face.
        MeshExtrusion.ExtrudeMesh(this.sourceMesh, mesh, sections, true);

        // Preparing CSG objects for substraction.
        // Again, passing a new refference to the same mesh is important for some reason.
        CSG plane = CSG.fromMesh(GetComponent <MeshFilter>().mesh, this.transform);
        CSG cube  = CSG.fromMesh(this.cubeCutter.GetComponent <MeshFilter>().mesh, this.cubeCutter.transform);

        // Save the operation, this does not affect neither meshes yet.
        CSG result = plane.subtract(cube);

        // Replace the mesh of THIS object with the mesh representation of the operation.
        this.GetComponent <MeshFilter>().mesh = result.toMesh();

        // Hide the cube to visualize the result.
        this.cubeCutter.SetActive(false);
    }
Example #5
0
    public static Mesh Extrude(Mesh mesh, GameObject obj, float height)
    {
        bool normalFaceDown = mesh.normals [0].y > 0;

        Matrix4x4 [] extrusionPath = new Matrix4x4 [2];
        Matrix4x4    a             = obj.transform.worldToLocalMatrix * Matrix4x4.TRS(obj.transform.position, Quaternion.identity, Vector3.one);
        Matrix4x4    b             = obj.transform.worldToLocalMatrix * Matrix4x4.TRS(obj.transform.position + new Vector3(0, height, 0), Quaternion.identity, Vector3.one);

        //		Check if normal are facing inside
        if (!normalFaceDown)
        {
            extrusionPath [0] = a;
            extrusionPath [1] = b;
        }
        else               //This is the base case
        {
            extrusionPath [0] = b;
            extrusionPath [1] = a;
        }

        MeshExtrusion.ExtrudeMesh(mesh, mesh, extrusionPath, false);

//		FixUV (mesh, height);

        return(mesh);
    }
Example #6
0
    override public GameObject execute()
    {
        Mesh mesh = _shape.GetComponent <MeshFilter>().mesh;

        Matrix4x4 [] extrusionPath = new Matrix4x4 [2];
        extrusionPath[0] = _shape.transform.worldToLocalMatrix * Matrix4x4.TRS(_shape.transform.position, Quaternion.identity, Vector3.one);
        extrusionPath[1] = _shape.transform.worldToLocalMatrix * Matrix4x4.TRS(_shape.transform.position + new Vector3(0, 1f, 0), Quaternion.identity, Vector3.one);
        MeshExtrusion.ExtrudeMesh(mesh, _shape.GetComponent <MeshFilter>().mesh, extrusionPath, false);
        return(_shape);
    }
Example #7
0
    public IEnumerator BuildMesh()
    {
        if (roads.Count < 2)
        {
            yield break;
        }

        float   roadHeight = city.settings.roadDimensions.y;
        Texture texture    = city.settings.roadTexture;

        Vector3[] vertices = LocalSpaceVertices().ToArray();


        if (vertices.Length < 3)
        {
            //print("Not enough vertices to make a shape! Vertex count: " + vertices.Length);
            yield break;
        }

        Vector2 mainTexScale;
        Mesh    m = HullMesher2D.BuildPolygon(vertices, out mainTexScale);

        Material mat = GetComponent <MeshRenderer>().material;

        if (texture != null)
        {
            mat.mainTexture      = texture;
            mat.mainTextureScale = mainTexScale;
        }
        else
        {
            mat.color = Color.gray;
        }


        GizmosToDraw = new List <Vector3>();
        GizmosToDraw.AddRange(vertices);

        Quaternion rotation = Quaternion.identity;
        Vector3    z        = Vector3.zero;
        Matrix4x4  op0      = Matrix4x4.TRS(z, rotation, Vector3.one);
        Matrix4x4  op1      = Matrix4x4.TRS(transform.up * roadHeight, rotation, Vector3.one);

        Matrix4x4[] ops = new Matrix4x4[] { op0, op1, };

        MeshExtrusion.ExtrudeMesh(m, GetComponent <MeshFilter>().mesh, ops, true);

        m.RecalculateNormals();
        m.RecalculateBounds();

        //print("Finished building intersection.");
        yield break;
    }
    void LateUpdate()
    {
        Vector3 position = transform.position;
        float   now      = Time.time;

        // Remove old sections
        while (sections.Count > 0 && now > sections[sections.Count - 1].time + time)
        {
            sections.RemoveAt(sections.Count - 1);
        }


        // Add a new trail section to beginning of array
        if (sections.Count == 0 || (sections[0].point - position).sqrMagnitude > minDistance * minDistance)
        {
            ExtrudedTrailSection section = new ExtrudedTrailSection();
            section.point  = position;
            section.matrix = transform.localToWorldMatrix;
            section.time   = now;
            sections.Insert(0, section);
            // print(sections.Count);
        }

        // We need at least 2 sections to create the line
        if (sections.Count < 2)
        {
            return;
        }

        Matrix4x4 worldToLocal = transform.worldToLocalMatrix;

        Matrix4x4[] finalSections = new Matrix4x4[sections.Count];

        for (int i = 0; i < sections.Count; i++)
        {
            finalSections[i] = worldToLocal * sections[i].matrix;
        }

        // Rebuild the extrusion mesh
        MeshExtrusion.ExtrudeMesh(srcMesh, GetComponent <MeshFilter>().mesh, finalSections, precomputedEdges, invertFaces, buildCaps);
        //
        GetComponent <MeshFilter>().mesh.RecalculateTangents();
    }
        void Start()
        {
            Mesh mesh = gameObject.GetComponent <MeshFilter>().mesh;

            normal = mesh.normals [0];
            //		bool normalFaceDown = mesh.normals [0].y > 0 ;

            Matrix4x4 [] extrusionPath = new Matrix4x4 [2];
            extrusionPath[0] = gameObject.transform.worldToLocalMatrix * Matrix4x4.TRS(gameObject.transform.position, Quaternion.identity, Vector3.one);
            extrusionPath[1] = gameObject.transform.worldToLocalMatrix * Matrix4x4.TRS(gameObject.transform.position + new Vector3(0, height, 0), Quaternion.identity, Vector3.one);
            MeshExtrusion.ExtrudeMesh(mesh, gameObject.GetComponent <MeshFilter>().mesh, extrusionPath, false);

            mesh = Extrude(mesh, gameObject, height);

            //		//Check if normal are facing inside
            //		if (normalFaceDown) {
            //			gameObject.AddComponent<ReverseNormals>();
            //		}
        }
Example #10
0
    public static Mesh SliceExtrude(Mesh mesh, GameObject obj, float height, float topSectionH, float bottomSectionH, float sliceHeight)
    {
//		bool normalFaceDown = mesh.normals [0].y > 0 ;

        if (height < sliceHeight)
        {
            return(Extrude(mesh, obj, height));
        }

        int numberOfSlices = (int)Mathf.Ceil((height) / sliceHeight);

        sliceHeight = height / numberOfSlices;

        List <Matrix4x4> extrusion = new List <Matrix4x4> ();

        for (int i = numberOfSlices; i > -1; i--)
        {
            Vector3 pos = obj.transform.position;
            pos.y = (i - 1) * sliceHeight;
            Matrix4x4 mat = obj.transform.worldToLocalMatrix * Matrix4x4.TRS(pos + new Vector3(0, sliceHeight, 0), Quaternion.identity, Vector3.one);
            extrusion.Add(mat);
        }

        Profiler.BeginSample("[GoMap] extrudemesh");
        MeshExtrusion.ExtrudeMesh(mesh, mesh, extrusion.ToArray(), false);
        Profiler.EndSample();

        Profiler.BeginSample("[GoMap] FixUv extruded");
//		FixUV (mesh,sliceHeight);
        Profiler.EndSample();


//		//TODO: TEST
//		ChangeUV changeUV = obj.AddComponent<ChangeUV>();
//		changeUV.sliceH = sliceHeight;
//		changeUV.numberOfSlices = numberOfSlices;

        return(mesh);
    }
    void UpdateMesh()
    {
        // get points
        Vector3[] vertices = new Vector3[transform.childCount];
        for (int i = 0; i < transform.childCount; i++)
        {
            vertices[i] = transform.GetChild(i).localPosition;
        }

        // triangulate
        Vector3[] transformedVertices = new Vector3[vertices.Length];
        for (int i = 0; i < vertices.Length; i++)
        {
            transformedVertices[i] = triangulationPlane ? triangulationPlane.InverseTransformPoint(vertices[i]): vertices[i];
        }
        int[] triangles = DelaunayTriangulator.Triangulator.ConvertToVertexIndexList(DelaunayTriangulator.Triangulator.Triangulate(transformedVertices));

        // generate colors
        Color[] colors = new Color[transform.childCount];
        for (int i = 0; i < colors.Length; i++)
        {
            colors[i] = color;
        }

        MeshExtrusion.Edge[] edges = MeshExtrusion.BuildManifoldEdges(vertices.Length, mesh.triangles);  // get edges to color them differently
        for (int i = 0; i < edges.Length; i++)
        {
            int vertId0 = edges[i].vertexIndex[0]; // one of the two points of the edge
            colors[vertId0] = edgeColor;
        }

        // update mesh
        mesh.Clear();
        mesh.vertices  = vertices;
        mesh.triangles = triangles;
        mesh.colors    = colors;
        mesh.RecalculateBounds();
    }
Example #12
0
        private GameObject getZObject()
        {
            ExtractFaces extractZFace = new ExtractFaces(this.form, ExtractFaces.FACE.Z);

            int[] verticesInCenter;
            Mesh  planeMesh = extractZFace.getFace(out verticesInCenter);

            GameObject   go           = new GameObject("FormForZPlane");
            MeshFilter   meshFilter   = go.AddComponent <MeshFilter>();
            MeshCollider meshCollider = go.AddComponent <MeshCollider>();

            go.AddComponent <MeshRenderer>();

            meshFilter.sharedMesh   = planeMesh;
            meshCollider.sharedMesh = planeMesh;

            MeshExtrusion.Edge[] falseEdges = MeshExtrusion.BuildManifoldEdges(planeMesh);
            MeshExtrusion.Edge[] realEdges  = VertexClassifier.getRealEdges(falseEdges, verticesInCenter);

            // Defining transformations to extrude the mesh.
            Matrix4x4[] sections = new Matrix4x4[2];

            // Starting point (where the mesh already is, but its needed so the new mesh does not generate with a hole).
            sections[0] = go.transform.localToWorldMatrix;
            // The end point.
            sections[1] = go.transform.worldToLocalMatrix * Matrix4x4.TRS(new Vector3(0, 0, 1), Quaternion.Euler(0, 0, 0), new Vector3(1, 1, 1));

            // Get the mesh again (the script need a different reference to the same mesh for some reason?).
            Mesh deepMesh = new Mesh();

            // Actually perform the extrusion, the parameter [invertFaces] is extremely important in this case but its kind of hard to programatically tell when it is needed.
            // I would guess you would need to somehow see the direction of the normals before even creating the face.
            MeshExtrusion.ExtrudeMesh(planeMesh, deepMesh, sections, realEdges, true);

            asignNewMesh(deepMesh, go);

            return(go);
        }
Example #13
0
    // Update is called once per frame
    void LateUpdate()
    {
        var position = transform.position;
        var now      = Time.time;

        while (sections.Count > 0 && now > sections [sections.Count - 1].time + time)
        {
            sections.RemoveAt(0);
        }

        // Add a new trail section to beginning of array
        if (sections.Count == 0 || (sections[0].point - position).sqrMagnitude > minDistance * minDistance)
        {
            ExtrudedTrailSection section = new ExtrudedTrailSection();
            section.point  = position;
            section.matrix = transform.localToWorldMatrix;
            section.time   = now;
            sections.Insert(0, section);
        }

        if (sections.Count < 2)
        {
            return;
        }

        worldToLocal  = transform.worldToLocalMatrix;
        finalSections = new Matrix4x4[sections.Count];


        for (int i = 0; i < sections.Count; i++)
        {
            if (autoCalculateOrientation)
            {
                if (i == 0)
                {
                    direction        = sections[0].point - sections[1].point;
                    rotation         = Quaternion.LookRotation(direction, Vector3.up);
                    previousRotation = rotation;
                    finalSections[i] = worldToLocal * Matrix4x4.TRS(position, rotation, Vector3.one);
                }
                // all elements get the direction by looking up the next section
                else if (i != sections.Count - 1)
                {
                    direction = sections[i].point - sections[i + 1].point;
                    rotation  = Quaternion.LookRotation(direction, Vector3.up);

                    angle = Quaternion.Angle(previousRotation, rotation);
                    // When the angle of the rotation compared to the last segment is too high
                    // smooth the rotation a little bit. Optimally we would smooth the entire sections array.
                    if (angle > 20)
                    {
                        rotation = Quaternion.Slerp(previousRotation, rotation, .5f);
                    }

                    previousRotation = rotation;
                    finalSections[i] = worldToLocal * Matrix4x4.TRS(sections[i].point, rotation, Vector3.one);
                }
                // except the last one, which just copies the previous one
                else
                {
                    finalSections[i] = finalSections[i - 1];
                }
            }
            else
            {
                if (i == 0)
                {
                    finalSections[i] = Matrix4x4.identity;
                }
                else
                {
                    finalSections[i] = worldToLocal * sections[i].matrix;
                }
            }
        }

        MeshExtrusion.ExtrudeMesh(srcMesh, GetComponent <MeshFilter> ().mesh, finalSections, precomputedEdges, invertFaces);
    }
    public void GeneratePrefab()
    {
        maskObjects = new GameObject[sprites.Length];

        // Applies every sprite mesh to a new MaskObject prefab
        for (int i = 0; i < sprites.Length; i++)
        {
            // Create a new MaskObject
            maskObjects[i] = Instantiate(maskObject);
            MeshFilter meshFilter3D =
                maskObjects[i].transform.GetChild(0).GetComponent <MeshFilter>();
            MeshFilter meshFilterQuad =
                maskObjects[i].transform.GetChild(1).GetComponent <MeshFilter>();
            MeshCollider meshColliderQuad =
                maskObjects[i].transform.GetChild(1).GetComponent <MeshCollider>();

            Mesh mesh3D   = new Mesh();
            Mesh meshQuad = new Mesh();

            // Create extruded version of sprite mesh for 3D parent
            Matrix4x4[] matrix =
            {
                new Matrix4x4(
                    new Vector4(1,            0,              0, 0),
                    new Vector4(0,            1,              0, 0),
                    new Vector4(0,            0,              1, 0),
                    new Vector4(0,            0,              0,1)),

                new Matrix4x4(
                    new Vector4(1,            0,              0, 0),
                    new Vector4(0,            1,              0, 0),
                    new Vector4(0,            0,              1, 0),
                    new Vector4(0,            0, extrusionDepth, 1))
            };
            MeshExtrusion.ExtrudeMesh(Create2DMesh(sprites[i]), mesh3D, matrix, false);

            // Create 2D mesh for quad
            meshQuad = Create2DMesh(sprites[i]);

            // Apply mesh to 3D parent and quad child
            meshFilter3D.mesh   = mesh3D;
            meshFilterQuad.mesh = meshQuad;

            // Assign to the MeshCollider for tap recognition
            MeshCollider meshCollider = maskObjects[i].GetComponent <MeshCollider>();
            meshCollider.sharedMesh = mesh3D;

            // Apply sprite material to sprite quad
            string   filePath       = "SpriteMaterials/" + paintingName + "/" + sprites[i].name;
            Material spriteMaterial = Resources.Load(filePath, typeof(Material)) as Material;

            MeshRenderer quadRenderer = maskObjects[i]
                                        .transform.GetChild(1).GetComponent <MeshRenderer>();
            quadRenderer.material = spriteMaterial;

            // Recalculate normals
            mesh3D.RecalculateNormals();

            // Change names
            maskObjects[i].name = sprites[i].name;
            maskObjects[i].tag  = "MaskObject";

            // Add the PieceManager script if the current MaskObject is not a crop piece
            if (!maskObjects[i].name.Contains("[crop]"))
            {
                maskObjects[i].AddComponent <PieceManager>();
            }

            // Add an instance of the card prefab for each piece for positioning later if not a crop piece
            if (!maskObjects[i].name.Contains("[crop]"))
            {
                Vector3    centerOfMesh        = mesh3D.bounds.center;
                GameObject contextCardInstance = Instantiate(contextCard,
                                                             centerOfMesh,
                                                             maskObjects[i].transform.rotation);
                contextCardInstance.transform.parent     = maskObjects[i].transform;
                contextCardInstance.name                 = "ContextCard";
                contextCardInstance.transform.localScale = contextCardScale;
                contextCardInstance.SetActive(false);

                // Setup card manager references
                PieceManager       pieceManager       = maskObjects[i].GetComponent <PieceManager>();
                ContextCardManager contextCardManager = contextCardInstance.GetComponent <ContextCardManager>();
                pieceManager.contextCard    = contextCardInstance;
                pieceManager.contextManager = contextCardManager;

                Transform contentObject = contextCardInstance.transform
                                          .GetChild(0).GetChild(0)
                                          .GetChild(0).GetChild(0);
                contextCardManager.pieceTitle     = contentObject.GetChild(1).GetComponent <Text>();
                contextCardManager.pieceCaption   = contentObject.GetChild(2).GetComponent <Text>();
                contextCardManager.pieceParagraph = contentObject.GetChild(3).GetComponent <Text>();
            }

            string name3D   = sprites[i].name + " 3D";
            string nameQuad = sprites[i].name + " Quad";
            mesh3D.name   = name3D;
            meshQuad.name = nameQuad;
        }

        // Wrap MaskObjects in empty painting parent
        GameObject paintingEmpty = new GameObject();

        paintingEmpty.name = "Painting";
        paintingEmpty.tag  = "PaintingPrefab";
        foreach (GameObject g in maskObjects)
        {
            g.transform.parent = paintingEmpty.transform;
        }

        // Add properly sized BlackoutQuad prefab
        GameObject newBlackoutQuad =
            Instantiate(blackoutQuad,
                        new Vector3(0, 0, extrusionDepth),
                        Quaternion.identity);

        newBlackoutQuad.name             = "BlackoutQuad";
        newBlackoutQuad.tag              = "BlackoutQuad";
        newBlackoutQuad.transform.parent = paintingEmpty.transform;

        Bounds parentBounds = new Bounds(paintingEmpty.transform.position, Vector3.one);

        for (int i = 0; i < maskObjects.Length; i++)
        {
            Mesh    m      = maskObjects[i].transform.GetChild(0).GetComponent <MeshFilter>().sharedMesh;
            Vector3 bounds = m.bounds.size;
            parentBounds.Encapsulate(bounds);
        }
        newBlackoutQuad.transform.localScale = parentBounds.size;

        // Add the PaintingManager script
        paintingEmpty.AddComponent <PaintingManager>();
        PaintingManager pm = paintingEmpty.GetComponent <PaintingManager>();

        pm.bounds       = parentBounds;
        pm.paintingName = paintingName;

        // Create another empty parent for entire prefab
        GameObject rootEmpty = new GameObject();

        rootEmpty.name = paintingName;
        rootEmpty.tag  = "PaintingWrapper";

        // Create an empty parent for the UI cards
        GameObject UIEmpty = new GameObject();

        UIEmpty.name = "UICards";
        UIEmpty.tag  = "UI";

        // Attach the empties to the root
        paintingEmpty.transform.parent = rootEmpty.transform;
        UIEmpty.transform.parent       = rootEmpty.transform;

        // Add the instances of the card prefabs for positioning later
        GameObject bioCardInstance = Instantiate(bioCard,
                                                 UIEmpty.transform.position,
                                                 UIEmpty.transform.rotation);

        bioCardInstance.transform.parent     = UIEmpty.transform;
        bioCardInstance.name                 = "BioCard";
        bioCardInstance.transform.localScale = bioCardScale;
        pm.bioCard = bioCardInstance;

        GameObject controlCardInstance = Instantiate(controlCard,
                                                     UIEmpty.transform.position,
                                                     UIEmpty.transform.rotation);

        controlCardInstance.transform.parent     = UIEmpty.transform;
        controlCardInstance.name                 = "ControlCard";
        controlCardInstance.transform.localScale = controlCardScale;
        pm.controlCard = controlCardInstance;

        // Rotate the prefab
        float x = rootEmpty.transform.rotation.x;

        rootEmpty.transform.Rotate(new Vector3(x + 90, 0, 0));
    }
    void Start()
    {
        // check for invalid stuff and issue errors.
        // require:
        //   nodes.Length > 1
        //   no adjacent nodes overlap
        //   trackWidth > 0
        //   uvSize.x > 0 and ufSize.y > 0

        if (nodes.Length < 2)
        {
            return;
        }

        // tileHeight and tileWidth are in world units.
        tileHeight = trackWidth;
        tileWidth  = trackWidth * uvSize.x / uvSize.y;

        // build the data for each track piece
        TrackData = new TrackPiece[nodes.Length - 1];
        Vertices.Clear();
        UVs.Clear();
        Triangles.Clear();

        int     i, t;
        Vector3 a, b, ab, v1, v2, n;
        Vector3 previousAB = Vector3.zero;

        Vector3 previousTopVert = Vector3.zero, previousBottomVert = Vector3.zero;
        Vector3 firstTopVert = Vector3.zero, firstBottomVert = Vector3.zero;
        Vector2 previousTopUV = Vector2.zero, previousBottomUV = Vector2.zero;
        Vector2 firstTopUV = Vector2.zero, firstBottomUV = Vector2.zero;

        float distanceRemaining = 0;
        float uvleft = 0, uvright = 0;
        int   firstVert;

        for (t = 0; t < TrackData.Length; t++)
        {
            a   = nodes[t].transform.localPosition;
            a.z = drawDepth;
            b   = nodes[t + 1].transform.localPosition;
            b.z = drawDepth;
            ab  = b - a;

            v1 = a;
            n  = Vector3.Cross(Vector3.forward, ab).normalized;
            i  = 0;

            // add the wedge triangle
            if (t > 0)
            {
                if (stretchPieces)
                {
                    uvleft = 0;
                }
                else if (distanceRemaining > 0)
                {
                    uvleft = 1f - (distanceRemaining / tileWidth);
                }
                else
                {
                    uvleft = 0;
                }
                firstBottomVert = v1 - (tileHeight * 0.5f) * n;
                firstTopVert    = v1 + (tileHeight * 0.5f) * n;
                firstBottomUV   = new Vector2(uvBottomLeft.x + (uvleft * uvSize.x), uvBottomLeft.y);
                firstTopUV      = new Vector2(uvBottomLeft.x + (uvleft * uvSize.x), uvBottomLeft.y + uvSize.y);

                firstVert = Vertices.Count;

                if (Vector3.Cross(-previousAB, ab).z > 0)
                {
                    // top wedge
                    Vertices.Add(a);
                    Vertices.Add(firstTopVert);
                    Vertices.Add(previousTopVert);

                    UVs.Add(firstTopUV - Vector2.up * uvSize.y * 0.5f);
                    UVs.Add(firstTopUV);
                    UVs.Add(previousTopUV);
                }
                else
                {
                    // bottom wedge
                    Vertices.Add(a);
                    Vertices.Add(previousBottomVert);
                    Vertices.Add(firstBottomVert);

                    UVs.Add(firstBottomUV + Vector2.up * uvSize.y * 0.5f);
                    UVs.Add(previousBottomUV);
                    UVs.Add(firstBottomUV);
                }

                Triangles.Add(firstVert + 0);
                Triangles.Add(firstVert + 1);
                Triangles.Add(firstVert + 2);
            }

            bool endOfSection = false;
            while (!endOfSection)
            {
                if (stretchPieces)
                {
                    v2     = b;
                    uvleft = 0;
                }
                else if (distanceRemaining > 0)
                {
                    v2     = v1 + ab.normalized * distanceRemaining;
                    uvleft = 1f - (distanceRemaining / tileWidth);
                }
                else
                {
                    v2     = v1 + ab.normalized * tileWidth;
                    uvleft = 0;
                }

                if (stretchPieces)
                {
                    previousBottomVert = v2 - (tileHeight * 0.5f) * n;
                    previousTopVert    = v2 + (tileHeight * 0.5f) * n;

                    uvright      = 1f;
                    endOfSection = true;
                }
                else if (Vector3.Distance(a, v2) >= ab.magnitude)
                {
                    distanceRemaining = Vector3.Distance(v2, b);
                    v2      = b;
                    uvright = 1f - (distanceRemaining / tileWidth);

                    previousBottomVert = v2 - (tileHeight * 0.5f) * n;
                    previousTopVert    = v2 + (tileHeight * 0.5f) * n;
                    previousBottomUV   = new Vector2(uvBottomLeft.x + (uvright * uvSize.y), uvBottomLeft.y);
                    previousTopUV      = new Vector2(uvBottomLeft.x + (uvleft * uvSize.y), uvBottomLeft.y + uvSize.y);
                    endOfSection       = true;
                }
                else
                {
                    distanceRemaining = 0;
                    uvright           = 1f;
                }

                firstVert = Vertices.Count;

                Vertices.Add(v1 - (tileHeight * 0.5f) * n);
                Vertices.Add(v1 + (tileHeight * 0.5f) * n);
                Vertices.Add(v2 - (tileHeight * 0.5f) * n);
                Vertices.Add(v2 + (tileHeight * 0.5f) * n);

                UVs.Add(new Vector2(uvBottomLeft.x + (uvleft * uvSize.x), uvBottomLeft.y));
                UVs.Add(new Vector2(uvBottomLeft.x + (uvleft * uvSize.x), uvBottomLeft.y + uvSize.y));
                UVs.Add(new Vector2(uvBottomLeft.x + (uvright * uvSize.x), uvBottomLeft.y));
                UVs.Add(new Vector2(uvBottomLeft.x + (uvright * uvSize.x), uvBottomLeft.y + uvSize.y));

                Triangles.Add(firstVert + 0);
                Triangles.Add(firstVert + 1);
                Triangles.Add(firstVert + 3);
                Triangles.Add(firstVert + 0);
                Triangles.Add(firstVert + 3);
                Triangles.Add(firstVert + 2);

                i += 4;
                v1 = v2;
            }

            previousAB = ab;
        }

        // build the mesh
        Mesh msh = new Mesh();

        msh.vertices  = Vertices.ToArray();
        msh.triangles = Triangles.ToArray();
        msh.uv        = UVs.ToArray();
        msh.RecalculateNormals();
        msh.RecalculateBounds();

        this.gameObject.AddComponent(typeof(MeshRenderer));
        MeshFilter filter = this.gameObject.AddComponent(typeof(MeshFilter)) as MeshFilter;

        filter.mesh = msh;

        this.renderer.material = chunkMaterial;

        if (addMeshCollider)
        {
            //(this.gameObject.AddComponent(typeof(MeshCollider)) as MeshCollider).sharedMesh = msh;
            (this.gameObject.AddComponent(typeof(MeshCollider)) as MeshCollider).sharedMesh = MeshExtrusion.ExtrudeZ(msh, 1f);
        }

        if (deactivateNodesOnStart)
        {
            foreach (Transform node in nodes)
            {
                node.gameObject.SetActive(false);
            }
        }
    }
Example #16
0
        public void BuildRollercoasterTrack(GameObject trackGameObject, GameObject splineRootGameObject, GameObject leftRailPrefab, GameObject rightRailPrefab, GameObject crossBeamPrefab, float resolution)
        {
            BezierSpline bezierSpline = splineRootGameObject.GetComponent <BezierSpline>();
            // Delete all of the children of the track holding game object
            List <Component> childComponents = new List <Component>(trackGameObject.GetComponentsInChildren(typeof(Transform))); //Returns all components of Type type in the GameObject and any of its children.
            List <Transform> childTransforms = childComponents.ConvertAll(c => (Transform)c);

            childTransforms.Remove(trackGameObject.transform); //Remove the current game object (parent)'s transform from the list. We need only the transforms of the children
            foreach (Transform childTransform in childTransforms)
            {
                if (childTransform.gameObject.name == "left rail" || childTransform.gameObject.name == "right rail")
                {
                    UnityEngine.Object.DestroyImmediate(childTransform.gameObject.GetComponent <MeshFilter>().sharedMesh);
                }
                UnityEngine.Object.DestroyImmediate(childTransform.gameObject); //Destroy cannot be called in edit mode
            }


            // Build a list of affine transformation matricies that represent the track sections
            List <Matrix4x4> leftTrackPolyline  = new List <Matrix4x4>();
            List <Matrix4x4> rightTrackPolyline = new List <Matrix4x4>();


            //GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
            //cube.transform.parent = transform;
            //cube.transform.localScale = new Vector3(0.4f, 0.4f, 0.4f);
            //cube.transform.position = bezierSpline.GetPoint(0);
            //cube.transform.localRotation = Quaternion.LookRotation(bezierSpline.GetTangent(0));

            //GameObject cube2 = GameObject.CreatePrimitive(PrimitiveType.Cube);
            //cube2.transform.parent = transform;
            //cube2.transform.localScale = new Vector3(0.4f, 0.4f, 0.4f);
            //cube2.transform.position = bezierSpline.GetPoint(1);
            //cube2.transform.localRotation = Quaternion.LookRotation(bezierSpline.GetTangent(1));


            for (float t = 0; t <= 1; t += resolution)
            {
                //print("T: " + t);
                Transform trans = new GameObject().transform;

                trans.position = bezierSpline.GetPoint(t);
                trans.rotation = Quaternion.LookRotation(bezierSpline.GetTangent(t));

                leftTrackPolyline.Add(trans.localToWorldMatrix * leftRailPrefab.transform.localToWorldMatrix);
                rightTrackPolyline.Add(trans.localToWorldMatrix * rightRailPrefab.transform.localToWorldMatrix);
                UnityEngine.Object.DestroyImmediate(trans.gameObject);

                //Debug.Log(trans.localToWorldMatrix);

                float t2 = t + resolution + resolution;
                if (bezierSpline.loop && t2 >= 1)
                {
                    Transform trans1 = new GameObject().transform;

                    trans1.position = bezierSpline.GetPoint(0);
                    trans1.rotation = Quaternion.LookRotation(bezierSpline.GetTangent(0));

                    leftTrackPolyline.Add(trans1.localToWorldMatrix * leftRailPrefab.transform.localToWorldMatrix);
                    rightTrackPolyline.Add(trans1.localToWorldMatrix * rightRailPrefab.transform.localToWorldMatrix);
                    UnityEngine.Object.DestroyImmediate(trans1.gameObject);

                    break;
                }
            }


            // Generate the rails
            GameObject leftRail = new GameObject();
            Mesh       leftMesh = new Mesh();

            leftRail.name             = "left rail";
            leftRail.transform.parent = trackGameObject.transform;
            leftRail.AddComponent <MeshFilter>();
            leftRail.GetComponent <MeshFilter>().sharedMesh = leftMesh;                                                          // Not allowed to access MeshFilter.mesh on prefab object. So Use MeshFilter.sharedMesh
            leftRail.AddComponent <MeshRenderer>();
            leftRail.GetComponent <MeshRenderer>().sharedMaterial = leftRailPrefab.GetComponent <MeshRenderer>().sharedMaterial; // Not allowed to access MeshRenderer.material on prefab object. So Use MeshRenderer.sharedMaterial
            MeshExtrusion.ExtrudeMesh(leftRailPrefab.GetComponent <MeshFilter>().sharedMesh, leftRail.GetComponent <MeshFilter>().sharedMesh, leftTrackPolyline.ToArray(), false);

            GameObject rightRail = new GameObject();
            Mesh       rightMesh = new Mesh();

            rightRail.name             = "right rail";
            rightRail.transform.parent = trackGameObject.transform;
            rightRail.AddComponent <MeshFilter>();
            rightRail.GetComponent <MeshFilter>().sharedMesh = rightMesh;
            rightRail.AddComponent <MeshRenderer>();
            rightRail.GetComponent <MeshRenderer>().sharedMaterial = rightRailPrefab.GetComponent <MeshRenderer>().sharedMaterial;
            MeshExtrusion.ExtrudeMesh(rightRailPrefab.GetComponent <MeshFilter>().sharedMesh, rightRail.GetComponent <MeshFilter>().sharedMesh, rightTrackPolyline.ToArray(), false);


            // generateCrossBeams

            if (crossBeamPrefab != null)
            {
                // Generate the cross bars
                float distSinceLastCrossbar = 0;
                float cbRes        = resolution / 5.0f;
                float beamDistance = 2.0f;
                for (float t = 0; t <= 1; t += cbRes)
                {
                    Vector3 dP = bezierSpline.GetPoint(t) - bezierSpline.GetPoint(t - cbRes);
                    distSinceLastCrossbar += dP.magnitude;
                    if (distSinceLastCrossbar >= beamDistance)
                    {
                        GameObject crossbar = UnityEngine.Object.Instantiate(crossBeamPrefab); //Creates a gameObject from the prefab
                        crossbar.transform.parent   = trackGameObject.transform;
                        crossbar.transform.position = bezierSpline.GetPoint(t);
                        crossbar.transform.rotation = Quaternion.LookRotation(bezierSpline.GetTangent(t));

                        crossbar.transform.position += crossbar.transform.right * crossBeamPrefab.transform.position.x;
                        crossbar.transform.position += crossbar.transform.up * crossBeamPrefab.transform.position.y;
                        crossbar.transform.position += crossbar.transform.forward * crossBeamPrefab.transform.position.z;

                        crossbar.transform.rotation *= crossBeamPrefab.transform.rotation;

                        distSinceLastCrossbar -= beamDistance;
                    }
                }
            }
        }
Example #17
0
    public void BuildTrack()
    {
        // Delete all of the children of the track holding game object
        List <Component> childComponents = new List <Component>(GetComponentsInChildren(typeof(Transform)));
        List <Transform> childTransforms = childComponents.ConvertAll(c => (Transform)c);

        childTransforms.Remove(transform);
        foreach (Transform childTransform in childTransforms)
        {
            if (childTransform.gameObject.name == "left rail" || childTransform.gameObject.name == "right rail")
            {
                DestroyImmediate(childTransform.gameObject.GetComponent <MeshFilter>().sharedMesh);
            }
            DestroyImmediate(childTransform.gameObject);
        }

        // Get all of the spline node information from the splineRoot
        Transform[] splineNodeTransforms = GetTransforms();
        if (splineNodeTransforms.Length < 2)
        {
            return;
        }

        // Build the spline interpolator object
        SplineInterpolator interp = GetComponent(typeof(SplineInterpolator)) as SplineInterpolator;

        SetupSplineInterpolator(interp, splineNodeTransforms);
        interp.StartInterpolation(null, eRotationMode.PATH_ANGLE, eWrapMode.ONCE);

        // Build a list of affine transformation matricies that represent the track sections
        List <Matrix4x4> leftTrackPolyline  = new List <Matrix4x4>();
        List <Matrix4x4> rightTrackPolyline = new List <Matrix4x4>();

        float tMax = AutoClose ? splineNodeTransforms.Length : splineNodeTransforms.Length - 1;

        tMax += 2 * resolution;

        for (float t = 0; t < tMax; t += resolution)
        {
            Transform trans = new GameObject().transform;

            trans.position = interp.GetHermiteAtTime(t);
            trans.rotation = interp.GetPathAngleAtTime(t);

            leftTrackPolyline.Add(trans.localToWorldMatrix * LeftRailPrefab.transform.localToWorldMatrix);
            rightTrackPolyline.Add(trans.localToWorldMatrix * RightRailPrefab.transform.localToWorldMatrix);

            //Debug.Log(trans.localToWorldMatrix);
            DestroyImmediate(trans.gameObject);
        }

        // Generate the rails
        GameObject leftRail = new GameObject();
        Mesh       leftMesh = new Mesh();

        leftRail.name             = "left rail";
        leftRail.transform.parent = transform;
        leftRail.AddComponent <MeshFilter>();
        leftRail.GetComponent <MeshFilter>().sharedMesh = leftMesh;
        leftRail.AddComponent <MeshRenderer>();
        leftRail.GetComponent <MeshRenderer> ().sharedMaterial = LeftRailPrefab.GetComponent <MeshRenderer>().sharedMaterial;
        MeshExtrusion.ExtrudeMesh(LeftRailPrefab.GetComponent <MeshFilter>().sharedMesh, leftRail.GetComponent <MeshFilter>().sharedMesh, leftTrackPolyline.ToArray(), false);

        GameObject rightRail = new GameObject();
        Mesh       rightMesh = new Mesh();

        rightRail.name             = "right rail";
        rightRail.transform.parent = transform;
        rightRail.AddComponent <MeshFilter>();
        rightRail.GetComponent <MeshFilter>().sharedMesh = rightMesh;
        rightRail.AddComponent <MeshRenderer>();
        rightRail.GetComponent <MeshRenderer> ().sharedMaterial = RightRailPrefab.GetComponent <MeshRenderer>().sharedMaterial;
        MeshExtrusion.ExtrudeMesh(RightRailPrefab.GetComponent <MeshFilter>().sharedMesh, rightRail.GetComponent <MeshFilter>().sharedMesh, rightTrackPolyline.ToArray(), false);

        // Generate the cross bars
        float distSinceLastCrossbar = 0;
        float cbRes = resolution / 5.0f;

        for (float t = cbRes; t < tMax; t += cbRes)
        {
            Vector3 dP = interp.GetHermiteAtTime(t) - interp.GetHermiteAtTime(t - cbRes);
            distSinceLastCrossbar += dP.magnitude;
            if (distSinceLastCrossbar >= beamDistance)
            {
                GameObject crossbar = Instantiate(crossBeamPrefab);
                crossbar.transform.parent   = transform;
                crossbar.transform.position = interp.GetHermiteAtTime(t);
                crossbar.transform.rotation = interp.GetPathAngleAtTime(t);

                crossbar.transform.position += crossbar.transform.right * crossBeamPrefab.transform.position.x;
                crossbar.transform.position += crossbar.transform.up * crossBeamPrefab.transform.position.y;
                crossbar.transform.position += crossbar.transform.forward * crossBeamPrefab.transform.position.z;

                crossbar.transform.rotation *= crossBeamPrefab.transform.rotation;

                distSinceLastCrossbar -= beamDistance;
            }
        }
    }
Example #18
0
    public void SimpleExtrude(float extrude_length)
    {
        selectedPlane  = planeProperties.SearchSelectedPlane();
        sketchToExtude = selectedPlane.transform.GetChild(1).GetChild(selectedPlane.transform.GetChild(1).childCount - 1).gameObject;
        sketchToExtude.transform.GetChild(0).gameObject.GetComponent <Canvas>().enabled = false;
        sketchLineRenderer = sketchToExtude.GetComponent <LineRenderer>();
        Vector2[] pos = new Vector2[sketchLineRenderer.positionCount];

        for (int j = 0; j < pos.Length; j++)
        {
            pos[j] = new Vector2(selectedPlane.transform.InverseTransformPoint(sketchLineRenderer.GetPosition(j)).x, selectedPlane.transform.InverseTransformPoint(sketchLineRenderer.GetPosition(j)).z);
            //Debug.Log(pos[j]);
        }


        // Use triangulator to get indices for creating triangles
        Triangulator tr = new Triangulator(pos);

        int[] indices = tr.Triangulate();

        // Create the Vector3 vertices
        Vector3[] vertices = new Vector3[pos.Length];

        for (int j = 0; j < vertices.Length; j++)
        {
            vertices[j] = new Vector3(pos[j].x, pos[j].y, 0); //XY Plane
                                                              //  vertices[j] = new Vector3(pos[j].x, 0, pos[j].y);  //XZ Plane
                                                              //  vertices[j] = new Vector3(0, pos[j].x, pos[j].y); //YZ Plane
        }

        // Create the mesh
        Mesh msh = new Mesh();

        msh.vertices  = vertices;
        msh.triangles = indices;
        msh.RecalculateNormals();
        msh.RecalculateBounds();

        float[] length     = new float[vertices.Length];
        float   net_length = 0;

        for (int j = 0; j < vertices.Length; j++)
        {
            if (j < vertices.Length - 1)
            {
                length[j]   = (vertices[j] - vertices[j + 1]).magnitude;
                net_length += length[j];
            }
            else
            {
                length[j]   = (vertices[j] - vertices[0]).magnitude;
                net_length += length[j];
            }
        }

        Vector3[] tvertices         = msh.vertices;
        Vector2[] uvs               = new Vector2[tvertices.Length];
        float     cummulated_length = 0;

        for (int j = 0; j < uvs.Length; j++)
        {
            //uvs[j] = new Vector2 (vertices[j].x, vertices[j].z);

            uvs[j]             = new Vector2(cummulated_length / net_length, 0);
            cummulated_length += length[j];
        }

        msh.uv = uvs;

        Matrix4x4[] finalSections = new Matrix4x4[2];
        if (extrude_length >= 0)
        {
            finalSections[0] = Matrix4x4.TRS(selectedPlane.transform.position, Quaternion.LookRotation(-selectedPlane.transform.up, selectedPlane.transform.forward), Vector3.one);
        }
        else
        {
            finalSections[0] = Matrix4x4.TRS(selectedPlane.transform.position + selectedPlane.transform.up * extrude_length, Quaternion.LookRotation(-selectedPlane.transform.up, selectedPlane.transform.forward), Vector3.one);
        }

        Debug.Log(Quaternion.LookRotation(selectedPlane.transform.up, selectedPlane.transform.forward));
        //  finalSections[1] = Matrix4x4.TRS(new Vector3(extrude_length,0,0), Quaternion.identity, Vector3.one);
        //  finalSections[1] = Matrix4x4.TRS(new Vector3(0, extrude_length, 0), Quaternion.identity, Vector3.one);
        if (extrude_length >= 0)
        {
            finalSections[1] = Matrix4x4.TRS(selectedPlane.transform.position + selectedPlane.transform.up * extrude_length, Quaternion.LookRotation(-selectedPlane.transform.up, selectedPlane.transform.forward), Vector3.one);
        }
        else
        {
            finalSections[1] = Matrix4x4.TRS(selectedPlane.transform.position, Quaternion.LookRotation(-selectedPlane.transform.up, selectedPlane.transform.forward), Vector3.one);
        }


        MeshExtrusion.Edge[] precomputedEdges = MeshExtrusion.BuildManifoldEdges(msh);
        MeshExtrusion.ExtrudeMesh(msh, msh, finalSections, precomputedEdges, true);


        // Set up game object with mesh;
        extruded_object = new GameObject();
        // extruded_object.name = "extrude1";
        MeshFilter filter = extruded_object.AddComponent <MeshFilter>();

        filter.mesh = msh;
        MeshRenderer mr = extruded_object.AddComponent <MeshRenderer>();

        mr.material        = mtl;
        mr.material.shader = Shader.Find("Custom/VertexColor");

        MeshCollider mc = extruded_object.AddComponent <MeshCollider>();

        //mc.sharedMesh = null;
        mc.sharedMesh = msh;
        extruded_object.transform.SetParent(sketchToExtude.transform);
        extruded_object.name = "Extrusion";
        extruded_object.AddComponent <extrusionProperties>();
        extruded_object.GetComponent <extrusionProperties>().extrude_length = extrude_length;
    }
Example #19
0
    // Use this for initialization
    void Start()
    {
        int   nvertex        = 4;
        float extrude_length = 5.0f;

        Vector2[] pos = new Vector2[nvertex];

        pos[0] = new Vector2(-1, -1);
        pos[1] = new Vector2(1, -1);
        pos[2] = new Vector2(1, 1);
        pos[3] = new Vector2(-1, 1);

        // Use triangulator to get indices for creating triangles
        Triangulator tr = new Triangulator(pos);

        int[] indices = tr.Triangulate();

        // Create the Vector3 vertices
        Vector3[] vertices = new Vector3[pos.Length];
        for (int j = 0; j < vertices.Length; j++)
        {
            vertices[j] = new Vector3(pos[j].x, 0, pos[j].y);
        }

        // Create the mesh
        Mesh msh = new Mesh();

        msh.vertices  = vertices;
        msh.triangles = indices;
        msh.RecalculateNormals();
        msh.RecalculateBounds();

        float[] length     = new float[vertices.Length];
        float   net_length = 0;

        for (int j = 0; j < vertices.Length; j++)
        {
            if (j < vertices.Length - 1)
            {
                length[j]   = (vertices[j] - vertices[j + 1]).magnitude;
                net_length += length[j];
            }
            else
            {
                length[j]   = (vertices[j] - vertices[0]).magnitude;
                net_length += length[j];
            }
        }


        Vector3[] tvertices         = msh.vertices;
        Vector2[] uvs               = new Vector2[tvertices.Length];
        float     cummulated_length = 0;

        for (int j = 0; j < uvs.Length; j++)
        {
            //uvs[j] = new Vector2 (vertices[j].x, vertices[j].z);

            uvs[j]             = new Vector2(cummulated_length / net_length, 0);
            cummulated_length += length[j];
        }
        msh.uv = uvs;

        Matrix4x4[] finalSections = new Matrix4x4[2];
        finalSections[0] = Matrix4x4.identity;
        finalSections[1] = Matrix4x4.TRS(new Vector3(0, extrude_length, 0), Quaternion.identity, Vector3.one);
        MeshExtrusion.Edge[] precomputedEdges = MeshExtrusion.BuildManifoldEdges(msh);
        MeshExtrusion.ExtrudeMesh(msh, msh, finalSections, precomputedEdges, true);


        // Set up game object with mesh;
        GameObject extruded_object = new GameObject();
        MeshFilter filter          = extruded_object.AddComponent <MeshFilter>();

        filter.mesh = msh;
        MeshRenderer mr = extruded_object.AddComponent <MeshRenderer>();

        mr.material = mtl;

        MeshCollider mc = extruded_object.AddComponent <MeshCollider>();

        //mc.sharedMesh = null;
        mc.sharedMesh = msh;
    }
Example #20
0
File: Road.cs Project: yazici/Cigen
    public void BuildMesh()
    {
        float   roadWidth  = city.settings.roadDimensions.x;
        float   roadHeight = city.settings.roadDimensions.y;
        Texture texture    = city.settings.roadTexture;

        Vector3 from      = city.transform.TransformPoint(parentNode.Position);
        Vector3 to        = city.transform.TransformPoint(childNode.Position);
        Vector3 direction = (from - to).normalized;
        Vector3 offset    = direction * roadWidth / 2f;

        from -= offset; //so the endings don't go all the way to the point, they line up neatly with intersections
        to   += offset;
        transform.position = from;
        float length = Vector3.Distance(from, to);

        Vector3[] vertices = new Vector3[4];
        vertices[0] = -transform.right * roadWidth / 2f;
        vertices[1] = (transform.forward * length) - (transform.right * roadWidth / 2f);
        vertices[2] = (transform.forward * length) + (transform.right * roadWidth / 2f);
        vertices[3] = transform.right * roadWidth / 2f;

        Vector2 mainTexScale;

        GetComponent <MeshFilter>().mesh = HullMesher2D.BuildPolygon(vertices, out mainTexScale);
        Material mat = GetComponent <MeshRenderer>().material;

        if (texture != null)
        {
            mat.mainTexture      = texture;
            mat.mainTextureScale = mainTexScale;
        }
        else
        {
            mat.color = Color.gray;
        }

        Mesh m = GetComponent <MeshFilter>().mesh;

        Quaternion rotation = Quaternion.identity;
        Vector3    z        = Vector3.zero;
        Matrix4x4  op0      = Matrix4x4.TRS(z, rotation, Vector3.one);
        Matrix4x4  op1      = Matrix4x4.TRS(transform.up * roadHeight, rotation, Vector3.one);

        Matrix4x4[] ops = new Matrix4x4[] { op0, op1, };

        MeshExtrusion.ExtrudeMesh(m, GetComponent <MeshFilter>().mesh, ops, true);

        m.RecalculateNormals();
        m.RecalculateBounds();

        transform.position = from;
        transform.LookAt(to);

        {
            Func <Vector3, Transform, Vector3> a = (v, t) => {
                Vector3 b;
                //converts the vector from this local space into world space, then converts it again into the transforms local space
                b = t.InverseTransformPoint(transform.TransformPoint(v)); //store the vertices in world coordinates
                GizmosToDraw.Add(b);
                return(b);
            };

            //maybe add these vertices to the intersections vertex list?
            parentNode.AddVerts(a(vertices[0], parentNode.transform), a(vertices[3], parentNode.transform));
            childNode.AddVerts(a(vertices[1], childNode.transform), a(vertices[2], childNode.transform));
        }
    }
Example #21
0
 void Start()
 {
     srcMesh          = GetComponent <MeshFilter>().sharedMesh;
     precomputedEdges = MeshExtrusion.BuildManifoldEdges(srcMesh);
 }
    void Update()
    {
        while (sections.Count < geomBuffer)
        {
            Restock();
            collisionNeedsUpdate = true;
        }
        if (sections[1].point.x - player.transform.position.x < 1)
        {
            Matrix4x4 localSpaceTransform = transform.localToWorldMatrix;
            Vector3   upDir = sections[sections.Count - 1].upDir;

            newHeightData.Set(sections[sections.Count - 1].point.x, randomizer.Next(heightMin, heightMax), sections[sections.Count - 1].point.z);
            if (sections[sections.Count - 1].usesOverride)
            {
                newHeightData.Set(sections[sections.Count - 1].point.x, sections[sections.Count - 1].heightOverride, sections[sections.Count - 1].point.z);
            }
            else
            {
                newHeightData.Set(sections[sections.Count - 1].point.x, randomizer.Next(heightMin, heightMax), sections[sections.Count - 1].point.z);
            }
            vertices.Add(localSpaceTransform.MultiplyPoint(sections[sections.Count - 1].point));
            vertices.Add(localSpaceTransform.MultiplyPoint(newHeightData + upDir * height));

            float u = 0.0f;
            for (int i = 0; i < 2; i++)
            {
                if (i != 0)
                {
                    u = Mathf.Clamp01((Time.time - sections[sections.Count - 1].time) / time);
                }
                uv.Add(new Vector2(u, 0));
                uv.Add(new Vector2(u, 1));
            }
            for (int i = 0; i < 4; i++)
            {
                if (i == 0 || i == 1)
                {
                    vertices.RemoveAt(i);
                }
                uv.RemoveAt(i);
            }
            sections.RemoveAt(0);
        }
        triangles.Clear();
        ResetTris();

        mesh.Clear();
        mesh.vertices  = vertices.ToArray();
        mesh.triangles = triangles.ToArray();
        mesh.uv        = uv.ToArray();
        mesh.RecalculateNormals();
        edges = MeshExtrusion.BuildManifoldEdges(mesh);

        extrusion.Clear();
        extrusion.Add(transform.worldToLocalMatrix * Matrix4x4.TRS(depthPoints[0].point, extrudeRotation, Vector3.one));
        extrusion.Add(transform.worldToLocalMatrix * Matrix4x4.TRS(depthPoints[1].point, extrudeRotation, Vector3.one));
        MeshExtrusion.ExtrudeMesh(mesh, out_mesh, extrusion.ToArray(), edges, invertFaces);

        if (collisionNeedsUpdate == true)
        {
            meshc.sharedMesh = null;
            meshc.sharedMesh = out_mesh;
            if (floorPhysMat != null)
            {
                meshc.sharedMaterial = null;
                meshc.sharedMaterial = floorPhysMat;
            }
            collisionNeedsUpdate = false;
        }
    }