コード例 #1
0
	// Use this for initialization
	void Start()
	{
		CreateLineMaterial();

		mesh = new Mesh();
		Vertex3[] vertices = new Vertex3[NumberOfVertices];
		Vector3[] meshVerts = new Vector3[NumberOfVertices];
		int[] indices = new int[NumberOfVertices];

		Random.seed = 1;
		for (var i = 0; i < NumberOfVertices; i++)
		{
			vertices[i] = new Vertex3(size * Random.Range(-1.0f, 1.0f), size * Random.Range(-1.0f, 1.0f), size * Random.Range(-1.0f, 1.0f));
			meshVerts[i] = vertices[i].ToVector3();
			indices[i] = i;
		}

		mesh.vertices = meshVerts;
		mesh.SetIndices(indices, MeshTopology.Points, 0);
		mesh.bounds = new Bounds(Vector3.zero, new Vector3(size, size, size));

		float now = Time.realtimeSinceStartup;
		voronoiMesh = VoronoiMesh.Create<Vertex3, Cell3>(vertices);
		float interval = Time.realtimeSinceStartup - now;

		Debug.Log("time = " + interval * 1000.0f);

	}
コード例 #2
0
ファイル: Cuboid.cs プロジェクト: luxkun/AEngine
        private void CreateTriangles()
        {
            // face 1
            var a = new Vertex3(new Vector3(Min.X, Min.Y, Min.Z));
            var b = new Vertex3(new Vector3(Max.X, Min.Y, Min.Z));
            var c = new Vertex3(new Vector3(Min.X, Max.Y, Min.Z));
            var d = new Vertex3(new Vector3(Max.X, Max.Y, Min.Z));
            TriangleList.Add(new Triangle(this, a, b, d));
            TriangleList.Add(new Triangle(this, a, d, c));

            // lateral 1
            a = new Vertex3(new Vector3(Min.X, Min.Y, Min.Z));
            b = new Vertex3(new Vector3(Min.X, Min.Y, Max.Z));
            c = new Vertex3(new Vector3(Min.X, Max.Y, Min.Z));
            d = new Vertex3(new Vector3(Min.X, Max.Y, Max.Z));
            TriangleList.Add(new Triangle(this, a, b, d));
            TriangleList.Add(new Triangle(this, a, d, c));

            // lateral 2
            a = new Vertex3(new Vector3(Max.X, Min.Y, Min.Z));
            b = new Vertex3(new Vector3(Max.X, Min.Y, Max.Z));
            c = new Vertex3(new Vector3(Max.X, Max.Y, Min.Z));
            d = new Vertex3(new Vector3(Max.X, Max.Y, Max.Z));
            TriangleList.Add(new Triangle(this, a, b, d));
            TriangleList.Add(new Triangle(this, a, d, c));

            // face 2
            a = new Vertex3(new Vector3(Min.X, Min.Y, Max.Z));
            b = new Vertex3(new Vector3(Max.X, Min.Y, Max.Z));
            c = new Vertex3(new Vector3(Min.X, Max.Y, Max.Z));
            d = new Vertex3(new Vector3(Max.X, Max.Y, Max.Z));
            TriangleList.Add(new Triangle(this, a, b, d));
            TriangleList.Add(new Triangle(this, a, d, c));
        }
コード例 #3
0
        public AtomicSectorStruct_0001 Read(BinaryReader binaryReader)
        {
            sectionIdentifier = Section.Struct;
            sectionSize       = binaryReader.ReadInt32();
            renderWareVersion = binaryReader.ReadInt32();

            long startSectionPosition = binaryReader.BaseStream.Position;

            matListWindowBase = binaryReader.ReadInt32();
            numTriangles      = binaryReader.ReadInt32();
            numVertices       = binaryReader.ReadInt32();
            boxMaximum        = new Vertex3(binaryReader.ReadSingle(), binaryReader.ReadSingle(), binaryReader.ReadSingle());
            boxMinimum        = new Vertex3(binaryReader.ReadSingle(), binaryReader.ReadSingle(), binaryReader.ReadSingle());
            collSectorPresent = binaryReader.ReadInt32();
            unused            = binaryReader.ReadInt32();

            if (binaryReader.BaseStream.Position == startSectionPosition + sectionSize)
            {
                isNativeData = true;
                return(this);
            }

            binaryReader.BaseStream.Position = startSectionPosition + 11 * 4;

            vertexArray = new Vertex3[numVertices];
            for (int i = 0; i < numVertices; i++)
            {
                vertexArray[i].X = binaryReader.ReadSingle();
                vertexArray[i].Y = binaryReader.ReadSingle();
                vertexArray[i].Z = binaryReader.ReadSingle();
            }

            binaryReader.BaseStream.Position = startSectionPosition + 11 * 4 + 12 * numVertices;

            if (!ReadFileMethods.isCollision)
            {
                int  supposedTotalSectionLenght = (11 * 4) + (12 + 4 + 8) * numVertices + 8 * numTriangles;
                bool twoVcolorArrays            = false;

                if (sectionSize - supposedTotalSectionLenght == numVertices * 4)
                {
                    twoVcolorArrays = true;
                }
                else if (sectionSize - supposedTotalSectionLenght == numVertices * 12)
                {
                    twoVcolorArrays = true;
                }

                if (twoVcolorArrays)
                {
                    binaryReader.BaseStream.Position += 4 * numVertices;
                }

                colorArray = new Color[numVertices];
                for (int i = 0; i < numVertices; i++)
                {
                    colorArray[i].R = binaryReader.ReadByte();
                    colorArray[i].G = binaryReader.ReadByte();
                    colorArray[i].B = binaryReader.ReadByte();
                    colorArray[i].A = binaryReader.ReadByte();
                }

                if (twoVcolorArrays)
                {
                    binaryReader.BaseStream.Position = startSectionPosition + 11 * 4 + 20 * numVertices;
                }
                else
                {
                    binaryReader.BaseStream.Position = startSectionPosition + 11 * 4 + 16 * numVertices;
                }

                uvArray = new Vertex2[numVertices];
                for (int i = 0; i < numVertices; i++)
                {
                    uvArray[i].X = binaryReader.ReadSingle();
                    uvArray[i].Y = binaryReader.ReadSingle();
                }
            }

            binaryReader.BaseStream.Position = startSectionPosition + sectionSize - 8 * numTriangles;

            if (ReadFileMethods.isShadow)
            {
                // shadow
                triangleArray = new Triangle[numTriangles];
                for (int i = 0; i < numTriangles; i++)
                {
                    triangleArray[i].vertex1       = binaryReader.ReadUInt16();
                    triangleArray[i].vertex2       = binaryReader.ReadUInt16();
                    triangleArray[i].vertex3       = binaryReader.ReadUInt16();
                    triangleArray[i].materialIndex = binaryReader.ReadUInt16();
                }
            }
            else
            {
                // heroes
                triangleArray = new Triangle[numTriangles];
                for (int i = 0; i < numTriangles; i++)
                {
                    triangleArray[i].materialIndex = binaryReader.ReadUInt16();
                    triangleArray[i].vertex1       = binaryReader.ReadUInt16();
                    triangleArray[i].vertex2       = binaryReader.ReadUInt16();
                    triangleArray[i].vertex3       = binaryReader.ReadUInt16();
                }
            }

            binaryReader.BaseStream.Position = startSectionPosition + sectionSize;

            return(this);
        }
コード例 #4
0
        public static RWSection[] CreateShadowCollisionBSPFile(ModelConverterData data)
        {
            Vertex3 Max = new Vertex3(data.VertexList[0].Position.X, data.VertexList[0].Position.Y, data.VertexList[0].Position.Z);
            Vertex3 Min = new Vertex3(data.VertexList[0].Position.X, data.VertexList[0].Position.Y, data.VertexList[0].Position.Z);

            foreach (Vertex i in data.VertexList)
            {
                if (i.Position.X > Max.X)
                {
                    Max.X = i.Position.X;
                }
                if (i.Position.Y > Max.Y)
                {
                    Max.Y = i.Position.Y;
                }
                if (i.Position.Z > Max.Z)
                {
                    Max.Z = i.Position.Z;
                }
                if (i.Position.X < Min.X)
                {
                    Min.X = i.Position.X;
                }
                if (i.Position.Y < Min.Y)
                {
                    Min.Y = i.Position.Y;
                }
                if (i.Position.Z < Min.Z)
                {
                    Min.Z = i.Position.Z;
                }
            }

            List <Vertex3> vList = new List <Vertex3>(data.VertexList.Count);

            foreach (Vertex v in data.VertexList)
            {
                vList.Add(new Vertex3(v.Position.X, v.Position.Y, v.Position.Z));
            }

            List <RenderWareFile.Triangle> tList = new List <RenderWareFile.Triangle>(data.TriangleList.Count);

            foreach (Triangle t in data.TriangleList)
            {
                tList.Add(new RenderWareFile.Triangle((ushort)t.MaterialIndex, (ushort)t.vertex1, (ushort)t.vertex2, (ushort)t.vertex3));
            }

            List <BinMesh> binMeshList = new List <BinMesh>();
            int            TotalNumberOfTristripIndicies = 0;

            for (int i = 0; i < data.MaterialList.Count; i++)
            {
                List <int> indices = new List <int>();
                foreach (Triangle f in data.TriangleList)
                {
                    if (f.MaterialIndex == i)
                    {
                        indices.Add(f.vertex1);
                        indices.Add(f.vertex2);
                        indices.Add(f.vertex3);
                    }
                }
                TotalNumberOfTristripIndicies += indices.Count();

                binMeshList.Add(new BinMesh
                {
                    materialIndex = i,
                    indexCount    = indices.Count(),
                    vertexIndices = indices.ToArray()
                });
            }

            // GENERATE COLLISION DATA

            List <ushort> TriangleIndexList = new List <ushort>();
            List <Split>  splitlist         = new List <Split>();
            ushort        loop              = 0;
            bool          exitloop          = false;
            Split         split             = new Split();
            byte          trianglesPerSplit = 200;

            while (!exitloop)
            {
                split = new Split
                {
                    negativeSector = new Sector()
                    {
                        Max = Max,
                        Min = Min,
                        TriangleIndexList = new List <ushort>(),
                        splitPosition     = Max.X,
                        type = SectorType.NegativeX
                    },
                    positiveSector = new Sector()
                    {
                        Max = Max,
                        Min = Min,
                        TriangleIndexList = new List <ushort>(),
                        splitPosition     = Min.X,
                        type = SectorType.PositiveX
                    }
                };

                for (ushort i = (ushort)(trianglesPerSplit * loop); i < tList.Count(); i++)
                {
                    TriangleIndexList.Add(i);

                    split.negativeSector.TriangleIndexList.Add(i);

                    if (split.negativeSector.TriangleIndexList.Count() == trianglesPerSplit)
                    {
                        split.negativeSector.triangleAmount = trianglesPerSplit;
                        split.negativeSector.referenceIndex = (ushort)(trianglesPerSplit * loop);
                        loop += 1;

                        split.positiveSector.triangleAmount = 0xFF;
                        split.positiveSector.referenceIndex = loop;
                        splitlist.Add(split);
                        split    = new Split();
                        exitloop = false;
                        break;
                    }

                    exitloop = true;
                }
            }

            split.negativeSector.triangleAmount = (byte)split.negativeSector.TriangleIndexList.Count();
            split.negativeSector.referenceIndex = (ushort)(trianglesPerSplit * loop);
            split.positiveSector.triangleAmount = 0;
            split.positiveSector.referenceIndex = 0;
            loop += 1;
            splitlist.Add(split);

            //Sector sector = new Sector()
            //{
            //    Max = Max,
            //    Min = Min,
            //    TriangleIndexList = new List<ushort>()
            //};

            // sector.TriangleIndexList = FindTrianglesInsideNode(vList, tList, sector, TriangleIndexList);

            // List<ushort> TriangleIndexReferenceList = new List<ushort>();
            // List<Split> splitList = new List<Split>();

            //PositionOnList = 0;
            //SplitSector(sector, 20, 0, splitList, TriangleIndexReferenceList, vList, tList);

            // COLLISION FLAGS

            Color[] cFlagList = new Color[data.MaterialList.Count];
            for (int i = 0; i < cFlagList.Length; i++)
            {
                cFlagList[i] = new Color(0x01, 0x00, 0x02, 0x00);

                string a = data.MaterialList[i].Split('_').Last();

                if (a == "c") // ceiling
                {
                    cFlagList[i] = new Color(0x00, 0x00, 0x00, 0x00);
                }
                else if (a == "f") // road floor
                {
                    cFlagList[i] = new Color(0x01, 0x00, 0x02, 0x00);
                }
                else if (a == "fs") // stone floor
                {
                    cFlagList[i] = new Color(0x01, 0x00, 0x00, 0x60);
                }
                else if (a == "fm") // metal floor
                {
                    cFlagList[i] = new Color(0x01, 0x01, 0x01, 0x10);
                }
                else if (a == "t") // triangle jump wall
                {
                    cFlagList[i] = new Color(0x02, 0x00, 0x00, 0x00);
                }
                else if (a == "a") // angle wall
                {
                    cFlagList[i] = new Color(0x02, 0x01, 0x01, 0x10);
                }
                else if (a == "i") // invisible wall
                {
                    cFlagList[i] = new Color(0x02, 0x02, 0x00, 0x00);
                }
                else if (a == "g") // green goo
                {
                    cFlagList[i] = new Color(0x05, 0x00, 0x02, 0x00);
                }
                else if (a == "k") // barrier
                {
                    cFlagList[i] = new Color(0x08, 0x00, 0x00, 0x00);
                }
                else if (a == "i2") // invisible wall at distance
                {
                    cFlagList[i] = new Color(0x10, 0x00, 0x00, 0x00);
                }
                else if (a == "x") // death
                {
                    cFlagList[i] = new Color(0x20, 0x00, 0x00, 0x00);
                }
                else if (a.Count() == 8)
                {
                    try
                    {
                        cFlagList[i] = Color.FromString(a);
                    }
                    catch
                    {
                        cFlagList[i] = new Color(0x01, 0x00, 0x02, 0x00);
                    }
                }
            }

            List <Color> cFlags = new List <Color>();

            foreach (Triangle t in data.TriangleList)
            {
                cFlags.Add(cFlagList[t.MaterialIndex]);
            }

            // GENERATE RENDERWARE DATA

            World_000B world = new World_000B
            {
                worldStruct = new WorldStruct_0001()
                {
                    rootIsWorldSector = 1,
                    inverseOrigin     = new Vertex3(-0f, -0f, -0f),
                    numTriangles      = (uint)data.TriangleList.Count(),
                    numVertices       = (uint)data.VertexList.Count(),
                    numPlaneSectors   = 0,
                    numAtomicSectors  = 1,
                    colSectorSize     = 0,
                    worldFlags        = WorldFlags.WorldSectorsOverlap,// | WorldFlags.ModulateMaterialColors, //(WorldFlags)0x40000040,
                    boxMaximum        = Max,
                    boxMinimum        = Min
                },

                materialList = new MaterialList_0008()
                {
                    materialListStruct = new MaterialListStruct_0001()
                    {
                        materialCount = data.MaterialList.Count()
                    },
                    materialList = new Material_0007[data.MaterialList.Count()]
                },

                firstWorldChunk = new AtomicSector_0009()
                {
                    atomicSectorStruct = new AtomicSectorStruct_0001()
                    {
                        matListWindowBase = 0,
                        numTriangles      = data.TriangleList.Count(),
                        numVertices       = data.VertexList.Count(),
                        boxMaximum        = Max,
                        boxMinimum        = Min,
                        collSectorPresent = 0x0012f410,
                        unused            = 0,
                        vertexArray       = vList.ToArray(),
                        colorArray        = null,
                        uvArray           = null,
                        triangleArray     = tList.ToArray()
                    },
                    atomicSectorExtension = new Extension_0003()
                    {
                        extensionSectionList = new List <RWSection>()
                        {
                            new BinMeshPLG_050E()
                            {
                                binMeshHeaderFlags = BinMeshHeaderFlags.TriangleList,
                                numMeshes          = binMeshList.Count(),
                                totalIndexCount    = TotalNumberOfTristripIndicies,
                                binMeshList        = binMeshList.ToArray()
                            },
                            new CollisionPLG_011D()
                            {
                                colTree = new ColTree_002C()
                                {
                                    colTreeStruct = new ColTreeStruct_0001()
                                    {
                                        useMap        = 1,
                                        boxMaximum    = Max,
                                        boxMinimum    = Min,
                                        numSplits     = splitlist.Count(),
                                        numTriangles  = TriangleIndexList.Count(),
                                        splitArray    = splitlist.ToArray(),
                                        triangleArray = TriangleIndexList.ToArray(),
                                    },
                                },
                                unknownValue = 0x00037002
                            },
                            new UserDataPLG_011F()
                            {
                                userDataType   = 0x02,
                                unknown2       = 0x0A,
                                attribute      = "attribute",
                                unknown3       = 0x01,
                                numTriangles   = tList.Count(),
                                collisionFlags = cFlags.ToArray(),
                                unknown4       = 0x0D,
                                userData       = "FVF.UserData",
                                unknown5       = 0x01,
                                unknown6       = 0x01,
                                unknown7       = 0x3003
                            }
                        }
                    }
                },

                worldExtension = new Extension_0003()
            };

            for (int i = 0; i < data.MaterialList.Count; i++)
            {
                world.materialList.materialList[i] = new Material_0007()
                {
                    materialStruct = new MaterialStruct_0001()
                    {
                        unusedFlags = 0,
                        color       = new Color()
                        {
                            R = 0xFF, G = 0xFF, B = 0xFF, A = 0xFF
                        },
                        unusedInt2 = 0x01FAE70C,
                        isTextured = 0,
                        ambient    = 1f,
                        specular   = 1f,
                        diffuse    = 1f
                    },
                    texture           = null,
                    materialExtension = new Extension_0003()
                };
            }

            return(new RWSection[] { world });
        }
コード例 #5
0
 public Joint(JointType jointType, Vertex3 position)
 {
     this.jointType = jointType;
     this.position  = position;
 }
コード例 #6
0
        static void InitInternal()
        {
            Console.WriteLine(ConsoleColor.DarkCyan, "Starting RealSense");

            if (!FakePosition)
            {
                IEnumerable <FrameData> Resolutions      = RealSenseCamera.QueryResolutions().OrderBy((Data) => - Data.Framerate);
                IEnumerable <FrameData> DepthResolutions = Resolutions.Where((Data) => Data.Type == FrameType.Depth);

                int ReqW = 640;
                int ReqH = 480;

                //int ReqW = 848;
                //int ReqH = 480;

                //int ReqW = 1280;
                //int ReqH = 720;

                FrameData DepthRes = DepthResolutions.Where((Data) => Data.Width == ReqW && Data.Height == ReqH && Data.Format == FrameFormat.Z16).First();
                FrameData ColorRes = Resolutions.Where((Data) => Data.Width == ReqW && Data.Height == ReqH && Data.Format == FrameFormat.Rgb8).First();

                W = ColorRes.Width;
                H = ColorRes.Height;

                Console.WriteLine(ConsoleColor.DarkCyan, "RealSense running at {0}x{1}", W, H);

                RealSenseCamera.SetOption(DepthRes, RealSenseOption.VisualPreset, 1);                //4
                RealSenseCamera.SetOption(DepthRes, RealSenseOption.EmitterEnabled, 0);
                RealSenseCamera.SetOption(DepthRes, RealSenseOption.EnableAutoExposure, 1);

                //RealSenseCamera.SetOption(DepthRes, RealSenseOption.LaserPower, 30);

                RealSenseCamera.DisableAllStreams();
                RealSenseCamera.EnableStream(DepthRes, ColorRes);
                RealSenseCamera.Start();

                Console.WriteLine(ConsoleColor.DarkCyan, "RealSense ready");

                if (Program.UseThreading)
                {
                    while (true)
                    {
                        Loop();
                    }
                }
            }
            else
            {
                Ready = true;

                float     Scale     = 1.0f / 500.0f;
                int       PlaneSize = 100;
                Vertex3[] Verts     = OnPointCloud(PlaneSize * PlaneSize, null, null);

                for (int y = 0; y < PlaneSize; y++)
                {
                    for (int x = 0; x < PlaneSize; x++)
                    {
                        Verts[y * PlaneSize + x] = new Vertex3(x * Scale - ((PlaneSize / 2) * Scale), y * Scale - ((PlaneSize / 2) * Scale), 0.5f);
                    }
                }

                while (true)
                {
                    OnPointCloud(Verts.Length, Verts, null);
                }
            }
        }
コード例 #7
0
 public void MultiplyWeight(float value, Vertex3 vertex)
 {
     Weight(value, vertex, WeightType.Multiply);
 }
コード例 #8
0
ファイル: CubesScene.cs プロジェクト: matyjb/GK-3D
        public CubesScene()
        {
            Vec3 v00 = new Vec3(0, 0, 0);
            Vec3 v01 = new Vec3(0, 0, 1);
            Vec3 v02 = new Vec3(0, 1, 0);
            Vec3 v03 = new Vec3(0, 1, 1);
            Vec3 v04 = new Vec3(1, 0, 0);
            Vec3 v05 = new Vec3(1, 0, 1);
            Vec3 v06 = new Vec3(1, 1, 0);
            Vec3 v07 = new Vec3(1, 1, 1);


            Vertex3 vert20 = new Vertex3(v00, (Vec4)Color.White);
            Vertex3 vert21 = new Vertex3(v01, (Vec4)Color.Blue);
            Vertex3 vert22 = new Vertex3(v02, (Vec4)Color.Green);
            Vertex3 vert23 = new Vertex3(v03, (Vec4)Color.Cyan);
            Vertex3 vert24 = new Vertex3(v04, (Vec4)Color.Red);
            Vertex3 vert25 = new Vertex3(v05, (Vec4)Color.Magenta);
            Vertex3 vert26 = new Vertex3(v06, (Vec4)Color.Yellow);
            Vertex3 vert27 = new Vertex3(v07, (Vec4)Color.Black);
            Mesh    cube1  = new Mesh()
            {
                // SOUTH
                new Tri(v00, v02, v06, (Vec4)Color.Blue),
                new Tri(v00, v06, v04, (Vec4)Color.Blue),

                // EAST
                new Tri(v04, v06, v07, (Vec4)Color.Red),
                new Tri(v04, v07, v05, (Vec4)Color.Red),

                // NORTH
                new Tri(v05, v07, v03, (Vec4)Color.Blue),
                new Tri(v05, v03, v01, (Vec4)Color.Blue),

                // WEST
                new Tri(v01, v03, v02, (Vec4)Color.Red),
                new Tri(v01, v02, v00, (Vec4)Color.Red),

                // TOP
                new Tri(v02, v03, v07, (Vec4)Color.Green),
                new Tri(v02, v07, v06, (Vec4)Color.Green),

                // BOTTOM
                new Tri(v05, v01, v00, (Vec4)Color.Green),
                new Tri(v05, v00, v04, (Vec4)Color.Green),
            };
            Mesh cube2 = new Mesh()
            {
                // SOUTH
                new Tri(v00, v02, v06, (Vec4)Color.Blue),
                new Tri(v00, v06, v04, (Vec4)Color.Blue),

                // EAST
                new Tri(v04, v06, v07, (Vec4)Color.Red),
                new Tri(v04, v07, v05, (Vec4)Color.Red),

                // NORTH
                new Tri(v05, v07, v03, (Vec4)Color.Blue),
                new Tri(v05, v03, v01, (Vec4)Color.Blue),

                // WEST
                new Tri(v01, v03, v02, (Vec4)Color.Red),
                new Tri(v01, v02, v00, (Vec4)Color.Red),

                // TOP
                new Tri(v02, v03, v07, (Vec4)Color.Green),
                new Tri(v02, v07, v06, (Vec4)Color.Green),

                // BOTTOM
                new Tri(v05, v01, v00, (Vec4)Color.Green),
                new Tri(v05, v00, v04, (Vec4)Color.Green),
            };
            Mesh cubeRGB = new Mesh()
            {
                // SOUTH
                new Tri(vert20, vert22, vert26),
                new Tri(vert20, vert26, vert24),

                // EAST
                new Tri(vert24, vert26, vert27),
                new Tri(vert24, vert27, vert25),

                // NORTH
                new Tri(vert25, vert27, vert23),
                new Tri(vert25, vert23, vert21),

                // WEST
                new Tri(vert21, vert23, vert22),
                new Tri(vert21, vert22, vert20),

                // TOP
                new Tri(vert22, vert23, vert27),
                new Tri(vert22, vert27, vert26),

                // BOTTOM
                new Tri(vert25, vert21, vert20),
                new Tri(vert25, vert20, vert24),
            };
            Sphere sphere = new Sphere(1, 3, (Vec4)Color.Green);

            Triangle triangle = new Triangle(v00, v02, v06, (Vec4)Color.Blue);

            cube1.Origin    = new Vec3(0.5f, 0.5f, 0.5f);
            cube2.Origin    = new Vec3(0.5f, 0.5f, 0.5f);
            cubeRGB.Origin  = new Vec3(0.5f, 0.5f, 0.5f);
            triangle.Origin = new Vec3(0.5f, 0.5f, 0.5f);
            sphere.Origin   = new Vec3(0.5f, 0.5f, 0.5f);

            Vec3 moveV = new Vec3(2, 2, 3);

            cube2.Position    = moveV;
            cube2.Scale       = new Vec3(1.5f, 1.5f, 1.5f);
            cubeRGB.Position  = moveV / 2;
            triangle.Position = moveV * 2;
            sphere.Position   = new Vec3(0, 5, 0);
            drawables.Add(cube1);
            drawables.Add(cube2);
            drawables.Add(cubeRGB);
            drawables.Add(triangle);
            drawables.Add(sphere);
            lightSources.Add(new LightSource()
            {
                Position = new Vec3(-3, 3, -3), Intensity = 1f
            });
            lightSources.Add(new LightSource()
            {
                Position = new Vec3(3, -3, 5), Intensity = 1f
            });
            mainCamera.Position = new Vec3(0, 0, -10);
        }
コード例 #9
0
 static void AppendLine(Vertex3 Start, Vertex3 End, bool DepthEnabled)
 {
     ref int FreeIdx = ref FreeLineIdx;
コード例 #10
0
        public static RWSection[] CreateDFFFile(ModelConverterData data, bool flipUVs)
        {
            Vertex3 Max = new Vertex3(data.VertexList[0].Position.X, data.VertexList[0].Position.Y, data.VertexList[0].Position.Z);
            Vertex3 Min = new Vertex3(data.VertexList[0].Position.X, data.VertexList[0].Position.Y, data.VertexList[0].Position.Z);

            foreach (Vertex i in data.VertexList)
            {
                if (i.Position.X > Max.X)
                {
                    Max.X = i.Position.X;
                }
                if (i.Position.Y > Max.Y)
                {
                    Max.Y = i.Position.Y;
                }
                if (i.Position.Z > Max.Z)
                {
                    Max.Z = i.Position.Z;
                }
                if (i.Position.X < Min.X)
                {
                    Min.X = i.Position.X;
                }
                if (i.Position.Y < Min.Y)
                {
                    Min.Y = i.Position.Y;
                }
                if (i.Position.Z < Min.Z)
                {
                    Min.Z = i.Position.Z;
                }
            }

            Vertex3 sphereCenter;

            sphereCenter.X = (Max.X + Min.X) / 2f;
            sphereCenter.Y = (Max.Y + Min.Y) / 2f;
            sphereCenter.Z = (Max.Z + Min.Z) / 2f;

            float sphereRadius = Math.Max((Max.X - Min.X) / 2f, Math.Max((Max.Y - Min.Y) / 2f, (Max.Z - Min.Z) / 2f));

            List <Vertex3> vList = new List <Vertex3>(data.VertexList.Count);

            foreach (Vertex v in data.VertexList)
            {
                vList.Add(new Vertex3(v.Position.X, v.Position.Y, v.Position.Z));
            }

            List <Vertex3> nList = new List <Vertex3>(data.VertexList.Count);

            foreach (Vertex v in data.VertexList)
            {
                nList.Add(new Vertex3(-v.Normal.X, -v.Normal.Y, -v.Normal.Z));
            }

            List <Color> cList = new List <Color>(data.VertexList.Count);

            foreach (Vertex v in data.VertexList)
            {
                cList.Add(new Color(v.Color.R, v.Color.G, v.Color.B, v.Color.A));
            }

            List <Vertex2> uvList = new List <Vertex2>(data.VertexList.Count);

            if (flipUVs)
            {
                foreach (Vertex v in data.VertexList)
                {
                    uvList.Add(new Vertex2(v.TexCoord.X, v.TexCoord.Y));
                }
            }
            else
            {
                foreach (Vertex v in data.VertexList)
                {
                    uvList.Add(new Vertex2(v.TexCoord.X, -v.TexCoord.Y));
                }
            }

            List <RenderWareFile.Triangle> tList = new List <RenderWareFile.Triangle>(data.TriangleList.Count);

            foreach (Triangle t in data.TriangleList)
            {
                tList.Add(new RenderWareFile.Triangle((ushort)t.materialIndex, (ushort)t.vertex1, (ushort)t.vertex2, (ushort)t.vertex3));
            }

            List <Material_0007> materials = new List <Material_0007>(data.MaterialList.Count);

            for (int i = 0; i < data.MaterialList.Count; i++)
            {
                materials.Add(new Material_0007()
                {
                    materialStruct = new MaterialStruct_0001()
                    {
                        unusedFlags = 0,
                        color       = new Color()
                        {
                            R = 0xFF, G = 0xFF, B = 0xFF, A = 0xFF
                        },
                        unusedInt2 = currentRenderWareVersion == scoobyRenderWareVersion ? 0x27584014 : 0,
                        isTextured = 1,
                        ambient    = 1f,
                        specular   = 1f,
                        diffuse    = 1f
                    },
                    texture = new Texture_0006()
                    {
                        textureStruct = new TextureStruct_0001()
                        {
                            filterMode   = TextureFilterMode.FILTERLINEARMIPLINEAR,
                            addressModeU = TextureAddressMode.TEXTUREADDRESSWRAP,
                            addressModeV = TextureAddressMode.TEXTUREADDRESSWRAP,
                            useMipLevels = 1
                        },
                        diffuseTextureName = new String_0002()
                        {
                            stringString = data.MaterialList[i]
                        },
                        alphaTextureName = new String_0002()
                        {
                            stringString = ""
                        },
                        textureExtension = new Extension_0003()
                    },
                    materialExtension = new Extension_0003()
                });
            }

            List <BinMesh> binMeshList = new List <BinMesh>();
            int            TotalNumberOfTristripIndicies = 0;

            for (int i = 0; i < data.MaterialList.Count; i++)
            {
                List <int> indices = new List <int>();
                foreach (Triangle f in data.TriangleList)
                {
                    if (f.materialIndex == i)
                    {
                        indices.Add(f.vertex1);
                        indices.Add(f.vertex2);
                        indices.Add(f.vertex3);
                    }
                }
                TotalNumberOfTristripIndicies += indices.Count();

                binMeshList.Add(new BinMesh
                {
                    materialIndex = i,
                    indexCount    = indices.Count(),
                    vertexIndices = indices.ToArray()
                });
            }

            Clump_0010 clump = new Clump_0010()
            {
                clumpStruct = new ClumpStruct_0001()
                {
                    atomicCount = 1
                },
                frameList = new FrameList_000E()
                {
                    frameListStruct = new FrameListStruct_0001()
                    {
                        frames = new List <Frame>()
                        {
                            new Frame()
                            {
                                position       = new Vertex3(),
                                rotationMatrix = new Matrix3x3()
                                {
                                    M11 = 1f,
                                    M12 = 0f,
                                    M13 = 0f,
                                    M21 = 0f,
                                    M22 = 1f,
                                    M23 = 0f,
                                    M31 = 0f,
                                    M32 = 0f,
                                    M33 = 1f,
                                },
                                parentFrame = -1,
                                unknown     = 131075
                            },
                            new Frame()
                            {
                                position       = new Vertex3(),
                                rotationMatrix = new Matrix3x3()
                                {
                                    M11 = 1f,
                                    M12 = 0f,
                                    M13 = 0f,
                                    M21 = 0f,
                                    M22 = 1f,
                                    M23 = 0f,
                                    M31 = 0f,
                                    M32 = 0f,
                                    M33 = 1f,
                                },
                                parentFrame = 0,
                                unknown     = 0
                            }
                        }
                    },
                    extensionList = new List <Extension_0003>()
                    {
                        new Extension_0003(),
                        new Extension_0003()
                    }
                },
                geometryList = new GeometryList_001A()
                {
                    geometryListStruct = new GeometryListStruct_0001()
                    {
                        numberOfGeometries = 1,
                    },
                    geometryList = new List <Geometry_000F>()
                    {
                        new Geometry_000F()
                        {
                            geometryStruct = new GeometryStruct_0001()
                            {
                                geometryFlags   = GeometryFlags.hasLights | GeometryFlags.modeulateMaterialColor | GeometryFlags.hasTextCoords | GeometryFlags.hasVertexColors | GeometryFlags.hasVertexPositions | (nList.Count > 0 ? GeometryFlags.hasNormals:0),
                                geometryFlags2  = (GeometryFlags2)1,
                                numTriangles    = data.TriangleList.Count(),
                                numVertices     = data.VertexList.Count(),
                                numMorphTargets = 1,
                                ambient         = 1f,
                                specular        = 1f,
                                diffuse         = 1f,
                                vertexColors    = cList.ToArray(),
                                textCoords      = uvList.ToArray(),
                                triangles       = tList.ToArray(),
                                morphTargets    = new MorphTarget[]
                                {
                                    new MorphTarget()
                                    {
                                        hasNormals   = nList.Count > 0 ? 1 : 0,
                                        hasVertices  = 1,
                                        sphereCenter = sphereCenter,
                                        radius       = sphereRadius,
                                        vertices     = vList.ToArray(),
                                        normals      = nList.ToArray(),
                                    }
                                }
                            },

                            materialList = new MaterialList_0008()
                            {
                                materialListStruct = new MaterialListStruct_0001()
                                {
                                    materialCount = materials.Count()
                                },

                                materialList = materials.ToArray()
                            },

                            geometryExtension = new Extension_0003()
                            {
                                extensionSectionList = new List <RWSection>()
                                {
                                    new BinMeshPLG_050E()
                                    {
                                        binMeshHeaderFlags = BinMeshHeaderFlags.TriangleList,
                                        numMeshes          = binMeshList.Count(),
                                        totalIndexCount    = TotalNumberOfTristripIndicies,
                                        binMeshList        = binMeshList.ToArray()
                                    }
                                }
                            }
                        }
                    }
                },
                atomicList = new List <Atomic_0014>()
                {
                    new Atomic_0014()
                    {
                        atomicStruct = new AtomicStruct_0001()
                        {
                            frameIndex    = 1,
                            geometryIndex = 0,
                            unknown1      = 5,
                            unknown2      = 0
                        },
                        atomicExtension = currentRenderWareVersion == scoobyRenderWareVersion ? new Extension_0003()
                        {
                            extensionSectionList = new List <RWSection>()
                            {
                                new MaterialEffectsPLG_0120()
                                {
                                    value = 0
                                }
                            }
                        } : new Extension_0003()
                    }
                },

                clumpExtension = new Extension_0003()
            };

            return(new RWSection[] { clump });
        }
コード例 #11
0
        private void Weight(float value, Vertex3 vertex, bool increment)
        {
            //LET'S TANGO

            Influence  targetInf     = null;
            BoneWeight targetWeight  = null;
            float      max           = 1.0f;
            int        selectedIndex = 0;

            IMatrixNode node = vertex.MatrixNode;

            if (node == null)
            {
                vertex._object.ConvertInf();
                node = vertex.MatrixNode;
            }

            List <BoneWeight> weights = node.Weights;

            if (_targetBone == null || _targetBone._locked)
            {
                return;
            }

            MDL0BoneNode origBone = null;

            if (node is MDL0BoneNode)
            {
                origBone = node as MDL0BoneNode;
                node     = new Influence(origBone);
            }

            bool refs = node.Users.Count > 1;

            if (refs)
            {
                targetInf = (node as Influence).Clone();
            }
            else
            {
                targetInf = (node as Influence);
            }

            weights = targetInf._weights;

            selectedIndex = vertex.IndexOfBone(TargetBone);
            if (selectedIndex == -1)
            {
                weights.Add(new BoneWeight(TargetBone, 0.0f));
                selectedIndex = weights.Count - 1;
            }

            targetWeight = targetInf._weights[selectedIndex];
            if (targetWeight.Locked)
            {
                return;
            }

            max = 1.0f;
            foreach (BoneWeight b in weights)
            {
                if (b.Locked)
                {
                    max -= b.Weight;
                }
            }

            value = increment ? RoundValue(targetWeight.Weight + value, max) : RoundValue(value, max);

            if (targetWeight.Weight == value)
            {
                return;
            }

            List <int> editableWeights = new List <int>();

            int c = 0;

            foreach (BoneWeight b in targetInf._weights)
            {
                if (!b.Locked && c != selectedIndex)
                {
                    editableWeights.Add(c);
                }
                c++;
            }

            if (editableWeights.Count == 0)
            {
                return;
            }

            float diff = targetWeight.Weight - value;

            targetWeight.Weight = value;

            float val = diff / (editableWeights.Count);

            if (value != max)
            {
                foreach (int i in editableWeights)
                {
                    targetInf._weights[i].Weight = (float)Math.Round((targetInf._weights[i].Weight + val).Clamp(0.0f, 1.0f), 7);
                }
            }
            else
            {
                foreach (int i in editableWeights)
                {
                    targetInf._weights[i].Weight = 0;
                }
            }

            //Don't want the modified value to be normalized
            bool locked = targetWeight.Locked;

            targetWeight.Locked = true;
            targetInf.Normalize();
            targetWeight.Locked = locked;

            vertex.MatrixNode = vertex._object.Model._influences.FindOrCreate(targetInf, false);
            vertex._object.ConvertInf();
            vertex._object.Model.SignalPropertyChange();

            _mainWindow.UpdateModel();
        }
コード例 #12
0
ファイル: ExampleConvexHull3D.cs プロジェクト: fecca/Code
	// Use this for initialization
	void Start()
	{
		CreateLineMaterial();

		mesh = new Mesh();
		Vertex3[] vertices = new Vertex3[NumberOfVertices];
		meshVerts = new Vector3[NumberOfVertices];
		int[] meshIndices = new int[NumberOfVertices];

		Random.seed = 0;
		int i = 0;
		while (i < NumberOfVertices)
		{
			Vector3 v = new Vector3(Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f));

			if (mode == MODE.CUBE_VOLUME)
			{
				vertices[i] = new Vertex3(size * v.x, size * v.y, size * v.z);
				meshVerts[i] = vertices[i].ToVector3();
				meshIndices[i] = i;

				i++;
			}
			else if (mode == MODE.SPHERE_VOLUME)
			{
				if (v.magnitude < 1.0f)
				{
					vertices[i] = new Vertex3(size * v.x, size * v.y, size * v.z);
					meshVerts[i] = vertices[i].ToVector3();
					meshIndices[i] = i;

					i++;
				}

			}
			else if (mode == MODE.SPHERE_SURFACE)
			{
				v.Normalize();

				vertices[i] = new Vertex3(size * v.x, size * v.y, size * v.z);
				meshVerts[i] = vertices[i].ToVector3();
				meshIndices[i] = i;

				i++;
			}
		}

		mesh.vertices = meshVerts;
		mesh.SetIndices(meshIndices, MeshTopology.Points, 0);
		//mesh.bounds = new Bounds(Vector3.zero, new Vector3((float)size,(float)size,(float)size));

		float now = Time.realtimeSinceStartup;
		ConvexHull<Vertex3, Face3> convexHull = ConvexHull.Create<Vertex3, Face3>(vertices);
		float interval = Time.realtimeSinceStartup - now;

		convexHullVertices = new List<Vertex3>(convexHull.Points);
		convexHullFaces = new List<Face3>(convexHull.Faces);
		convexHullIndices = new List<int>();

		Debug.Log("#test# " + vertices.Length);
		Debug.Log("#test# " + convexHullVertices.Count);
		Vector3[] newVertices = new Vector3[vertices.Length];
		triangles = new int[newVertices.Length * 3];
		var triIndex = 0;
		foreach (Face3 face in convexHullFaces)
		{
			for (int vIndex = 0; vIndex < face.Vertices.Length; vIndex++)
			{
				var indexOf = convexHullVertices.IndexOf(face.Vertices[vIndex]);
				convexHullIndices.Add(indexOf);
				newVertices[indexOf] = face.Vertices[vIndex].ToVector3();
				triangles[triIndex + vIndex] = indexOf;
			}
			triIndex += 3;
			//convexHullIndices.Add(convexHullVertices.IndexOf(face.Vertices[0]));
			//convexHullIndices.Add(convexHullVertices.IndexOf(face.Vertices[1]));
			//convexHullIndices.Add(convexHullVertices.IndexOf(face.Vertices[2]));

			Debug.DrawLine(face.Vertices[0].ToVector3(), face.Vertices[1].ToVector3(), new Color(0.1f, 0.1f, 0.1f), 100f);
			Debug.DrawLine(face.Vertices[1].ToVector3(), face.Vertices[2].ToVector3(), new Color(0.1f, 0.1f, 0.1f), 100f);
			Debug.DrawLine(face.Vertices[2].ToVector3(), face.Vertices[0].ToVector3(), new Color(0.1f, 0.1f, 0.1f), 100f);
		}
		mesh.vertices = newVertices;
		mesh.triangles = triangles;

		GameObject.Find("Test").GetComponent<MeshFilter>().mesh = mesh;
		GameObject.Find("Test").GetComponent<MeshCollider>().sharedMesh = mesh;

		Debug.Log("Out of the " + NumberOfVertices + " vertices, there are " + convexHullVertices.Count + " verts on the convex hull.");
		Debug.Log("time = " + interval * 1000.0f + " ms");
	}
コード例 #13
0
 public void IncrementWeight(float value, Vertex3 vertex)
 {
     Weight(value, vertex, true);
 }
コード例 #14
0
 public void SetWeight(float value, Vertex3 vertex)
 {
     Weight(value, vertex, false);
 }
コード例 #15
0
        //private void uvIndex_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    _uvIndex = uvIndex.SelectedIndex;
        //    UpdatePropDisplay();
        //}

        public void UpdatePropDisplay()
        {
            _updating = true;

            if (_targetVertices != null && _targetVertices.Count != 0)
            {
                if (Enabled != true)
                {
                    Enabled = true;
                }
            }
            else
            {
                if (Enabled != false)
                {
                    Enabled = false;
                }
            }

            Vertex3 vertex = TargetVertex;

            if (vertex == null || _targetVertices.Count > 1)
            {
                numPosX.Value = 0;
                numPosY.Value = 0;
                numPosZ.Value = 0;

                bool nonNull = vertex != null;
                btnAverage.Enabled = groupBox1.Enabled = nonNull;

                groupBox1.Text = nonNull ? "Offset" : "Position";

                if (nonNull)
                {
                    label7.Text = String.Format("{0} vertices selected", _targetVertices.Count);
                }
                else
                {
                    label7.Text = "No vertices selected";
                }

                //numNormX.Value = 0;
                //numNormY.Value = 0;
                //numNormZ.Value = 0;

                //numTexX.Value = 0;
                //numTexY.Value = 0;

                //colorBox.BackColor = Color.FromKnownColor(KnownColor.Control);
            }
            else
            {
                Vector3 v3 = vertex.WeightedPosition;
                numPosX.Value = v3._x;
                numPosY.Value = v3._y;
                numPosZ.Value = v3._z;

                groupBox1.Text     = "Position";
                groupBox1.Enabled  = true;
                btnAverage.Enabled = false;

                label7.Text = "1 vertex selected";

                //v3 = vertex.WeightedNormal;
                //numNormX.Value = v3._x;
                //numNormY.Value = v3._y;
                //numNormZ.Value = v3._z;

                //Vector2 v2 = vertex._uvs[_uvIndex];
                //numTexX.Value = v2._x;
                //numTexY.Value = v2._y;

                //RGBAPixel p = vertex._colors[_colorIndex];
                //colorBox.BackColor = Color.FromArgb(p.A, p.R, p.G, p.B);
            }

            _updating = false;
        }
コード例 #16
0
ファイル: MovingJoint.cs プロジェクト: rjabaker/Skynet
 public MovingJoint(JointType jointType, Vertex3 position, double bendAngle)
     : base(jointType, position)
 {
     this.bendAngle = bendAngle;
 }
コード例 #17
0
 public void SetWeight(float value, Vertex3 vertex)
 {
     Weight(value, vertex, WeightType.Set);
 }
コード例 #18
0
ファイル: Triangle.cs プロジェクト: tricyclelad/HW1-OO
 public void Move(double deltaX, double deltaY)
 {
     Vertex1.Move(deltaX, deltaY);
     Vertex2.Move(deltaX, deltaY);
     Vertex3.Move(deltaX, deltaY);
 }
コード例 #19
0
		/// <summary>
		/// Set uniform state variable (variant type variable)
		/// </summary>
		/// <param name="ctx">
		/// A <see cref="GraphicsContext"/> used for operations.
		/// </param>
		/// <param name="uniformName">
		/// A <see cref="String"/> that specify the variable name in the shader source.
		/// </param>
		/// <param name="v">
		/// A <see cref="Vertex3"/> holding the uniform variabile data.
		/// </param>
		public void SetVariantUniform(GraphicsContext ctx, string uniformName, Vertex3 v)
		{
			if (v == null)
				throw new ArgumentNullException("v");

			SetUniform(ctx, uniformName, v.X, v.Y, v.Z);
		}
コード例 #20
0
        public static RWSection[] CreateBSPFromAssimp(string fileName, bool flipUVs, bool ignoreMeshColors)
        {
            PostProcessSteps pps =
                PostProcessSteps.Debone | PostProcessSteps.FindInstances |
                PostProcessSteps.FindInvalidData | PostProcessSteps.OptimizeGraph |
                PostProcessSteps.OptimizeMeshes | PostProcessSteps.Triangulate |
                PostProcessSteps.PreTransformVertices;

            Scene scene = new AssimpContext().ImportFile(fileName, pps);

            int vertexCount   = scene.Meshes.Sum(m => m.VertexCount);
            int triangleCount = scene.Meshes.Sum(m => m.FaceCount);

            if (vertexCount > 65535 || triangleCount > 65536)
            {
                throw new ArgumentException("Model has too many vertices or triangles. Please import a simpler model.");
            }

            List <Vertex3> vertices                  = new List <Vertex3>(vertexCount);
            List <RenderWareFile.Color> vColors      = new List <RenderWareFile.Color>(vertexCount);
            List <Vertex2> textCoords                = new List <Vertex2>(vertexCount);
            List <RenderWareFile.Triangle> triangles = new List <RenderWareFile.Triangle>(triangleCount);

            int totalVertices = 0;

            foreach (var m in scene.Meshes)
            {
                foreach (Vector3D v in m.Vertices)
                {
                    vertices.Add(new Vertex3(v.X, v.Y, v.Z));
                }

                if (m.HasTextureCoords(0))
                {
                    foreach (Vector3D v in m.TextureCoordinateChannels[0])
                    {
                        textCoords.Add(new Vertex2(v.X, flipUVs ? -v.Y : v.Y));
                    }
                }
                else
                {
                    for (int i = 0; i < m.VertexCount; i++)
                    {
                        textCoords.Add(new Vertex2());
                    }
                }

                if (m.HasVertexColors(0))
                {
                    foreach (Color4D c in m.VertexColorChannels[0])
                    {
                        vColors.Add(new RenderWareFile.Color(
                                        (byte)(c.R * 255),
                                        (byte)(c.G * 255),
                                        (byte)(c.B * 255),
                                        (byte)(c.A * 255)));
                    }
                }
                else
                {
                    for (int i = 0; i < m.VertexCount; i++)
                    {
                        vColors.Add(new RenderWareFile.Color(255, 255, 255, 255));
                    }
                }

                foreach (var t in m.Faces)
                {
                    triangles.Add(new RenderWareFile.Triangle()
                    {
                        vertex1       = (ushort)(t.Indices[0] + totalVertices),
                        vertex2       = (ushort)(t.Indices[1] + totalVertices),
                        vertex3       = (ushort)(t.Indices[2] + totalVertices),
                        materialIndex = (ushort)m.MaterialIndex
                    });
                }

                totalVertices += m.VertexCount;
            }

            if (vertices.Count != textCoords.Count || vertices.Count != vColors.Count)
            {
                throw new ArgumentException("Internal error: texture coordinate or vertex color count is different from vertex count.");
            }

            triangles = triangles.OrderBy(t => t.materialIndex).ToList();

            Vertex3 Max = new Vertex3(vertices[0].X, vertices[0].Y, vertices[0].Z);
            Vertex3 Min = new Vertex3(vertices[0].X, vertices[0].Y, vertices[0].Z);

            foreach (Vertex3 i in vertices)
            {
                if (i.X > Max.X)
                {
                    Max.X = i.X;
                }
                if (i.Y > Max.Y)
                {
                    Max.Y = i.Y;
                }
                if (i.Z > Max.Z)
                {
                    Max.Z = i.Z;
                }
                if (i.X < Min.X)
                {
                    Min.X = i.X;
                }
                if (i.Y < Min.Y)
                {
                    Min.Y = i.Y;
                }
                if (i.Z < Min.Z)
                {
                    Min.Z = i.Z;
                }
            }

            Max = new Vertex3(MaximumBoundary, MaximumBoundary, MaximumBoundary);
            Min = new Vertex3(-MaximumBoundary, -MaximumBoundary, -MaximumBoundary);

            BinMesh[] binMeshes = new BinMesh[scene.MaterialCount];

            Material_0007[] materials = new Material_0007[scene.MaterialCount];

            for (int i = 0; i < scene.MaterialCount; i++)
            {
                List <int> indices = new List <int>(triangles.Count);
                foreach (RenderWareFile.Triangle f in triangles)
                {
                    if (f.materialIndex == i)
                    {
                        indices.Add(f.vertex1);
                        indices.Add(f.vertex2);
                        indices.Add(f.vertex3);
                    }
                }

                binMeshes[i] = new BinMesh()
                {
                    materialIndex = i,
                    indexCount    = indices.Count(),
                    vertexIndices = indices.ToArray()
                };

                materials[i] = new Material_0007()
                {
                    materialStruct = new MaterialStruct_0001()
                    {
                        unusedFlags = 0,
                        color       = ignoreMeshColors ?
                                      new RenderWareFile.Color(255, 255, 255, 255) :
                                      new RenderWareFile.Color(
                            (byte)(scene.Materials[i].ColorDiffuse.R / 255),
                            (byte)(scene.Materials[i].ColorDiffuse.G / 255),
                            (byte)(scene.Materials[i].ColorDiffuse.B / 255),
                            (byte)(scene.Materials[i].ColorDiffuse.A / 255)),
                        unusedInt2 = 0x2DF53E84,
                        isTextured = scene.Materials[i].HasTextureDiffuse ? 1 : 0,
                        ambient    = ignoreMeshColors ? 1f : scene.Materials[i].ColorAmbient.A,
                        specular   = ignoreMeshColors ? 1f : scene.Materials[i].ColorSpecular.A,
                        diffuse    = ignoreMeshColors ? 1f : scene.Materials[i].ColorDiffuse.A
                    },
                    texture           = scene.Materials[i].HasTextureDiffuse ? RWTextureFromAssimpMaterial(scene.Materials[i].TextureDiffuse) : null,
                    materialExtension = new Extension_0003()
                    {
                        extensionSectionList = new List <RWSection>()
                    },
                };
            }

            WorldFlags worldFlags = WorldFlags.HasOneSetOfTextCoords | WorldFlags.HasVertexColors | WorldFlags.WorldSectorsOverlap | (WorldFlags)0x00010000;

            World_000B world = new World_000B()
            {
                worldStruct = new WorldStruct_0001()
                {
                    rootIsWorldSector = 1,
                    inverseOrigin     = new Vertex3(-0f, -0f, -0f),
                    numTriangles      = (uint)triangleCount,
                    numVertices       = (uint)vertexCount,
                    numPlaneSectors   = 0,
                    numAtomicSectors  = 1,
                    colSectorSize     = 0,
                    worldFlags        = worldFlags,
                    boxMaximum        = Max,
                    boxMinimum        = Min,
                },

                materialList = new MaterialList_0008()
                {
                    materialListStruct = new MaterialListStruct_0001()
                    {
                        materialCount = scene.MaterialCount
                    },
                    materialList = materials
                },

                firstWorldChunk = new AtomicSector_0009()
                {
                    atomicSectorStruct = new AtomicSectorStruct_0001()
                    {
                        matListWindowBase = 0,
                        numTriangles      = triangleCount,
                        numVertices       = vertexCount,
                        boxMaximum        = Max,
                        boxMinimum        = Min,
                        collSectorPresent = 0x2F50D984,
                        unused            = 0,
                        vertexArray       = vertices.ToArray(),
                        colorArray        = vColors.ToArray(),
                        uvArray           = textCoords.ToArray(),
                        triangleArray     = triangles.ToArray()
                    },
                    atomicSectorExtension = new Extension_0003()
                    {
                        extensionSectionList = new List <RWSection>()
                        {
                            new BinMeshPLG_050E()
                            {
                                binMeshHeaderFlags = BinMeshHeaderFlags.TriangleList,
                                numMeshes          = binMeshes.Count(),
                                totalIndexCount    = binMeshes.Sum(b => b.indexCount),
                                binMeshList        = binMeshes
                            },
                            new CollisionPLG_011D_Scooby()
                            {
                                splits = new Split_Scooby[0],
                                startIndex_amountOfTriangles = new short[][] { new short[] { 0, (short)triangles.Count } },
                                triangles = TriangleRange(triangles.Count)
                            }
                        }
                    }
                },

                worldExtension = new Extension_0003()
            };

            return(new RWSection[] { world });
        }
コード例 #21
0
ファイル: Program.cs プロジェクト: addicted-by/MAI
    Vertex3 FindClosestVertex(DMatrix4 mat, DVector4 vec)
    {
        List <Vertex3> vs = new List <Vertex3>();

        double radius = NormalizeDistance(VertexSize);

        foreach (Vertex3 v in surface.border0.vertices)
        {
            DVector4 tmp = mat * new DVector4(v.Point, 1.0);
            DVector2 d   = new DVector2(tmp.X, tmp.Y) - new DVector2(vec.X, vec.Y);

            if (d.GetLength() < radius)
            {
                vs.Add(v);
            }
        }

        foreach (Vertex3 v in surface.border1.vertices)
        {
            DVector4 tmp = mat * new DVector4(v.Point, 1.0);
            DVector2 d   = new DVector2(tmp.X, tmp.Y) - new DVector2(vec.X, vec.Y);

            if (d.GetLength() < radius)
            {
                vs.Add(v);
            }
        }

        foreach (Vertex3 v in surface.border2.vertices)
        {
            DVector4 tmp = mat * new DVector4(v.Point, 1.0);
            DVector2 d   = new DVector2(tmp.X, tmp.Y) - new DVector2(vec.X, vec.Y);

            if (d.GetLength() < radius)
            {
                vs.Add(v);
            }
        }

        foreach (Vertex3 v in surface.border3.vertices)
        {
            DVector4 tmp = mat * new DVector4(v.Point, 1.0);
            DVector2 d   = new DVector2(tmp.X, tmp.Y) - new DVector2(vec.X, vec.Y);

            if (d.GetLength() < radius)
            {
                vs.Add(v);
            }
        }

        Vertex3 res     = null;
        double  minDist = 100000000;

        foreach (Vertex3 v in vs)
        {
            DVector4 tmp = mat * new DVector4(v.Point, 1.0);
            DVector2 d   = new DVector2(tmp.X, tmp.Y) - new DVector2(vec.X, vec.Y);

            double dist = d.GetLength();

            if (dist < minDist)
            {
                res     = v;
                minDist = dist;
            }
        }

        return(res);
    }
コード例 #22
0
 public void IncrementWeight(float value, Vertex3 vertex)
 {
     Weight(value, vertex, WeightType.Add);
 }
コード例 #23
0
    public void Create()
    {
        foreach (Transform child in transform)
        {
            Destroy(child.gameObject);
        }

        //InputField[] fields = FindObjectsOfType<InputField>();
        //InputField numseed = fields[0];
        //InputField numplates = fields[1];
        //InputField numtiles = fields[2];
        //numberOfVertices = Convert.ToInt32(numtiles.text);
        //plates = Convert.ToInt32(numplates.text);
        //seed = Convert.ToInt32(numseed.text);

        // INITIALIZATION
        Vertex3[] vertices = new Vertex3[numberOfVertices];
        Vector3[] meshVerts = new Vector3[numberOfVertices];
        allVerts = new List<Vector3>();
        vertsForVoronoiHull = new List<Vector3>();

        // VORONOI VERTICES NEED ONE EXTRA ONE IN CENTER
        Vertex3[] voronoiVertices = new Vertex3[numberOfVertices + 1];

        // RANDOM SEED
        Random.seed = seed;

        // GENERATE UNIFORM POINTS
        allVerts = GeneratePointsUniformly(); 
        allVerts.Sort((v1, v2) => v1.y.CompareTo(v2.y));

        // SET INDICES FOR VORONOI
        int i = 0;
        while (i < numberOfVertices)
        {
            vertices[i] = new Vertex3(allVerts[i].x, allVerts[i].y, allVerts[i].z);
            voronoiVertices[i] = vertices[i];
            meshVerts[i] = vertices[i].ToVector3(); ;
            i++;
        }
        // SET LAST EXTRA VERTEX
        voronoiVertices[numberOfVertices] = new Vertex3(0, 0, 0);

        
        // VORONOI
        voronoiMesh = VoronoiMesh.Create<Vertex3, Cell3>(voronoiVertices);
        

        
        // VORONOI HULL GENERATION
        int index = 0;
        foreach (var edge in voronoiMesh.Edges)
        {
            Vector3 source = new Vector3(edge.Source.Circumcenter.x, edge.Source.Circumcenter.y, edge.Source.Circumcenter.z);
            Vector3 target = new Vector3(edge.Target.Circumcenter.x, edge.Target.Circumcenter.y, edge.Target.Circumcenter.z);
            source *= ((float)size / 2.5f);
            target *= ((float)size / 2.5f);
            vertsForVoronoiHull.Add(source);
            vertsForVoronoiHull.Add(target);
            index++;
        }

        // REMOVE DUPLICATE POINTS
        vertsForVoronoiHull = vertsForVoronoiHull.Distinct().ToList();

        // CONVERT FROM VECTOR3 LIST TO VERTEX3 LIST FOR FINAL HULL
        Vertex3[] verticesDelaunay = new Vertex3[vertsForVoronoiHull.Count];

        int g = 0;
        while (g < vertsForVoronoiHull.Count)
        {
            verticesDelaunay[g] = new Vertex3(vertsForVoronoiHull[g].x, vertsForVoronoiHull[g].y, vertsForVoronoiHull[g].z);
            g++;
        }

        // GENERATE VORONOI HULL
        ConvexHull<Vertex3, Face3> convexHull = ConvexHull.Create<Vertex3, Face3>(verticesDelaunay);
        convexHullVertices = new List<Vertex3>(convexHull.Points);
        convexHullFaces = new List<Face3>(convexHull.Faces);
        convexHullIndices = new List<int>();

        foreach (Face3 f in convexHullFaces)
        {
            convexHullIndices.Add(convexHullVertices.IndexOf(f.Vertices[0]));
            convexHullIndices.Add(convexHullVertices.IndexOf(f.Vertices[1]));
            convexHullIndices.Add(convexHullVertices.IndexOf(f.Vertices[2]));
        }

        Dictionary<Vector3, List<Vector3>> normals = new Dictionary<Vector3, List<Vector3>>();

        // CREATE TRIANGLES FOR MESH
        for (int j = 0; j < convexHullIndices.Count; j += 3)
        {
            int v0 = convexHullIndices[j + 0];
            int v1 = convexHullIndices[j + 1];
            int v2 = convexHullIndices[j + 2];

            Vector3 a = new Vector3((float)convexHullVertices[v0].x, (float)convexHullVertices[v0].y, (float)convexHullVertices[v0].z);
            Vector3 b = new Vector3((float)convexHullVertices[v1].x, (float)convexHullVertices[v1].y, (float)convexHullVertices[v1].z);
            Vector3 c = new Vector3((float)convexHullVertices[v2].x, (float)convexHullVertices[v2].y, (float)convexHullVertices[v2].z);

            Vector3 normal = Vector3.Cross(a - b, a - c);

            // DECLARE KEY AND ROUND IT TO AVOID FLOATING POINT ISSUES
            Vector3 key = normal.normalized;
            float roundX = Mathf.Round(key.x * 100) / 100;
            float roundY = Mathf.Round(key.y * 100) / 100;
            float roundZ = Mathf.Round(key.z * 100) / 100;
            Vector3 roundedKey = new Vector3(roundX, roundY, roundZ);

            // POPULATE DICTIONARY
            if (!normals.ContainsKey(roundedKey))
            {
                normals.Add(roundedKey, new List<Vector3>());
            }
            normals[roundedKey].Add(a);
            normals[roundedKey].Add(b);
            normals[roundedKey].Add(c);
        }
 
        // CREATE VORONOI TILES
        List<VoronoiTile> tiles = new List<VoronoiTile>();
        foreach (var pair in normals)
        {
            List<Vector3> tileVerts = new List<Vector3>();
            for (int p = 0; p < pair.Value.Count; ++p)
            {
                tileVerts.Add(pair.Value[p]);
            }
            GameObject tile = new GameObject("Tile", typeof(VoronoiTile), typeof(MeshFilter), typeof(MeshRenderer), typeof(MeshCollider));
            var thisTile = tile.GetComponent<VoronoiTile>() as VoronoiTile;
            
            thisTile.Initialize(tileVerts, false); // OPTIMIZE HERE
            
            tile.GetComponent<MeshFilter>().mesh = thisTile.tileMesh;
            tile.GetComponent<MeshCollider>().sharedMesh = thisTile.tileMesh;

            thisTile.Normal = pair.Key;
            tiles.Add(thisTile);
            ++numberOfTiles;
        }

        foreach (var tile in tiles)
        {
            tile.FindNeighbors(tiles); 
        }

        List<VoronoiTile> waterTiles = new List<VoronoiTile>();
        Material oceanMat = (Material)Resources.Load("Ocean", typeof(Material));
        foreach (var pair in normals)
        {
            List<Vector3> tileVerts = new List<Vector3>();
            for (int p = 0; p < pair.Value.Count; ++p)
            {
                tileVerts.Add(pair.Value[p]);
            }
            GameObject tile = new GameObject("WaterTile", typeof(VoronoiTile), typeof(MeshFilter), typeof(MeshRenderer));
            var thisTile = tile.GetComponent<VoronoiTile>() as VoronoiTile;
            thisTile.Initialize(tileVerts, true);
            tile.GetComponent<MeshFilter>().mesh = thisTile.tileMesh;
            tile.GetComponent<MeshRenderer>().material = oceanMat;
            waterTiles.Add(thisTile);
        }

        ocean = new GameObject("Ocean");
        ocean.transform.parent = transform;
        foreach (var tile in waterTiles)
        {
            tile.transform.parent = ocean.transform;
        }

        // FLOOD FILLS
        // GENERATE PLATES
        List<VoronoiTile> plateStartNodes = GeneratePlateStartNodes(plates, ref tiles);

        // GENERATE PLATE MATERIALS
        List<Material> plateMaterials = GenerateMaterials(1); // changed here

        // GENERATE START LISTS
        List<List<VoronoiTile>> colors = new List<List<VoronoiTile>>();
        for (int b = 0; b < plates; ++b)
        {
            colors.Add(new List<VoronoiTile>() { plateStartNodes[b] });
        }

        
        // FILL
        FloodFillSimultaneous(ref colors, plateMaterials, ref tiles);
        
        
        // GROUP PLATES
        plateList = new List<TectonicPlate>();
        for (int q = 0; q < plates; ++q)
        {
            GameObject plateTest = new GameObject("Plate" + q, typeof(TectonicPlate));
            List<VoronoiTile> testPlateTiles = new List<VoronoiTile>();
            foreach (var voronoiTile in tiles)
            {
                if (voronoiTile.plate == q) testPlateTiles.Add(voronoiTile);
            }
            var thisTecPlate = plateTest.GetComponent<TectonicPlate>();
            thisTecPlate.Initialize(ref testPlateTiles);
            int land = Random.Range(0, 10);
            if (land < landAmount) thisTecPlate.isLand = true;
            plateTest.transform.parent = transform;
            plateList.Add(thisTecPlate);
        }

        LoadMaterials();
        
        // CREATE WATER AND LAND AREAS FOR HEIGHT
        FindWaterAndLandPoints();

        // DETERMINE BIOMES
        AssignPlateProperties();
        AssignTileProperties();
        DetermineBiomes(true);
        GenerateHeight();
        DetermineHeightBiomes();
    }
コード例 #24
0
        //Returns true if the vertex's matrix node is changed.
        private bool Weight(float value, Vertex3 vertex, WeightType type)
        {
            if (_targetBone == null || _targetBone.Locked)
            {
                return(false);
            }

            Influence  targetInf    = null;
            BoneWeight targetWeight = null;
            float      max          = 1.0f;

            //Get the matrix that influences this vertex
            IMatrixNode node = vertex.GetMatrixNode();

            bool startsAsBone = false;

            //Convert a single bone into an influence so bones can be added to it later
            if (node is MDL0BoneNode)
            {
                startsAsBone = true;
                node         = new Influence(node as MDL0BoneNode);
            }

            //Duplicate the influence if it affects more than just this vertex
            targetInf = node.Users.Count > 1 ?
                        (node as Influence).Clone() :
                        node as Influence;

            //Find or add the current bone to the influence
            List <BoneWeight> weights = targetInf.Weights;
            int selectedIndex         = weights.Select(x => x.Bone).ToArray().IndexOf(TargetBone);

            if (selectedIndex < 0)
            {
                weights.Add(new BoneWeight(TargetBone, 0.0f));
                selectedIndex = weights.Count - 1;
            }

            //Get the weight at the index of the current bone
            targetWeight = targetInf.Weights[selectedIndex];

            //Can't do anything to a locked weight
            if (targetWeight.Locked)
            {
                return(false);
            }

            //Get the sum of all weights that can be edited by subtracting all locked values from 1.0f
            max = 1.0f;
            foreach (BoneWeight b in weights)
            {
                if (b.Locked)
                {
                    max -= b.Weight;
                }
            }

            //Get the new value for the target weight
            //Clamp it between 0.0f and the max value
            switch (type)
            {
            default:
                value = RoundValue(value, max);
                break;

            case WeightType.Add:
                value = RoundValue(targetWeight.Weight + value, max);
                break;

            case WeightType.Multiply:
                value = RoundValue(targetWeight.Weight * value, max);
                break;
            }

            //Nothing to do if there's no change in value
            if (targetWeight.Weight == value)
            {
                return(false);
            }

            //Collect all unlocked weights that are not the current weight
            //These are weights that will be changed to accomodate the current weight edit
            List <int> editableWeights = new List <int>();

            for (int i = 0; i < targetInf.Weights.Count; i++)
            {
                if (!targetInf.Weights[i].Locked && i != selectedIndex)
                {
                    editableWeights.Add(i);
                }
            }

            //Return if nothing can be edited
            if (editableWeights.Count == 0)
            {
                return(false);
            }

            //Set the current weight with the calculated value
            targetWeight.Weight = value;

            //Get the change in value, divide it by all other editable weights,
            //and then add that value to those weights to bring the overall weight sum back to 1.0f
            float perBoneDiff = (targetWeight.Weight - value) / editableWeights.Count;

            if (value < max)
            {
                foreach (int i in editableWeights)
                {
                    targetInf.Weights[i].Weight = RoundValue(targetInf.Weights[i].Weight + perBoneDiff, 1.0f);
                }
            }
            else
            {
                foreach (int i in editableWeights)
                {
                    targetInf.Weights[i].Weight = 0.0f;
                }
            }

            //Normalize the influence just in case, this will scale all weights so they add up to 1.0f
            //Don't let the modified value be normalized, lock it
            bool locked = targetWeight.Locked;

            targetWeight.Locked = true;
            targetInf.Normalize();
            targetWeight.Locked = locked;

            //Clean influence by removing zero weights
            for (int i = 0; i < targetInf.Weights.Count; i++)
            {
                if (targetInf.Weights[i].Weight <= 0.0f)
                {
                    targetInf.Weights.RemoveAt(i--);
                }
            }

            MDL0ObjectNode obj   = vertex.Parent as MDL0ObjectNode;
            MDL0Node       model = obj.Model;
            IMatrixNode    matrixNode;

            //See if the influence is just one bone
            if (targetInf.Weights.Count == 1)
            {
                matrixNode = targetInf.Weights[0].Bone;
                if (!startsAsBone && !_anyConverted.Contains(obj))
                {
                    _anyConverted.Add(obj);
                }
            }
            else
            {
                matrixNode = model._influences.FindOrCreate(targetInf);
                if (startsAsBone && !_anyConverted.Contains(obj))
                {
                    _anyConverted.Add(obj);
                }
            }

            //Move influence to each vertex before modifying the influence of one vertex
            if (obj.MatrixNode != null)
            {
                obj.TryConvertMatrixToVertex();
            }

            vertex.DeferUpdateAssets();
            vertex.MatrixNode = matrixNode;

            return(true);
        }
コード例 #25
0
ファイル: ShotCube.cs プロジェクト: conovich/Fracturing
    /*
     * float triangleIntersection(Vector3 v0, Vector3 v1, Vector3 v2, Vector3 dir, Vector3 orig) {
     *      //Intersection inter;
     *      Vector3 xc = Vector3.Cross((v1 - v0), (v2 - v0));
     *      Vector3 p = Vector3.Cross(dir, v2 - v0);
     *      Vector3 norm = xc.normalized;
     *
     *      if (Mathf.Abs(norm[0]) < .0001f && Mathf.Abs(norm[1]) < .0001f && Mathf.Abs(norm[2]) < .0001){
     *
     *              return -1.0f;
     *      }
     *
     *      float t;
     *      float a = Vector3.Dot(v1 - v0, p);
     *
     *      if (a < .00001 && a > -.00001){
     *
     *              return -1.0f;
     *      }
     *      else{
     *              float f = 1.0f/a;
     *              Vector3 s = orig - v0;
     *              float u = f*(Vector3.Dot(s, p));
     *              if ( u < 0.0f || u > 1.0f){
     *
     *                      return -1.0f;
     *              }
     *
     *              Vector3 q = Vector3.Cross(s, v1 - v0);
     *              float v = f*Vector3.Dot(dir, q);
     *
     *              if (v < 0.0f || u + v > 1.0f){
     *
     *                      return -1.0f;
     *              }
     *
     *              t = f*Vector3.Dot(v2 - v0, q); //set t
     *
     *              if (t < 0){
     *
     *                      return -1.0f;
     *              }
     *      }
     *
     *      //inter.t = t;
     *      //inter.normal = xc;
     *
     *      return t;
     * }
     */
    void OnCollisionEnter(Collision collider)
    {
        if (collider.gameObject.tag == "bullet" && lifetime < maxLife)
        {
            ContactPoint contact   = collider.contacts [0];
            Vector3      hitPoint  = contact.point;
            Vector3      local_vec = transform.InverseTransformPoint(contact.point);

            //Debug.Log (local_vec);
            //Rigidbody rg = gameObject.GetComponent<Rigidbody>();
            //Vector3 final = collider.rigidbody.mass * collider.relativeVelocity / (rg.mass + collider.rigidbody.mass);
            //Vector3 impulse = final * rg.mass;
            MeshFilter oldMesh    = gameObject.GetComponent <MeshFilter>();
            Vector3[]  oldMeshVrt = oldMesh.mesh.vertices;
            float[]    oldVrts    = new float[oldMeshVrt.Length * 3];
            for (int i = 0; i < oldMeshVrt.Length; i++)
            {
                oldVrts[i * 3]       = oldMeshVrt[i].x * gameObject.transform.localScale.x;
                oldVrts[(i * 3) + 1] = oldMeshVrt[i].y * gameObject.transform.localScale.y;
                oldVrts[(i * 3) + 2] = oldMeshVrt[i].z * gameObject.transform.localScale.z;
            }
            int[]   oldMeshInd = oldMesh.mesh.triangles;
            Vector3 vel        = (collider.rigidbody.velocity).normalized;
            //TRYING TO FIND POINT OF INTERSECTION

            /*
             * float dist = -1.0f;
             * Vector3 dir = vel;
             * Vector3 orig = local_vec;
             * //loop through the indices
             * float xScale = gameObject.transform.localScale.x;
             * float yScale = gameObject.transform.localScale.y;
             * float zScale = gameObject.transform.localScale.z;
             * for(int i = 0; i < oldMeshInd.Length; i+=3)
             * {
             *      Vector3 p0 = new Vector3(oldMeshVrt[oldMeshInd[i]].x*xScale, oldMeshVrt[oldMeshInd[i]].y*yScale, oldMeshVrt[oldMeshInd[i]].z*zScale);
             *      Vector3 p1 = new Vector3(oldMeshVrt[oldMeshInd[i+1]].x*xScale, oldMeshVrt[oldMeshInd[i+1]].y*yScale, oldMeshVrt[oldMeshInd[i+1]].z*zScale);
             *      Vector3 p2 = new Vector3(oldMeshVrt[oldMeshInd[i+2]].x*xScale, oldMeshVrt[oldMeshInd[i+2]].y*yScale, oldMeshVrt[oldMeshInd[i+2]].z*zScale);
             *
             *      float t = triangleIntersection(p0, p1, p2, dir, orig); //check every face
             *
             *      //if(smallest_inter.t == -1) smallest_inter = inter; //set smallest_inter to the first intersection
             *      if (dist < 0.0f){
             *              dist = t;
             *      }
             *      if(dist > t && t > 0) {
             *              dist = t;
             *              //smallest_inter = inter;
             *              //numOfIntersections++;  //only add to numOfIntersections if t != -1
             *      }
             *
             * }
             * if (dist != -1){
             *      local_vec += dist*(dir);
             *
             * }
             */

            RaycastHit hit;
            Ray        ray = new Ray(collider.transform.position, -1 * collider.transform.forward);
            if (Physics.Raycast(ray, out hit))
            {
                if (hit.rigidbody != null && hit.collider.gameObject.tag == "explode")
                {
                    local_vec = transform.InverseTransformPoint(hit.point);
                }
            }
            //local_vec = new Vector3(0, 0, 0);
            local_vec[0] = local_vec[0] * gameObject.transform.localScale.x;
            local_vec[1] = local_vec[1] * gameObject.transform.localScale.y;
            local_vec[2] = local_vec[2] * gameObject.transform.localScale.z;
            //DONE TRYING
            //local_vec += (vel * (-.1f));
            //GETTING INFO TO PASS TO OUR FUNCTION
            //Collider coll = collider.gameObject.GetComponent<Collider>();
            //Vector3 local_vec = coll.ClosestPointOnBounds(hitPoint);
            //local_vec = transform.InverseTransformPoint(local_vec);

            /*
             * Rigidbody rb = gameObject.GetComponent<Rigidbody>();
             * rb.constraints = RigidbodyConstraints.FreezeAll;
             * Rigidbody rb1 = collider.gameObject.GetComponent<Rigidbody>();
             * rb1.constraints = RigidbodyConstraints.FreezeAll;
             */
            //CALL AND INPUT NEW FRAGMENTED CELLS
            //NEW STUFF BEGINS
            //int NumberOfVertices = 24;

            //int run = voroCubeExample();
            Mesh mesh = new Mesh();
            //int numberOfMeshes = numNewMesh();

            //int numberOfMeshes = voroCubeExample (local_vec.x, local_vec.y, local_vec.z);
            //int numberOfMeshes = voroCubeExample (local_vec.x*2, local_vec.y*2, local_vec.z*2);
            //float num = voroGeoDecomp(local_vec.x, local_vec.y, local_vec.z, oldMeshInd, oldVrts);
            //fixed (int* data = &oldMeshInd[0]);
            IntPtr initIndArray = Marshal.AllocHGlobal(oldMeshInd.Length * sizeof(int));
            IntPtr initVrtArray = Marshal.AllocHGlobal(oldVrts.Length * sizeof(float));
            //IntPtr allocIndArray = Marshal.AllocHGlobal (sizeof(int)*4);
            //Marshal.WriteInt32(initIndArray, allocIndArray.ToInt32 ());
            //Marshal.WriteInt32 (initIndArray + 4, allocIndArray.ToInt32 () + 2*sizeof(int));
            Marshal.Copy(oldMeshInd, 0, initIndArray, oldMeshInd.Length);
            Marshal.Copy(oldVrts, 0, initVrtArray, oldVrts.Length);
            float mag          = collider.relativeVelocity.magnitude;
            int   numParticles = (int)Mathf.Floor(mag * 2);
            //Marshal.Copy (
            float numberOfMeshes = voroGeoDecomp(local_vec.x, local_vec.y, local_vec.z, initIndArray, initVrtArray, oldMeshInd.Length, oldVrts.Length, numParticles);
            Debug.Log(numberOfMeshes);
            Marshal.FreeHGlobal(initIndArray);
            Marshal.FreeHGlobal(initVrtArray);


            float[] verts;             //= new float[72];
            bool    inLoop = false;
            //bool run = false;

            ConvexHull <Vertex3, Face3> convexHull;
            for (int r = 0; r < numberOfMeshes; r++)
            {
                //int numberOfVertices = numVertices(r);

                int otherNumber = voroGetNumCellVerts(r);
                if (otherNumber == 0)
                {
                    continue;
                }
                int numberOfVertices = otherNumber * 3;
                verts = new float[numberOfVertices];
                //mesh = new Mesh();
                mesh.Clear();

                //outPutMesh (verts, oldMeshInd, oldMeshVrt, r);
                voroGetCellVertices(verts, ref r, ref inLoop);

                /*
                 * Vector3 p0 = new Vector3(-.5f,.5f,-.5f);
                 * Vector3 p1 = new Vector3(.5f,.5f,-.5f);
                 * Vector3 p2 = new Vector3(0.5f, 0.5f, 0.5f);
                 * Vector3 p3 = new Vector3(-0.5f, 0.5f, 0.5f);
                 * Vector3 p4 = new Vector3(-0.5f, -0.5f, -0.5f);
                 * Vector3 p5 = new Vector3(0.5f, -0.5f, -0.5f);
                 * Vector3 p6 = new Vector3(0.5f, -0.5f, 0.5f);
                 * Vector3 p7 = new Vector3(-0.5f, -0.5f, 0.5f);
                 * Vector3 p8 = new Vector3 (.5f, 1, .5f);
                 */

                int       NumberOfVertices = (verts.Length / 3);
                Vertex3[] vertices         = new Vertex3[NumberOfVertices];
                Vector3[] meshVerts        = new Vector3[NumberOfVertices];
                int[]     meshIndices      = new int[NumberOfVertices];

                int m = 0;
                //Vector3[] vert2;
                Vector3[] vert = new Vector3[NumberOfVertices];
                for (int j = 0; j < verts.Length; j += 3)
                {
                    vert[m] = new Vector3(verts[j], verts[j + 1], verts[j + 2]);
                    m++;
                }
                //vert = new Vector3[]{p4,p5,p6,p7,p8};//,p1,p5,p4,p1,p5,p6,p2,p2,p3,p7,p6,p3,p0,p4,p7,p4,p5,p6,p7};
                int i = 0;
                while (i < NumberOfVertices)
                {
                    Vector3 v = vert[i];                     //new Vector3(Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f));

                    if (mode == MODE.CUBE_VOLUME)
                    {
                        vertices[i]    = new Vertex3(v.x, v.y, v.z);
                        meshVerts[i]   = vert[i];                       //vertices[i].ToVector3();
                        meshIndices[i] = i;

                        i++;
                    }
                    else if (mode == MODE.SPHERE_VOLUME)
                    {
                        if (v.magnitude < 1.0f)
                        {
                            vertices[i]    = new Vertex3(v.x, v.y, v.z);
                            meshVerts[i]   = vertices[i].ToVector3();
                            meshIndices[i] = i;

                            i++;
                        }
                    }
                    else if (mode == MODE.SPHERE_SURFACE)
                    {
                        v.Normalize();

                        vertices[i]    = new Vertex3(v.x, v.y, v.z);
                        meshVerts[i]   = vertices[i].ToVector3();
                        meshIndices[i] = i;

                        i++;
                    }
                }

                mesh.vertices = meshVerts;
                mesh.SetIndices(meshIndices, MeshTopology.Points, 0);
                //mesh.bounds = new Bounds(Vector3.zero, new Vector3((float)size,(float)size,(float)size));

                float now = Time.realtimeSinceStartup;
                convexHull = ConvexHull.Create <Vertex3, Face3>(vertices);
                float interval = Time.realtimeSinceStartup - now;

                convexHullVertices = new List <Vertex3>(convexHull.Points);
                convexHullFaces    = new List <Face3>(convexHull.Faces);
                convexHullIndices  = new List <int>();

                foreach (Face3 f in convexHullFaces)
                {
                    convexHullIndices.Add(convexHullVertices.IndexOf(f.Vertices[0]));
                    convexHullIndices.Add(convexHullVertices.IndexOf(f.Vertices[1]));
                    convexHullIndices.Add(convexHullVertices.IndexOf(f.Vertices[2]));
                }
                //Debug.Log ("There are " + convexHullFaces.Count + " faces in this convex hull.");
                //Debug.Log("Out of the " + NumberOfVertices + " vertices, there are " + convexHullVertices.Count + " verts on the convex hull.");
                //Debug.Log("time = " + interval * 1000.0f + " ms");



                //NEW STUFF ENDS

                GameObject frag = Instantiate(fragment, gameObject.transform.position, gameObject.transform.rotation) as GameObject;
                Cell       s    = frag.gameObject.AddComponent <Cell>();
                //frag.gameObject.AddComponent<Rigidbody>();
                MeshFilter meshFilter = gameObject.GetComponent <MeshFilter>();
                meshFilter.mesh = new Mesh();
                Vector3[] vrts;
                vrts = new Vector3[convexHullVertices.Count];
                for (i = 0; i < convexHullVertices.Count; i++)
                {
                    vrts[i] = new Vector3((float)convexHullVertices[i].x, (float)convexHullVertices[i].y, (float)convexHullVertices[i].z);
                }
                s.VerticesArray = vrts;
                int[] inds;
                inds = new int[convexHullIndices.Count];
                for (i = 0; i < convexHullIndices.Count; i++)
                {
                    inds[i] = convexHullIndices[i];
                }
                s.IndicesArray = inds;
                Renderer rend = gameObject.GetComponent <Renderer>();
                s.life     = lifetime + 1;
                s.material = rend.material;
                s.Build();
            }

            Destroy(gameObject);
            Destroy(collider.gameObject);
            //Rigidbody rg = gameObject.GetComponent<Rigidbody>();
            //rg.constraints = RigidbodyConstraints.FreezeAll;
            //collider.gameObject.transform.position = Transform.localtoWorl(local_vec);
            //collider.rigidbody.constraints = RigidbodyConstraints.FreezeAll;
        }
        if (collider.gameObject.tag == "ground" && lifetime < maxLife)
        {
            ContactPoint contact   = collider.contacts [0];
            Vector3      hitPoint  = contact.point;
            Vector3      local_vec = transform.InverseTransformPoint(contact.point);

            //Debug.Log (local_vec);
            //Rigidbody rg = gameObject.GetComponent<Rigidbody>();
            //Vector3 final = collider.rigidbody.mass * collider.relativeVelocity / (rg.mass + collider.rigidbody.mass);
            //Vector3 impulse = final * rg.mass;
            MeshFilter oldMesh    = gameObject.GetComponent <MeshFilter>();
            Vector3[]  oldMeshVrt = oldMesh.mesh.vertices;
            float[]    oldVrts    = new float[oldMeshVrt.Length * 3];
            for (int i = 0; i < oldMeshVrt.Length; i++)
            {
                oldVrts[i * 3]       = oldMeshVrt[i].x * gameObject.transform.localScale.x;
                oldVrts[(i * 3) + 1] = oldMeshVrt[i].y * gameObject.transform.localScale.y;
                oldVrts[(i * 3) + 2] = oldMeshVrt[i].z * gameObject.transform.localScale.z;
            }
            int[] oldMeshInd = oldMesh.mesh.triangles;
            //Vector3 vel = (collider.rigidbody.velocity).normalized;
            //TRYING TO FIND POINT OF INTERSECTION

            /*
             * float dist = -1.0f;
             * Vector3 dir = vel;
             * Vector3 orig = local_vec;
             * //loop through the indices
             * float xScale = gameObject.transform.localScale.x;
             * float yScale = gameObject.transform.localScale.y;
             * float zScale = gameObject.transform.localScale.z;
             * for(int i = 0; i < oldMeshInd.Length; i+=3)
             * {
             *      Vector3 p0 = new Vector3(oldMeshVrt[oldMeshInd[i]].x*xScale, oldMeshVrt[oldMeshInd[i]].y*yScale, oldMeshVrt[oldMeshInd[i]].z*zScale);
             *      Vector3 p1 = new Vector3(oldMeshVrt[oldMeshInd[i+1]].x*xScale, oldMeshVrt[oldMeshInd[i+1]].y*yScale, oldMeshVrt[oldMeshInd[i+1]].z*zScale);
             *      Vector3 p2 = new Vector3(oldMeshVrt[oldMeshInd[i+2]].x*xScale, oldMeshVrt[oldMeshInd[i+2]].y*yScale, oldMeshVrt[oldMeshInd[i+2]].z*zScale);
             *
             *      float t = triangleIntersection(p0, p1, p2, dir, orig); //check every face
             *
             *      //if(smallest_inter.t == -1) smallest_inter = inter; //set smallest_inter to the first intersection
             *      if (dist < 0.0f){
             *              dist = t;
             *      }
             *      if(dist > t && t > 0) {
             *              dist = t;
             *              //smallest_inter = inter;
             *              //numOfIntersections++;  //only add to numOfIntersections if t != -1
             *      }
             *
             * }
             * if (dist != -1){
             *      local_vec += dist*(dir);
             *
             * }
             */

            RaycastHit hit;
            Ray        ray = new Ray(collider.transform.position, -1 * collider.transform.forward);
            if (Physics.Raycast(ray, out hit))
            {
                if (hit.rigidbody != null && hit.collider.gameObject.tag == "explode")
                {
                    local_vec = transform.InverseTransformPoint(hit.point);
                }
            }
            local_vec    = new Vector3(0, 0, 0);
            local_vec[0] = local_vec[0] * gameObject.transform.localScale.x;
            local_vec[1] = local_vec[1] * gameObject.transform.localScale.y;
            local_vec[2] = local_vec[2] * gameObject.transform.localScale.z;
            //DONE TRYING
            //local_vec += (vel * (-.1f));
            //GETTING INFO TO PASS TO OUR FUNCTION
            //Collider coll = collider.gameObject.GetComponent<Collider>();
            //Vector3 local_vec = coll.ClosestPointOnBounds(hitPoint);
            //local_vec = transform.InverseTransformPoint(local_vec);

            /*
             * Rigidbody rb = gameObject.GetComponent<Rigidbody>();
             * rb.constraints = RigidbodyConstraints.FreezeAll;
             * Rigidbody rb1 = collider.gameObject.GetComponent<Rigidbody>();
             * rb1.constraints = RigidbodyConstraints.FreezeAll;
             */
            //CALL AND INPUT NEW FRAGMENTED CELLS
            //NEW STUFF BEGINS
            //int NumberOfVertices = 24;

            //int run = voroCubeExample();
            Mesh mesh = new Mesh();
            //int numberOfMeshes = numNewMesh();

            //int numberOfMeshes = voroCubeExample (local_vec.x, local_vec.y, local_vec.z);
            //int numberOfMeshes = voroCubeExample (local_vec.x*2, local_vec.y*2, local_vec.z*2);
            //float num = voroGeoDecomp(local_vec.x, local_vec.y, local_vec.z, oldMeshInd, oldVrts);
            //fixed (int* data = &oldMeshInd[0]);
            IntPtr initIndArray = Marshal.AllocHGlobal(oldMeshInd.Length * sizeof(int));
            IntPtr initVrtArray = Marshal.AllocHGlobal(oldVrts.Length * sizeof(float));
            //IntPtr allocIndArray = Marshal.AllocHGlobal (sizeof(int)*4);
            //Marshal.WriteInt32(initIndArray, allocIndArray.ToInt32 ());
            //Marshal.WriteInt32 (initIndArray + 4, allocIndArray.ToInt32 () + 2*sizeof(int));
            Marshal.Copy(oldMeshInd, 0, initIndArray, oldMeshInd.Length);
            Marshal.Copy(oldVrts, 0, initVrtArray, oldVrts.Length);
            //float mag = collider.relativeVelocity.magnitude;
            int numParticles = 100;            //(int)Mathf.Floor(mag*2);
            //Marshal.Copy (
            float numberOfMeshes = voroGeoDecomp(local_vec.x, local_vec.y, local_vec.z, initIndArray, initVrtArray, oldMeshInd.Length, oldVrts.Length, numParticles);
            Debug.Log(numberOfMeshes);
            Marshal.FreeHGlobal(initIndArray);
            Marshal.FreeHGlobal(initVrtArray);


            float[] verts;             //= new float[72];
            bool    inLoop = false;
            //bool run = false;

            ConvexHull <Vertex3, Face3> convexHull;
            for (int r = 0; r < numberOfMeshes; r++)
            {
                //int numberOfVertices = numVertices(r);

                int otherNumber = voroGetNumCellVerts(r);
                if (otherNumber == 0)
                {
                    continue;
                }
                int numberOfVertices = otherNumber * 3;
                verts = new float[numberOfVertices];
                //mesh = new Mesh();
                mesh.Clear();

                //outPutMesh (verts, oldMeshInd, oldMeshVrt, r);
                voroGetCellVertices(verts, ref r, ref inLoop);

                /*
                 * Vector3 p0 = new Vector3(-.5f,.5f,-.5f);
                 * Vector3 p1 = new Vector3(.5f,.5f,-.5f);
                 * Vector3 p2 = new Vector3(0.5f, 0.5f, 0.5f);
                 * Vector3 p3 = new Vector3(-0.5f, 0.5f, 0.5f);
                 * Vector3 p4 = new Vector3(-0.5f, -0.5f, -0.5f);
                 * Vector3 p5 = new Vector3(0.5f, -0.5f, -0.5f);
                 * Vector3 p6 = new Vector3(0.5f, -0.5f, 0.5f);
                 * Vector3 p7 = new Vector3(-0.5f, -0.5f, 0.5f);
                 * Vector3 p8 = new Vector3 (.5f, 1, .5f);
                 */

                int       NumberOfVertices = (verts.Length / 3);
                Vertex3[] vertices         = new Vertex3[NumberOfVertices];
                Vector3[] meshVerts        = new Vector3[NumberOfVertices];
                int[]     meshIndices      = new int[NumberOfVertices];

                int m = 0;
                //Vector3[] vert2;
                Vector3[] vert = new Vector3[NumberOfVertices];
                for (int j = 0; j < verts.Length; j += 3)
                {
                    vert[m] = new Vector3(verts[j], verts[j + 1], verts[j + 2]);
                    m++;
                }
                //vert = new Vector3[]{p4,p5,p6,p7,p8};//,p1,p5,p4,p1,p5,p6,p2,p2,p3,p7,p6,p3,p0,p4,p7,p4,p5,p6,p7};
                int i = 0;
                while (i < NumberOfVertices)
                {
                    Vector3 v = vert[i];                     //new Vector3(Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f));

                    if (mode == MODE.CUBE_VOLUME)
                    {
                        vertices[i]    = new Vertex3(v.x, v.y, v.z);
                        meshVerts[i]   = vert[i];                       //vertices[i].ToVector3();
                        meshIndices[i] = i;

                        i++;
                    }
                    else if (mode == MODE.SPHERE_VOLUME)
                    {
                        if (v.magnitude < 1.0f)
                        {
                            vertices[i]    = new Vertex3(v.x, v.y, v.z);
                            meshVerts[i]   = vertices[i].ToVector3();
                            meshIndices[i] = i;

                            i++;
                        }
                    }
                    else if (mode == MODE.SPHERE_SURFACE)
                    {
                        v.Normalize();

                        vertices[i]    = new Vertex3(v.x, v.y, v.z);
                        meshVerts[i]   = vertices[i].ToVector3();
                        meshIndices[i] = i;

                        i++;
                    }
                }

                mesh.vertices = meshVerts;
                mesh.SetIndices(meshIndices, MeshTopology.Points, 0);
                //mesh.bounds = new Bounds(Vector3.zero, new Vector3((float)size,(float)size,(float)size));

                float now = Time.realtimeSinceStartup;
                convexHull = ConvexHull.Create <Vertex3, Face3>(vertices);
                float interval = Time.realtimeSinceStartup - now;

                convexHullVertices = new List <Vertex3>(convexHull.Points);
                convexHullFaces    = new List <Face3>(convexHull.Faces);
                convexHullIndices  = new List <int>();

                foreach (Face3 f in convexHullFaces)
                {
                    convexHullIndices.Add(convexHullVertices.IndexOf(f.Vertices[0]));
                    convexHullIndices.Add(convexHullVertices.IndexOf(f.Vertices[1]));
                    convexHullIndices.Add(convexHullVertices.IndexOf(f.Vertices[2]));
                }
                //Debug.Log ("There are " + convexHullFaces.Count + " faces in this convex hull.");
                //Debug.Log("Out of the " + NumberOfVertices + " vertices, there are " + convexHullVertices.Count + " verts on the convex hull.");
                //Debug.Log("time = " + interval * 1000.0f + " ms");



                //NEW STUFF ENDS

                GameObject frag = Instantiate(fragment, gameObject.transform.position, gameObject.transform.rotation) as GameObject;
                Cell       s    = frag.gameObject.AddComponent <Cell>();
                //frag.gameObject.AddComponent<Rigidbody>();
                MeshFilter meshFilter = gameObject.GetComponent <MeshFilter>();
                meshFilter.mesh = new Mesh();
                Vector3[] vrts;
                vrts = new Vector3[convexHullVertices.Count];
                for (i = 0; i < convexHullVertices.Count; i++)
                {
                    vrts[i] = new Vector3((float)convexHullVertices[i].x, (float)convexHullVertices[i].y, (float)convexHullVertices[i].z);
                }
                s.VerticesArray = vrts;
                int[] inds;
                inds = new int[convexHullIndices.Count];
                for (i = 0; i < convexHullIndices.Count; i++)
                {
                    inds[i] = convexHullIndices[i];
                }
                s.IndicesArray = inds;
                Renderer rend = gameObject.GetComponent <Renderer>();
                s.life     = lifetime + 1;
                s.material = rend.material;
                s.Build();
            }

            Destroy(gameObject);
            //Destroy (collider.gameObject);
            //Rigidbody rg = gameObject.GetComponent<Rigidbody>();
            //rg.constraints = RigidbodyConstraints.FreezeAll;
            //collider.gameObject.transform.position = Transform.localtoWorl(local_vec);
            //collider.rigidbody.constraints = RigidbodyConstraints.FreezeAll;
        }
    }
コード例 #26
0
        public static RWSection[] CreateBSPFile(string FileNameForBox, ModelConverterData data, bool useTristrips, bool flipUVs)
        {
            Vertex3 Max = new Vertex3(data.VertexList[0].Position.X, data.VertexList[0].Position.Y, data.VertexList[0].Position.Z);
            Vertex3 Min = new Vertex3(data.VertexList[0].Position.X, data.VertexList[0].Position.Y, data.VertexList[0].Position.Z);

            foreach (Vertex i in data.VertexList)
            {
                if (i.Position.X > Max.X)
                {
                    Max.X = i.Position.X;
                }
                if (i.Position.Y > Max.Y)
                {
                    Max.Y = i.Position.Y;
                }
                if (i.Position.Z > Max.Z)
                {
                    Max.Z = i.Position.Z;
                }
                if (i.Position.X < Min.X)
                {
                    Min.X = i.Position.X;
                }
                if (i.Position.Y < Min.Y)
                {
                    Min.Y = i.Position.Y;
                }
                if (i.Position.Z < Min.Z)
                {
                    Min.Z = i.Position.Z;
                }
            }

            List <Vertex3> vList = new List <Vertex3>(data.VertexList.Count);

            foreach (Vertex v in data.VertexList)
            {
                vList.Add(new Vertex3(v.Position.X, v.Position.Y, v.Position.Z));
            }

            List <Color> cList = new List <Color>(data.VertexList.Count);

            foreach (Vertex v in data.VertexList)
            {
                cList.Add(new Color(v.Color.R, v.Color.G, v.Color.B, v.Color.A));
            }

            List <Vertex2> uvList = new List <Vertex2>(data.VertexList.Count);

            if (flipUVs)
            {
                foreach (Vertex v in data.VertexList)
                {
                    uvList.Add(new Vertex2(v.TexCoord.X, v.TexCoord.Y));
                }
            }
            else
            {
                foreach (Vertex v in data.VertexList)
                {
                    uvList.Add(new Vertex2(v.TexCoord.X, -v.TexCoord.Y));
                }
            }

            List <RenderWareFile.Triangle> tList = new List <RenderWareFile.Triangle>(data.TriangleList.Count);

            foreach (Triangle t in data.TriangleList)
            {
                tList.Add(new RenderWareFile.Triangle((ushort)t.MaterialIndex, (ushort)t.vertex1, (ushort)t.vertex2, (ushort)t.vertex3));
            }

            List <BinMesh> binMeshList = new List <BinMesh>();
            int            TotalNumberOfTristripIndicies = 0;

            if (useTristrips) // tristrip generator
            {
                for (int i = 0; i < data.MaterialList.Count; i++)
                {
                    List <Triangle> TriangleStream2 = new List <Triangle>();
                    foreach (Triangle f in data.TriangleList)
                    {
                        if (f.MaterialIndex == i)
                        {
                            TriangleStream2.Add(f);
                        }
                    }

                    List <List <int> > indexLists = GenerateTristrips(TriangleStream2);

                    foreach (List <int> indices in indexLists)
                    {
                        TotalNumberOfTristripIndicies += indices.Count();
                        binMeshList.Add(new BinMesh()
                        {
                            materialIndex = i,
                            indexCount    = indices.Count(),
                            vertexIndices = indices.ToArray()
                        });
                    }
                }
            }
            else //trilist generator
            {
                for (int i = 0; i < data.MaterialList.Count; i++)
                {
                    List <int> indices = new List <int>();
                    foreach (Triangle f in data.TriangleList)
                    {
                        if (f.MaterialIndex == i)
                        {
                            indices.Add(f.vertex1);
                            indices.Add(f.vertex2);
                            indices.Add(f.vertex3);
                        }
                    }
                    TotalNumberOfTristripIndicies += indices.Count();

                    binMeshList.Add(new BinMesh
                    {
                        materialIndex = i,
                        indexCount    = indices.Count(),
                        vertexIndices = indices.ToArray()
                    });
                }
            }

            WorldFlags worldFlags = WorldFlags.HasOneSetOfTextCoords | WorldFlags.HasVertexColors | WorldFlags.WorldSectorsOverlap | (WorldFlags)0x00010000;

            if (useTristrips)
            {
                worldFlags |= WorldFlags.UseTriangleStrips;
            }

            World_000B world = new World_000B()
            {
                worldStruct = new WorldStruct_0001()
                {
                    rootIsWorldSector = 1,
                    inverseOrigin     = new Vertex3(-0f, -0f, -0f),
                    numTriangles      = (uint)data.TriangleList.Count(),
                    numVertices       = (uint)data.VertexList.Count(),
                    numPlaneSectors   = 0,
                    numAtomicSectors  = 1,
                    colSectorSize     = 0,
                    worldFlags        = worldFlags,
                    boxMaximum        = Max,
                    boxMinimum        = Min,
                },

                materialList = new MaterialList_0008()
                {
                    materialListStruct = new MaterialListStruct_0001()
                    {
                        materialCount = data.MaterialList.Count()
                    },
                    materialList = new Material_0007[data.MaterialList.Count()]
                },

                firstWorldChunk = new AtomicSector_0009()
                {
                    atomicSectorStruct = new AtomicSectorStruct_0001()
                    {
                        matListWindowBase = 0,
                        numTriangles      = data.TriangleList.Count(),
                        numVertices       = data.VertexList.Count(),
                        boxMaximum        = Max,
                        boxMinimum        = Min,
                        collSectorPresent = 0x2F50D984,
                        unused            = 0,
                        vertexArray       = vList.ToArray(),
                        colorArray        = cList.ToArray(),
                        uvArray           = uvList.ToArray(),
                        triangleArray     = tList.ToArray()
                    },
                    atomicSectorExtension = new Extension_0003()
                    {
                        extensionSectionList = new List <RWSection>()
                        {
                            new BinMeshPLG_050E()
                            {
                                binMeshHeaderFlags = useTristrips ? BinMeshHeaderFlags.TriangleStrip : BinMeshHeaderFlags.TriangleList,
                                numMeshes          = binMeshList.Count(),
                                totalIndexCount    = TotalNumberOfTristripIndicies,
                                binMeshList        = binMeshList.ToArray()
                            }
                        }
                    }
                },

                worldExtension = new Extension_0003()
            };

            for (int i = 0; i < data.MaterialList.Count; i++)
            {
                world.materialList.materialList[i] = new Material_0007()
                {
                    materialStruct = new MaterialStruct_0001()
                    {
                        unusedFlags = 0,
                        color       = new RenderWareFile.Color()
                        {
                            R = 0xFF, G = 0xFF, B = 0xFF, A = 0xFF
                        },
                        unusedInt2 = 0x2DF53E84,
                        isTextured = 1,
                        ambient    = 1f,
                        specular   = 1f,
                        diffuse    = 1f
                    },
                    texture = new Texture_0006()
                    {
                        textureStruct = new TextureStruct_0001()
                        {
                            filterMode   = TextureFilterMode.FILTERLINEAR,
                            addressModeU = TextureAddressMode.TEXTUREADDRESSWRAP,
                            addressModeV = TextureAddressMode.TEXTUREADDRESSWRAP,
                            useMipLevels = 1
                        },
                        diffuseTextureName = new String_0002()
                        {
                            stringString = data.MaterialList[i]
                        },
                        alphaTextureName = new String_0002()
                        {
                            stringString = ""
                        },
                        textureExtension = new Extension_0003()
                    },
                    materialExtension = new Extension_0003(),
                };
            }

            return(new RWSection[] { world });
        }
コード例 #27
0
ファイル: Joint.cs プロジェクト: rjabaker/Skynet
 public Joint(JointType jointType, Vertex3 position)
 {
     this.jointType = jointType;
     this.position = position;
 }
コード例 #28
0
        static Vertex3[] OnPointCloud(int Count, Vertex3[] Verts, FrameData[] Frames)
        {
            if (Verts == null)
            {
                if (VertsArr == null || VertsArr.Length < Count)
                {
                    VertsArr = new Vertex3[Count];

                    lock (Lck)
                        Points = new Vertex3[Count];
                }

                return(VertsArr);
            }

            FrameData Clr = Frames[1];

            lock (Lck) {
                Vector3 CamPos = OptotrakClient.GetPos();
                OptotrakClient.GetRotationAngles(out float Yaw, out float Pitch, out float Roll);
                Matrix4x4 TransMat = Matrix4x4.CreateFromYawPitchRoll(Yaw, Pitch + (float)Math.PI, -Roll) * OptotrakClient.GetTranslation();
                PointCount = 0;

                fixed(Vertex3 *PointsPtr = Points)
                Util.MemSet(new IntPtr(PointsPtr), 0, Points.Length * sizeof(Vertex3));

                //Voxels.SetVoxel(0, 0, 0, new VoxelEntry(VoxelType.Solid));

                //Voxels.Fill(new VoxelEntry(VoxelType.Solid));
                Voxels.Fill(VoxelEntry.Empty);

                for (int i = 0, j = 0; i < Count; i++)
                {
                    if (Verts[i].Position == Vector3.Zero)
                    {
                        continue;
                    }

                    Vertex3 Vert = Verts[i];
                    Vert.Position = Vector3.Transform((Vert.Position * 1000), TransMat);

                    if (Vector3.Distance(CamPos, Vert.Position) < 500)
                    {
                        continue;
                    }

                    Vert.Color  = Clr.GetPixel(Vert.UV, false);
                    Points[j++] = Vert;
                    PointCount++;

                    Vector3 WorldPos = Vert.Position + Program.WorldOrigin;

                    /*Voxels.Cast(CamPos, WorldPos, (X, Y, Z) => {
                     *      Voxels.SetVoxel(X, Y, Z, new VoxelEntry(VoxelType.None));
                     * });*/

                    Voxels.SetVoxel(WorldPos, new VoxelEntry(VoxelType.Solid, Vert.Color));
                }

                RightLegCollides = !Voxels.Ray(LegClient.R_Start, LegClient.R_End, (X, Y, Z) => {
                    if (Voxels.IsSolid(X, Y, Z))
                    {
                        return(false);
                    }

                    Voxels.SetVoxel(X, Y, Z, new VoxelEntry(VoxelType.NonSolid, RightLegCollides ? Color.Red : Color.Green));
                    return(true);
                });

                LeftLegCollides = !Voxels.Ray(LegClient.L_Start, LegClient.L_End, (X, Y, Z) => {
                    if (Voxels.IsSolid(X, Y, Z))
                    {
                        return(false);
                    }

                    Voxels.SetVoxel(X, Y, Z, new VoxelEntry(VoxelType.NonSolid, LeftLegCollides ? Color.Red : Color.Green));
                    return(true);
                });

                if (!Program.MarkDirtyAuto)
                {
                    Voxels.MarkDirty();
                }
            }

            return(null);
        }
コード例 #29
0
 public float Distance(Vertex3 v)
 {
     return(length(StoredPosition - v.StoredPosition));
 }
コード例 #30
0
ファイル: Mouse.cs プロジェクト: Ruin0x11/RSEQEditor
        private void GetVertex(ModelPanel panel, MouseEventArgs e, float depth, ModelPanelViewport v)
        {
            //Try targeting a vertex
            if (RenderVertices)
            {
                if (panel.CurrentViewport.Selecting)
                {
                    if (NotCtrlAlt)
                    {
                        ClearSelectedVertices();
                    }

                    bool selected = false;
                    if (TargetModel != null)
                    {
                        if (TargetModel.SelectedObjectIndex < 0)
                        {
                            foreach (IObject o in TargetModel.Objects)
                            {
                                if (o.IsRendering)
                                {
                                    SelectVertices(o, panel);
                                    selected = true;
                                }
                            }
                        }
                        else
                        {
                            IObject w = TargetModel.Objects[TargetModel.SelectedObjectIndex];
                            if (w.IsRendering)
                            {
                                SelectVertices(w, panel);
                                selected = true;
                            }
                            else
                            {
                                foreach (IObject h in TargetModel.Objects)
                                {
                                    if (h.IsRendering)
                                    {
                                        SelectVertices(h, panel);
                                        selected = true;
                                    }
                                }
                            }
                        }
                    }
                    else if (_targetModels != null)
                    {
                        foreach (IModel m in _targetModels)
                        {
                            if (m.SelectedObjectIndex < 0)
                            {
                                foreach (IObject o in m.Objects)
                                {
                                    if (o.IsRendering)
                                    {
                                        SelectVertices(o, panel);
                                        selected = true;
                                    }
                                }
                            }
                            else
                            {
                                IObject w = m.Objects[m.SelectedObjectIndex];
                                if (w.IsRendering)
                                {
                                    SelectVertices(w, panel);
                                    selected = true;
                                }
                                else
                                {
                                    foreach (IObject h in m.Objects)
                                    {
                                        if (h.IsRendering)
                                        {
                                            SelectVertices(h, panel);
                                            selected = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (selected)
                    {
                        OnSelectedVerticesChanged();
                    }
                }
                else
                {
                    if (depth < 1.0f && _targetModel != null)
                    {
                        Vector3 point  = v.UnProject(e.X, e.Y, depth);
                        Vertex3 vertex = CompareVertexDistance(point);
                        bool    update = false;
                        if (_hiVertex != null && !_hiVertex._selected)
                        {
                            update = true;
                            _hiVertex._highlightColor = Color.Transparent;
                            ModelPanel.CurrentViewport.AllowSelection = true;
                        }
                        if ((_hiVertex = vertex) != null)
                        {
                            update = true;
                            _hiVertex._highlightColor = Color.Orange;
                            panel.Cursor = Cursors.Cross;
                            ModelPanel.CurrentViewport.AllowSelection = false;
                        }
                        if (update)
                        {
                            panel.Invalidate();
                        }
                    }
                    else if (_hiVertex != null)
                    {
                        if (!_hiVertex._selected)
                        {
                            _hiVertex._highlightColor = Color.Transparent;
                            ModelPanel.CurrentViewport.AllowSelection = true;
                            panel.Invalidate();
                        }
                        _hiVertex = null;
                    }
                }
            }
        }
コード例 #31
0
        //Only updates single-bind vertices and objects!
        //Influences using this bone must be handled separately
        private void InfluenceAssets(bool influence)
        {
            Matrix m = influence ? InverseBindMatrix : BindMatrix;

            Matrix rm = m.GetRotationMatrix();

            foreach (IMatrixNodeUser user in Users)
            {
                if (user is MDL0ObjectNode)
                {
                    Vector3 *      pData = null;
                    MDL0ObjectNode o     = user as MDL0ObjectNode;

                    if (o._manager._faceData[1] != null)
                    {
                        pData = (Vector3 *)o._manager._faceData[1].Address;
                    }

                    foreach (Vertex3 v in o._manager._vertices)
                    {
                        v.Position *= m;

                        if (pData != null)
                        {
                            foreach (int i in v._faceDataIndices)
                            {
                                pData[i] *= rm;
                            }
                        }
                    }
                }
                else if (user is Vertex3)
                {
                    Vertex3        v = user as Vertex3;
                    MDL0ObjectNode o = v.Parent as MDL0ObjectNode;

                    v.Position *= m;

                    if (o._manager._faceData[1] != null)
                    {
                        Vector3 *pData = (Vector3 *)o._manager._faceData[1].Address;
                        foreach (int i in v._faceDataIndices)
                        {
                            pData[i] *= rm;
                        }
                    }
                }
            }
            foreach (MDL0ObjectNode o in _singleBindObjects)
            {
                Vector3 *pData = null;
                if (o._manager._faceData[1] != null)
                {
                    pData = (Vector3 *)o._manager._faceData[1].Address;
                }

                foreach (Vertex3 v in o._manager._vertices)
                {
                    v.Position *= m;

                    if (pData != null)
                    {
                        foreach (int i in v._faceDataIndices)
                        {
                            pData[i] *= rm;
                        }
                    }
                }
            }
        }
コード例 #32
0
        public static RWSection[] CreateBSPFromAssimp(string fileName, bool flipUVs)
        {
            PostProcessSteps pps =
                PostProcessSteps.Debone | PostProcessSteps.FindInstances |
                PostProcessSteps.FindInvalidData | PostProcessSteps.OptimizeGraph |
                PostProcessSteps.OptimizeMeshes | PostProcessSteps.Triangulate |
                PostProcessSteps.PreTransformVertices;

            Scene scene = new AssimpContext().ImportFile(fileName, pps);

            int vertexCount   = scene.Meshes.Sum(m => m.VertexCount);
            int triangleCount = scene.Meshes.Sum(m => m.FaceCount);

            if (vertexCount > 65535 || triangleCount > 65536)
            {
                throw new ArgumentException("Model has too many vertices or triangles. Please import a simpler model.");
            }

            List <Vertex3> vertices                  = new List <Vertex3>(vertexCount);
            List <RenderWareFile.Color> vColors      = new List <RenderWareFile.Color>(vertexCount);
            List <Vertex2> textCoords                = new List <Vertex2>(vertexCount);
            List <RenderWareFile.Triangle> triangles = new List <RenderWareFile.Triangle>(triangleCount);

            int totalVertices = 0;

            foreach (var m in scene.Meshes)
            {
                foreach (Vector3D v in m.Vertices)
                {
                    vertices.Add(new Vertex3(v.X, v.Y, v.Z));
                }

                if (m.HasTextureCoords(0))
                {
                    foreach (Vector3D v in m.TextureCoordinateChannels[0])
                    {
                        textCoords.Add(new Vertex2(v.X, flipUVs ? -v.Y : v.Y));
                    }
                }
                else
                {
                    for (int i = 0; i < m.VertexCount; i++)
                    {
                        textCoords.Add(new Vertex2());
                    }
                }

                if (m.HasVertexColors(0))
                {
                    foreach (Color4D c in m.VertexColorChannels[0])
                    {
                        vColors.Add(new RenderWareFile.Color(
                                        (byte)(c.R * 255),
                                        (byte)(c.G * 255),
                                        (byte)(c.B * 255),
                                        (byte)(c.A * 255)));
                    }
                }
                else
                {
                    for (int i = 0; i < m.VertexCount; i++)
                    {
                        vColors.Add(new RenderWareFile.Color(255, 255, 255, 255));
                    }
                }

                foreach (var t in m.Faces)
                {
                    triangles.Add(new RenderWareFile.Triangle()
                    {
                        vertex1       = (ushort)(t.Indices[0] + totalVertices),
                        vertex2       = (ushort)(t.Indices[1] + totalVertices),
                        vertex3       = (ushort)(t.Indices[2] + totalVertices),
                        materialIndex = (ushort)m.MaterialIndex
                    });
                }

                totalVertices += m.VertexCount;
            }

            if (vertices.Count != textCoords.Count || vertices.Count != vColors.Count)
            {
                throw new ArgumentException("Internal error: texture coordinate or vertex color count is different from vertex count.");
            }

            triangles = triangles.OrderBy(t => t.materialIndex).ToList();

            Vertex3 Max = new Vertex3(vertices[0].X, vertices[0].Y, vertices[0].Z);
            Vertex3 Min = new Vertex3(vertices[0].X, vertices[0].Y, vertices[0].Z);

            foreach (Vertex3 i in vertices)
            {
                if (i.X > Max.X)
                {
                    Max.X = i.X;
                }
                if (i.Y > Max.Y)
                {
                    Max.Y = i.Y;
                }
                if (i.Z > Max.Z)
                {
                    Max.Z = i.Z;
                }
                if (i.X < Min.X)
                {
                    Min.X = i.X;
                }
                if (i.Y < Min.Y)
                {
                    Min.Y = i.Y;
                }
                if (i.Z < Min.Z)
                {
                    Min.Z = i.Z;
                }
            }

            BinMesh[] binMeshes = new BinMesh[scene.MaterialCount];

            Material_0007[] materials = new Material_0007[scene.MaterialCount];

            for (int i = 0; i < scene.MaterialCount; i++)
            {
                List <int> indices = new List <int>(triangles.Count);
                foreach (RenderWareFile.Triangle f in triangles)
                {
                    if (f.materialIndex == i)
                    {
                        indices.Add(f.vertex1);
                        indices.Add(f.vertex2);
                        indices.Add(f.vertex3);
                    }
                }

                binMeshes[i] = new BinMesh()
                {
                    materialIndex = i,
                    indexCount    = indices.Count(),
                    vertexIndices = indices.ToArray()
                };

                materials[i] = new Material_0007()
                {
                    materialStruct = new MaterialStruct_0001()
                    {
                        unusedFlags = 0,
                        color       = new RenderWareFile.Color(
                            (byte)(scene.Materials[i].ColorDiffuse.R / 255),
                            (byte)(scene.Materials[i].ColorDiffuse.G / 255),
                            (byte)(scene.Materials[i].ColorDiffuse.B / 255),
                            (byte)(scene.Materials[i].ColorDiffuse.A / 255)),
                        unusedInt2 = 0x2DF53E84,
                        isTextured = scene.Materials[i].HasTextureDiffuse ? 1 : 0,
                        ambient    = 1f,
                        specular   = 1f,
                        diffuse    = 1f
                    },
                    texture = scene.Materials[i].HasTextureDiffuse ? new Texture_0006()
                    {
                        textureStruct = new TextureStruct_0001() // use wrap as default
                        {
                            filterMode = TextureFilterMode.FILTERLINEAR,

                            addressModeU =
                                scene.Materials[i].TextureDiffuse.WrapModeU == TextureWrapMode.Clamp ? TextureAddressMode.TEXTUREADDRESSCLAMP :
                                scene.Materials[i].TextureDiffuse.WrapModeU == TextureWrapMode.Decal ? TextureAddressMode.TEXTUREADDRESSBORDER :
                                scene.Materials[i].TextureDiffuse.WrapModeU == TextureWrapMode.Mirror ? TextureAddressMode.TEXTUREADDRESSMIRROR :
                                TextureAddressMode.TEXTUREADDRESSWRAP,

                            addressModeV =
                                scene.Materials[i].TextureDiffuse.WrapModeV == TextureWrapMode.Clamp ? TextureAddressMode.TEXTUREADDRESSCLAMP :
                                scene.Materials[i].TextureDiffuse.WrapModeV == TextureWrapMode.Decal ? TextureAddressMode.TEXTUREADDRESSBORDER :
                                scene.Materials[i].TextureDiffuse.WrapModeV == TextureWrapMode.Mirror ? TextureAddressMode.TEXTUREADDRESSMIRROR :
                                TextureAddressMode.TEXTUREADDRESSWRAP,

                            useMipLevels = 1
                        },
                        diffuseTextureName = new String_0002()
                        {
                            stringString = Path.GetFileNameWithoutExtension(scene.Materials[i].TextureDiffuse.FilePath)
                        },
                        alphaTextureName = new String_0002()
                        {
                            stringString = ""
                        },
                        textureExtension = new Extension_0003()
                    } : null,
                    materialExtension = new Extension_0003(),
                };
            }

            WorldFlags worldFlags = WorldFlags.HasOneSetOfTextCoords | WorldFlags.HasVertexColors | WorldFlags.WorldSectorsOverlap | (WorldFlags)0x00010000;

            World_000B world = new World_000B()
            {
                worldStruct = new WorldStruct_0001()
                {
                    rootIsWorldSector = 1,
                    inverseOrigin     = new Vertex3(-0f, -0f, -0f),
                    numTriangles      = (uint)triangleCount,
                    numVertices       = (uint)vertexCount,
                    numPlaneSectors   = 0,
                    numAtomicSectors  = 1,
                    colSectorSize     = 0,
                    worldFlags        = worldFlags,
                    boxMaximum        = Max,
                    boxMinimum        = Min,
                },

                materialList = new MaterialList_0008()
                {
                    materialListStruct = new MaterialListStruct_0001()
                    {
                        materialCount = scene.MaterialCount
                    },
                    materialList = materials
                },

                firstWorldChunk = new AtomicSector_0009()
                {
                    atomicSectorStruct = new AtomicSectorStruct_0001()
                    {
                        matListWindowBase = 0,
                        numTriangles      = triangleCount,
                        numVertices       = vertexCount,
                        boxMaximum        = Max,
                        boxMinimum        = Min,
                        collSectorPresent = 0x2F50D984,
                        unused            = 0,
                        vertexArray       = vertices.ToArray(),
                        colorArray        = vColors.ToArray(),
                        uvArray           = textCoords.ToArray(),
                        triangleArray     = triangles.ToArray()
                    },
                    atomicSectorExtension = new Extension_0003()
                    {
                        extensionSectionList = new List <RWSection>()
                        {
                            new BinMeshPLG_050E()
                            {
                                binMeshHeaderFlags = BinMeshHeaderFlags.TriangleList,
                                numMeshes          = binMeshes.Count(),
                                totalIndexCount    = binMeshes.Sum(b => b.indexCount),
                                binMeshList        = binMeshes
                            }
                        }
                    }
                },

                worldExtension = new Extension_0003()
            };

            return(new RWSection[] { world });
        }
コード例 #33
0
 public override double CalculateDistance(Vertex3 v)
 {
     throw new NotImplementedException();
 }
コード例 #34
0
 private void DrawLine(Vertex3 v0, Vertex3 v1)
 {
     GL.Vertex3(v0.X, v0.Y, v0.Z);
     GL.Vertex3(v1.X, v1.Y, v1.Z);
 }
コード例 #35
0
    // Use this for initialization
    void Start()
    {
        CreateLineMaterial();

        mesh = new Mesh();
        Vertex3[] vertices    = new Vertex3[NumberOfVertices];
        Vector3[] meshVerts   = new Vector3[NumberOfVertices];
        int[]     meshIndices = new int[NumberOfVertices];

        Random.seed = 0;
        int i = 0;

        while (i < NumberOfVertices)
        {
            Vector3 v = new Vector3(Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f));

            if (mode == MODE.CUBE_VOLUME)
            {
                vertices[i]    = new Vertex3(size * v.x, size * v.y, size * v.z);
                meshVerts[i]   = vertices[i].ToVector3();
                meshIndices[i] = i;

                i++;
            }
            else if (mode == MODE.SPHERE_VOLUME)
            {
                if (v.magnitude < 1.0f)
                {
                    vertices[i]    = new Vertex3(size * v.x, size * v.y, size * v.z);
                    meshVerts[i]   = vertices[i].ToVector3();
                    meshIndices[i] = i;

                    i++;
                }
            }
            else if (mode == MODE.SPHERE_SURFACE)
            {
                v.Normalize();

                vertices[i]    = new Vertex3(size * v.x, size * v.y, size * v.z);
                meshVerts[i]   = vertices[i].ToVector3();
                meshIndices[i] = i;

                i++;
            }
        }

        mesh.vertices = meshVerts;
        mesh.SetIndices(meshIndices, MeshTopology.Points, 0);
        //mesh.bounds = new Bounds(Vector3.zero, new Vector3((float)size,(float)size,(float)size));

        float now = Time.realtimeSinceStartup;
        ConvexHull <Vertex3, Face3> convexHull = ConvexHull.Create <Vertex3, Face3>(vertices);
        float interval = Time.realtimeSinceStartup - now;

        convexHullVertices = new List <Vertex3>(convexHull.Points);
        convexHullFaces    = new List <Face3>(convexHull.Faces);
        convexHullIndices  = new List <int>();

        foreach (Face3 f in convexHullFaces)
        {
            convexHullIndices.Add(convexHullVertices.IndexOf(f.Vertices[0]));
            convexHullIndices.Add(convexHullVertices.IndexOf(f.Vertices[1]));
            convexHullIndices.Add(convexHullVertices.IndexOf(f.Vertices[2]));
        }

        Debug.Log("Out of the " + NumberOfVertices + " vertices, there are " + convexHullVertices.Count + " verts on the convex hull.");
        Debug.Log("time = " + interval * 1000.0f + " ms");
    }
コード例 #36
0
ファイル: Mouse.cs プロジェクト: 0000duck/brawltools
        public void HighlightStuff(MouseEventArgs e)
        {
            ModelPanel.Cursor = Cursors.Default;
            float depth = ModelPanel.GetDepth(e.X, e.Y);

            _hiX = _hiY = _hiZ = _hiCirc = _hiSphere = false;

            MDL0BoneNode bone = SelectedBone;
            //Vertex3 vertex = TargetVertex;
            MDL0ObjectNode poly = leftPanel.SelectedPolygon;

            if (bone != null)
            {
                //Get the location of the bone
                Vector3 center = BoneLoc;

                //Standard radius scaling snippet. This is used for orb scaling depending on camera distance.
                float radius = center.TrueDistance(ModelPanel._camera.GetPoint()) / _orbRadius * 0.1f;

                if (_editType == TransformType.Rotation)
                {
                    //Get point projected onto our orb.
                    Vector3 point = ModelPanel.ProjectCameraSphere(new Vector2(e.X, e.Y), center, radius, false);

                    //Get the distance of the mouse point from the bone
                    float distance = point.TrueDistance(center);

                    if (Math.Abs(distance - radius) < (radius * _selectOrbScale)) //Point lies within orb radius
                    {
                        _hiSphere = true;

                        //Determine axis snapping
                        Vector3 angles = (bone._inverseFrameMatrix * point).GetAngles() * Maths._rad2degf;
                        angles._x = (float)Math.Abs(angles._x);
                        angles._y = (float)Math.Abs(angles._y);
                        angles._z = (float)Math.Abs(angles._z);

                        if (Math.Abs(angles._y - 90.0f) <= _axisSnapRange)
                        {
                            _hiX = true;
                        }
                        else if (angles._x >= (180 - _axisSnapRange) || angles._x <= _axisSnapRange)
                        {
                            _hiY = true;
                        }
                        else if (angles._y >= (180 - _axisSnapRange) || angles._y <= _axisSnapRange)
                        {
                            _hiZ = true;
                        }
                    }
                    else if (Math.Abs(distance - (radius * _circOrbScale)) < (radius * _selectOrbScale)) //Point lies on circ line
                    {
                        _hiCirc = true;
                    }

                    if (_hiX || _hiY || _hiZ || _hiCirc)
                    {
                        ModelPanel.Cursor = Cursors.Hand;
                    }
                }
                else if (_editType == TransformType.Translation)
                {
                    Vector3 point = ModelPanel.UnProject(e.X, e.Y, depth);
                    Vector3 diff  = (point - center) / radius;

                    float halfDist = _axisHalfLDist;
                    if (diff._x > -_axisSelectRange && diff._x < (_axisLDist + 0.01f) &&
                        diff._y > -_axisSelectRange && diff._y < (_axisLDist + 0.01f) &&
                        diff._z > -_axisSelectRange && diff._z < (_axisLDist + 0.01f))
                    {
                        //Point lies within axes
                        if (diff._x < halfDist && diff._y < halfDist && diff._z < halfDist)
                        {
                            //Point lies inside the double drag areas
                            if (diff._x > _axisSelectRange)
                            {
                                _hiX = true;
                            }
                            if (diff._y > _axisSelectRange)
                            {
                                _hiY = true;
                            }
                            if (diff._z > _axisSelectRange)
                            {
                                _hiZ = true;
                            }

                            ModelPanel.Cursor = Cursors.Hand;
                        }
                        else
                        {
                            //Check if point lies on a specific axis
                            float errorRange = _axisSelectRange;

                            if (diff._x > halfDist && Math.Abs(diff._y) < errorRange && Math.Abs(diff._z) < errorRange)
                            {
                                _hiX = true;
                            }
                            if (diff._y > halfDist && Math.Abs(diff._x) < errorRange && Math.Abs(diff._z) < errorRange)
                            {
                                _hiY = true;
                            }
                            if (diff._z > halfDist && Math.Abs(diff._x) < errorRange && Math.Abs(diff._y) < errorRange)
                            {
                                _hiZ = true;
                            }

                            if (!_hiX && !_hiY && !_hiZ)
                            {
                                goto GetBone;
                            }
                            else
                            {
                                ModelPanel.Cursor = Cursors.Hand;
                            }
                        }
                    }
                    else
                    {
                        goto GetBone;
                    }
                }
                else if (_editType == TransformType.Scale)
                {
                    Vector3 point = ModelPanel.UnProject(e.X, e.Y, depth);
                    Vector3 diff  = (point - center) / radius;

                    if (diff._x > -_axisSelectRange && diff._x < (_axisLDist + 0.01f) &&
                        diff._y > -_axisSelectRange && diff._y < (_axisLDist + 0.01f) &&
                        diff._z > -_axisSelectRange && diff._z < (_axisLDist + 0.01f))
                    {
                        //Point lies within axes

                        //Check if point lies on a specific axis first
                        float errorRange = _axisSelectRange;

                        if (diff._x > errorRange && Math.Abs(diff._y) < errorRange && Math.Abs(diff._z) < errorRange)
                        {
                            _hiX = true;
                        }
                        if (diff._y > errorRange && Math.Abs(diff._x) < errorRange && Math.Abs(diff._z) < errorRange)
                        {
                            _hiY = true;
                        }
                        if (diff._z > errorRange && Math.Abs(diff._x) < errorRange && Math.Abs(diff._y) < errorRange)
                        {
                            _hiZ = true;
                        }

                        if (!_hiX && !_hiY && !_hiZ)
                        {
                            //Determine if the point is in the double or triple drag triangles
                            float halfDist   = _scaleHalf2LDist;
                            float centerDist = _scaleHalf1LDist;
                            if (IsInTriangle(diff, new Vector3(), new Vector3(halfDist, 0, 0), new Vector3(0, halfDist, 0)))
                            {
                                if (IsInTriangle(diff, new Vector3(), new Vector3(centerDist, 0, 0), new Vector3(0, centerDist, 0)))
                                {
                                    _hiX = _hiY = _hiZ = true;
                                }
                                else
                                {
                                    _hiX = _hiY = true;
                                }
                            }
                            else if (IsInTriangle(diff, new Vector3(), new Vector3(halfDist, 0, 0), new Vector3(0, 0, halfDist)))
                            {
                                if (IsInTriangle(diff, new Vector3(), new Vector3(centerDist, 0, 0), new Vector3(0, 0, centerDist)))
                                {
                                    _hiX = _hiY = _hiZ = true;
                                }
                                else
                                {
                                    _hiX = _hiZ = true;
                                }
                            }
                            else if (IsInTriangle(diff, new Vector3(), new Vector3(0, halfDist, 0), new Vector3(0, 0, halfDist)))
                            {
                                if (IsInTriangle(diff, new Vector3(), new Vector3(0, centerDist, 0), new Vector3(0, 0, centerDist)))
                                {
                                    _hiX = _hiY = _hiZ = true;
                                }
                                else
                                {
                                    _hiY = _hiZ = true;
                                }
                            }

                            if (!_hiX && !_hiY && !_hiZ)
                            {
                                goto GetBone;
                            }
                            else
                            {
                                ModelPanel.Cursor = Cursors.Hand;
                            }
                        }
                        else
                        {
                            ModelPanel.Cursor = Cursors.Hand;
                        }
                    }
                    else
                    {
                        goto GetBone;
                    }
                }
            }

            //modelPanel1.Invalidate();

GetBone:

            //Try selecting new bone
            //if (modelPanel._selecting)
            //{

            //}
            //else
            {
                if (!(_scaling || _rotating || _translating) && (depth < 1.0f) && (_targetModel != null) && (_targetModel._boneList != null))
                {
                    MDL0BoneNode o = null;

                    Vector3 point = ModelPanel.UnProject(e.X, e.Y, depth);

                    //Find orb near chosen point
                    if (_editingAll)
                    {
                        foreach (MDL0Node m in _targetModels)
                        {
                            foreach (MDL0BoneNode b in m._boneList)
                            {
                                if (CompareDistanceRecursive(b, point, ref o))
                                {
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        foreach (MDL0BoneNode b in _targetModel._boneList)
                        {
                            if (CompareDistanceRecursive(b, point, ref o))
                            {
                                break;
                            }
                        }
                    }

                    if (_hiBone != null && _hiBone != SelectedBone)
                    {
                        _hiBone._nodeColor = Color.Transparent;
                    }

                    if ((_hiBone = o) != null)
                    {
                        _hiBone._nodeColor = Color.FromArgb(255, 128, 0);
                        ModelPanel.Cursor  = Cursors.Hand;
                    }
                }
                else if (_hiBone != null)
                {
                    if (_hiBone != SelectedBone)
                    {
                        _hiBone._nodeColor = Color.Transparent;
                    }
                    _hiBone = null;
                }
            }

            if (VertexLoc != null && RenderVertices)
            {
                //Get the location of the vertex
                Vector3 center = ((Vector3)VertexLoc);

                //Standard radius scaling snippet. This is used for orb scaling depending on camera distance.
                float radius = center.TrueDistance(ModelPanel._camera.GetPoint()) / _orbRadius * 0.1f;

                //if (_editType == TransformType.Rotation)
                //{
                //    //Get point projected onto our orb.
                //    Vector3 point = ModelPanel.ProjectCameraSphere(new Vector2(e.X, e.Y), center, radius, false);

                //    //Get the distance of the mouse point from the bone
                //    float distance = point.TrueDistance(center);

                //    if (Math.Abs(distance - radius) < (radius * _selectOrbScale)) //Point lies within orb radius
                //    {
                //        _hiSphere = true;

                //        //Determine axis snapping
                //        Vector3 angles = center.LookatAngles(point) * Maths._rad2degf;
                //        angles._x = (float)Math.Abs(angles._x);
                //        angles._y = (float)Math.Abs(angles._y);
                //        angles._z = (float)Math.Abs(angles._z);

                //        if (Math.Abs(angles._y - 90.0f) <= _axisSnapRange)
                //            _hiZ = true;
                //        else if (angles._x >= (180 - _axisSnapRange) || angles._x <= _axisSnapRange)
                //            _hiY = true;
                //        else if (angles._y >= (180 - _axisSnapRange) || angles._y <= _axisSnapRange)
                //            _hiX = true;
                //    }
                //    else if (Math.Abs(distance - (radius * _circOrbScale)) < (radius * _selectOrbScale)) //Point lies on circ line
                //        _hiCirc = true;

                //    if (_hiX || _hiY || _hiZ || _hiCirc)
                //        ModelPanel.Cursor = Cursors.Hand;
                //}
                //else if (_editType == TransformType.Translation)
                //{
                Vector3 point = ModelPanel.UnProject(e.X, e.Y, depth);
                Vector3 diff  = (point - center) / radius;

                float halfDist = _axisHalfLDist;
                if (diff._x > -_axisSelectRange && diff._x < (_axisLDist + 0.01f) &&
                    diff._y > -_axisSelectRange && diff._y < (_axisLDist + 0.01f) &&
                    diff._z > -_axisSelectRange && diff._z < (_axisLDist + 0.01f))
                {
                    //Point lies within axes
                    if (diff._x < halfDist && diff._y < halfDist && diff._z < halfDist)
                    {
                        //Point lies inside the double drag areas
                        if (diff._x > _axisSelectRange)
                        {
                            _hiX = true;
                        }
                        if (diff._y > _axisSelectRange)
                        {
                            _hiY = true;
                        }
                        if (diff._z > _axisSelectRange)
                        {
                            _hiZ = true;
                        }

                        ModelPanel.Cursor = Cursors.Hand;
                    }
                    else
                    {
                        //Check if point lies on a specific axis
                        float errorRange = _axisSelectRange;

                        if (diff._x > halfDist && Math.Abs(diff._y) < errorRange && Math.Abs(diff._z) < errorRange)
                        {
                            _hiX = true;
                        }
                        if (diff._y > halfDist && Math.Abs(diff._x) < errorRange && Math.Abs(diff._z) < errorRange)
                        {
                            _hiY = true;
                        }
                        if (diff._z > halfDist && Math.Abs(diff._x) < errorRange && Math.Abs(diff._y) < errorRange)
                        {
                            _hiZ = true;
                        }

                        if (!_hiX && !_hiY && !_hiZ)
                        {
                            goto GetVertex;
                        }
                        else
                        {
                            ModelPanel.Cursor = Cursors.Hand;
                        }
                    }
                }
                //}
            }

GetVertex:

            //Try targeting a vertex
            if (RenderVertices)
            {
                if (ModelPanel._selecting)
                {
                    if (NotCtrlAlt)
                    {
                        ResetVertexColors();
                    }

                    if (TargetModel._polyIndex == -1)
                    {
                        foreach (MDL0ObjectNode o in TargetModel._objList)
                        {
                            if (o._render)
                            {
                                SelectVerts(o);
                            }
                        }
                    }
                    else
                    {
                        MDL0ObjectNode w = (MDL0ObjectNode)TargetModel._objList[TargetModel._polyIndex];
                        if (w._render)
                        {
                            SelectVerts(w);
                        }
                        else
                        {
                            foreach (MDL0ObjectNode h in TargetModel._objList)
                            {
                                if (h._render)
                                {
                                    SelectVerts(h);
                                }
                            }
                        }
                    }
                }
                else
                {
                    Vector3 point = ModelPanel.UnProject(e.X, e.Y, depth);
                    if ((depth < 1.0f) && (_targetModel != null) && (_targetModel._objList != null))
                    {
                        Vertex3 v = null;

                        CompareVertexDistance(point, ref v);

                        if (_hiVertex != null && !_hiVertex._selected)
                        {
                            _hiVertex._highlightColor    = Color.Transparent;
                            ModelPanel._forceNoSelection = false;
                        }
                        if ((_hiVertex = v) != null)
                        {
                            _hiVertex._highlightColor    = Color.Orange;
                            ModelPanel.Cursor            = Cursors.Cross;
                            ModelPanel._forceNoSelection = true;
                        }
                    }
                    else if (_hiVertex != null)
                    {
                        if (!_hiVertex._selected)
                        {
                            _hiVertex._highlightColor    = Color.Transparent;
                            ModelPanel._forceNoSelection = false;
                        }
                        _hiVertex = null;
                    }
                }
            }

            ModelPanel.Invalidate();
        }
コード例 #37
0
        private static PrimitiveManager DecodePrimitivesUnweighted(Matrix bindMatrix, GeometryEntry geo)
        {
            PrimitiveManager manager = DecodePrimitives(geo);

            Vector3 *      pVert = null, pNorms = null;
            ushort *       pVInd    = (ushort *)manager._indices.Address;
            int            vCount   = 0;
            List <Vertex3> vertList = new List <Vertex3>(manager._pointCount);

            manager._vertices = vertList;

            if (manager._faceData[1] != null)
            {
                pNorms = (Vector3 *)manager._faceData[1].Address;
            }

            //Find vertex source
            foreach (SourceEntry s in geo._sources)
            {
                if (s._id == geo._verticesInput._source)
                {
                    UnsafeBuffer b = s._arrayData as UnsafeBuffer;
                    pVert  = (Vector3 *)b.Address;
                    vCount = b.Length / 12;
                    break;
                }
            }

            UnsafeBuffer remap  = new UnsafeBuffer(vCount * 2);
            ushort *     pRemap = (ushort *)remap.Address;

            //Create remap table
            for (int i = 0; i < vCount; i++)
            {
                //Create vertex and look for match
                Vertex3 v = new Vertex3(bindMatrix * pVert[i]);

                int index = 0;
                while (index < vertList.Count)
                {
                    if (v.Equals(vertList[index]))
                    {
                        break;
                    }

                    index++;
                }

                if (index == vertList.Count)
                {
                    vertList.Add(v);
                }

                pRemap[i] = (ushort)index;
            }

            //Remap vertex indices and fix normals
            for (int i = 0; i < manager._pointCount; i++, pVInd++)
            {
                *pVInd = pRemap[*pVInd];

                if (pNorms != null)
                {
                    pNorms[i] = bindMatrix.GetRotationMatrix() * pNorms[i];
                }
            }

            remap.Dispose();

            return(manager);
        }