Ejemplo n.º 1
0
        public void CollectRecastMeshObjs(List <RasterizationMesh> buffer)
        {
            List <RecastMeshObj> list = ListPool <RecastMeshObj> .Claim();

            RecastMeshObj.GetAllInBounds(list, this.bounds);
            Dictionary <Mesh, Vector3[]> dictionary  = new Dictionary <Mesh, Vector3[]>();
            Dictionary <Mesh, int[]>     dictionary2 = new Dictionary <Mesh, int[]>();

            for (int i = 0; i < list.Count; i++)
            {
                MeshFilter meshFilter = list[i].GetMeshFilter();
                Renderer   renderer   = (meshFilter != null) ? meshFilter.GetComponent <Renderer>() : null;
                if (meshFilter != null && renderer != null)
                {
                    Mesh sharedMesh = meshFilter.sharedMesh;
                    RasterizationMesh rasterizationMesh;
                    if (dictionary.ContainsKey(sharedMesh))
                    {
                        rasterizationMesh = new RasterizationMesh(dictionary[sharedMesh], dictionary2[sharedMesh], renderer.bounds);
                    }
                    else
                    {
                        rasterizationMesh       = new RasterizationMesh(sharedMesh.vertices, sharedMesh.triangles, renderer.bounds);
                        dictionary[sharedMesh]  = rasterizationMesh.vertices;
                        dictionary2[sharedMesh] = rasterizationMesh.triangles;
                    }
                    rasterizationMesh.matrix   = renderer.localToWorldMatrix;
                    rasterizationMesh.original = meshFilter;
                    rasterizationMesh.area     = list[i].area;
                    buffer.Add(rasterizationMesh);
                }
                else
                {
                    Collider collider = list[i].GetCollider();
                    if (collider == null)
                    {
                        Debug.LogError("RecastMeshObject (" + list[i].gameObject.name + ") didn't have a collider or MeshFilter+Renderer attached", list[i].gameObject);
                    }
                    else
                    {
                        RasterizationMesh rasterizationMesh2 = this.RasterizeCollider(collider);
                        if (rasterizationMesh2 != null)
                        {
                            rasterizationMesh2.area = list[i].area;
                            buffer.Add(rasterizationMesh2);
                        }
                    }
                }
            }
            this.capsuleCache.Clear();
            ListPool <RecastMeshObj> .Release(list);
        }
Ejemplo n.º 2
0
    public void InitFace(bool needSnap = true)
    {
        MeshFilter meshFilter = gameObject.GetComponent <MeshFilter>();

        if (meshFilter == null)
        {
            return;
        }

        mesh = meshFilter.mesh;

        UISpriteData mSprite1 = Atlas.GetSprite(spriteName);

        if (mSprite1 == null)
        {
            return;
        }

        Texture tex = meshFilter.GetComponent <Renderer>().material.mainTexture;

        //Texture tex = gameObject.GetComponent<MeshRenderer>().material.mainTexture;

        Rect outer = new Rect(mSprite1.x, mSprite1.y, mSprite1.width, mSprite1.height);//0,0,1,1

        if (!mirrorX)
        {
            //mesh.uv = new Vector2[]{new Vector2(outer.xMin/tex.width,1.0f-outer.yMax/tex.height),//0,1,1,0
            //new Vector2(outer.xMax/tex.width,1.0f-outer.xMin/tex.height),
            //new Vector2(outer.xMax/tex.width,1.0f-outer.yMax/tex.height),
            //new Vector2(outer.xMin/tex.width,1.0f-outer.yMin/tex.height)};

            mesh.uv = new Vector2[] { new Vector2(outer.xMin / tex.width, 1.0f - outer.yMax / tex.height),//0,1,1,0
                                      new Vector2(outer.xMax / tex.width, 1.0f - outer.yMin / tex.height),
                                      new Vector2(outer.xMax / tex.width, 1.0f - outer.yMax / tex.height),
                                      new Vector2(outer.xMin / tex.width, 1.0f - outer.yMin / tex.height) };
        }
        else
        {
            //mesh.uv = new Vector2[]{new Vector2(outer.xMax/tex.width,1.0f-outer.yMax/tex.height),//1,0,0,1
            //new Vector2(outer.xMin/tex.width,1.0f-outer.yMin/tex.height),
            //new Vector2(outer.xMin/tex.width,1.0f-outer.yMax/tex.height),
            //new Vector2(outer.xMax/tex.width,1.0f-outer.xMin/tex.height)};

            mesh.uv = new Vector2[] { new Vector2(outer.xMax / tex.width, 1.0f - outer.yMax / tex.height),//1,0,0,1
                                      new Vector2(outer.xMin / tex.width, 1.0f - outer.yMin / tex.height),
                                      new Vector2(outer.xMin / tex.width, 1.0f - outer.yMax / tex.height),
                                      new Vector2(outer.xMax / tex.width, 1.0f - outer.yMin / tex.height) };
        }
        float scale = (float)(Screen.height / 2.0f) / 5;

        transform.localScale = new Vector3((float)mSprite1.width / scale, (float)mSprite1.height / scale, 1.0f) * ScaleFactor;
    }
Ejemplo n.º 3
0
    public static string MeshToString(MeshFilter mf, Transform t)
    {
        Vector3    s = t.localScale;
        Vector3    p = t.localPosition;
        Quaternion r = t.localRotation;


        int  numVertices = 0;
        Mesh m           = mf.sharedMesh;

        if (!m)
        {
            return("####Error####");
        }
        Material[] mats = mf.GetComponent <Renderer>().sharedMaterials;

        StringBuilder sb = new StringBuilder();

        foreach (Vector3 vv in m.vertices)
        {
            Vector3 v = t.TransformPoint(vv);
            numVertices++;
            sb.Append(string.Format("v {0} {1} {2}\n", v.x, v.y, v.z));
        }
        sb.Append("\n");
        foreach (Vector3 nn in m.normals)
        {
            Vector3 v = r * nn;
            sb.Append(string.Format("vn {0} {1} {2}\n", -v.x, -v.y, v.z));
        }
        sb.Append("\n");
        foreach (Vector3 v in m.uv)
        {
            sb.Append(string.Format("vt {0} {1}\n", v.x, v.y));
        }
        for (int material = 0; material < m.subMeshCount; material++)
        {
            sb.Append("\n");
            sb.Append("usemtl ").Append(mats[material].name).Append("\n");
            sb.Append("usemap ").Append(mats[material].name).Append("\n");

            int[] triangles = m.GetTriangles(material);
            for (int i = 0; i < triangles.Length; i += 3)
            {
                sb.Append(string.Format("f {0}/{0}/{0} {1}/{1}/{1} {2}/{2}/{2}\n",
                                        triangles[i] + 1 + StartIndex, triangles[i + 1] + 1 + StartIndex, triangles[i + 2] + 1 + StartIndex));
            }
        }

        StartIndex += numVertices;
        return(sb.ToString());
    }
Ejemplo n.º 4
0
 private void OnStateChanged(State state)
 {
     if (state == State.Paint)
     {
         simRatio = CalculateSimilarityRatio(false);
         goalMeshFilter.GetComponent <Outline>().enabled = false;
         playerMeshFilter.GetComponent <Rotater>().OnStateChanged(state);
     }
     else if (state == State.Evaluate)
     {
         playerMeshFilter.GetComponent <Rotater>().OnStateChanged(state);
     }
 }
Ejemplo n.º 5
0
        protected override void OnAttachToController()
        {
            displayObject.sharedMesh = availableMeshes[meshIndex];
            displayObject.GetComponent <Renderer>().sharedMaterial = instantiatedMaterial;

#if UNITY_WSA && UNITY_2017_2_OR_NEWER
            // Subscribe to input now that we're parented under the controller
            InteractionManager.InteractionSourcePressed  += InteractionSourcePressed;
            InteractionManager.InteractionSourceReleased += InteractionSourceReleased;
#endif

            state = StateEnum.Idle;
        }
    private void ValidateData()
    {
        if (_previewRenderUtility == null)
        {
            _previewRenderUtility = new PreviewRenderUtility();

            _previewRenderUtility.m_Camera.transform.position = new Vector3(0, 0, -6);
            _previewRenderUtility.m_Camera.transform.rotation = Quaternion.identity;
        }

        _targetMeshFilter   = target as MeshFilter;
        _targetMeshRenderer = _targetMeshFilter.GetComponent <MeshRenderer>();
    }
Ejemplo n.º 7
0
        public static int GetUniqueId(this MeshFilter filter)
        {
            MeshRenderer renderer = filter.GetComponent <MeshRenderer>();
            Vector3      center   = renderer != null ? renderer.bounds.center : Vector3.zero;

            string id = string.Format("{0}|{1}{2}{3}"
                                      , filter.sharedMesh.name
                                      , center.x
                                      , center.y
                                      , center.z);

            return(id.GetHashCode());
        }
        private void OnEnable()
        {
            // init native containers
            blocks          = new NativeArray <BlockType>(FixedChunkSizeXZ * ChunkSizeY * FixedChunkSizeXZ, Allocator.Persistent);
            lightingData    = new NativeArray <int>(FixedChunkSizeXZ * ChunkSizeY * FixedChunkSizeXZ, Allocator.Persistent);
            biomeTypes      = new NativeArray <BiomeType>(FixedChunkSizeXZ * FixedChunkSizeXZ, Allocator.Persistent);
            blockParameters = new NativeHashMap <BlockParameter, short>(2048, Allocator.Persistent);

            blockVerticles = new NativeList <float3>(16384, Allocator.Persistent);
            blockTriangles = new NativeList <int>(32768, Allocator.Persistent);
            blockUVs       = new NativeList <float2>(16384, Allocator.Persistent);

            liquidVerticles = new NativeList <float3>(8192, Allocator.Persistent);
            liquidTriangles = new NativeList <int>(16384, Allocator.Persistent);
            liquidUVs       = new NativeList <float2>(8192, Allocator.Persistent);

            plantsVerticles = new NativeList <float3>(4096, Allocator.Persistent);
            plantsTriangles = new NativeList <int>(8192, Allocator.Persistent);
            plantsUVs       = new NativeList <float2>(4096, Allocator.Persistent);

            chunkDissapearingAnimation = GetComponent <ChunkDissapearingAnimation>();
            chunkAnimation             = GetComponent <ChunkAnimation>();

            World.TimeToBuild += BuildBlocks;
            StartCoroutine(CheckNeighbours());

            if (biomeColorsTexture == null)
            {
                biomeColorsTexture            = new Texture2D(FixedChunkSizeXZ, FixedChunkSizeXZ, TextureFormat.RGB24, true);
                biomeColorsTexture.filterMode = FilterMode.Bilinear;
                biomeColorsTexture.wrapMode   = TextureWrapMode.Clamp;
                biomeColorsTexture.Apply();
            }

            lightingBuffer = new ComputeBuffer(FixedChunkSizeXZ * ChunkSizeY * FixedChunkSizeXZ, sizeof(int), ComputeBufferType.Default);
            var mr = blockMeshFilter.GetComponent <MeshRenderer>();

            mr.material.SetBuffer("lightData", lightingBuffer);
        }
Ejemplo n.º 9
0
    public static string MeshToString(MeshFilter mf, bool invertXAxis = false, bool useWorldMatrix = false)
    {
        Mesh m = mf.sharedMesh;

        Material[] mats = mf.GetComponent <Renderer>().sharedMaterials;

        StringBuilder sb = new StringBuilder();

        sb.Append("g ").Append(mf.name).Append("\n");

        foreach (Vector3 v in m.vertices)
        {
            Vector3 vertexPos = new Vector3(v.x, v.y, v.z);
            if (useWorldMatrix)
            {
                vertexPos = mf.transform.localToWorldMatrix.MultiplyPoint(vertexPos);
            }
            if (invertXAxis)
            {
                sb.Append(string.Format("v {0} {1} {2}\n", -vertexPos.x, vertexPos.y, vertexPos.z));
            }
            else
            {
                sb.Append(string.Format("v {0} {1} {2}\n", vertexPos.x, vertexPos.y, vertexPos.z));
            }
        }
        sb.Append("\n");
        foreach (Vector3 v in m.normals)
        {
            sb.Append(string.Format("vn {0} {1} {2}\n", v.x, v.y, v.z));
        }
        sb.Append("\n");
        foreach (Vector3 v in m.uv)
        {
            sb.Append(string.Format("vt {0} {1}\n", v.x, v.y));
        }
        for (int material = 0; material < m.subMeshCount; material++)
        {
            sb.Append("\n");
            sb.Append("usemtl ").Append(mats[material].name).Append("\n");
            sb.Append("usemap ").Append(mats[material].name).Append("\n");

            int[] triangles = m.GetTriangles(material);
            for (int i = 0; i < triangles.Length; i += 3)
            {
                sb.Append(string.Format("f {0}/{0}/{0} {1}/{1}/{1} {2}/{2}/{2}\n",
                                        triangles[i + 2] + 1, triangles[i + 1] + 1, triangles[i] + 1));
            }
        }
        return(sb.ToString());
    }
Ejemplo n.º 10
0
    static void MeshToHightMapFun()
    {
        GameObject g = Selection.activeObject as GameObject;

        if (null == g)
        {
            return;
        }
        MeshFilter m = g.GetComponent <MeshFilter> ();

        if (null == m)
        {
            return;
        }


        Mesh mesh = m.sharedMesh;

        MeshToHightMap window = (MeshToHightMap)EditorWindow.GetWindow(typeof(MeshToHightMap));

        window.mesh = mesh;
        window.mat  = m.GetComponent <MeshRenderer> ().sharedMaterial;
        window.Show();

        Vector3 center;
        Vector3 size;

        Vector3 [] points = mesh.vertices;

        for (int i = 0; i < points.Length; i++)
        {
            Vector3 v = points [i];
            window.maxx = Mathf.Max(v.x, window.maxx);
            window.maxy = Mathf.Max(v.y, window.maxy);
            window.maxz = Mathf.Max(v.z, window.maxz);
            window.minx = Mathf.Min(v.x, window.minx);
            window.miny = Mathf.Min(v.y, window.miny);
            window.minz = Mathf.Min(v.z, window.minz);
        }
        center = new Vector3(0, 0, 0);
        int sizex = (int)(Mathf.Max(Mathf.Abs(window.maxx), Mathf.Abs(window.minx)) * 2 + 2f);
        int sizey = (int)(Mathf.Max(Mathf.Abs(window.maxy), Mathf.Abs(window.miny)) * 2 + 2f);
        int sizez = (int)(Mathf.Max(Mathf.Abs(window.maxz), Mathf.Abs(window.minz)) * 2 + 2f);

        sizex         = (int)Mathf.Max(sizex, sizey); //偷懶.
        sizey         = sizex;
        size          = new Vector3(sizex, sizey, sizez);
        window.bounds = new Bounds(center, size);
        //EditorUtility.DisplayDialog ("title", g.name, "确认", "取消");
        window.sel = g;
    }
Ejemplo n.º 11
0
        private void PutOnBottom(ClothingBottom bottom)
        {
            lowerSpineMesh.sharedMesh = bottom.lowerSpineMesh;
            leftHipMesh.sharedMesh    = bottom.hipMesh;
            rightHipMesh.sharedMesh   = bottom.hipMesh;
            leftKneeMesh.sharedMesh   = bottom.kneeMesh;
            rightKneeMesh.sharedMesh  = bottom.kneeMesh;

            lowerSpineMesh.GetComponent <MeshRenderer>().sharedMaterial = bottom.lowerSpine;
            leftHipMesh.GetComponent <MeshRenderer>().sharedMaterial    = bottom.legs;
            rightHipMesh.GetComponent <MeshRenderer>().sharedMaterial   = bottom.legs;
            leftKneeMesh.GetComponent <MeshRenderer>().sharedMaterial   = bottom.legs;
            rightKneeMesh.GetComponent <MeshRenderer>().sharedMaterial  = bottom.legs;
        }
    public void Fanzhuanfaxian()
    {
        GameObject model = noweditorModel;
        MeshFilter mf    = model.GetComponent <MeshFilter>();

        int[] triangles = mf.mesh.triangles;
        for (int i = 0; i < triangles.Length; i++)
        {
            triangles[i] = mf.mesh.triangles[triangles.Length - 1 - i];
        }
        mf.mesh.triangles = triangles;
        mf.mesh.RecalculateNormals();
        mf.GetComponent <MeshCollider>().sharedMesh = mf.mesh;
    }
Ejemplo n.º 13
0
    private IEnumerator StartDeadAnimation()
    {
        // material is switched Red color temporally
        ParticleManager.Instance.Play("Prefabs/Particles/PlayerDead",
                                      transform.position + (Vector3.down * 1f),
                                      meshFilter.GetComponent <Renderer>().material);

        yield return(new WaitForSeconds(0.06f));

        OnDead();

        // アニメーション終了まで適当に待つ
        yield return(new WaitForSeconds(1f));
    }
Ejemplo n.º 14
0
    IEnumerator Build()
    {
        building = true;
        noiseAudioSource.Play();
        ExoFabBuildInformation buildInformation = buildQueue[0].BuildInformation;

        SetupDisplayModel(buildInformation.displayModel);
        MeshRenderer displayRenderer = displayModel.GetComponent <MeshRenderer>();

        for (float t = 0; t < buildInformation.buildTime; t += Time.deltaTime)
        {
            float p = t / buildInformation.buildTime;
            buildQueue[0].Progress = p;
            displayRenderer.material.SetFloat("_ConstructY", p);
            yield return(null);
        }
        Instantiate(buildInformation.prefab, spawnPosition.transform.position, Quaternion.identity);
        Delete(0);
        noiseAudioSource.Stop();
        displayModel.mesh = null;
        building          = false;
        TryBuild();
    }
Ejemplo n.º 15
0
    //-------------------------------------------------------------------------------------------------
    // Method: EmitParticlesFromMesh()
    // Desc:   Each enemy has a cube childed to it that has it's mesh renderer turned off. When an enemy is ragdolled and
    //         we want to dispose of the body, we take a snapshot of the skinned mesh renderer and bake it to the cube
    //         then we emit particles from the baked mesh, and fade the material to transparent. I do this because
    //         for some reason emmitin particles from the enemies skinned mesh renderer did not work, probably has to do
    //         with how the mesh was created in blender/imported
    //--------------------------------------------------------------------------------------------------
    private void EmitParticlesFromMesh()
    {
        // asign rotation and position
        DeathMesh.transform.position = transform.position;
        DeathMesh.transform.rotation = transform.rotation;
        _bodyMesh.BakeMesh(DeathMesh.mesh);                 // Bake the skinned mesh renderer to the death mesh object
        DeathParticles.Play();                              // Start plaing the particle effect
        // the Deathparticles are set to emit from the cube mesh, which has been baked to a snapshot of the skinned mesh

        if (!GetComponent <StateControllerRanged>())
        {
            DeathMesh.GetComponent <MeshRenderer>().enabled = true; // Activate the baked mesh rendere if it is not a ranged enemy
            _bodyMesh.enabled = false;                              // Deactivate the skinned mesh
            // the ranged enemies contain submeshes, and so baking these skinned meshes to static meshes lead to undesireable results
        }
        // freeze the body to prevent twitching and erratic movement after the enemy has died:
        foreach (Rigidbody rb in _rigidbodies)
        {
            rb.isKinematic = true;
        }

        StartCoroutine(DestroyBody());
    }
Ejemplo n.º 16
0
        private void UpdateAffectChildren()
        {
            if (OldAffectChildren == AffectChildren)
            {
                return;
            }

            if (AffectChildren)
            {
                MeshFilter[] mfs = GetComponentsInChildren <MeshFilter>();
                if (mfs != null)
                {
                    Targets = new TransformMesh[mfs.Length];
                    for (int i = 0; i < mfs.Length; i++)
                    {
                        Targets[i] = new TransformMesh()
                        {
                            mesh     = mfs[i].sharedMesh,
                            renderer = mfs[i].GetComponent <Renderer>(),
                            visible  = true
                        }
                    }
                    ;
                }
                else
                {
                    Targets = new TransformMesh[0];
                }
            }
            else
            {
                MeshFilter mfs = GetComponentInChildren <MeshFilter>();
                if (mfs != null)
                {
                    Targets    = new TransformMesh[1];
                    Targets[0] = new TransformMesh()
                    {
                        mesh     = mfs.sharedMesh,
                        renderer = mfs.GetComponent <Renderer>(),
                        visible  = true
                    };
                }
                else
                {
                    Targets = new TransformMesh[0];
                }
            }

            OldAffectChildren = AffectChildren;
        }
Ejemplo n.º 17
0
        private static void MeshToString(MeshFilter meshFilter, Transform transform, ref StringBuilder stringBuilder)
        {
            Vector3    scale    = transform.localScale;
            Vector3    position = transform.localPosition;
            Quaternion rotation = transform.localRotation;

            int  vertexCount = 0;
            Mesh mesh        = meshFilter.sharedMesh;

            if (!mesh)
            {
                stringBuilder.Append("####Error####");
            }

            Material[] mats = meshFilter.GetComponent <Renderer>().sharedMaterials;

            foreach (var vertex in mesh.vertices)
            {
                ++vertexCount;
                stringBuilder.Append(string.Format("v {0} {1} {2}\n", vertex.x, vertex.y, -vertex.z));
            }
            stringBuilder.Append("\n");
            foreach (var normal in mesh.normals)
            {
                Vector3 rotatedNormal = rotation * normal;
                stringBuilder.Append(string.Format("vn {0} {1} {2}\n", -rotatedNormal.x, -rotatedNormal.y, rotatedNormal.z));
            }
            stringBuilder.Append("\n");
            foreach (var textureCoord in mesh.uv)
            {
                stringBuilder.Append(string.Format("vt {0} {1}\n", textureCoord.x, textureCoord.y));
            }
            for (int materialIndex = 0; materialIndex < mesh.subMeshCount; ++materialIndex)
            {
                stringBuilder.Append("\n");
                stringBuilder.Append("usemtl ").Append(mats[materialIndex].name).Append("\n");
                stringBuilder.Append("usemap ").Append(mats[materialIndex].name).Append("\n");

                int[] triangles = mesh.GetTriangles(materialIndex);
                for (int i = 0; i < triangles.Length; i += 3)
                {
                    stringBuilder.Append(string.Format("f {0}/{0}/{0} {1}/{1}/{1} {2}/{2}/{2}\n",
                                                       triangles[i] + 1 + _startIndex,
                                                       triangles[i + 1] + 1 + _startIndex,
                                                       triangles[i + 2] + 1 + _startIndex));
                }
            }

            _startIndex += vertexCount;
        }
Ejemplo n.º 18
0
    private MeshFilter InstantiateMesh(Mesh mesh, MeshFilter prefab, Vector3 pos, Quaternion rot, string name)
    {
        MeshFilter mf = Instantiate(prefab, pos, rot);

        mf.gameObject.name = name;
        mf.mesh            = mesh;
        MeshCollider col = mf.GetComponent <MeshCollider>();

        if (col != null)
        {
            col.sharedMesh = mf.mesh;
        }
        return(mf);
    }
Ejemplo n.º 19
0
    public void AddMesh(MeshFilter f)
    {
        //if(null == combinObj)
        //	combinObj = new MeshData[combinObjArrayLen];
        //combinObj.Extend();

        MeshData d = new MeshData();

        d.f = f;
        d.t = f.transform;
        d.r = f.GetComponent <MeshRenderer> ();
        combinObj.Add(d);
        //combinObj[combinObjCount++] = d;
    }
Ejemplo n.º 20
0
        // Derive transform information from a placeholder
        public static void ImportPlaceholder(MeshFilter meshFilter, bool rhinoBasis)
        {
            var sharedMesh = meshFilter.sharedMesh;
            var vertices   = sharedMesh?.vertices;

            if (vertices == null || vertices.Length != 4)
            {
                Debug.LogWarning($"Inconsistent placeholder mesh: {meshFilter.Path()}.{sharedMesh.name}");
                return;
            }
            var placeholder = meshFilter.transform;
            // OBSERVATION: At this stage of the import the layer parent transform is present
            // but on completion the layer may be absent, although the transform will persist.
            // NOTE: This also applies to the default import path.

            // Derive Rhino transform block basis in world coordinates
            var origin = placeholder.TransformPoint(vertices[0]);
            var basisX = placeholder.TransformPoint(vertices[1]) - origin;
            var basisY = placeholder.TransformPoint(vertices[2]) - origin;
            var basisZ = placeholder.TransformPoint(vertices[3]) - origin;

            if (rhinoBasis)
            {
                // Mesh basis describes transformation of Rhino basis
                var unityX = new Vector3(-basisX.x, basisX.y, -basisX.z);
                var unityY = new Vector3(-basisZ.x, basisZ.y, -basisZ.z);
                var unityZ = new Vector3(-basisY.x, basisY.y, -basisY.z);
                basisX = unityX;
                basisY = unityY;
                basisZ = unityZ;
            }

            // TODO: Use SVD to construct transform, which can include shear
            // TEMP: Assume transform is axial scaling followed by rotation only
            // NOTE: The origin and bases are simply the columns of an affine (3x4) transform matrix
            placeholder.localScale = new Vector3(basisX.magnitude, basisY.magnitude, basisZ.magnitude);
            placeholder.rotation   = Quaternion.LookRotation(basisZ, basisY);
            placeholder.position   = origin;

            // Remove meshes from placeholders
            // IMPORTANT: MeshRenderers must also be removed, in order to avoid
            // the application of renderer configations that could modify or remove the placeholder.
            var meshRenderer = meshFilter.GetComponent <MeshRenderer>();

            if (meshRenderer)
            {
                EP.Destroy(meshRenderer);
            }
            EP.Destroy(meshFilter);
        }
Ejemplo n.º 21
0
    private void ApplyMeshCollider()
    {
        if (m_unappliedMesh != null)
        {
            MeshCollider meshCollider = (MeshCollider)m_unappliedMesh.GetComponent("MeshCollider");

            if (meshCollider != null)
            {
                meshCollider.mesh = m_unappliedMesh.mesh;
            }
        }

        m_unappliedMesh = null;
    }
Ejemplo n.º 22
0
    //@ Root가 보유한 모든 Mesh들의 정점을 Get.
    public static void GetPointsRecursively(this Transform root, ref List <Vector3> listVertices, bool recursive = true)
    {
        if (null == root)
        {
            return;
        }

        if (false == recursive)
        {
            MeshFilter filter = root.GetComponent <MeshFilter>();

            if (null != filter)
            {
                if (null == filter.GetComponent <Renderer>())
                {
                    return;
                }
                Mesh      mesh         = filter.sharedMesh;
                Matrix4x4 localToWorld = filter.transform.localToWorldMatrix;
                foreach (int idx in mesh.triangles)
                {
                    Vector3 v = mesh.vertices[idx];
                    Vector3 p = localToWorld.MultiplyPoint3x4(v);

                    listVertices.Add(p);
                }
            }
        }
        else
        {
            MeshFilter[] meshfilters = root.GetComponentsInChildren <MeshFilter>();

            foreach (MeshFilter f in meshfilters)
            {
                if (null == f.GetComponent <Renderer>())
                {
                    continue;
                }
                Mesh      mesh         = f.sharedMesh;
                Matrix4x4 localToWorld = f.transform.localToWorldMatrix;
                foreach (int idx in mesh.triangles)
                {
                    Vector3 v = mesh.vertices[idx];
                    Vector3 p = localToWorld.MultiplyPoint3x4(v);

                    listVertices.Add(p);
                }
            }
        }
    }
        public static void ExportMeshFilterToObjFile(MeshFilter meshFilter, string fullObjFilePath)
        {
            var outputFolder           = Path.GetDirectoryName(fullObjFilePath);
            var objFileName            = Path.GetFileName(fullObjFilePath);
            var objFileNameNoExtension = Path.GetFileNameWithoutExtension(fullObjFilePath);
            var objAssetPath           = GetAssetPath(fullObjFilePath);

            // Write out the Obj file
            File.WriteAllText(fullObjFilePath, MeshFilterToString(meshFilter, objFileNameNoExtension));

            // Write out the materials file
            var materialNames = meshFilter.GetComponent <MeshRenderer>().sharedMaterials.Select(x => x.name).ToList();

            File.WriteAllText(Path.Combine(outputFolder, objFileNameNoExtension) + ".mtl", string.Concat(materialNames.Select(x => $"newmtl {x}\n")));

            // Import the Obj file
            AssetDatabase.Refresh();
            AssetDatabase.ImportAsset(objAssetPath);

            // Updating the Obj import settings and reimporting
            ModelImporter importer = (ModelImporter)ModelImporter.GetAtPath(objAssetPath);

            if (importer)
            {
                importer.importNormals        = ModelImporterNormals.Calculate;
                importer.optimizeMeshPolygons = true;
                importer.optimizeMeshVertices = true;

                foreach (var material in meshFilter.GetComponent <MeshRenderer>().sharedMaterials)
                {
                    importer.AddRemap(new AssetImporter.SourceAssetIdentifier(material), material);
                }

                EditorUtility.SetDirty(importer);
                importer.SaveAndReimport();
            }
        }
Ejemplo n.º 24
0
    public static void CreatePlayerMesh(ref MeshFilter mf, float alpha)
    {
        // Declarations
        List <Vector3> vertices  = new List <Vector3>();
        List <int>     triangles = new List <int>();
        List <Vector3> normals   = new List <Vector3>();

        // Calculations
        for (int i = 0; i < Player.inst.verticesCount; i++)
        {
            vertices.AddRange(new Vector3[2] {
                Player.inst.outerVertices_mesh[i],
                Player.inst.innerVertices_mesh[i]
            });
            triangles.AddRange(new int[6] {         // count clockwise!
                // outer triangle
                i *2,
                (i * 2 + 2) % (Player.inst.verticesCount * 2),
                i * 2 + 1,
                // inner triangle
                i * 2 + 1,
                (i * 2 + 2) % (Player.inst.verticesCount * 2),
                (i * 2 + 3) % (Player.inst.verticesCount * 2)
            });
            normals.AddRange(new Vector3[2] {
                -Vector3.forward,
                -Vector3.forward
            });
        }

        // Assign
        Mesh newMesh = new Mesh
        {
            vertices  = vertices.ToArray(),
            triangles = triangles.ToArray(),
            normals   = normals.ToArray()
        };

        newMesh.MarkDynamic();                      // for better performance
        mf.mesh = newMesh;
        // no UVs

        // Set Alpha
        Material mat   = mf.GetComponent <MeshRenderer>().material;
        Color    color = mat.color;

        color.a = alpha;
        mat.SetColor("_BaseColor", color);
    }
Ejemplo n.º 25
0
        private void OnGUI()
        {
            target   = EditorGUILayout.ObjectField("Target", target, typeof(MeshFilter), true) as MeshFilter;
            meshName = EditorGUILayout.TextField("Mesh name", meshName);
            fileType = (MeshSaver.FileType)EditorGUILayout.EnumPopup("File type", fileType);
            EditorCommon.BrowseFolder("Path", ref path);
            GUI.enabled =
                target != null &&
                target.sharedMesh != null &&
                !string.IsNullOrEmpty(meshName) &&
                !string.IsNullOrEmpty(path);
            if (EditorCommon.RightAnchoredButton("Save"))
            {
                Material     mat = null;
                MeshRenderer mr  = target.GetComponent <MeshRenderer>();
                if (mr != null)
                {
                    mat = mr.sharedMaterial;
                }
                MeshSaver.Save(target.sharedMesh, mat, path, meshName, fileType);
            }
            GUI.enabled = true;

            EditorCommon.Separator();
            showAd = EditorGUILayout.Foldout(showAd, "Introducing Polaris Ecosystem - The complete toolset for immersive Low Poly levels.");

            if (showAd)
            {
                if (GUILayout.Button("Polaris - Low Poly Terrain"))
                {
                    Application.OpenURL("https://assetstore.unity.com/packages/tools/terrain/low-poly-terrain-polaris-2020-170400?aid=1100l3QbW&pubref=mesh-to-file");
                }
                if (GUILayout.Button("Poseidon - Low Poly Water"))
                {
                    Application.OpenURL("https://assetstore.unity.com/packages/vfx/shaders/substances/poseidon-low-poly-water-system-builtin-lwrp-153826?aid=1100l3QbW&pubref=mesh-to-file");
                }
                if (GUILayout.Button("Jupiter - Procedural Sky"))
                {
                    Application.OpenURL("https://assetstore.unity.com/packages/2d/textures-materials/sky/procedural-sky-builtin-lwrp-urp-jupiter-159992?aid=1100l3QbW&pubref=mesh-to-file");
                }

                Texture2D bg = Resources.Load <Texture2D>("Background");
                if (bg != null)
                {
                    Rect bgRect = GUILayoutUtility.GetAspectRect(bg.width * 1.0f / bg.height);
                    GUI.DrawTexture(bgRect, bg);
                }
            }
        }
Ejemplo n.º 26
0
    public TrailRenderer(int max_vert, GameObject parent)
    {
        if (PerformanceManager.Instance.CurrentEnvironmentInfo != null) //by pj 重新修正 当当前有配置的时候使用配置 否则就不改变
        {
            _Quality = PerformanceManager.Instance.CurrentEnvironmentInfo.trailQuality;
        }

        _GameObject = new GameObject("TrailRenderer", typeof(MeshFilter), typeof(MeshRenderer));
        _GameObject.transform.parent = parent.transform;
        meshFilter = _GameObject.GetComponent <MeshFilter>();
        _Renderer  = meshFilter.GetComponent <Renderer>();
        if (!Application.isPlaying)
        {
            meshFilter.sharedMesh = new Mesh();
            _Mesh = meshFilter.sharedMesh;
        }
        else
        {
            meshFilter.mesh = new Mesh();
            _Mesh           = meshFilter.mesh;
        }
        _TotalSubsections = 0;
        _TextureYCount    = _TextureYSplit;
        _HermiteBasis     = new Vector4[4];
        _HermiteBasis[0]  = new Vector4(2, -3, 0, 1);
        _HermiteBasis[1]  = new Vector4(-2, 3, 0, 0);
        _HermiteBasis[2]  = new Vector4(1, -2, 1, 0);
        _HermiteBasis[3]  = new Vector4(1, -1, 0, 0);

        int max_indices = max_vert * 3 - 6;

        _MaxVerts   = max_vert;
        _MaxIndices = max_indices;
        _SegmentPositionTopBuffer    = new EB.CircularBuffer <Vector3>(max_vert);
        _SegmentPositionBottomBuffer = new EB.CircularBuffer <Vector3>(max_vert);
        _SegmentSubsectionsBuffer    = new EB.CircularBuffer <int>(max_vert);
        _SegmentTimesBuffer          = new EB.CircularBuffer <float>(max_vert);

        //move vert,etc. array creation here
        _vertices = new Vector3[max_vert];
        _uvs      = new Vector3[max_vert];
        _colors   = new Color[max_vert];
        _indices  = new int[max_indices];

        for (int i = 0; i < max_indices; ++i)
        {
            _indices[i] = 0;
        }
    }
Ejemplo n.º 27
0
        private void OnGUI()
        {
            target   = EditorGUILayout.ObjectField("Target", target, typeof(MeshFilter), true) as MeshFilter;
            meshName = EditorGUILayout.TextField("Mesh name", meshName);
            fileType = (MeshSaver.FileType)EditorGUILayout.EnumPopup("File type", fileType);
            EditorCommon.BrowseFolder("Path", ref path);
            GUI.enabled =
                target != null &&
                target.sharedMesh != null &&
                !string.IsNullOrEmpty(meshName) &&
                !string.IsNullOrEmpty(path);
            if (EditorCommon.RightAnchoredButton("Save"))
            {
                Material     mat = null;
                MeshRenderer mr  = target.GetComponent <MeshRenderer>();
                if (mr != null)
                {
                    mat = mr.sharedMaterial;
                }
                MeshSaver.Save(target.sharedMesh, mat, path, meshName, fileType);
            }
            GUI.enabled = true;

            EditorCommon.Separator();
            showAd = EditorGUILayout.Foldout(showAd, "This package is a part of the amazing Polaris - Low Poly Terrain Engine");

            if (showAd)
            {
                if (GUILayout.Button("Polaris Starter - FREE"))
                {
                    Application.OpenURL("https://assetstore.unity.com/packages/slug/134981");
                }
                if (GUILayout.Button("Polaris Basic"))
                {
                    Application.OpenURL("https://assetstore.unity.com/packages/tools/terrain/polaris-lite-procedural-low-poly-terrain-engine-118854?aid=1100l3QbW");
                }
                if (GUILayout.Button("Polaris Pro"))
                {
                    Application.OpenURL("https://assetstore.unity.com/packages/tools/terrain/polaris-low-poly-terrain-engine-123717?aid=1100l3QbW");
                }

                Texture2D bg = Resources.Load <Texture2D>("Background");
                if (bg != null)
                {
                    Rect bgRect = GUILayoutUtility.GetAspectRect(bg.width * 1.0f / bg.height);
                    GUI.DrawTexture(bgRect, bg);
                }
            }
        }
Ejemplo n.º 28
0
    void Awake()
    {
        Transform  groundPlatformVisibilityMaskTransform = this.transform.FindChild("GroundPlatformVisibilityMask");
        GameObject visibilityMaskGameObject = null;

        if (groundPlatformVisibilityMaskTransform == null)
        {
            Logger.Info("Creating visibility check game object and attach as child.");

            visibilityMaskGameObject = new GameObject("GroundPlatformVisibilityMask");
            visibilityMaskGameObject.transform.SetParent(this.transform);
            visibilityMaskGameObject.layer = LayerMask.NameToLayer("Background");
            visibilityMaskGameObject.transform.localPosition = Vector3.zero;

            Instantiate(visibilityMaskGameObject, Vector3.zero, Quaternion.identity);
        }
        else
        {
            visibilityMaskGameObject = groundPlatformVisibilityMaskTransform.gameObject;
        }
        visibilityMaskGameObject.hideFlags = HideFlags.NotEditable;

        _visibilityCollider = visibilityMaskGameObject.GetComponent <BoxCollider2D>();
        if (_visibilityCollider == null)
        {
            _visibilityCollider           = visibilityMaskGameObject.AddComponent <BoxCollider2D>();
            _visibilityCollider.isTrigger = true;
            _visibilityCollider.hideFlags = HideFlags.NotEditable;
        }

        _physicsCollider = this.gameObject.GetComponent <BoxCollider2D>();
        if (_physicsCollider == null)
        {
            Logger.Info("Creating physics controller");

            _physicsCollider           = this.gameObject.AddComponent <BoxCollider2D>();
            _physicsCollider.hideFlags = HideFlags.NotEditable;
        }

#if UNITY_EDITOR
        _physicsCollider.hideFlags = HideFlags.NotEditable;
#endif

        _physicsCollider.size    = new Vector2(width, height);
        _visibilityCollider.size = new Vector2(width + Screen.width / 2, height + Screen.height / 2); // add some padding

        _meshFilter   = GetComponent <MeshFilter>();
        _meshRenderer = _meshFilter.GetComponent <MeshRenderer>();
    }
Ejemplo n.º 29
0
    public void BuildMesh()
    {
        var storableMesh = MeshBuilder.BuildMeshFromLayers(layers);
        var verts        = storableMesh.vertices;

        meshFilter.mesh.SetVertices(storableMesh.vertices);
        meshFilter.mesh.SetTriangles(storableMesh.triangles, 0);
        meshFilter.mesh.RecalculateNormals();
        MeshHelper.TurnOutNormals(meshFilter.mesh);


        meshFilter.GetComponent <MeshCollider>().sharedMesh = meshFilter.mesh;

        for (int i = 0; i < verts.Count; i++)
        {
            var go = Instantiate(spherePrefab, dragSpheresParent);
            go.OnPositionChange       += OnSpherePositionChange;
            go.transform.localPosition = verts[i];
            sphereToVertex.Add(go, new Dictionary <MeshFilter, int>()
            {
                { meshFilter, i }
            });
            if (i < layers[0].Count)
            {
                sphereToVertex[go].Add(downBound, i);
            }
            if (i >= verts.Count - layers[layers.Count - 1].Count)
            {
                sphereToVertex[go].Add(upperBound, i - verts.Count + layers[layers.Count - 1].Count);
            }
        }

        ToggleMainMeshComponents(true);

        state = LayerBankState.drawMainMesh;
    }
Ejemplo n.º 30
0
        public static Collider AddCollider(this MeshFilter mesh, bool isTrigger = false)
        {
            var col = mesh.GetComponent <Collider>();

            if (col == null || !col.isTrigger)
            {
                var collider = mesh.gameObject.AddComponent <MeshCollider>();
                collider.sharedMesh = mesh.sharedMesh;
                collider.convex     = true;
                collider.isTrigger  = isTrigger;
                col = collider;
            }
            col.enabled = true;
            return(col);
        }