示例#1
0
            //

            public Item(SubMesh subMesh)
            {
                this.subMesh = subMesh;

                subMesh.GetSomeGeometry(out positions, out indices);

                Bounds bounds = Bounds.Cleared;

                foreach (Vec3 pos in positions)
                {
                    bounds.Add(pos);
                }
                bounds.Expand(bounds.GetSize() * .001f);

                OctreeContainer.InitSettings initSettings = new OctreeContainer.InitSettings();
                initSettings.InitialOctreeBounds       = bounds;
                initSettings.OctreeBoundsRebuildExpand = Vec3.Zero;
                initSettings.MinNodeSize = bounds.GetSize() / 50;
                octreeContainer          = new OctreeContainer(initSettings);

                for (int nTriangle = 0; nTriangle < indices.Length / 3; nTriangle++)
                {
                    Vec3 vertex0 = positions[indices[nTriangle * 3 + 0]];
                    Vec3 vertex1 = positions[indices[nTriangle * 3 + 1]];
                    Vec3 vertex2 = positions[indices[nTriangle * 3 + 2]];

                    Bounds triangleBounds = new Bounds(vertex0);
                    triangleBounds.Add(vertex1);
                    triangleBounds.Add(vertex2);

                    int octreeIndex = octreeContainer.AddObject(triangleBounds, 1);
                }
            }
示例#2
0
        private Bounds CreateArrow(double minWidth, double minHeight)
        {
            var arrow         = new Bounds();
            var headThickness = minHeight / 3;
            var inset         = 0.8;
            var headLength    = minHeight;

            switch (direction)
            {
            case ReactionDirection.Forward:
            {
                var fp = new PathFigure();
                arrow.Add(new LineElement(new Point(0, 0), new Point(minWidth - 0.5 * headLength, 0), minHeight / 14, fgcol));
                fp.StartPoint = new Point(minWidth, 0);
                fp.Segments.Add(new LineSegment(new Point(minWidth - headLength, +headThickness), true));
                fp.Segments.Add(new LineSegment(new Point(minWidth - inset * headLength, 0), true));
                fp.Segments.Add(new LineSegment(new Point(minWidth - headLength, -headThickness), true));
                fp.IsClosed = true;
                var path = new PathGeometry(new[] { fp });
                arrow.Add(GeneralPath.ShapeOf(path, fgcol));
            }
            break;

            case ReactionDirection.Backward:
            {
                var fp = new PathFigure();
                arrow.Add(new LineElement(new Point(0.5 * headLength, 0), new Point(minWidth, 0), minHeight / 14, fgcol));
                fp.StartPoint = new Point(0, 0);
                fp.Segments.Add(new LineSegment(new Point(minHeight, +headThickness), true));
                fp.Segments.Add(new LineSegment(new Point(minHeight - (1 - inset) * minHeight, 0), true));
                fp.Segments.Add(new LineSegment(new Point(minHeight, -headThickness), true));
                fp.IsClosed = true;
                var path = new PathGeometry(new[] { fp });
                arrow.Add(GeneralPath.ShapeOf(path, fgcol));
            }
            break;

            case ReactionDirection.Bidirectional:     // equilibrium?
            {
                var fp1 = new PathFigure
                {
                    StartPoint = new Point(0, 0.5 * +headThickness)
                };
                fp1.Segments.Add(new LineSegment(new Point(minWidth + minHeight + minHeight, 0.5 * +headThickness), true));
                fp1.Segments.Add(new LineSegment(new Point(minWidth + minHeight, 1.5 * +headThickness), true));
                var fp2 = new PathFigure
                {
                    StartPoint = new Point(minWidth + minHeight + minHeight, 0.5 * -headThickness)
                };
                fp2.Segments.Add(new LineSegment(new Point(0, 0.5 * -headThickness), true));
                fp2.Segments.Add(new LineSegment(new Point(minHeight, 1.5 * -headThickness), true));
                var path = new PathGeometry(new[] { fp1, fp2 });
                arrow.Add(GeneralPath.OutlineOf(path, minHeight / 14, fgcol));
            }
            break;
            }

            return(arrow);
        }
示例#3
0
        public Triangle(Tuple p1, Tuple p2, Tuple p3)
        {
            P1 = p1;
            P2 = p2;
            P3 = p3;
            E1 = p2 - p1;
            E2 = p3 - p1;
            N  = (E2 * E1).Normalize();
            var box = new Bounds();

            box.Add(P1);
            box.Add(P2);
            box.Add(P3);
            Box = box;
        }
示例#4
0
 private void InitBounds(int widthBackdown, int heightUpBackdown, int heightDownBackdown)
 {
     Bounds.Add(MinWidth + widthBackdown);
     Bounds.Add(MaxWidth - widthBackdown);
     Bounds.Add(MinHeight + heightUpBackdown);
     Bounds.Add(MaxHeight - heightDownBackdown);
 }
示例#5
0
 public void addBounds(PictureBox[] bounds) // add bounds from an array of pic boxes
 {
     foreach (PictureBox pic in bounds)     // loop through boxes
     {
         Bounds.Add(pic);
     }
 }
        public override void GetGlobalBounds(out Bounds bounds)
        {
            Vec3 globalPos = Body.Position;
            Quat globalRot = Body.Rotation;

            if (!IsIdentityTransform)
            {
                globalPos += Body.Rotation * Position;
                globalRot *= Rotation;
            }
            Mat3 globalRotMat3;

            globalRot.ToMat3(out globalRotMat3);

            Vec3 axMat0 = halfDimensions.X * globalRotMat3.Item0;
            Vec3 axMat1 = halfDimensions.Y * globalRotMat3.Item1;
            Vec3 axMat2 = halfDimensions.Z * globalRotMat3.Item2;

            Vec3 temp0 = new Vec3(globalPos - axMat0);
            Vec3 temp1 = new Vec3(globalPos + axMat0);
            Vec3 temp2 = new Vec3(axMat1 - axMat2);
            Vec3 temp3 = new Vec3(axMat1 + axMat2);

            bounds = new Bounds(temp0 - temp3);
            bounds.Add(temp1 - temp3);
            bounds.Add(temp1 + temp2);
            bounds.Add(temp0 + temp2);
            bounds.Add(temp0 - temp2);
            bounds.Add(temp1 - temp2);
            bounds.Add(temp1 + temp3);
            bounds.Add(temp0 + temp3);
        }
示例#7
0
		static BBox3 ToSharpNav( Bounds v )
		{
			var min = new Vector3( v.Minimum.X, v.Minimum.Z, -v.Minimum.Y );
			var max = new Vector3( v.Maximum.X, v.Maximum.Z, -v.Maximum.Y );

			var b = new Bounds( min );
			b.Add( max );
			return new BBox3( (float)b.Minimum.X, (float)b.Minimum.Y, (float)b.Minimum.Z, (float)b.Maximum.X, (float)b.Maximum.Y, (float)b.Maximum.Z );
		}
示例#8
0
        public Triangle(Tuple p1, Tuple p2, Tuple p3)
        {
            P1  = p1;
            P2  = p2;
            P3  = p3;
            E1  = p2 - p1;
            E2  = p3 - p1;
            vP1 = new Vector3((float)P1.X, (float)P1.Y, (float)P1.Z);
            e1  = new Vector3((float)E1.X, (float)E1.Y, (float)E1.Z);
            e2  = new Vector3((float)E2.X, (float)E2.Y, (float)E2.Z);
            N   = (E2 * E1).Normalize();
            var box = new Bounds();

            box.Add(P1);
            box.Add(P2);
            box.Add(P3);
            Box = box;
        }
        protected override void OnCalculateMapBounds(ref Bounds bounds)
        {
            base.OnCalculateMapBounds(ref bounds);

            Bounds b = new Bounds(Position);

            b.Expand(new Vec3(.5f, .5f, .1f));
            bounds.Add(b);
        }
        public void AddBoxToBox()
        {
            var b1 = new Bounds {
                Min = Point(-5, -2, 0), Max = Point(7, 4, 4)
            };
            var b2 = new Bounds {
                Min = Point(8, -7, -2), Max = Point(14, 2, 8)
            };

            b1.Add(b2);
            Assert.AreEqual(b1.Max, Point(14, 4, 8));
            Assert.AreEqual(b1.Min, Point(-5, -7, -2));
        }
        public static Bounds GetSharpDXBoxBounds()
        {
            var vertexBuffer = GetSharpDXBoxVertexBuffer();

            var bounds = new Bounds();

            for (var i = 0; i < vertexBuffer.Length; i += 2)
            {
                bounds.Add(new Vector3(vertexBuffer[i].X, vertexBuffer[i].Y, vertexBuffer[i].Z));
            }

            return(bounds);
        }
示例#12
0
            public void Update(bool extraSurrounding)
            {
                ulong steamId;

                if (SteamId == null || !ulong.TryParse(SteamId, out steamId))
                {
                    throw new InvalidDataException(
                              $"The Steam ID ({SteamId ?? "NULL"}) for the zone '{Name}' is invalid.");
                }
                var identity = GameManager.Instance.GetIdentity(steamId);

                if (identity == null)
                {
                    throw new InvalidDataException($"Couldn't find the Identity for {SteamId} in the zone '{Name}'.");
                }
                if (MainCell <= 0)
                {
                    throw new InvalidDataException(
                              $"The Cell ({SteamId ?? "NULL"}) for the zone '{Name}' is invalid.");
                }
                var cluster = BuildConnectedOwnedCellCluster(identity, MainCell);

                Stakes.Clear();
                foreach (var cell in cluster)
                {
                    var stake = GetStakeOnCell(cell);
                    if (stake != null)
                    {
                        Stakes.Add(stake);
                    }
                }
                if (extraSurrounding)
                {
                    var surroundingCells = GetUniqueSurroundingUnownedCells(cluster);
                    foreach (var surroundingCell in surroundingCells)
                    {
                        cluster.Add(surroundingCell);
                    }
                }
                Bounds.Clear();
                AllCells.Clear();
                foreach (var cell in cluster)
                {
                    Bounds.Add(GetCellBounds(cell));
                    AllCells.Add(cell);
                }
            }
示例#13
0
        public void Read(Stream input, Endian endian = Endian.Little)
        {
            Index = input.ReadValueU16(endian);

            byte junctionsCount = input.ReadValueU8();

            for (int i = 0; i < junctionsCount; i++)
            {
                var junction = new RoadJunctionDe();
                junction.Read(input, endian);
                Junctions.Add(junction);
            }

            ushort boundsCount = input.ReadValueU16(endian);

            for (int i = 0; i < boundsCount; i++)
            {
                Bounds.Add(new Vector3(
                               input.ReadValueF32(endian),
                               input.ReadValueF32(endian),
                               input.ReadValueF32(endian)
                               ));
            }

            PivotPoint = new Vector3(
                input.ReadValueF32(endian),
                input.ReadValueF32(endian),
                input.ReadValueF32(endian)
                );

            ushort trafficLightSemaphoresCount = input.ReadValueU16(endian);

            ushort unkn4 = input.ReadValueU16(endian);

            if (unkn4 != 0)
            {
                throw new IOException($"Unexpected non-zero unkn4 value {unkn4}");
            }

            for (int i = 0; i < trafficLightSemaphoresCount; i++)
            {
                var semaphore = new TrafficLightSemaphoreDe();
                semaphore.Read(input, endian);
                TrafficLightSemaphores.Add(semaphore);
            }
        }
        Bounds GetTotalBoundsOfObjectInSpace()
        {
            Bounds total = NeoAxis.Bounds.Cleared;

            if (displayObject != null)
            {
                //if( createdObject.SpaceBounds.BoundingBox.HasValue )
                //	total.Add( createdObject.SpaceBounds.BoundingBox.Value );
                foreach (var obj in displayObject.GetComponents <Component_ObjectInSpace>(false, true))
                {
                    if (obj.SpaceBounds.BoundingBox.HasValue)
                    {
                        total.Add(obj.SpaceBounds.BoundingBox.Value);
                    }
                }
            }

            return(total);
        }
        private void SetInitBound(PhysicalTopology topo, double x1, double y1, double x2, double y2, double thicknessT, bool isRelative = true,
                                  double bottomHeightT = 0, bool isOnNormalArea = true, bool isOnAlarmArea = false, bool isOnLocationArea = false)
        {
            Bound      initBound = new Bound(x1, y1, x2, y2, bottomHeightT, thicknessT, isRelative);
            Bound      editBound = new Bound(x1, y1, x2, y2, bottomHeightT, thicknessT, isRelative);
            TransformM transfrom = new TransformM(initBound);

            Bounds.Add(initBound);
            Bounds.Add(editBound);
            transfrom.IsCreateAreaByData = isOnNormalArea;
            transfrom.IsOnAlarmArea      = isOnAlarmArea;
            transfrom.IsOnLocationArea   = isOnLocationArea;
            TransformMs.Add(transfrom);

            topo.Transfrom = transfrom;
            topo.InitBound = initBound;
            topo.EditBound = editBound;
            PhysicalTopologys.Edit(topo);
        }
示例#16
0
 internal override void ParseXml(XmlElement xml)
 {
     base.ParseXml(xml);
     foreach (XmlNode child in xml.ChildNodes)
     {
         string name = child.Name;
         if (string.Compare(name, "Bounds") == 0)
         {
             foreach (XmlNode cn in child.ChildNodes)
             {
                 IfcFaceBound f = mDatabase.ParseXml <IfcFaceBound>(cn as XmlElement);
                 if (f != null)
                 {
                     Bounds.Add(f);
                 }
             }
         }
     }
 }
示例#17
0
        public void Read(BinaryReader br, bool isMultiTexture)
        {
            var baseOffset = br.BaseStream.Position;

            Id = br.ReadUInt32();
            ushort mipsCount = br.ReadUInt16();

            Flags = (AlTextureEntryFlags)br.ReadByte();
            br.ReadByte(); // Alignment
            if (!isMultiTexture)
            {
                return;
            }

            for (int i = 0; i < mipsCount; ++i)
            {
                Bounds.Add(new AlXYWH
                {
                    X = br.ReadInt16(),
                    Y = br.ReadInt16(),
                    W = br.ReadUInt16(),
                    H = br.ReadUInt16()
                });
            }

            if ((Flags & AlTextureEntryFlags.IsHasCenterPoint) != 0)
            {
                CenterPoint = new AlPoint
                {
                    X = br.ReadInt16(),
                    Y = br.ReadInt16()
                };
            }

            if ((Flags & AlTextureEntryFlags.IsHasName) != 0)
            {
                br.BaseStream.Seek(baseOffset - 0x20, SeekOrigin.Begin);
                Name = StringReadingHelper.ReadNullTerminatedStringFromFixedSizeBlock(br, 0x20, Encoding.UTF8);
            }
        }
示例#18
0
        public void LoadFormatsFile(string filePath)
        {
            FormatsFile file = new FormatsFile(filePath);

            var versionNode = file.Root.Properties.FirstOrDefault(n => n.Name == "Version");

            if (!Formats.CheckVersion(versionNode, Type, Version))
            {
                return;
            }

            Locked    = Formats.GetBoolProperty(versionNode, "Locked");
            Skinned   = Formats.GetBoolProperty(versionNode, "Skinned");
            BoneCount = Formats.GetUshortProperty(versionNode, "BoneCount");
            Mask      = Formats.GetByteProperty(versionNode, "Mask");

            var boundsNode = versionNode.Properties.FirstOrDefault(n => n.Name == "Bounds");

            if (boundsNode != null)
            {
                foreach (var aabbNode in boundsNode.Properties)
                {
                    Aabb aabb = new Aabb();
                    aabb.LoadFormatsNode(aabbNode);
                    Bounds.Add(aabb);
                }
            }

            var geometriesNode = versionNode.Properties.FirstOrDefault(n => n.Name == "Geometries");

            if (geometriesNode != null)
            {
                foreach (var geometryNode in geometriesNode.Properties)
                {
                    Geometry geom = new Geometry();
                    geom.LoadFormatsNode(geometryNode);
                    Geometries.Add(geom);
                }
            }
        }
        private unsafe void UpdateGeometry()
        {
            DestroyGeometry();

            Curve positionCurve = GetPositionCurve();

            Curve radiusCurve = null;

            {
                bool existsSpecialRadius = false;
                foreach (MapCurvePoint point in Points)
                {
                    RenderableCurvePoint point2 = point as RenderableCurvePoint;
                    if (point2 != null && point2.OverrideRadius >= 0)
                    {
                        existsSpecialRadius = true;
                        break;
                    }
                }

                if (existsSpecialRadius)
                {
                    switch (radiusCurveType)
                    {
                    case RadiusCurveTypes.UniformCubicSpline:
                        radiusCurve = new UniformCubicSpline();
                        break;

                    case RadiusCurveTypes.Bezier:
                        radiusCurve = new BezierCurve();
                        break;

                    case RadiusCurveTypes.Line:
                        radiusCurve = new LineCurve();
                        break;
                    }

                    for (int n = 0; n < Points.Count; n++)
                    {
                        MapCurvePoint point = Points[n];

                        if (!point.Editor_IsExcludedFromWorld())
                        {
                            float rad = radius;
                            RenderableCurvePoint renderableCurvePoint = point as RenderableCurvePoint;
                            if (renderableCurvePoint != null && renderableCurvePoint.OverrideRadius >= 0)
                            {
                                rad = renderableCurvePoint.OverrideRadius;
                            }
                            radiusCurve.AddValue(point.Time, new Vec3(rad, 0, 0));
                        }
                    }
                }
            }

            //create mesh
            Vertex[] vertices = null;
            int[]    indices  = null;
            if (positionCurve != null && positionCurve.Values.Count > 1 && Points.Count >= 2)
            {
                Vec3 positionOffset = -Position;

                int steps       = (Points.Count - 1) * pathSteps + 1;
                int vertexCount = steps * (shapeSegments + 1);
                int indexCount  = (steps - 1) * shapeSegments * 2 * 3;

                vertices = new Vertex[vertexCount];
                indices  = new int[indexCount];

                //fill data
                {
                    int   currentVertex   = 0;
                    int   currentIndex    = 0;
                    float currentDistance = 0;
                    Vec3  lastPosition    = Vec3.Zero;
                    Quat  lastRot         = Quat.Identity;

                    for (int nStep = 0; nStep < steps; nStep++)
                    {
                        int startStepVertexIndex = currentVertex;

                        float coefficient = (float)nStep / (float)(steps - 1);
                        Vec3  pos         = CalculateCurvePointByCoefficient(coefficient) + positionOffset;

                        Quat rot;
                        {
                            Vec3 v = CalculateCurvePointByCoefficient(coefficient + .3f / (float)(steps - 1)) -
                                     CalculateCurvePointByCoefficient(coefficient);
                            if (v != Vec3.Zero)
                            {
                                rot = Quat.FromDirectionZAxisUp(v.GetNormalize());
                            }
                            else
                            {
                                rot = lastRot;
                            }
                        }

                        if (nStep != 0)
                        {
                            currentDistance += (pos - lastPosition).Length();
                        }

                        float rad;
                        if (radiusCurve != null)
                        {
                            Range range = new Range(radiusCurve.Times[0], radiusCurve.Times[radiusCurve.Times.Count - 1]);
                            float t     = range.Minimum + (range.Maximum - range.Minimum) * coefficient;
                            rad = radiusCurve.CalculateValueByTime(t).X;
                        }
                        else
                        {
                            rad = radius;
                        }

                        for (int nSegment = 0; nSegment < shapeSegments + 1; nSegment++)
                        {
                            float rotateCoefficient = ((float)nSegment / (float)(shapeSegments));
                            float angle             = rotateCoefficient * MathFunctions.PI * 2;
                            Vec3  p = pos + rot * new Vec3(0, MathFunctions.Cos(angle) * rad, MathFunctions.Sin(angle) * rad);

                            Vertex vertex = new Vertex();
                            vertex.position = p;
                            Vec3 pp = p - pos;
                            if (pp != Vec3.Zero)
                            {
                                vertex.normal = pp.GetNormalize();
                            }
                            else
                            {
                                vertex.normal = Vec3.XAxis;
                            }
                            //vertex.normal = ( p - pos ).GetNormalize();
                            vertex.texCoord           = new Vec2(currentDistance * textureCoordinatesTilesPerMeter, rotateCoefficient + .25f);
                            vertex.tangent            = new Vec4(rot.GetForward(), 1);
                            vertices[currentVertex++] = vertex;
                        }

                        if (nStep < steps - 1)
                        {
                            for (int nSegment = 0; nSegment < shapeSegments; nSegment++)
                            {
                                indices[currentIndex++] = startStepVertexIndex + nSegment;
                                indices[currentIndex++] = startStepVertexIndex + nSegment + 1;
                                indices[currentIndex++] = startStepVertexIndex + nSegment + 1 + shapeSegments + 1;
                                indices[currentIndex++] = startStepVertexIndex + nSegment + 1 + shapeSegments + 1;
                                indices[currentIndex++] = startStepVertexIndex + nSegment + shapeSegments + 1;
                                indices[currentIndex++] = startStepVertexIndex + nSegment;
                            }
                        }

                        lastPosition = pos;
                        lastRot      = rot;
                    }
                    if (currentVertex != vertexCount)
                    {
                        Log.Fatal("RenderableCurve: UpdateRenderingGeometry: currentVertex != vertexCount.");
                    }
                    if (currentIndex != indexCount)
                    {
                        Log.Fatal("RenderableCurve: UpdateRenderingGeometry: currentIndex != indexCount.");
                    }
                }

                if (vertices.Length != 0 && indices.Length != 0)
                {
                    //create mesh
                    string meshName = MeshManager.Instance.GetUniqueName(
                        string.Format("__RenderableCurve_{0}_{1}", Name, uniqueMeshIdentifier));
                    uniqueMeshIdentifier++;
                    //string meshName = MeshManager.Instance.GetUniqueName( string.Format( "__RenderableCurve_{0}", Name ) );
                    mesh = MeshManager.Instance.CreateManual(meshName);
                    SubMesh subMesh = mesh.CreateSubMesh();
                    subMesh.UseSharedVertices = false;

                    //init vertexData
                    VertexDeclaration declaration = subMesh.VertexData.VertexDeclaration;
                    declaration.AddElement(0, 0, VertexElementType.Float3, VertexElementSemantic.Position);
                    declaration.AddElement(0, 12, VertexElementType.Float3, VertexElementSemantic.Normal);
                    declaration.AddElement(0, 24, VertexElementType.Float2, VertexElementSemantic.TextureCoordinates, 0);
                    declaration.AddElement(0, 32, VertexElementType.Float4, VertexElementSemantic.Tangent, 0);

                    fixed(Vertex *pVertices = vertices)
                    {
                        subMesh.VertexData = VertexData.CreateFromArray(declaration, (IntPtr)pVertices,
                                                                        vertices.Length * Marshal.SizeOf(typeof(Vertex)));
                    }

                    subMesh.IndexData = IndexData.CreateFromArray(indices, 0, indices.Length, false);

                    //set material
                    subMesh.MaterialName = materialName;

                    //set mesh gabarites
                    Bounds bounds = Bounds.Cleared;
                    foreach (Vertex vertex in vertices)
                    {
                        bounds.Add(vertex.position);
                    }
                    mesh.SetBoundsAndRadius(bounds, bounds.GetRadius());
                }
            }

            //create MeshObject, SceneNode
            if (mesh != null)
            {
                meshObject = SceneManager.Instance.CreateMeshObject(mesh.Name);
                if (meshObject != null)
                {
                    meshObject.SetMaterialNameForAllSubObjects(materialName);
                    meshObject.CastShadows = true;

                    sceneNode = new SceneNode();
                    sceneNode.Attach(meshObject);
                    //apply offset
                    sceneNode.Position = Position;
                    MapObject.AssociateSceneNodeWithMapObject(sceneNode, this);
                }
            }

            //create collision body
            if (mesh != null && collision)
            {
                Vec3[] positions = new Vec3[vertices.Length];
                for (int n = 0; n < vertices.Length; n++)
                {
                    positions[n] = vertices[n].position;
                }
                string meshPhysicsMeshName = PhysicsWorld.Instance.AddCustomMeshGeometry(positions, indices, null,
                                                                                         MeshShape.MeshTypes.TriangleMesh, 0, 0);

                collisionBody                   = PhysicsWorld.Instance.CreateBody();
                collisionBody.Static            = true;
                collisionBody._InternalUserData = this;
                collisionBody.Position          = Position;

                MeshShape shape = collisionBody.CreateMeshShape();
                shape.MeshName     = meshPhysicsMeshName;
                shape.MaterialName = CollisionMaterialName;
                shape.ContactGroup = (int)ContactGroup.Collision;
                //shape.VehicleDrivableSurface = collisionVehicleDrivableSurface;

                collisionBody.PushedToWorld = true;
            }

            needUpdate = false;
        }
        private void CreateMesh()
        {
            Vec3 size = new Vec3(.97f, .97f, .1f);

            Vec3[] positions;
            Vec3[] normals;
            int[]  indices;
            GeometryGenerator.GenerateBox(size, out positions, out normals, out indices);

            string meshName = MeshManager.Instance.GetUniqueName(
                string.Format("JigsawPuzzlePiece[{0},{1}]", index.X, index.Y));

            mesh = MeshManager.Instance.CreateManual(meshName);

            //create submesh
            SubMesh subMesh = mesh.CreateSubMesh();

            subMesh.UseSharedVertices = false;

            //init VertexData
            VertexDeclaration declaration = subMesh.VertexData.VertexDeclaration;

            declaration.AddElement(0, 0, VertexElementType.Float3, VertexElementSemantic.Position);
            declaration.AddElement(0, 12, VertexElementType.Float3, VertexElementSemantic.Normal);
            declaration.AddElement(0, 24, VertexElementType.Float2,
                                   VertexElementSemantic.TextureCoordinates, 0);

            VertexBufferBinding  bufferBinding = subMesh.VertexData.VertexBufferBinding;
            HardwareVertexBuffer vertexBuffer  = HardwareBufferManager.Instance.CreateVertexBuffer(
                32, positions.Length, HardwareBuffer.Usage.StaticWriteOnly);

            bufferBinding.SetBinding(0, vertexBuffer, true);

            subMesh.VertexData.VertexCount = positions.Length;

            unsafe
            {
                Vertex *buffer = (Vertex *)vertexBuffer.Lock(HardwareBuffer.LockOptions.Normal);

                for (int n = 0; n < positions.Length; n++)
                {
                    Vertex vertex = new Vertex();
                    vertex.position = positions[n];
                    vertex.normal   = normals[n];

                    if (JigsawPuzzleManager.Instance != null)
                    {
                        Vec2I pieceCount = JigsawPuzzleManager.Instance.PieceCount;

                        Vec2I i = index;
                        if (vertex.position.X > 0)
                        {
                            i.X++;
                        }
                        if (vertex.position.Y > 0)
                        {
                            i.Y++;
                        }

                        vertex.texCoord = new Vec2(
                            (float)i.X / (float)pieceCount.X,
                            1.0f - (float)i.Y / (float)pieceCount.Y);
                    }

                    *buffer = vertex;
                    buffer++;
                }

                vertexBuffer.Unlock();
            }

            //calculate mesh bounds
            Bounds bounds = Bounds.Cleared;
            float  radius = 0;

            foreach (Vec3 position in positions)
            {
                bounds.Add(position);
                float r = position.Length();
                if (r > radius)
                {
                    radius = r;
                }
            }
            mesh.SetBoundsAndRadius(bounds, radius);

            //init IndexData
            subMesh.IndexData = IndexData.CreateFromArray(indices, 0, indices.Length, false);

            //init material
            subMesh.MaterialName = "JigsawPuzzleImage";
        }
示例#21
0
        protected override void OnCalculateMapBounds( ref Bounds bounds )
        {
            base.OnCalculateMapBounds( ref bounds );

            Bounds b = new Bounds( Position );
            b.Expand( new Vec3( .5f, .5f, .1f ) );
            bounds.Add( b );
        }
示例#22
0
 protected override void OnCalculateMapBounds( ref Bounds bounds )
 {
     base.OnCalculateMapBounds( ref bounds );
     bounds.Add( GetBox().ToBounds() );
 }
示例#23
0
文件: Tank.cs 项目: whztt07/SDK
        protected override void OnCalculateMapBounds( ref Bounds bounds )
        {
            base.OnCalculateMapBounds( ref bounds );

            //add gun bounds to the tank
            if( MainGun != null )
                bounds.Add( MainGun.MapBounds );
        }
示例#24
0
        public override void Update(GameTime gameTime)
        {
            if (!(Game as Main).Started)
            {
                return;
            }

            var dt = (float)gameTime.ElapsedGameTime.TotalSeconds;

            var keys = Keyboard.GetState().GetPressedKeys();

            if (Arma.Municao <= 0)
            {
                Arma = new CanhaoSimples();
            }

            if (keys.Contains(Keys.Up))
            {
                Animation.Start();
                Inercia -= Direcao * dt * Aceleracao;
            }
            else if (keys.Contains(Keys.Down))
            {
                Inercia += Direcao * dt * Aceleracao / 5;
            }
            else
            {
                Animation.Stop().SelectIndex(6);
            }

            Animation.Update(gameTime);

            if (keys.Contains(Keys.Right))
            {
                Direcao = Direcao.Rotate(0.1f);
            }
            else if (keys.Contains(Keys.Left))
            {
                Direcao = Direcao.Rotate(-0.1f);
            }

            if (Posicao.X > Game.Window.ClientBounds.Width)
            {
                Posicao = new Vector2(0, Posicao.Y);
            }
            if (Posicao.X < 0)
            {
                Posicao = new Vector2(Game.Window.ClientBounds.Width, Posicao.Y);
            }

            if (Posicao.Y > Game.Window.ClientBounds.Height)
            {
                Posicao = new Vector2(Posicao.X, 0);
            }
            if (Posicao.Y < 0)
            {
                Posicao = new Vector2(Posicao.X, Game.Window.ClientBounds.Height);
            }

            var angle = -Direcao.Angle();

            Bounds.Clear();

            Bounds.Add(Posicao);
            Bounds.Add(new Vector2(Posicao.X, Posicao.Y - Animation.Source.Height / 2).Rotate(angle, Posicao));
            Bounds.Add(new Vector2(Posicao.X - Animation.Source.Width / 2 + 5, Posicao.Y - Animation.Source.Height / 2 + 5).Rotate(angle, Posicao));
            Bounds.Add(new Vector2(Posicao.X + Animation.Source.Width / 2 - 5, Posicao.Y - Animation.Source.Height / 2 + 5).Rotate(angle, Posicao));


            if (Keyboard.GetState().IsKeyDown(Keys.Space))
            {
                Arma.Atira(Game, gameTime, new [] { Bounds[2], Bounds[3] }, -Direcao);
            }

            if (Keyboard.GetState().IsKeyUp(Keys.Space))
            {
                Arma.Reset();
            }

            Posicao += Inercia;

            var meteoros = Game.Components.OfType <Meteoro>();

            // if (meteoros.Any(p => p.Contem(Bounds)))
            //     (Game as Main).End();
        }
            //
            public Item( SubMesh subMesh )
            {
                this.subMesh = subMesh;

                subMesh.GetSomeGeometry( out positions, out indices );

                Bounds bounds = Bounds.Cleared;
                foreach( Vec3 pos in positions )
                    bounds.Add( pos );
                bounds.Expand( bounds.GetSize() * .001f );

                OctreeContainer.InitSettings initSettings = new OctreeContainer.InitSettings();
                initSettings.InitialOctreeBounds = bounds;
                initSettings.OctreeBoundsRebuildExpand = Vec3.Zero;
                initSettings.MinNodeSize = bounds.GetSize() / 50;
                octreeContainer = new OctreeContainer( initSettings );

                for( int nTriangle = 0; nTriangle < indices.Length / 3; nTriangle++ )
                {
                    Vec3 vertex0 = positions[ indices[ nTriangle * 3 + 0 ] ];
                    Vec3 vertex1 = positions[ indices[ nTriangle * 3 + 1 ] ];
                    Vec3 vertex2 = positions[ indices[ nTriangle * 3 + 2 ] ];

                    Bounds triangleBounds = new Bounds( vertex0 );
                    triangleBounds.Add( vertex1 );
                    triangleBounds.Add( vertex2 );

                    int octreeIndex = octreeContainer.AddObject( triangleBounds, 1 );
                }
            }
示例#26
0
        void CreateDecal()
        {
            Bounds bounds = Bounds.Cleared;

            foreach (Vertex vertex in vertices)
            {
                bounds.Add(vertex.position);
            }

            VertexData vertexData = new VertexData();
            IndexData  indexData  = new IndexData();

            //init vertexData
            VertexDeclaration declaration = vertexData.VertexDeclaration;

            declaration.AddElement(0, 0, VertexElementType.Float3, VertexElementSemantic.Position);
            declaration.AddElement(0, 12, VertexElementType.Float3, VertexElementSemantic.Normal);
            declaration.AddElement(0, 24, VertexElementType.Float2,
                                   VertexElementSemantic.TextureCoordinates, 0);
            declaration.AddElement(0, 32, VertexElementType.Float3, VertexElementSemantic.Tangent);

            VertexBufferBinding  bufferBinding = vertexData.VertexBufferBinding;
            HardwareVertexBuffer vertexBuffer  = HardwareBufferManager.Instance.CreateVertexBuffer(
                44, vertices.Length, HardwareBuffer.Usage.StaticWriteOnly);

            bufferBinding.SetBinding(0, vertexBuffer, true);
            vertexData.VertexCount = vertices.Length;

            //init indexData
            Trace.Assert(vertices.Length < 65536, "Decal: vertices.Length < 65536");

            HardwareIndexBuffer indexBuffer = HardwareBufferManager.Instance.CreateIndexBuffer(
                HardwareIndexBuffer.IndexType._16Bit, indices.Length,
                HardwareBuffer.Usage.StaticWriteOnly);

            indexData.SetIndexBuffer(indexBuffer, true);
            indexData.IndexCount = indices.Length;

            //init material
            Material material = null;

            shaderBaseMaterial = HighLevelMaterialManager.Instance.
                                 GetMaterialByName(sourceMaterialName) as ShaderBaseMaterial;
            //only default shader technique for ShaderBase material
            if (shaderBaseMaterial != null && !shaderBaseMaterial.IsDefaultTechniqueCreated())
            {
                shaderBaseMaterial = null;
            }

            if (shaderBaseMaterial != null)
            {
                //ShaderBase material
                material = shaderBaseMaterial.BaseMaterial;
            }
            else
            {
                //standard material or fallback ShaderBase technique
                Material sourceMaterial = MaterialManager.Instance.GetByName(sourceMaterialName);
                if (sourceMaterial != null)
                {
                    //clone standard material
                    clonedStandardMaterial = MaterialManager.Instance.Clone(sourceMaterial,
                                                                            MaterialManager.Instance.GetUniqueName(sourceMaterialName + "_Cloned"));
                    material = clonedStandardMaterial;
                }
            }

            staticMeshObject = SceneManager.Instance.CreateStaticMeshObject(bounds + Position,
                                                                            Position, Quat.Identity, new Vec3(1, 1, 1), true, material, vertexData, indexData, true);
            staticMeshObject.AddToRenderQueue += StaticMeshObject_AddToRenderQueue;

            UpdateBuffers();
        }
示例#27
0
 /// <summary>Overridden from <see cref="Engine.MapSystem.MapObject.OnCalculateMapBounds(ref Bounds)"/>.</summary>
 protected override void OnCalculateMapBounds(ref Bounds bounds)
 {
     base.OnCalculateMapBounds(ref bounds);
     bounds.Add(GetBox().ToBounds());
 }
示例#28
0
        void GenerateGrid()
        {
            ClearGrid();

            if (FreezeObjectsArea.Instances.Count != 0)
            {
                //init grid
                {
                    Bounds bounds = Bounds.Cleared;
                    foreach (FreezeObjectsArea area in FreezeObjectsArea.Instances)
                    {
                        bounds.Add(area.MapBounds);
                    }
                    if (bounds.GetSize().X < 1)
                    {
                        bounds.Expand(new Vec3(1, 0, 0));
                    }
                    if (bounds.GetSize().Y < 1)
                    {
                        bounds.Expand(new Vec3(0, 1, 0));
                    }
                    if (bounds.GetSize().Z < 1)
                    {
                        bounds.Expand(new Vec3(0, 0, 1));
                    }

                    gridStartPosition = bounds.Minimum;

                    gridCellSize = bounds.GetSize() / cellCount.ToVec3();
                    for (int n = 0; n < 3; n++)
                    {
                        if (gridCellSize[n] < cellMinSize[n])
                        {
                            gridCellSize[n] = cellMinSize[n];
                        }
                    }
                    gridCellSizeInv = 1.0f / gridCellSize;
                    grid            = new GridItem[cellCount.X, cellCount.Y, cellCount.Z];
                }

                //fill areas

                GridAreasIndexByListOfAreasKey        comparer = new GridAreasIndexByListOfAreasKey();
                Dictionary <FreezeObjectsArea[], int> gridAreasIndexByListOfAreas = new Dictionary <FreezeObjectsArea[], int>(comparer);
                List <FreezeObjectsArea> gridAreasList = new List <FreezeObjectsArea>();

                foreach (FreezeObjectsArea area in FreezeObjectsArea.Instances)
                {
                    Box    box    = area.GetBox();
                    Bounds bounds = box.ToBounds();

                    Vec3I startIndex = GetCellIndexWithoutClamp(bounds.Minimum);
                    Vec3I endIndex   = GetCellIndexWithoutClamp(bounds.Maximum);
                    ClampCellIndex(ref startIndex);
                    ClampCellIndex(ref endIndex);

                    for (int z = startIndex.Z; z <= endIndex.Z; z++)
                    {
                        for (int y = startIndex.Y; y <= endIndex.Y; y++)
                        {
                            for (int x = startIndex.X; x <= endIndex.X; x++)
                            {
                                Vec3I  cellIndex  = new Vec3I(x, y, z);
                                Bounds cellBounds = GetCellBounds(cellIndex);
                                if (box.IsIntersectsBounds(cellBounds))
                                {
                                    GridItem item = grid[cellIndex.X, cellIndex.Y, cellIndex.Z];

                                    FreezeObjectsArea[] array = new FreezeObjectsArea[item.count + 1];
                                    for (int n = 0; n < item.count; n++)
                                    {
                                        array[n] = gridAreas[item.startIndex + n];
                                    }
                                    array[array.Length - 1] = area;

                                    int gridAreasIndex;
                                    if (!gridAreasIndexByListOfAreas.TryGetValue(array, out gridAreasIndex))
                                    {
                                        gridAreasIndex = gridAreasList.Count;

                                        gridAreasIndexByListOfAreas.Add(array, gridAreasIndex);
                                        gridAreasList.AddRange(array);
                                    }

                                    item.startIndex = gridAreasIndex;
                                    item.count      = array.Length;
                                    grid[cellIndex.X, cellIndex.Y, cellIndex.Z] = item;
                                }
                            }
                        }
                    }

                    gridAreas = gridAreasList.ToArray();
                }
            }
        }
示例#29
0
        private static void Awake_On(HooksCore.RoR2.SceneInfo.Awake.Orig orig, RoR2.SceneInfo self)
        {
            orig(self);
            var initMode = GarbageCollector.GCMode;

            GarbageCollector.GCMode = GarbageCollector.Mode.Disabled;
            var initMemory = GC.GetTotalMemory(false);

            var timer    = new Stopwatch();
            var initTime = new TimeDif(timer);
            var tempTime = new TimeDif(timer);


            Bounds origBounds = default;

            if (self.groundNodes.nodes != null && self.airNodes.nodes != null)
            {
                timer.Start();
                origBounds = Util.initBounds;
                for (Int32 i = 0; i < self.groundNodes.nodes.Length; ++i)
                {
                    var before = origBounds;
                    origBounds.Add(self.groundNodes.nodes[i].position);
                    var after = origBounds;
                    if (before != after)
                    {
                        if (after.IsNaN())
                        {
                            Log.Fatal(before);
                            Log.Fatal(self.groundNodes.nodes[i].position);
                            Log.Fatal(after);
                        }
                    }
                }
                for (Int32 i = 0; i < self.airNodes.nodes.Length; ++i)
                {
                    origBounds.Add(self.airNodes.nodes[i].position);
                }

                timer.Stop();
                Log.Warning($"Getting original node bounds: {timer.TimeSince(ref tempTime)}");
            }


            Log.Error("Getting geometry");
            timer.Start();
            using var geometry = new SceneGeometry(self, origBounds);
            timer.Stop();
            Log.Warning($"Geometry get: {timer.TimeSince(ref tempTime)}");

            Log.Error("Starting bake");

            Log.Error("Ground");
            BakeGround(self, timer, geometry);


            //Log.Warning("Air");
            //BakeAir(self, timer, geometry);
            //Log.Warning($"Total ticks: {timer.ElapsedTicks}");

            var endMemory = GC.GetTotalMemory(false);

            GarbageCollector.GCMode = GarbageCollector.Mode.Enabled;
            GC.Collect();
            GarbageCollector.GCMode = initMode;
            Log.Warning($"Total time: {timer.TimeSince(ref initTime)}");
            Log.Warning($"Allocation: {(((Double)endMemory - (Double)initMemory)/1024.0) / 1024.0} mb");

            RoR2Console.instance.SubmitCmd(NetworkUser.localPlayers[0], "debug_scene_draw_nodegraph 1 ground human");
        }
示例#30
0
        public override void GetGlobalBounds( out Bounds bounds )
        {
            Vec3 globalPos = Body.Position;
            Quat globalRot = Body.Rotation;
            if( !IsIdentityTransform )
            {
                globalPos += Body.Rotation * Position;
                globalRot *= Rotation;
            }
            Mat3 globalRotMat3;
            globalRot.ToMat3( out globalRotMat3 );

            Vec3 axMat0 = halfDimensions.X * globalRotMat3.Item0;
            Vec3 axMat1 = halfDimensions.Y * globalRotMat3.Item1;
            Vec3 axMat2 = halfDimensions.Z * globalRotMat3.Item2;

            Vec3 temp0 = new Vec3( globalPos - axMat0 );
            Vec3 temp1 = new Vec3( globalPos + axMat0 );
            Vec3 temp2 = new Vec3( axMat1 - axMat2 );
            Vec3 temp3 = new Vec3( axMat1 + axMat2 );

            bounds = new Bounds( temp0 - temp3 );
            bounds.Add( temp1 - temp3 );
            bounds.Add( temp1 + temp2 );
            bounds.Add( temp0 + temp2 );
            bounds.Add( temp0 - temp2 );
            bounds.Add( temp1 - temp2 );
            bounds.Add( temp1 + temp3 );
            bounds.Add( temp0 + temp3 );
        }