public override bool PreDraw(SpriteBatch spriteBatch, Color lightColor)
        {
            float alpha = MathHelper.Clamp(projectile.localAI[0] / AppearTime, 0f, 1f) * MathHelper.Clamp((projectile.timeLeft - 50) / AppearTime, 0f, 1f);

            spriteBatch.End();
            spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.None, RasterizerState.CullCounterClockwise, null, Main.GameViewMatrix.TransformationMatrix);

            if (alpha > 0)
            {
                Vector2[] points = new Vector2[] { startingloc, startingloc + projectile.velocity };

                TrailHelper trail = new TrailHelper("BasicEffectAlphaPass", mod.GetTexture("SmallLaser"));
                //UnifiedRandom rando = new UnifiedRandom(projectile.whoAmI);
                Color colorz  = Color.Lerp(color1, Color.White, 0.50f);
                Color colorz2 = color2;
                trail.color = delegate(float percent)
                {
                    return(Color.Lerp(colorz, colorz2, percent));
                };
                trail.projsize               = Vector2.Zero;
                trail.coordOffset            = new Vector2(0, Main.GlobalTime * -1f);
                trail.coordMultiplier        = new Vector2(1f, 1f);
                trail.doFade                 = false;
                trail.trailThickness         = 16;
                trail.trailThicknessIncrease = 0;
                //trail.capsize = new Vector2(6f, 0f);
                trail.strength = alpha * 1f;
                trail.DrawTrail(points.ToList(), projectile.Center);
            }

            Texture2D mainTex = SGAmod.ExtraTextures[96];
            Texture2D glowTex = ModContent.GetTexture("SGAmod/Glow");

            float alpha2 = MathHelper.Clamp(projectile.localAI[0] / 3f, 0f, 1f) * MathHelper.Clamp(projectile.timeLeft / 25f, 0f, 1f);

            if (GetType() != typeof(Accessories.RefractorLaserProj))
            {
                spriteBatch.End();
                spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Additive, SamplerState.PointClamp, DepthStencilState.None, RasterizerState.CullCounterClockwise, null, Main.GameViewMatrix.TransformationMatrix);

                Effect effect = SGAmod.TextureBlendEffect;

                effect.Parameters["coordMultiplier"].SetValue(new Vector2(1f, 1f));
                effect.Parameters["coordOffset"].SetValue(new Vector2(0f, 0f));
                effect.Parameters["noiseMultiplier"].SetValue(new Vector2(1f, 1f));
                effect.Parameters["noiseOffset"].SetValue(new Vector2(0f, 0f));

                effect.Parameters["Texture"].SetValue(SGAmod.Instance.GetTexture("Extra_49c"));
                effect.Parameters["noiseTexture"].SetValue(SGAmod.Instance.GetTexture("Extra_49c"));
                effect.Parameters["noiseProgress"].SetValue(projectile.localAI[0] / 30f);
                effect.Parameters["textureProgress"].SetValue(0f);
                effect.Parameters["noiseBlendPercent"].SetValue(1f);
                effect.Parameters["strength"].SetValue(alpha2);

                effect.Parameters["colorTo"].SetValue(color1.ToVector4() * new Vector4(0.5f, 0.5f, 0.5f, 1f));
                effect.Parameters["colorFrom"].SetValue(Color.Black.ToVector4());

                effect.CurrentTechnique.Passes["TextureBlend"].Apply();

                Main.spriteBatch.Draw(mainTex, startingloc + projectile.velocity - Main.screenPosition, null, Color.White, projectile.rotation, mainTex.Size() / 2f, (alpha2 + (projectile.localAI[0] / 60f)) * 0.75f, default, 0);
Example #2
0
        public void ClientRead(ServerNetObject type, NetBuffer msg, float sendingTime)
        {
            int eventIndex     = msg.ReadRangedInteger(0, (int)Math.Ceiling(MaxNodeCount / (float)MaxNodesPerNetworkEvent));
            int nodeCount      = msg.ReadRangedInteger(0, MaxNodesPerNetworkEvent);
            int nodeStartIndex = eventIndex * MaxNodesPerNetworkEvent;

            Vector2[] nodePositions = new Vector2[nodeStartIndex + nodeCount];
            for (int i = 0; i < nodes.Count && i < nodePositions.Length; i++)
            {
                nodePositions[i] = nodes[i];
            }

            for (int i = 0; i < nodeCount; i++)
            {
                nodePositions[nodeStartIndex + i] = new Vector2(msg.ReadFloat(), msg.ReadFloat());
            }

            if (nodePositions.Any(n => !MathUtils.IsValid(n)))
            {
                nodes.Clear();
                return;
            }

            nodes = nodePositions.ToList();
            UpdateSections();
            Drawable = nodes.Any();
        }
 void GenerateLineVBO()
 {
     Vector2[] vecs = new Vector2[2];
     uint[]    inds = new uint[2];
     inds[0]       = 0;
     vecs[0]       = new Vector2(0, 0);
     inds[1]       = 1;
     vecs[1]       = new Vector2(1, 0);
     Line          = new VBO();
     Line.Vertices = vecs.ToList();
     Line.Indices  = inds.ToList();
     Line.GenerateVBO();
 }
 void GenerateSquareVBO()
 {
     Vector2[] vecs = new Vector2[4];
     uint[]    inds = new uint[4];
     for (uint u = 0; u < 4; u++)
     {
         inds[u] = u;
     }
     vecs[0]         = new Vector2(1, 0);
     vecs[1]         = new Vector2(1, 1);
     vecs[2]         = new Vector2(0, 1);
     vecs[3]         = new Vector2(0, 0);
     Square          = new VBO();
     Square.Vertices = vecs.ToList();
     Square.Indices  = inds.ToList();
     Square.GenerateVBO();
 }
    private static Rect BuildScreenRect(Vector2[] screenPoints)
    {
        List<Vector2> sp = screenPoints.ToList();
        float minX = sp.Min(point => point.x);
        float maxX = sp.Max(point => point.x);
        float minY = sp.Min(point => point.y);
        float maxY = sp.Max(point => point.y);

        Rect screenRect = new Rect(minX, minY, maxX - minX + 1, maxY - minY + 1);

        screenRect.xMin = Mathf.Clamp(screenRect.xMin, 1.0f, Screen.width - 1);
        screenRect.xMax = Mathf.Clamp(screenRect.xMax, 1.0f, Screen.width - 1);
        screenRect.yMin = Mathf.Clamp(screenRect.yMin, 1.0f, Screen.height - 1);
        screenRect.yMax = Mathf.Clamp(screenRect.yMax, 1.0f, Screen.height - 1);

        return screenRect;
    }
Example #6
0
        public void ClientRead(ServerNetObject type, NetBuffer msg, float sendingTime)
        {
            nodes.Clear();

            int nodeCount = msg.ReadByte();

            Vector2[] nodePositions = new Vector2[nodeCount];

            for (int i = 0; i < nodeCount; i++)
            {
                nodePositions[i] = new Vector2(msg.ReadFloat(), msg.ReadFloat());
            }

            if (nodePositions.Any(n => !MathUtils.IsValid(n)))
            {
                return;
            }

            nodes = nodePositions.ToList();

            UpdateSections();
            Drawable = nodes.Any();
        }
Example #7
0
        private void CreateMadelineSprite(bool badeline = false)
        {
            PlayerSpriteMode mode;

            if (badeline)
            {
                mode = PlayerSpriteMode.Badeline;
            }
            else
            {
                bool backpack = player.SceneAs <Level>()?.Session.Inventory.Backpack ?? true;
                mode = backpack ? PlayerSpriteMode.Madeline : PlayerSpriteMode.MadelineNoBackpack;
            }

            PlayerSprite origSprite = player.Sprite;

            if (playerSprite != null)
            {
                origSprite = playerSprite;
            }

            playerSprite = new PlayerSprite(mode)
            {
                Position  = origSprite.Position,
                Rotation  = origSprite.Rotation,
                HairCount = origSprite.HairCount,
                Scale     = origSprite.Scale,
                Rate      = origSprite.Rate,
                Justify   = origSprite.Justify
            };
            if (player.StateMachine.State == Player.StStarFly)
            {
                playerSprite.Color = StarFlyColor;
            }

            playerSprite.Scale.X = playerSprite.Scale.Abs().X *(int)facing;

            playerSprite.Active = false;
            try {
                if (!string.IsNullOrEmpty(origSprite.CurrentAnimationID))
                {
                    playerSprite.Play(origSprite.CurrentAnimationID);
                    playerSprite.SetAnimationFrame(origSprite.CurrentAnimationFrame);
                }
            }
            // ReSharper disable once EmptyGeneralCatchClause
            catch (Exception) { }

            if (playerHair == null)
            {
                playerHair = new PlayerHair(playerSprite)
                {
                    Alpha  = player.Hair.Alpha,
                    Facing = facing,
                    Border = player.Hair.Border,
                    DrawPlayerSpriteOutline = player.Hair.DrawPlayerSpriteOutline
                };
                Vector2[] nodes = new Vector2[player.Hair.Nodes.Count];
                player.Hair.Nodes.CopyTo(nodes);
                playerHair.Nodes  = nodes.ToList();
                playerHair.Active = false;
            }

            Color hairColor = Player.NormalHairColor;

            if (player.StateMachine.State != Player.StStarFly)
            {
                switch (player.Dashes)
                {
                case 0:
                    hairColor = badeline ? Player.UsedBadelineHairColor : Player.UsedHairColor;
                    break;

                case 1:
                    hairColor = badeline ? Player.NormalBadelineHairColor : Player.NormalHairColor;
                    break;

                case 2:
                    hairColor = badeline ? Player.TwoDashesBadelineHairColor : Player.TwoDashesHairColor;
                    break;
                }
            }
            else
            {
                hairColor = StarFlyColor;
            }

            playerHair.Color = hairColor;
        }
Example #8
0
        public static dynamic ParseBufferViews(this byte[] bufferBytes, Accessor accessors, BufferView bufferViews)
        {
            if (accessors.ComponentType == Accessor.ComponentTypeEnum.UNSIGNED_SHORT && accessors.Type == Accessor.TypeEnum.VEC4)
            {
                byte[] subarray = bufferBytes.SubArray(bufferViews.ByteOffset, bufferViews.ByteLength);

                var size = subarray.Count() / sizeof(ushort);
                var ints = new int[size];
                for (var index = 0; index < size; index++)
                {
                    ints[index] = BitConverter.ToUInt16(subarray, index * sizeof(ushort));
                }
                Vector4[] vectors = new Vector4[ints.Count() / 4];
                for (int f = 0; f < ints.Count(); f += 4)
                {
                    vectors[f / 4] = new Vector4(ints[f], ints[f + 1], ints[f + 2], ints[f + 3]);
                }
                return(vectors.ToList());
            }

            if (accessors.ComponentType == Accessor.ComponentTypeEnum.UNSIGNED_SHORT && accessors.Type == Accessor.TypeEnum.SCALAR)
            {
                byte[] subarray = bufferBytes.SubArray(bufferViews.ByteOffset, bufferViews.ByteLength);

                var   size = subarray.Count() / sizeof(ushort);
                int[] ints = new int[size];
                for (var index = 0; index < size; index++)
                {
                    ints[index] = BitConverter.ToUInt16(subarray, index * sizeof(ushort));
                }
                return(ints);
            }

            if (accessors.ComponentType == Accessor.ComponentTypeEnum.UNSIGNED_INT && accessors.Type == Accessor.TypeEnum.SCALAR)
            {
                byte[] subarray = bufferBytes.SubArray(bufferViews.ByteOffset, bufferViews.ByteLength);

                var   size = subarray.Count() / sizeof(uint);
                int[] ints = new int[size];
                for (var index = 0; index < size; index++)
                {
                    ints[index] = (int)BitConverter.ToUInt32(subarray, index * sizeof(uint));
                }
                return(ints);
            }

            if (accessors.ComponentType == Accessor.ComponentTypeEnum.UNSIGNED_BYTE && accessors.Type == Accessor.TypeEnum.SCALAR)
            {
                byte[] subarray = bufferBytes.SubArray(bufferViews.ByteOffset, bufferViews.ByteLength);

                int[] ints = new int[subarray.Length];
                for (var index = 0; index < subarray.Length; index++)
                {
                    ints[index] = subarray[index];
                }

                return(ints);
            }

            if (accessors.ComponentType == Accessor.ComponentTypeEnum.FLOAT && accessors.Type == Accessor.TypeEnum.VEC3)
            {
                byte[] subarray = bufferBytes.SubArray(bufferViews.ByteOffset, bufferViews.ByteLength);

                var size   = subarray.Count() / sizeof(float);
                var floats = new float[size];
                for (var index = 0; index < size; index++)
                {
                    floats[index] = BitConverter.ToSingle(subarray, index * sizeof(float));
                }
                Vector3[] vectors = new Vector3[floats.Count() / 3];
                for (int f = 0; f < floats.Count(); f += 3)
                {
                    vectors[f / 3] = new Vector3(floats[f], floats[f + 1], floats[f + 2]);
                }
                return(vectors.ToList());
            }

            if (accessors.ComponentType == Accessor.ComponentTypeEnum.FLOAT && accessors.Type == Accessor.TypeEnum.VEC2)
            {
                byte[] subarray = bufferBytes.SubArray(bufferViews.ByteOffset, bufferViews.ByteLength);

                var size   = subarray.Count() / sizeof(float);
                var floats = new float[size];
                for (var index = 0; index < size; index++)
                {
                    floats[index] = BitConverter.ToSingle(subarray, index * sizeof(float));
                }
                Vector2[] vectors = new Vector2[floats.Count() / 2];
                for (int f = 0; f < floats.Count(); f += 2)
                {
                    vectors[f / 2] = new Vector2(floats[f], floats[f + 1]);
                }
                return(vectors.ToList());
            }

            if (accessors.ComponentType == Accessor.ComponentTypeEnum.FLOAT && accessors.Type == Accessor.TypeEnum.VEC4)
            {
                byte[] subarray = bufferBytes.SubArray(bufferViews.ByteOffset, bufferViews.ByteLength);

                var size   = subarray.Count() / sizeof(float);
                var floats = new float[size];
                for (var index = 0; index < size; index++)
                {
                    floats[index] = BitConverter.ToSingle(subarray, index * sizeof(float));
                }
                Vector4[] vectors = new Vector4[floats.Count() / 4];
                for (int f = 0; f < floats.Count(); f += 4)
                {
                    vectors[f / 4] = new Vector4(floats[f], floats[f + 1], floats[f + 2], floats[f + 3]);
                }
                return(vectors.ToList());
            }

            return(null);
        }
Example #9
0
        /*create meash for linear rendered 3D object*/
        public void CreateMesh(Curve curve, float offset, Material linearMaterial, Material crossMaterial, Polygon cross)
        {
            List <Vector2> fragments = cross.toFragments();

            int segmentCount = Mathf.CeilToInt(curve.length * curve.maximumCurvature / maxAngleDiff);
            int base_vcount  = (segmentCount + 1) * fragments.Count;
            int base_tcount  = segmentCount * 2 * 3 * fragments.Count;

            int[] crossTriangles = cross.createMeshTriangle();
            int   cross_vcount   = fragments.Count;
            int   cross_tcount   = crossTriangles.Length;

            Vector2[] crossUVs = cross.createUV();

            Vector3[] all_vertices     = new Vector3[base_vcount + 2 * cross_vcount];
            int[]     linear_triangles = new int[base_tcount];
            Vector2[] linearUVs        = new Vector2[base_vcount];

            for (int i = 0; i != segmentCount + 1; ++i)
            {
                Vector3        roadPoint      = curve.At(1.0f / segmentCount * i);
                float          direction      = curve.Angle_2d(1.0f / segmentCount * i) - Mathf.PI / 2;
                List <Vector3> localFragments = fragments.ConvertAll((input) => roadPoint +
                                                                     Algebra.toVector3(Algebra.twodRotate(Vector2.right * (offset + input.x), direction)) +
                                                                     Vector3.up * input.y);
                /*stretch Z*/
                List <float> cross_y_offset = cross.getVResizeOffset(roadPoint.y);
                for (int j = 0; j != localFragments.Count; ++j)
                {
                    localFragments[j] += Vector3.up * cross_y_offset[j];
                }

                float cross_diameter   = fragments.Sum((input) => input.magnitude);
                float partial_diameter = 0f;
                for (int j = i * cross_vcount, local_j = 0; j != i * cross_vcount + cross_vcount; ++j, ++local_j)
                {
                    all_vertices[j]   = localFragments[local_j];
                    linearUVs[j]      = new Vector2(partial_diameter / cross_diameter, i * 1.0f / segmentCount * curve.length / cross_diameter);
                    partial_diameter += fragments[local_j].magnitude;
                }
            }

            for (int i = 0; i != cross_vcount; ++i)
            {
                all_vertices[base_vcount + i] = all_vertices[i];
                all_vertices[base_vcount + cross_vcount + i] = all_vertices[base_vcount - cross_vcount + i];
            }

            for (int i = 0, triangle = 0; i != segmentCount; ++i)
            {
                for (int j = 0; j != cross_vcount; ++j, triangle += 6)
                {
                    linear_triangles[triangle]     = i * cross_vcount + j;
                    linear_triangles[triangle + 1] = i * cross_vcount + (j + 1) % cross_vcount;
                    linear_triangles[triangle + 2] = (i + 1) * cross_vcount + j;

                    linear_triangles[triangle + 3] = i * cross_vcount + (j + 1) % cross_vcount;
                    linear_triangles[triangle + 4] = (i + 1) * cross_vcount + (j + 1) % cross_vcount;
                    linear_triangles[triangle + 5] = (i + 1) * cross_vcount + j;
                }
            }

            int[] cross_triangles = new int[2 * cross_tcount];
            /*Add tris at start*/
            for (int j = 0; j != cross_tcount; ++j)
            {
                cross_triangles[j] = crossTriangles[j] + base_vcount;
            }

            /*Add tris at end*/
            for (int j = 0; j != cross_tcount; ++j)
            {
                if (j % 3 == 1)
                {
                    cross_triangles[cross_tcount + j] = crossTriangles[j + 1];
                }
                else
                {
                    if (j % 3 == 2)
                    {
                        cross_triangles[cross_tcount + j] = crossTriangles[j - 1];
                    }
                    else
                    {
                        cross_triangles[cross_tcount + j] = crossTriangles[j];
                    }
                }
                cross_triangles[cross_tcount + j] += (base_vcount + cross_vcount);
            }

            Vector2[] modifiedCrossUVs = new Vector2[base_vcount + 2 * cross_vcount];
            for (int i = 0; i != base_vcount; ++i)
            {
                modifiedCrossUVs[i] = linearUVs[i];
            }
            for (int i = 0; i != cross_vcount; ++i)
            {
                modifiedCrossUVs[i + base_vcount] = modifiedCrossUVs[i + base_vcount + cross_vcount] = crossUVs[i];
            }


            GetComponent <MeshRenderer>().sharedMaterials = new Material[2] {
                crossMaterial, linearMaterial
            };

            MeshFilter meshFilter = GetComponent <MeshFilter>();

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

            meshFilter.sharedMesh.subMeshCount = 2;
            meshFilter.sharedMesh.SetVertices(all_vertices.ToList());
            meshFilter.sharedMesh.SetTriangles(cross_triangles, 0);
            meshFilter.sharedMesh.SetTriangles(linear_triangles, 1);
            meshFilter.sharedMesh.SetUVs(0, modifiedCrossUVs.ToList());
        }
Example #10
0
        /// <summary>
        /// Partitions a connected node group by:
        ///     1. Repeatedly running BFS on its nodes to find cycles and removing edges for the next BFS until no more
        ///        cycles can be found.
        ///         1.1 Note that the BFS only runs on nodes with two or less VALID EDGES.  Edges are only removed IFF either
        ///             of its vertices has two or less valid edges.  This ensures we do not remove an edge that could be used
        ///             twice, for example two adjacent cycles that share an edge.
        ///     2. The cycle is added to a list of perimeters (AKA a list of nodes) IFF it is NOT a hole.
        /// </summary>
        /// <param name="connectedGroup">ConnectedNodeGroup that is being partitioned.</param>
        /// <param name="idsContainedInGroup">The IDs of the ConnectedNodeGroups contained within <param>connectedGroup</param></param>
        /// <param name="connectedGroups">List of all ConnectedNodeGroups.</param>
        /// <param name="nodes">List of all nodes.</param>
        /// <param name="holes">Holes of the polygon that was made into a PolygonSplittingGraph.</param>
        /// <returns></returns>
        public static List <ChordlessPolygon> PartitionConnectedNodeGroup(ConnectedNodeGroup connectedGroup,
                                                                          SortedDictionary <int, HashSet <int> > idsContainedInGroup,
                                                                          SortedList <int, ConnectedNodeGroup> connectedGroups,
                                                                          SortedList <int, PolygonSplittingGraphNode> nodes,
                                                                          List <Vector2>[] holes)
        {
            if (connectedGroup is null)
            {
                throw new ArgumentNullException(nameof(connectedGroup));
            }
            if (idsContainedInGroup is null)
            {
                throw new ArgumentNullException(nameof(idsContainedInGroup));
            }
            if (connectedGroups is null)
            {
                throw new ArgumentNullException(nameof(connectedGroups));
            }
            if (nodes is null)
            {
                throw new ArgumentNullException(nameof(nodes));
            }
            if (holes is null)
            {
                throw new ArgumentNullException(nameof(holes));
            }

            var outerPerimCycle = new List <PolygonSplittingGraphNode>();
            var polyCycles      = new List <List <PolygonSplittingGraphNode> >();
            var holeCycles      = new List <List <PolygonSplittingGraphNode> >();

            List <List <PolygonSplittingGraphNode> > allFaces = _GetAllFaces(connectedGroup);
            var uniqueFaces = new List <List <Vector2> >();

            foreach (List <PolygonSplittingGraphNode> newFace in allFaces)
            {
                //construct Vector2[] or List<Vector2> describing face perim in Vector2s
                var newFacePerim = new Vector2[newFace.Count];
                for (int i = 0; i < newFace.Count; i++)
                {
                    PolygonSplittingGraphNode node = newFace[i];
                    newFacePerim[i] = new Vector2(node.x, node.y);
                }

                bool newFaceUnique = true;
                foreach (List <Vector2> uniqueFace in uniqueFaces)
                {
                    if (GeometryFuncs.ArePolysIdentical(uniqueFace.ToArray(), newFacePerim))
                    {
                        newFaceUnique = false;
                        break;
                    }
                }

                if (newFaceUnique)
                {
                    uniqueFaces.Add(newFacePerim.ToList());
                    if (IsCycleHole(newFacePerim, holes))
                    {
                        holeCycles.Add(newFace);
                    }
                    else if (IsCycleOuterPerim(newFacePerim, connectedGroup.outerPerimNodes))
                    {
                        outerPerimCycle.AddRange(newFace);
                    }
                    else if (IsCycleComplex(newFacePerim))
                    {
                        continue;
                    }
                    else
                    {
                        polyCycles.Add(newFace);
                    }
                }
            }

            var innerHoles = holeCycles.Select(_FinaliseInnerHole).ToList();
            var partitions = new List <ChordlessPolygon>();

            foreach (List <PolygonSplittingGraphNode> polyCycle in polyCycles)
            {
                partitions.Add(_FinalisePartition(polyCycle, connectedGroup, connectedGroups,
                                                  idsContainedInGroup, nodes, innerHoles));
            }

            if (partitions.Count == 0 && outerPerimCycle.Count > 0) //planar face that represents the outer perim is only relevant IFF there are no other (non-hole) faces
            {
                partitions.Add(_FinalisePartition(outerPerimCycle, connectedGroup, connectedGroups,
                                                  idsContainedInGroup, nodes, innerHoles));
            }
            return(partitions);
        }
    private void DrawLine(Vector3 startPoint, Vector3 finishPoint)
    {
        Vector3 firstNewVerticle  = RevertInYBasedOnPoint(finishPoint, SetPositionOnCircle(finishPoint, lineWeight, -AngleBetweenTwoPoints(startPoint, finishPoint)));
        Vector3 secondNewVerticle = SetPositionOnCircle(finishPoint, lineWeight, AngleBetweenTwoPoints(startPoint, finishPoint));

        if (_mesh.vertices.Length >= 2)
        {
            var lenght = _mesh.vertices.Length;

            var copyOfVertices = _mesh.vertices;

            copyOfVertices[lenght - 1] = Vector3.Lerp(_mesh.vertices[lenght - 1], secondNewVerticle, .5f);
            copyOfVertices[lenght - 2] = Vector3.Lerp(_mesh.vertices[lenght - 2], firstNewVerticle, .5f);

            _mesh.vertices = copyOfVertices;
        }

        //verts
        Vector3[] verts = new Vector3[]
        {
            firstNewVerticle,
            secondNewVerticle
        };
        _mesh.vertices = AddArrays <Vector3>(_mesh.vertices, verts);

        //normals
        if (_mesh.normals.Length > 1)
        {
            _mesh.normals[_mesh.normals.Length - 1] = new Vector3(0, 0, -1);
            _mesh.normals[_mesh.normals.Length - 2] = new Vector3(0, 0, -1);
        }

        //tris
        int vertLenght = _mesh.vertices.Length;

        if (vertLenght >= 4)
        {
            int[] tris = new int[]
            {
                vertLenght - 4, vertLenght - 3, vertLenght - 2,
                vertLenght - 2, vertLenght - 3, vertLenght - 1
            };
            _mesh.triangles = AddArrays <int>(_mesh.triangles, tris);
        }

        Vector2[] tempUvs = new Vector2[_mesh.vertices.Length];
        for (int i = 0; i < _mesh.vertices.Length; i++)
        {
            switch (i % 4)
            {
            case 0:
                tempUvs[i] = new Vector2(0, 0);
                break;

            case 1:
                tempUvs[i] = new Vector2(0, 1);
                break;

            case 2:
                tempUvs[i] = new Vector2(1, 0);
                break;

            case 3:
                tempUvs[i] = new Vector2(1, 1);
                break;
            }
        }
        _mesh.SetUVs(0, tempUvs.ToList());

        _mesh.RecalculateBounds();
        _mesh.RecalculateNormals();
    }
        public static bool ImportNewObjPatternUV(FullModelData fm, string filepath)
        {
            Log.Default.Info("Importing new obj with file for UV patterns: {0}", filepath);

            //Preload the .obj
            List <obj_data> objects = new List <obj_data>();

            try
            {
                using (FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read))
                {
                    using (StreamReader sr = new StreamReader(fs))
                    {
                        string   line;
                        obj_data obj           = new obj_data();
                        bool     reading_faces = false;
                        int      prevMaxVerts  = 0;
                        int      prevMaxUvs    = 0;
                        int      prevMaxNorms  = 0;


                        while ((line = sr.ReadLine()) != null)
                        {
                            //preloading objects
                            if (line.StartsWith("#"))
                            {
                                continue;
                            }
                            else if (line.StartsWith("o ") || line.StartsWith("g "))
                            {
                                if (reading_faces)
                                {
                                    reading_faces = false;
                                    prevMaxVerts += obj.verts.Count;
                                    prevMaxUvs   += obj.uv.Count;
                                    prevMaxNorms += obj.normals.Count;

                                    objects.Add(obj);
                                    obj = new obj_data();
                                }

                                obj.object_name = line.Substring(2);
                            }
                            else if (line.StartsWith("usemtl "))
                            {
                                obj.material_name = line.Substring(2);
                            }
                            else if (line.StartsWith("v "))
                            {
                                if (reading_faces)
                                {
                                    reading_faces = false;
                                    prevMaxVerts += obj.verts.Count;
                                    prevMaxUvs   += obj.uv.Count;
                                    prevMaxNorms += obj.normals.Count;

                                    objects.Add(obj);
                                    obj = new obj_data();
                                }

                                String[] verts = line.Replace("  ", " ").Split(' ');
                                Vector3  vert  = new Vector3();
                                vert.X = Convert.ToSingle(verts[1], CultureInfo.InvariantCulture);
                                vert.Y = Convert.ToSingle(verts[2], CultureInfo.InvariantCulture);
                                vert.Z = Convert.ToSingle(verts[3], CultureInfo.InvariantCulture);

                                obj.verts.Add(vert);
                            }
                            else if (line.StartsWith("vt "))
                            {
                                if (reading_faces)
                                {
                                    reading_faces = false;
                                    prevMaxVerts += obj.verts.Count;
                                    prevMaxUvs   += obj.uv.Count;
                                    prevMaxNorms += obj.normals.Count;

                                    objects.Add(obj);
                                    obj = new obj_data();
                                }

                                String[] uvs = line.Split(' ');
                                Vector2  uv  = new Vector2();
                                uv.X = Convert.ToSingle(uvs[1], CultureInfo.InvariantCulture);
                                uv.Y = Convert.ToSingle(uvs[2], CultureInfo.InvariantCulture);

                                obj.uv.Add(uv);
                            }
                            else if (line.StartsWith("vn "))
                            {
                                if (reading_faces)
                                {
                                    reading_faces = false;
                                    prevMaxVerts += obj.verts.Count;
                                    prevMaxUvs   += obj.uv.Count;
                                    prevMaxNorms += obj.normals.Count;

                                    objects.Add(obj);
                                    obj = new obj_data();
                                }

                                String[] norms = line.Split(' ');
                                Vector3  norm  = new Vector3();
                                norm.X = Convert.ToSingle(norms[1], CultureInfo.InvariantCulture);
                                norm.Y = Convert.ToSingle(norms[2], CultureInfo.InvariantCulture);
                                norm.Z = Convert.ToSingle(norms[3], CultureInfo.InvariantCulture);

                                obj.normals.Add(norm);
                            }
                            else if (line.StartsWith("f "))
                            {
                                reading_faces = true;
                                String[] faces = line.Substring(2).Split(' ');
                                for (int x = 0; x < 3; x++)
                                {
                                    ushort fa = 0, fb = 0, fc = 0;
                                    if (obj.verts.Count > 0)
                                    {
                                        fa = (ushort)(Convert.ToUInt16(faces[x].Split('/')[0]) - prevMaxVerts - 1);
                                    }
                                    if (obj.uv.Count > 0)
                                    {
                                        fb = (ushort)(Convert.ToUInt16(faces[x].Split('/')[1]) - prevMaxUvs - 1);
                                    }
                                    if (obj.normals.Count > 0)
                                    {
                                        fc = (ushort)(Convert.ToUInt16(faces[x].Split('/')[2]) - prevMaxNorms - 1);
                                    }
                                    if (fa < 0 || fb < 0 || fc < 0)
                                    {
                                        throw new Exception("What the actual flapjack, something is *VERY* wrong");
                                    }
                                    obj.faces.Add(new Face(fa, fb, fc));
                                }
                            }
                        }

                        if (!objects.Contains(obj))
                        {
                            objects.Add(obj);
                        }
                    }
                }



                //Read each object
                foreach (obj_data obj in objects)
                {
                    //Locate the proper model
                    uint modelSectionid = 0;
                    foreach (KeyValuePair <uint, ISection> pair in fm.parsed_sections)
                    {
                        if (modelSectionid != 0)
                        {
                            break;
                        }

                        if (pair.Value is Model)
                        {
                            UInt64 tryp;
                            if (UInt64.TryParse(obj.object_name, out tryp))
                            {
                                if (tryp == ((Model)pair.Value).HashName.Hash)
                                {
                                    modelSectionid = pair.Key;
                                }
                            }
                            else
                            {
                                if (Hash64.HashString(obj.object_name) == ((Model)pair.Value).HashName.Hash)
                                {
                                    modelSectionid = pair.Key;
                                }
                            }
                        }
                    }

                    //Apply new changes
                    if (modelSectionid == 0)
                    {
                        continue;
                    }

                    Model         model_data_section  = (Model)fm.parsed_sections[modelSectionid];
                    PassthroughGP passthrough_section = model_data_section.PassthroughGP;
                    Geometry      geometry_section    = passthrough_section.Geometry;
                    Topology      topology_section    = passthrough_section.Topology;

                    //Arrange UV and Normals
                    Vector2[] new_arranged_UV = new Vector2[geometry_section.verts.Count];
                    for (int x = 0; x < new_arranged_UV.Length; x++)
                    {
                        new_arranged_UV[x] = new Vector2(100f, 100f);
                    }
                    Vector2 sentinel = new Vector2(100f, 100f);

                    if (topology_section.facelist.Count != obj.faces.Count / 3)
                    {
                        return(false);
                    }

                    for (int fcount = 0; fcount < topology_section.facelist.Count; fcount += 3)
                    {
                        Face f1 = obj.faces[fcount + 0];
                        Face f2 = obj.faces[fcount + 1];
                        Face f3 = obj.faces[fcount + 2];

                        //UV
                        if (obj.uv.Count > 0)
                        {
                            if (new_arranged_UV[topology_section.facelist[fcount / 3 + 0].a].Equals(sentinel))
                            {
                                new_arranged_UV[topology_section.facelist[fcount / 3 + 0].a] = obj.uv[f1.b];
                            }
                            if (new_arranged_UV[topology_section.facelist[fcount / 3 + 0].b].Equals(sentinel))
                            {
                                new_arranged_UV[topology_section.facelist[fcount / 3 + 0].b] = obj.uv[f2.b];
                            }
                            if (new_arranged_UV[topology_section.facelist[fcount / 3 + 0].c].Equals(sentinel))
                            {
                                new_arranged_UV[topology_section.facelist[fcount / 3 + 0].c] = obj.uv[f3.b];
                            }
                        }
                    }



                    geometry_section.UVs[1] = new_arranged_UV.ToList();

                    passthrough_section.Geometry.UVs[1] = new_arranged_UV.ToList();
                }
            }
            catch (Exception exc)
            {
                System.Windows.Forms.MessageBox.Show(exc.ToString());
                return(false);
            }
            return(true);
        }
        private static void AddObject(bool is_new, obj_data obj,
                                      Model model_data_section, PassthroughGP passthrough_section,
                                      Geometry geometry_section, Topology topology_section)
        {
            List <Face>            called_faces    = new List <Face>();
            List <int>             duplicate_verts = new List <int>();
            Dictionary <int, Face> dup_faces       = new Dictionary <int, Face>();

            bool broken = false;

            for (int x_f = 0; x_f < obj.faces.Count; x_f++)
            {
                Face f = obj.faces[x_f];
                broken = false;

                foreach (Face called_f in called_faces)
                {
                    if (called_f.a == f.a && called_f.b != f.b)
                    {
                        duplicate_verts.Add(x_f);
                        broken = true;
                        break;
                    }
                }

                if (!broken)
                {
                    called_faces.Add(f);
                }
            }

            Dictionary <int, Face> done_faces = new Dictionary <int, Face>();

            foreach (int dupe in duplicate_verts)
            {
                int replacedF = -1;
                foreach (KeyValuePair <int, Face> pair in done_faces)
                {
                    Face f = pair.Value;
                    if (f.a == obj.faces[dupe].a && f.b == obj.faces[dupe].b)
                    {
                        replacedF = pair.Key;
                    }
                }

                Face new_face;
                if (replacedF > -1)
                {
                    new_face = new Face(obj.faces[replacedF].a, obj.faces[replacedF].b, obj.faces[dupe].c);
                }
                else
                {
                    new_face = new Face((ushort)obj.verts.Count, obj.faces[dupe].b, obj.faces[dupe].c);
                    obj.verts.Add(obj.verts[obj.faces[dupe].a]);

                    done_faces.Add(dupe, obj.faces[dupe]);
                }

                obj.faces[dupe] = new_face;
            }

            Vector3 new_Model_data_bounds_min = new Vector3(); // Z (max), X (low), Y (low)
            Vector3 new_Model_data_bounds_max = new Vector3(); // Z (low), X (max), Y (max)

            foreach (Vector3 vert in obj.verts)
            {
                //Z
                // Note these were previously broken
                if (vert.Z < new_Model_data_bounds_min.Z)
                {
                    new_Model_data_bounds_min.Z = vert.Z;
                }

                if (vert.Z > new_Model_data_bounds_max.Z)
                {
                    new_Model_data_bounds_max.Z = vert.Z;
                }

                //X
                if (vert.X < new_Model_data_bounds_min.X)
                {
                    new_Model_data_bounds_min.X = vert.X;
                }
                if (vert.X > new_Model_data_bounds_max.X)
                {
                    new_Model_data_bounds_max.X = vert.X;
                }

                //Y
                if (vert.Y < new_Model_data_bounds_min.Y)
                {
                    new_Model_data_bounds_min.Y = vert.Y;
                }

                if (vert.Y > new_Model_data_bounds_max.Y)
                {
                    new_Model_data_bounds_max.Y = vert.Y;
                }
            }

            //Arrange UV and Normals
            List <Vector3> new_arranged_Geometry_normals   = new List <Vector3>();
            List <Vector3> new_arranged_Geometry_unknown20 = new List <Vector3>();
            List <Vector3> new_arranged_Geometry_unknown21 = new List <Vector3>();
            List <int>     added_uvs     = new List <int>();
            List <int>     added_normals = new List <int>();

            Vector2[] new_arranged_UV = new Vector2[obj.verts.Count];
            for (int x = 0; x < new_arranged_UV.Length; x++)
            {
                new_arranged_UV[x] = new Vector2(100f, 100f);
            }
            Vector2 sentinel = new Vector2(100f, 100f);

            Vector3[] new_arranged_Normals = new Vector3[obj.verts.Count];
            for (int x = 0; x < new_arranged_Normals.Length; x++)
            {
                new_arranged_Normals[x] = new Vector3(0f, 0f, 0f);
            }
            Vector3[] new_arranged_unknown20 = new Vector3[obj.verts.Count];
            Vector3[] new_arranged_unknown21 = new Vector3[obj.verts.Count];

            List <Face> new_faces = new List <Face>();

            for (int fcount = 0; fcount < obj.faces.Count; fcount += 3)
            {
                Face f1 = obj.faces[fcount + 0];
                Face f2 = obj.faces[fcount + 1];
                Face f3 = obj.faces[fcount + 2];

                //UV
                if (obj.uv.Count > 0)
                {
                    if (new_arranged_UV[f1.a].Equals(sentinel))
                    {
                        new_arranged_UV[f1.a] = obj.uv[f1.b];
                    }
                    if (new_arranged_UV[f2.a].Equals(sentinel))
                    {
                        new_arranged_UV[f2.a] = obj.uv[f2.b];
                    }
                    if (new_arranged_UV[f3.a].Equals(sentinel))
                    {
                        new_arranged_UV[f3.a] = obj.uv[f3.b];
                    }
                }

                //normal
                if (obj.normals.Count > 0)
                {
                    new_arranged_Normals[f1.a] = obj.normals[f1.c];
                    new_arranged_Normals[f2.a] = obj.normals[f2.c];
                    new_arranged_Normals[f3.a] = obj.normals[f3.c];
                }

                Face new_f = new Face(f1.a, f2.a, f3.a);

                new_faces.Add(new_f);
            }

            for (int x = 0; x < new_arranged_Normals.Length; x++)
            {
                new_arranged_Normals[x] = Vector3.Normalize(new_arranged_Normals[x]);
            }

            List <Vector3> obj_verts = obj.verts;

            ComputeTangentBasis(ref new_faces, ref obj_verts, ref new_arranged_UV, ref new_arranged_Normals, ref new_arranged_unknown20, ref new_arranged_unknown21);

            List <RenderAtom> new_Model_items2 = new List <RenderAtom>();

            foreach (RenderAtom modelitem in model_data_section.RenderAtoms)
            {
                RenderAtom new_model_item = new RenderAtom();
                new_model_item.BaseVertex          = modelitem.BaseVertex;
                new_model_item.TriangleCount       = (uint)new_faces.Count;
                new_model_item.BaseIndex           = modelitem.BaseIndex;
                new_model_item.GeometrySliceLength = (uint)obj.verts.Count;
                new_model_item.MaterialId          = modelitem.MaterialId;

                new_Model_items2.Add(new_model_item);
            }

            model_data_section.RenderAtoms = new_Model_items2;

            if (model_data_section.version != 6)
            {
                model_data_section.BoundsMin      = new_Model_data_bounds_min;
                model_data_section.BoundsMax      = new_Model_data_bounds_max;
                model_data_section.BoundingRadius = obj.verts.Select(i => i.Length()).Max();
            }

            geometry_section.vert_count = (uint)obj.verts.Count;
            geometry_section.verts      = obj.verts;
            geometry_section.normals    = new_arranged_Normals.ToList();
            geometry_section.UVs[0]     = new_arranged_UV.ToList();
            geometry_section.binormals  = new_arranged_unknown20.ToList();
            geometry_section.tangents   = new_arranged_unknown21.ToList();

            topology_section.facelist = new_faces;
        }
        private void ProcessMesh(List <Vector3> positions, MeshFilter filter, bool ground)
        {
            if (positions.Count >= 3)
            {
                //UVs
                var uvs = new Vector2[positions.Count];

                for (var x = 0; x < positions.Count; x++)
                {
                    if ((x % 2) == 0)
                    {
                        uvs[x] = new Vector2(0, 0);
                    }
                    else
                    {
                        uvs[x] = new Vector2(1, 1);
                    }
                }

                int[] tris;
                if (ground)
                {
                    tris = _triangulator
                           .TriangulatePolygon(
                        positions.Select(position => new Vector2(position.x, position.z)).ToArray());
                }
                else
                {
                    tris = new int[3 * positions.Count];

                    var baseIndex = 0;
                    for (var x = 0; x < tris.Length; x += 3)
                    {
                        if (x % 2 == 0)
                        {
                            tris[x]     = baseIndex % positions.Count;
                            tris[x + 1] = (baseIndex + 1) % positions.Count;
                            tris[x + 2] = (baseIndex + 2) % positions.Count;
                        }
                        else
                        {
                            tris[x + 2] = baseIndex % positions.Count;
                            tris[x + 1] = (baseIndex + 1) % positions.Count;
                            tris[x]     = (baseIndex + 2) % positions.Count;
                        }
                        baseIndex++;
                    }
                }

                if (filter.mesh == null)
                {
                    filter.mesh = new Mesh();
                }
                filter.mesh.Clear();
                filter.mesh.SetVertices(positions);
                filter.mesh.SetUVs(0, uvs.ToList());
                filter.mesh.SetTriangles(tris, 0);
                filter.mesh.name = "MyMesh";
                filter.mesh.RecalculateNormals();
                filter.mesh.RecalculateBounds();
            }
            else
            {
                filter.mesh.Clear();
            }
        }
Example #15
0
        public static AbstractGeometry3D BuildSkyPlane(SkyPlaneData data)
        {
            var count  = (data.PlaneResolution + 1) * (data.PlaneResolution + 1);
            var points = new Vector3[count];
            var tex    = new Vector2[count];

            // Determine the size of each quad on the sky plane.
            float quadSize = data.PlaneWidth / (float)data.PlaneResolution;
            // Calculate the radius of the sky plane based on the width.
            float radius = data.PlaneWidth / 2.0f;
            // Calculate the height constant to increment by.
            float constant = (data.PlaneTop - data.PlaneBottom) / (radius * radius);
            // Calculate the texture coordinate increment value.
            float textureDelta = (float)data.TextureRepeat / (float)data.PlaneResolution;

            // Loop through the sky plane and build the coordinates based on the increment values given.
            for (int j = 0; j <= data.PlaneResolution; j++)
            {
                for (int i = 0; i <= data.PlaneResolution; i++)
                {
                    // Calculate the vertex coordinates.
                    float positionX = (-0.5f * data.PlaneWidth) + ((float)i * quadSize);
                    float positionZ = (-0.5f * data.PlaneWidth) + ((float)j * quadSize);
                    float positionY = data.PlaneTop - (constant * ((positionX * positionX) + (positionZ * positionZ)));

                    // Calculate the texture coordinates.
                    float tu = (float)i * textureDelta;
                    float tv = (float)j * textureDelta;

                    // Calculate the index into the sky plane array to add this coordinate.
                    int index = j * (data.PlaneResolution + 1) + i;

                    // Add the coordinates to the sky plane array.
                    points[index] = new Vector3(positionX, positionY, positionZ);
                    tex[index]    = new Vector2(tu, tv);
                }
            }
            var vertexCount = (data.PlaneResolution + 1) * (data.PlaneResolution + 1) * 6;

            var indices   = new int[vertexCount];
            var positions = new Vector3[vertexCount];
            var texture   = new Vector2[vertexCount];

            // Initialize the index into the vertex array.
            int indx = 0;

            // Load the vertex and index array with the sky plane array data.
            for (int j = 0; j < data.PlaneResolution; j++)
            {
                for (int i = 0; i < data.PlaneResolution; i++)
                {
                    int index1 = j * (data.PlaneResolution + 1) + i;
                    int index2 = j * (data.PlaneResolution + 1) + (i + 1);
                    int index3 = (j + 1) * (data.PlaneResolution + 1) + i;
                    int index4 = (j + 1) * (data.PlaneResolution + 1) + (i + 1);

                    // Triangle 1 - Upper Left
                    positions[indx] = points[index1];
                    texture[indx]   = tex[index1];
                    indices[indx]   = indx;
                    indx++;

                    // Triangle 1 - Upper Right
                    positions[indx] = points[index2];
                    texture[indx]   = tex[index2];
                    indices[indx]   = indx;
                    indx++;

                    // Triangle 1 - Bottom Left
                    positions[indx] = points[index3];
                    texture[indx]   = tex[index3];
                    indices[indx]   = indx;
                    indx++;

                    // Triangle 2 - Bottom Left
                    positions[indx] = points[index3];
                    texture[indx]   = tex[index3];
                    indices[indx]   = indx;
                    indx++;

                    // Triangle 2 - Upper Right
                    positions[indx] = points[index2];
                    texture[indx]   = tex[index2];
                    indices[indx]   = indx;
                    indx++;

                    // Triangle 2 - Bottom Right
                    positions[indx] = points[index4];
                    texture[indx]   = tex[index4];
                    indices[indx]   = indx;
                    indx++;
                }
            }

            return(new AbstractGeometry3D {
                Positions = positions.ToList(),
                Indices = indices.ToList(),
                TextureCoordinates = texture.ToList(),
            });
        }
    public void CreateMesh(Vector2[] vertsToCopy, Transform transform,int triangleIndex)
    {
        List<Vector3> resultsLocal = new List<Vector3>();
        List<int> resultsTriIndexesLocal = new List<int>();
        List<int> resultsTriIndexesReversedLocal = new List<int>();
        List<Vector2> uvsLocal = new List<Vector2>();
        List<Vector3> normalsLocal = new List<Vector3>();

        Sprite spr = transform.GetComponent<SpriteRenderer>().sprite;
        Rect rec = spr.rect;
        Vector3 bound = transform.GetComponent<Renderer>().bounds.max- transform.GetComponent<Renderer>().bounds.min ;
        TextureImporter textureImporter = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(spr)) as TextureImporter;

        List<PolygonPoint> p2 = new List<PolygonPoint>();

        if (triangleIndex > 0)
        {
            vertsToCopy = CreateSubVertPoints (spr.bounds,vertsToCopy.ToList(), triangleIndex).ToArray();
        }

        int i = 0;
        for (i = 0; i < vertsToCopy.Count(); i ++)
        {
            p2.Add(new PolygonPoint(vertsToCopy [i].x, vertsToCopy [i].y));
        }

        Polygon _polygon = new Polygon(p2);

        if (triangleIndex > 0)
        {
            List<TriangulationPoint> triPoints = GenerateGridPoints (spr.bounds, triangleIndex, _polygon);
            _polygon.AddSteinerPoints (triPoints);
        }

        P2T.Triangulate(_polygon);

        int idx = 0;

        foreach (DelaunayTriangle triangle in _polygon.Triangles)
        {
            Vector3 v = new Vector3();
            foreach (TriangulationPoint p in triangle.Points)
            {
                v = new Vector3((float)p.X, (float)p.Y,0);
                if(!resultsLocal.Contains(v))
                {
                    resultsLocal.Add(v);
                    resultsTriIndexesLocal.Add(idx);

                    Vector2 newUv = new Vector2((v.x/bound.x) + 0.5f,  (v.y /bound.y)  + 0.5f);

                    newUv.x *= rec.width/ spr.texture.width;
                    newUv.y *= rec.height/ spr.texture.height;

                    newUv.x += (rec.x)/ spr.texture.width;
                    newUv.y += (rec.y) / spr.texture.height;

                    SpriteMetaData[] smdArray = textureImporter.spritesheet;
                    Vector2 pivot = new Vector2(.0f,.0f);;

                    for (int k = 0; k < smdArray.Length; k++)
                    {
                        if (smdArray[k].name == spr.name)
                        {
                            switch(smdArray[k].alignment)
                            {
                                case(0):
                                smdArray[k].pivot = Vector2.zero;
                                break;
                                case(1):
                                smdArray[k].pivot = new Vector2(0f,1f) -new Vector2(.5f,.5f);
                                break;
                                case(2):
                                smdArray[k].pivot = new Vector2(0.5f,1f) -new Vector2(.5f,.5f);
                                break;
                                case(3):
                                smdArray[k].pivot = new Vector2(1f,1f) -new Vector2(.5f,.5f);
                                break;
                                case(4):
                                smdArray[k].pivot = new Vector2(0f,.5f) -new Vector2(.5f,.5f);
                                break;
                                case(5):
                                smdArray[k].pivot = new Vector2(1f,.5f) -new Vector2(.5f,.5f);
                                break;
                                case(6):
                                smdArray[k].pivot = new Vector2(0f,0f) -new Vector2(.5f,.5f);
                                break;
                                case(7):
                                smdArray[k].pivot = new Vector2(0.5f,0f) -new Vector2(.5f,.5f);
                                break;
                                case(8):
                                smdArray[k].pivot = new Vector2(1f,0f) -new Vector2(.5f,.5f);
                                break;
                                case(9):
                                smdArray[k].pivot -= new Vector2(.5f,.5f);
                                break;
                            }
                            pivot = smdArray[k].pivot ;
                        }
                    }
                    if(textureImporter.spriteImportMode == SpriteImportMode.Single)
                        pivot = textureImporter.spritePivot-new Vector2(.5f,.5f);
                    newUv.x += ((pivot.x)*rec.width)/ spr.texture.width;
                    newUv.y += ((pivot.y)*rec.height)/ spr.texture.height;

                    uvsLocal.Add(newUv);
                    normalsLocal.Add(new Vector3(0,0,-1));
                    idx++;
                }
                else
                {
                    resultsTriIndexesLocal.Add(resultsLocal.LastIndexOf(v));
                }

            }
        }

        for (int j = resultsTriIndexesLocal.Count-1; j >=0; j--)
        {
            resultsTriIndexesReversedLocal.Add(resultsTriIndexesLocal[j]);
        }

        results.AddRange(resultsLocal);
        resultsTriIndexes.AddRange(resultsTriIndexesLocal);
        resultsTriIndexesReversed.AddRange(resultsTriIndexesReversedLocal);
        uvs.AddRange(uvsLocal);
        normals.AddRange(normalsLocal);

        resultsLocal.Clear();
        resultsTriIndexesLocal.Clear();
        resultsTriIndexesReversedLocal.Clear();
        uvsLocal.Clear();
        normalsLocal.Clear();

        finalVertices = results.ToArray();

        finalNormals = normals.ToArray();
        finalUvs= uvs.ToArray();

        finalTriangles = resultsTriIndexesReversed.ToArray();
    }
Example #17
0
	//the callback from polyNav for when path is ready to use
	void SetPath(Vector2[] path){
		
		//in case the agent stoped somehow, but a path was pending
		if (requests == 0)
			return;

		requests --;

		if (path == null || path.Length == 0){
			OnInvalid();
			return;
		}

		activePath = path.ToList();
		if (OnNavigationStarted != null)
			OnNavigationStarted();
	}
    private void OnGUI()
    {
        EditorGUILayout.BeginVertical();

        /********************************************************************************
        * Prepare Mesh for Simulation:
        * Use this to pack the triangle ID to the uv2 coordinates of the mesh for the
        * simulation.
        ********************************************************************************/
        scrollPos = EditorGUILayout.BeginScrollView(scrollPos);
        meshPrep  = (Mesh)EditorGUILayout.ObjectField(meshPrep, typeof(Mesh), false);
        if (GUILayout.Button("Prepare Mesh for Vertex Shader"))
        {
            Vector2[] uvs2 = new Vector2[meshPrep.vertices.Length];
            for (int i = 0; i < meshPrep.triangles.Length; i++)
            {
                uvs2[meshPrep.triangles[i]] = new Vector2(i / 3, i);
                if (i % 100 == 0)
                {
                    EditorUtility.DisplayProgressBar(
                        "If I'm a progress bar",
                        "Then I will give you the illusion of progress: " + i.ToString() + "/" + meshPrep.triangles.Length.ToString(),
                        (float)i / (float)meshPrep.triangles.Length
                        );
                }
            }
            EditorUtility.ClearProgressBar();
            meshPrep.uv2 = uvs2;
            meshPrep.SetUVs(1, uvs2.ToList <Vector2>());
            meshPrep.MarkModified();
            Mesh outMesh = Instantiate(meshPrep);

            EditorUtility.SetDirty(meshPrep);
            AssetDatabase.CreateAsset(outMesh, "Assets\\StartShape.Asset");
            EditorUtility.SetDirty(outMesh);
            AssetDatabase.SaveAssets();
        }

        /********************************************************************************
        * Show Stats:
        * Use this to get information about a mesh that will get packed into simulation
        * textures.
        ********************************************************************************/
        meshStats = (Mesh)EditorGUILayout.ObjectField(meshStats, typeof(Mesh), false);
        if (GUILayout.Button("Show Stats"))
        {
            Debug.Log("If I can be a texture containing " + meshStats.triangles.Length + " verticies as pixels named " + meshStats.name + ".exr");
        }

        /********************************************************************************
        * Populate List:
        * Populate the list of meshes located in the folder Assets/world.execute/keyframes/
        * that will be packed into the textures for our simulation.
        ********************************************************************************/
        if (GUILayout.Button("Populate List"))
        {
            string path = "Assets/Keyframes/";

            string[] files = Directory.GetFiles(path);
            int      n     = 0;
            foreach (string file in files)
            {
                if (Path.GetExtension(file) == ".FBX" || Path.GetExtension(file) == ".fbx")
                {
                    Mesh mesh = (Mesh)AssetDatabase.LoadAssetAtPath(file, typeof(Mesh));
                    if (mesh != null)
                    {
                        n++;
                    }
                }
            }
            nOfMeshes = n;
            meshes    = new Mesh[nOfMeshes];
            n         = 0;
            foreach (string file in files)
            {
                if (Path.GetExtension(file) == ".FBX" || Path.GetExtension(file) == ".fbx")
                {
                    Mesh mesh = (Mesh)AssetDatabase.LoadAssetAtPath(file, typeof(Mesh));
                    if (mesh != null)
                    {
                        meshes[n] = mesh;
                        n++;
                    }
                }
            }
        }

        //Display the mesh list.
        nOfMeshes = EditorGUILayout.IntField(nOfMeshes);
        if (meshes == null || meshes.Length != nOfMeshes)
        {
            meshes = new Mesh[nOfMeshes];
        }
        for (int i = 0; i < nOfMeshes; i++)
        {
            meshes[i] = (Mesh)EditorGUILayout.ObjectField(i.ToString(), meshes[i], typeof(Mesh), false);
        }

        /********************************************************************************
        * Make Texture:
        * Begin packing the meshes into two textures. One that contains the mesh verticies
        * in triangle order. And the second containing offset and sizes of the
        * mesh. The offset and size have to be stored split into 2 numbers, as the
        * Quest only supports 16bit floats for HDR Textures. So we rebuild the number
        * with-in the Simulation.
        ********************************************************************************/
        if (GUILayout.Button("Make Texture"))
        {
            int tCount   = 0;
            int tCurrent = 0;
            int index    = 0;
            //calculate number of triangles and safety check.
            foreach (Mesh mesh in meshes)
            {
                if (mesh != null)
                {
                    tCount += mesh.triangles.Length;
                }
            }
            //Debug.Log(tCount + " / " + max);
            if (tCount > max)
            {
                Debug.Log("Cannot Continue, too many triangles in combined meshes.");
                return;
            }

            //create, then zero the textures first.
            Texture2D meshTex  = new Texture2D(2048, 2048, TextureFormat.RGBAFloat, false);
            Texture2D indexTex = new Texture2D(32, 32, TextureFormat.RGBAFloat, false);
            for (int i = 0; i < 2048; i++)
            {
                for (int j = 0; j < 2048; j++)
                {
                    meshTex.SetPixel(i, j, Vector4.zero);
                }
            }
            for (int i = 0; i < 32; i++)
            {
                for (int j = 0; j < 32; j++)
                {
                    indexTex.SetPixel(i, j, Vector4.zero);
                }
            }
            meshTex.Apply();
            indexTex.Apply();



            foreach (Mesh mesh in meshes)
            {
                if (mesh != null)
                {
                    Debug.Log("If I can be a mesh containing " + mesh.triangles.Length + " verticies");
                    int[]     tris   = mesh.triangles;
                    Vector3[] verts  = mesh.vertices;
                    Color[]   colors = meshTex.GetPixels();


                    for (int i = 0; i < mesh.triangles.Length; i++)
                    {
                        int n = tCurrent + i;
                        int x = n % 2048;
                        int y = n / 2048;
                        int t = tris[i];

                        Vector4 color = new Vector4(verts[t].x, verts[t].y, verts[t].z, 1);
                        colors[n] = color;

                        if (i % 100 == 0)
                        {
                            EditorUtility.DisplayProgressBar(
                                "If I'm a progress bar",
                                "Then I will give you the illusion of progress: " + n.ToString() + "/" + tCount,
                                (float)n / (float)tCount
                                );
                        }
                    }


                    meshTex.SetPixels(colors);
                    Debug.Log("Then, I will give you my pixels for execution.");

                    int x2 = index % 32;
                    int y2 = index / 32;
                    int p1 = tCurrent % 2048;
                    int p2 = tCurrent / 2048;
                    int l1 = mesh.triangles.Length % 2048;
                    int l2 = mesh.triangles.Length / 2048;
                    //Alpha is 1, just so I can tell something is there.
                    Vector4 color2 = new Vector4(p1, p2, l1, l2);  //position, then length.
                    indexTex.SetPixel(x2, y2, color2);
                    indexTex.Apply();

                    //end of loop stuff.
                    tCurrent += mesh.triangles.Length;
                    index++;
                }
            }
            EditorUtility.ClearProgressBar();



            meshTex.Apply();
            byte[] bytes = meshTex.EncodeToEXR(Texture2D.EXRFlags.None);
            Object.DestroyImmediate(meshTex);
            File.WriteAllBytes(Application.dataPath + "/world.execute/meshData.exr", bytes);

            indexTex.Apply();
            bytes = indexTex.EncodeToEXR(Texture2D.EXRFlags.None);
            Object.DestroyImmediate(indexTex);
            File.WriteAllBytes(Application.dataPath + "/world.execute/indexData.exr", bytes);
        }

        /********************************************************************************
        * World.Execute(me):
        * If you want to test the Simulation, before publishing, you can attach the
        * required components here, press play, and then click "World.Execute(me);"
        * to test the simulation before uploading.
        ********************************************************************************/
        worldExecute      = (Material)EditorGUILayout.ObjectField(worldExecute, typeof(Material), true);
        worldExecuteAudio = (AudioSource)EditorGUILayout.ObjectField(worldExecuteAudio, typeof(AudioSource), true);
        if (GUILayout.Button("World.Execute(me);"))
        {
            if (!playing)
            {
                worldExecute.SetFloat("_StartTime", UnityEngine.Time.timeSinceLevelLoad);
                worldExecute.SetInt("_Play", 1);
                worldExecuteAudio.time = 0;
                worldExecuteAudio.Play();
                playing = true;
            }
            else
            {
                worldExecute.SetFloat("_StartTime", 0);
                worldExecute.SetInt("_Play", 0);
                worldExecuteAudio.time = 0;
                worldExecuteAudio.Stop();
                playing = false;
            }
        }
        EditorGUILayout.EndScrollView();
        EditorGUILayout.EndVertical();
    }