Beispiel #1
0
        private void DrawAllModels(IEffectMatrices effect)
        {
            foreach (var entity in ActiveEntities)
            {
                if (_modelMapper.Has(entity))
                {
                    var model     = _modelMapper.Get(entity).Model;
                    var transform = _transformMapper.Get(entity);

                    if (model.VertexBuffer != null && model.IndexBuffer != null & model.PrimitiveCount != 0)
                    {
                        var sphere = BoundingSphere.CreateFromBoundingBox(model.BoundingBox);

                        if (CameraSystem.ActiveLens.BoundingFrustum.Intersects(sphere.Transform(transform.WorldMatrix)))
                        {
                            effect.World = transform.WorldMatrix;
                            DrawMesh((Effect)effect, model, _graphicsDevice);
                        }
                    }
                }
                else if (_primitiveMapper.Has(entity))
                {
                    var primitive = _primitiveMapper.Get(entity);
                    var transform = _transformMapper.Get(entity);

                    effect.World = transform.WorldMatrix;
                    Primitives.Instance.Draw((Effect)effect, primitive.Type);
                }
            }
        }
Beispiel #2
0
        private void UpdateLightMatrixForDirectionalLight(Camera camera, IList <DrawableElement> shadowCasters)
        {
            var directionNormalized = Vector3.Normalize(Direction);
            var lightViewMatrix     = Matrix.CreateLookAt(Vector3.Zero, Direction, Vector3.Up);

            var mergedBox = new BoundingBox();

            for (var i = 0; i < shadowCasters.Count; i++)
            {
                var drawableElement = shadowCasters[i];
                mergedBox = BoundingBox.CreateMerged(mergedBox, drawableElement.BoundingBox);
            }
            var sphere = BoundingSphere.CreateFromBoundingBox(mergedBox);

            var edges = new Vector3[8];

            edges[0] = Vector3.Transform(new Vector3(mergedBox.Min.X, mergedBox.Min.Y, mergedBox.Min.Z), lightViewMatrix);
            edges[1] = Vector3.Transform(new Vector3(mergedBox.Max.X, mergedBox.Min.Y, mergedBox.Min.Z), lightViewMatrix);
            edges[2] = Vector3.Transform(new Vector3(mergedBox.Min.X, mergedBox.Min.Y, mergedBox.Max.Z), lightViewMatrix);
            edges[3] = Vector3.Transform(new Vector3(mergedBox.Max.X, mergedBox.Min.Y, mergedBox.Max.Z), lightViewMatrix);
            edges[4] = Vector3.Transform(new Vector3(mergedBox.Min.X, mergedBox.Max.Y, mergedBox.Min.Z), lightViewMatrix);
            edges[5] = Vector3.Transform(new Vector3(mergedBox.Max.X, mergedBox.Max.Y, mergedBox.Min.Z), lightViewMatrix);
            edges[6] = Vector3.Transform(new Vector3(mergedBox.Min.X, mergedBox.Max.Y, mergedBox.Max.Z), lightViewMatrix);
            edges[7] = Vector3.Transform(new Vector3(mergedBox.Max.X, mergedBox.Max.Y, mergedBox.Max.Z), lightViewMatrix);

            var boundingBox = BoundingBox.CreateFromPoints(edges);
            var width       = boundingBox.Max.X - boundingBox.Min.X;
            var height      = boundingBox.Max.Y - boundingBox.Min.Y;

            var cameraPosition       = sphere.Center - directionNormalized * sphere.Radius;
            var cameraPositionTarget = cameraPosition + directionNormalized;

            LightViewMatrix = Matrix.CreateLookAt(cameraPosition, cameraPositionTarget, Vector3.Up) * Matrix.CreateOrthographic(width, height, 0.1f, sphere.Radius * 2);
        }
Beispiel #3
0
        public void AddCircularObstacle(IObject obj)
        {
            BoundingSphere    bs = BoundingSphere.CreateFromBoundingBox(obj.PhysicObject.BoundingBox.Value);
            SphericalObstacle so = new SphericalObstacle(bs.Radius, obj.PhysicObject.Position);

            obstacles.Add(so);
        }
Beispiel #4
0
        public void CreateFromBoundingBox_ContainsBox()
        {
            var box    = new BoundingBox(new Vector3(1, 7, 3), new Vector3(9, 0, 2));
            var sphere = BoundingSphere.CreateFromBoundingBox(box);

            Assert.AreEqual(ContainmentType.Contains, sphere.Contains(box));
        }
Beispiel #5
0
        protected override void UpdateWorldVolume()
        {
            this.PositionLeftBottomCorner = (this.WorldMatrix.Translation - this.SizeInMetresHalf);
            m_worldAABB   = MyUtils.GetNewBoundingBox(PositionLeftBottomCorner, SizeInMetres);
            m_worldVolume = BoundingSphere.CreateFromBoundingBox(m_worldAABB);

            InvalidateRenderObjects();
        }
Beispiel #6
0
        /// <summary>
        /// Calculates the object bounds.
        /// </summary>
        /// <param name="objectboundingbox">Object bounds to update.</param><param name="objectboundingsphere">Object bounds to update.</param>
        protected override void CalculateObjectBounds(ref BoundingBox objectboundingbox,
                                                      ref BoundingSphere objectboundingsphere)
        {
            base.CalculateObjectBounds(ref objectboundingbox, ref objectboundingsphere);

            objectboundingbox = new BoundingBox(new Vector3(-0.5f, -0.5f, -0.5f),
                                                new Vector3(0.5f, 0.5f, 0.5f));
            objectboundingsphere = BoundingSphere.CreateFromBoundingBox(objectboundingbox);
        }
        void AllocateChildOctree(Octree octree, int x, int y, int z)
        {
            if (octree[x, y, z] != null)
            {
                return;
            }

            // 子がまだ存在しないなら生成。
            var child = octreePool.Borrow();

            octree[x, y, z] = child;

            var min = octree.Box.Min;
            var max = octree.Box.Max;

            var childMin = new Vector3();
            var childMax = new Vector3();

            if (x == 0)
            {
                childMin.X = min.X;
                childMax.X = (min.X + max.X) / 2;
            }
            else
            {
                childMin.X = (min.X + max.X) / 2;
                childMax.X = max.X;
            }

            if (y == 0)
            {
                childMin.Y = min.Y;
                childMax.Y = (min.Y + max.Y) / 2;
            }
            else
            {
                childMin.Y = (min.Y + max.Y) / 2;
                childMax.Y = max.Y;
            }

            if (z == 0)
            {
                childMin.Z = min.Z;
                childMax.Z = (min.Z + max.Z) / 2;
            }
            else
            {
                childMin.Z = (min.Z + max.Z) / 2;
                childMax.Z = max.Z;
            }

            child.Box.Min = childMin;
            child.Box.Max = childMax;
            child.Sphere  = BoundingSphere.CreateFromBoundingBox(child.Box);
        }
Beispiel #8
0
        private void GenerateData(NodeContent node)
        {
            MeshContent mesh = node as MeshContent;

            if (mesh != null)
            {
                MeshHelper.OptimizeForCache(mesh);

                // Look up the absolute transform of the mesh.
                Matrix absoluteTransform = mesh.AbsoluteTransform;

                int i = 0;

                // Loop over all the pieces of geometry in the mesh.
                foreach (GeometryContent geometry in mesh.Geometry)
                {
                    Vector3 min = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
                    Vector3 max = new Vector3(float.MinValue, float.MinValue, float.MinValue);

                    // Loop over all the indices in this piece of geometry.
                    // Every group of three indices represents one triangle.
                    List <Vector3> thisVerts = new List <Vector3>();
                    List <int>     ind       = new List <int>();

                    Vector3 vertex = Vector3.Zero;

                    foreach (int index in geometry.Indices)
                    {
                        // Look up the position of this vertex.
                        vertex = Vector3.Transform(geometry.Vertices.Positions[index], absoluteTransform);

                        // Store this data.
                        min = Vector3.Min(min, vertex);
                        max = Vector3.Max(max, vertex);

                        thisVerts.Add(vertex);

                        ind.Add(i++);
                    }

                    if (EnableLogging)
                    {
                        LogWriter.WriteToLog(string.Format("BoundingBox created min = {0}, max = {1}", min, max));
                    }
                    boxs.Add(new BoundingBox(min, max));
                    spheres.Add(BoundingSphere.CreateFromBoundingBox(boxs[boxs.Count - 1]));
                }
            }

            // Recursively scan over the children of this node.
            foreach (NodeContent child in node.Children)
            {
                GenerateData(child);
            }
        }
Beispiel #9
0
        public Cube(Vector3 min, Vector3 max, Material material)
        {
            m_Min         = min;
            m_Max         = max;
            m_Material    = material;
            m_BoundingBox = new AABB(min, max);

            var sphere = BoundingSphere.CreateFromBoundingBox(new BoundingBox(min, max));

            m_Center = sphere.Center;
        }
Beispiel #10
0
        void UpdateLocalVolume()
        {
            float halfSize1 = this.Size / 2.0f;
            float halfSize2 = this.Size2 / 2.0f;
            float halfSize3 = this.Size3 / 2.0f;

            this.m_localBoundingBox = new BoundingBox(new Vector3(-halfSize1, -halfSize2, -halfSize3), new Vector3(halfSize1, halfSize2, halfSize3));

            float radius = (float)Math.Sqrt(3) * this.Size;

            BoundingSphere.CreateFromBoundingBox(ref m_localBoundingBox, out m_localVolume);
        }
        public static IMyEntity GetClosestTargetAlongRay(Ray ray, double maxDistance, double deviation, HashSet <IMyEntity> ignoreSet)
        {
            if (Math.Abs(deviation) < double.Epsilon)
            {
                deviation = 7.5;
            }
            Ray directionRay = ray;

            float               baseDistance   = 100.0f;
            float               lowestDistance = float.MaxValue;
            float               safetyDistance = (float)(deviation * 1.33);
            IMyEntity           bestTarget     = null;
            HashSet <IMyEntity> foundEntitySet = new HashSet <IMyEntity>();

            for (float i = (float)(deviation * 1.33); i < maxDistance; i += (float)((deviation / 2) / baseDistance * i))
            {
                var largeSphere = new BoundingSphereD(directionRay.Position + i * directionRay.Direction, (deviation / 2) / baseDistance * i * 2);
                foundEntitySet.UnionWith(MyAPIGateway.Entities.GetEntitiesInSphere(ref largeSphere));
            }

            foreach (IMyEntity foundEntity in foundEntitySet)
            {
                // Log.Info("foundentityset.count = " + foundEntitySet.Count);
                var targetBox =
                    BoundingSphere.CreateFromBoundingBox((BoundingBox)foundEntity.GetTopMostParent().WorldAABB);
                var posDistance = Vector3.Distance(targetBox.Center, ray.Position);
                if (posDistance >= baseDistance)
                {
                    targetBox.Radius *= posDistance / baseDistance;
                }

                var direction = targetBox.Center - ray.Position;
                var angle     = Math.Abs(Math.Acos(ray.Direction.Dot(direction) / (ray.Direction.Length() * direction.Length())));

                //  Log.Info("distance wasnt zero for: " + foundEntity.GetType().ToString());
                //  if ((float)distance < lowestDistance) Log.Info("distance < lowest distance for " + foundEntity.EntityId);
                //  if (foundEntity.GetTopMostParent().GetType().ToString() == "Sandbox.Game.Entities.MyCubeGrid") Log.Info("target is in a cubegrid  " + foundEntity.EntityId);
                //  if ((float)distance > safetyDistance) Log.Info("distance > safety distance for " + foundEntity.EntityId);
                if (((float)angle < lowestDistance) && ((float)posDistance > safetyDistance) && (foundEntity.GetTopMostParent().GetType().ToString() == "Sandbox.Game.Entities.MyCubeGrid"))
                {
                    if (!ignoreSet.Contains(foundEntity.GetTopMostParent()))
                    {
                        bestTarget     = foundEntity;
                        lowestDistance = (float)angle;
                        //  Log.Info("we found a fitting target: " + foundEntity.DisplayName);
                    }
                }
            }
            return(bestTarget);
        }
Beispiel #12
0
        public QuestItem(Matrix world, Model model, float colliderSize) : base(world, model)
        {
            this.colliderSize = colliderSize;
            angle             = 180;
            position          = world.Translation;
            collider          = new BoundingBox(new Vector3(world.Translation.X - colliderSize / 2, world.Translation.Y - colliderSize / 2, world.Translation.Z - colliderSize / 2),
                                                new Vector3(world.Translation.X + colliderSize / 2, world.Translation.Y + colliderSize / 2, world.Translation.Z + colliderSize / 2));

            world = Matrix.CreateRotationX(MathHelper.ToRadians(-90)) * Matrix.CreateRotationY(angle) * Matrix.CreateTranslation(position);

            foreach (ModelMesh mesh in model.Meshes)
            {
                mesh.BoundingSphere = BoundingSphere.CreateFromBoundingBox(collider);
            }
        }
Beispiel #13
0
        protected override void Init(MyObjectBuilder_DefinitionBase baseBuilder)
        {
            base.Init(baseBuilder);

            Id = baseBuilder.Id;

            var builder = baseBuilder as MyObjectBuilder_PrefabDefinition;

            BoundingSphere = new BoundingSphere(Vector3.Zero, float.MinValue);

            PrefabPath = builder.PrefabPath;

            if (builder.CubeGrid == null && builder.CubeGrids == null)
            {
                return;
            }
            // Backwards compatiblity
            if (builder.CubeGrid != null)
            {
                CubeGrids = new MyObjectBuilder_CubeGrid[1] {
                    builder.CubeGrid
                }
            }
            ;
            else
            {
                CubeGrids = builder.CubeGrids;
            }

            BoundingBox = BoundingBox.CreateInvalid();

            foreach (var grid in CubeGrids)
            {
                BoundingBox localBB       = grid.CalculateBoundingBox();
                Matrix      gridTransform = grid.PositionAndOrientation.HasValue ? (Matrix)grid.PositionAndOrientation.Value.GetMatrix() : Matrix.Identity;
                BoundingBox.Include(localBB.Transform(gridTransform));
            }

            BoundingSphere = BoundingSphere.CreateFromBoundingBox(BoundingBox);

            foreach (var gridBuilder in CubeGrids)
            {
                gridBuilder.CreatePhysics = true;
                gridBuilder.XMirroxPlane  = null;
                gridBuilder.YMirroxPlane  = null;
                gridBuilder.ZMirroxPlane  = null;
            }
        }
Beispiel #14
0
        void UpdateMesh()
        {
            var meshPositionWorld = new Vector3
            {
                X = Position.X + 0.5f,
                Y = Position.Y + 0.5f,
                Z = Position.Z + 0.5f
            };

            brushMesh.PositionWorld = meshPositionWorld;
            brushMesh.BoxWorld.Min  = meshPositionWorld - new Vector3(0.5f);
            brushMesh.BoxWorld.Max  = meshPositionWorld + new Vector3(0.5f);

            BoundingSphere.CreateFromBoundingBox(ref brushMesh.BoxWorld, out brushMesh.SphereWorld);

            brushMesh.VisibleAllFaces = true;
        }
        public void InitLazy(MyObjectBuilder_DefinitionBase baseBuilder)
        {
            var builder = baseBuilder as MyObjectBuilder_PrefabDefinition;

            Debug.Assert(builder.CubeGrid != null || builder.CubeGrids != null, "No cube grids defined in prefab " + PrefabPath);
            if (builder.CubeGrid == null && builder.CubeGrids == null)
            {
                return;
            }

            // Backwards compatiblity
            if (builder.CubeGrid != null)
            {
                m_cubeGrids = new MyObjectBuilder_CubeGrid[1] {
                    builder.CubeGrid
                }
            }
            ;
            else
            {
                m_cubeGrids = builder.CubeGrids;
            }

            m_boundingSphere = new BoundingSphere(Vector3.Zero, float.MinValue);
            m_boundingBox    = BoundingBox.CreateInvalid();

            foreach (var grid in m_cubeGrids)
            {
                BoundingBox localBB       = grid.CalculateBoundingBox();
                Matrix      gridTransform = grid.PositionAndOrientation.HasValue ? (Matrix)grid.PositionAndOrientation.Value.GetMatrix() : Matrix.Identity;
                m_boundingBox.Include(localBB.Transform(gridTransform));
            }

            m_boundingSphere = BoundingSphere.CreateFromBoundingBox(m_boundingBox);

            foreach (var gridBuilder in m_cubeGrids)
            {
                gridBuilder.CreatePhysics = true;
                gridBuilder.XMirroxPlane  = null;
                gridBuilder.YMirroxPlane  = null;
                gridBuilder.ZMirroxPlane  = null;
            }

            Initialized = true;
        }
Beispiel #16
0
        /// <summary>
        /// Once all verticies in this object are set, call ready() to prepare this entity for drawing.
        /// </summary>
        public void Ready()
        {
            vertexBuffer = new VertexBuffer(GraphicOptions.graphics.GraphicsDevice,
                                            vertices.Count * VertexPositionNormalTexture.SizeInBytes,
                                            BufferUsage.WriteOnly);
            vertexBuffer.SetData <VertexPositionNormalTexture>(vertices.ToArray());
            vertDeclaration = new VertexDeclaration(GraphicOptions.graphics.GraphicsDevice,
                                                    VertexPositionNormalTexture.VertexElements);

            List <Vector3> points = new List <Vector3>();

            foreach (VertexPositionNormalTexture vertex in vertices)
            {
                points.Add(vertex.Position);
            }
            this.boundingBox    = BoundingBox.CreateFromPoints(points);
            this.BoundingSphere = BoundingSphere.CreateFromBoundingBox(boundingBox);
        }
Beispiel #17
0
 public static void CalculateBounding(NodeContent node, ref BoundingBox box, ref BoundingSphere sphere)
 {
     if (node is MeshContent)
     {
         MeshContent mc  = node as MeshContent;
         Vector3[]   pts = new Vector3[mc.Positions.Count];
         Fill(pts, mc.Positions);
         Matrix mat = mc.AbsoluteTransform;
         Vector3.Transform(pts, ref mat, pts);
         BoundingBox b2 = BoundingBox.CreateFromPoints(pts);
         box    = BoundingBox.CreateMerged(box, b2);
         sphere = BoundingSphere.CreateFromBoundingBox(box);
     }
     foreach (NodeContent cld in node.Children)
     {
         CalculateBounding(cld, ref box, ref sphere);
     }
 }
Beispiel #18
0
        public QuestGiver(Model model, Matrix world, QuestGiver questsGiverNeedToStart) : base(world, model)
        {
            questsList     = new List <Quest>();
            questCompleted = new List <Quest>();
            this.questsGiverNeedToStart = questsGiverNeedToStart;

            position = world.Translation;
            position = position + new Vector3(0, -1f, 0);
            angle    = 180;
            collider = new BoundingBox(new Vector3(world.Translation.X - colliderSize / 2, world.Translation.Y - colliderSize / 2, world.Translation.Z - colliderSize / 2),
                                       new Vector3(world.Translation.X + colliderSize / 2, world.Translation.Y + colliderSize / 2, world.Translation.Z + colliderSize / 2));
            world = Matrix.CreateRotationX(MathHelper.ToRadians(-90)) * Matrix.CreateRotationY(angle) * Matrix.CreateTranslation(position);

            foreach (ModelMesh mesh in model.Meshes)
            {
                mesh.BoundingSphere = BoundingSphere.CreateFromBoundingBox(collider);
            }
        }
Beispiel #19
0
        float GetStableShadowVolumeSize(Vector3D[] verticesPos, float shadowmapResolution)
        {
            BoundingSphere boundingSphere = new BoundingSphere(Vector3.Zero, float.MinValue);
            BoundingBox    boundingBox    = BoundingBox.CreateInvalid();

            foreach (var pos in verticesPos)
            {
                boundingBox.Min = Vector3.Min(boundingBox.Min, pos);
                boundingBox.Max = Vector3.Max(boundingBox.Max, pos);
            }

            boundingSphere = BoundingSphere.CreateFromBoundingBox(boundingBox);

            float baseSize = boundingSphere.Radius * 2;

            baseSize *= 1 + 1.0f / shadowmapResolution;

            return(baseSize);
        }
Beispiel #20
0
        public void Render2DOverlay(PerspectiveCamera viewPoint, GBuffer gBuffer)
        {
            this.Effect.World      = Matrix.Identity;
            this.Effect.View       = Matrix.Identity;
            this.Effect.Projection = Matrix.Identity;

            this.Effect.DepthMap              = gBuffer.DepthTarget;
            this.Effect.CameraPosition        = viewPoint.Position;
            this.Effect.InverseViewProjection = viewPoint.InverseViewProjection;

            this.Device.PostProcessState();

            foreach ((var entity, var component, var info, var property, var attribute) in this.EnumerateAttributes <BoundaryAttribute>())
            {
                this.Effect.Color       = info.Color2D;
                this.Effect.VisibleTint = info.VisibileIconTint;
                this.Effect.ClippedTint = info.ClippedIconTint;

                var boundary = property.GetGetMethod().Invoke(component, null);
                switch (attribute.Type)
                {
                case BoundaryType.Frustum:
                    var frustum = (BoundingFrustum)boundary;
                    if (viewPoint.Frustum.Intersects(frustum))
                    {
                        this.Effect.WorldPosition = BoundingSphere.CreateFromFrustum(frustum).Center;
                        this.Effect.Apply(ColorEffectTechniques.ColorPointDepthTest);
                        this.Quad.RenderOutline(frustum, viewPoint);
                    }
                    break;

                case BoundaryType.BoundingBox:
                    var boundingBox = (BoundingBox)boundary;
                    if (viewPoint.Frustum.Intersects(boundingBox))
                    {
                        this.Effect.WorldPosition = BoundingSphere.CreateFromBoundingBox(boundingBox).Center;
                        this.Effect.Apply(ColorEffectTechniques.ColorPointDepthTest);
                        this.Quad.RenderOutline(boundingBox, viewPoint);
                    }
                    break;
                }
            }
        }
Beispiel #21
0
        //public Animal(Model model, String ModelName, ContentManager contentManager, Matrix world, float colliderSize, Camera cam) : base(world, model)
        //{
        //    this.cam = cam;
        //    ifColisionTerrain = false;
        //    position = world.Translation;
        //    angle = 180;
        //    collider = new BoundingBox(new Vector3(world.Translation.X - colliderSize / 2, world.Translation.Y - colliderSize / 2, world.Translation.Z - colliderSize / 2),
        //                                new Vector3(world.Translation.X + colliderSize / 2, world.Translation.Y + colliderSize / 2, world.Translation.Z + colliderSize / 2));
        //    this.colliderSize = colliderSize;
        //    speedFactor = 100;
        //    animationOffset = (float)rand.NextDouble() * 10;
        //}

        //ten kontruktor jest ok
        public Animal(Wolf wolf, Model model, Matrix world, float colliderSize, int meat, string kindOfAnimal) : base(world, model)
        {
            this.kindOfAnimal = kindOfAnimal;
            this.wolf         = wolf;
            this.meat         = meat;
            ifColisionTerrain = false;
            position          = world.Translation;
            position          = position + new Vector3(-8, -2.0f, -22);
            angle             = 108;
            collider          = new BoundingBox(new Vector3(world.Translation.X - colliderSize / 2, world.Translation.Y - colliderSize / 2, world.Translation.Z - colliderSize / 2),
                                                new Vector3(world.Translation.X + colliderSize / 2, world.Translation.Y + colliderSize / 2, world.Translation.Z + colliderSize / 2));

            foreach (ModelMesh mesh in model.Meshes)
            {
                mesh.BoundingSphere = BoundingSphere.CreateFromBoundingBox(collider);
            }
            this.colliderSize = colliderSize;
            speedFactor       = 6;
        }
Beispiel #22
0
        /// <summary>
        /// Initialize this octree node.
        /// </summary>
        void InitOctreeBox(BoundingBox boundingBox)
        {
            // set bounding box and sphere
            LastBoundingBox    = boundingBox;
            LastBoundingSphere = BoundingSphere.CreateFromBoundingBox(LastBoundingBox);

            // if not root, remove transformations
            if (!IsOctreeRoot)
            {
                Transformations = null;
            }

            // calculate half length
            _boxHalfLength = (boundingBox.Max - boundingBox.Min).Length() * 0.5f;

            // create the octree branches (subdivisions).
            if (_divisionsLeft > 0)
            {
                // create matrix of child trees and their bounding boxes
                _childOctrees       = new OctreeCullingNode[2, 2, 2];
                _childBoundingBoxes = new BoundingBox[2, 2, 2];

                // get min, max, and step
                Vector3 min  = boundingBox.Min;
                Vector3 max  = boundingBox.Max;
                Vector3 step = (max - min) * 0.5f;

                // init bounding boxes
                Vector3 center = (LastBoundingBox.Max - LastBoundingBox.Min);
                for (int x = 0; x < 2; ++x)
                {
                    for (int y = 0; y < 2; ++y)
                    {
                        for (int z = 0; z < 2; ++z)
                        {
                            Vector3 currMin = min + step * new Vector3(x, y, z);
                            Vector3 currMax = currMin + step;
                            _childBoundingBoxes[x, y, z] = new BoundingBox(currMin, currMax);
                        }
                    }
                }
            }
        }
        protected override void Init(MyObjectBuilder_DefinitionBase baseBuilder)
        {
            base.Init(baseBuilder);

            Id = baseBuilder.Id;

            var builder = baseBuilder as MyObjectBuilder_PrefabDefinition;

            BoundingSphere = new BoundingSphere(Vector3.Zero, float.MinValue);

            PrefabPath = builder.PrefabPath;

            if (builder.CubeGrid == null && builder.CubeGrids == null)
            {
                return;
            }
            // Backwards compatiblity
            if (builder.CubeGrid != null)
                CubeGrids = new MyObjectBuilder_CubeGrid[1] { builder.CubeGrid };
            else
                CubeGrids = builder.CubeGrids;

            BoundingBox = BoundingBox.CreateInvalid();
         
            foreach (var grid in CubeGrids)
            {
                BoundingBox localBB = grid.CalculateBoundingBox();
                Matrix gridTransform = grid.PositionAndOrientation.HasValue ? (Matrix)grid.PositionAndOrientation.Value.GetMatrix() : Matrix.Identity;
                BoundingBox.Include(localBB.Transform(gridTransform));
            }

            BoundingSphere = BoundingSphere.CreateFromBoundingBox(BoundingBox);

            foreach (var gridBuilder in CubeGrids)
            {
                gridBuilder.CreatePhysics = true;
                gridBuilder.XMirroxPlane = null;
                gridBuilder.YMirroxPlane = null;
                gridBuilder.ZMirroxPlane = null;
            }
        }
Beispiel #24
0
        public void Add(SceneNode node)
        {
            Vector3 center;

            node.BoxWorld.GetCenter(out center);

            var rootPositionGrid = new IntVector3
            {
                X = (int)Math.Floor(center.X / RegionSize.X),
                Y = (int)Math.Floor(center.Y / RegionSize.Y),
                Z = (int)Math.Floor(center.Z / RegionSize.Z)
            };

            Octree root;

            if (!rootsByPositionGrid.TryGetValue(rootPositionGrid, out root))
            {
                root = octreePool.Borrow();

                var min = new Vector3
                {
                    X = rootPositionGrid.X * RegionSize.X,
                    Y = rootPositionGrid.Y * RegionSize.Y,
                    Z = rootPositionGrid.Z * RegionSize.Z
                };

                var box = new BoundingBox
                {
                    Min = min,
                    Max = min + RegionSize
                };

                root.Box    = box;
                root.Sphere = BoundingSphere.CreateFromBoundingBox(root.Box);

                rootsByPositionGrid[rootPositionGrid] = root;
            }

            Add(node, root);
        }
Beispiel #25
0
 /// <summary>
 /// Propagate our global transform to the sub meshes, recomputing their bounding boxes
 /// </summary>
 private void UpdateSubMeshes()
 {
     Helpers.TransformBoundingBox(ref _localBoundingBox, ref _transform, out _globalBoundingBox);
     if (_model != null)
     {
         for (int i = 0; i < _model.Bones.Count; i++)
         {
             _transforms[i] = _model.Bones[i].Transform * _transform;
         }
         for (int i = 0; i < _subMeshes.Count; i++)
         {
             SubMesh subMesh = _subMeshes[i];
             //compute the global transform for this submesh
             subMesh.GlobalTransform = _transforms[_model.Meshes[subMesh._modelIndex].ParentBone.Index];
             MeshMetadata.SubMeshMetadata metadata = subMesh._metadata;
             BoundingBox source = metadata.BoundingBox;
             //compute the global bounding box
             Helpers.TransformBoundingBox(ref source, ref _transform, out subMesh.GlobalBoundingBox);
             subMesh.GlobalBoundingSphere = BoundingSphere.CreateFromBoundingBox(subMesh.GlobalBoundingBox);
         }
     }
 }
Beispiel #26
0
        /// <summary>
        /// Create a bounding box for each model mesh
        /// </summary>

        private static BoundingBox BuildBoundingBox(ModelMesh mesh, ref BoundingSphere sphere)
        {
            // Create initial variables to hold min and max xyz values for the mesh
            Vector3 meshMax = new Vector3(float.MinValue);
            Vector3 meshMin = new Vector3(float.MaxValue);

            Vector3[] vertexPositions = null;

            foreach (ModelMeshPart part in mesh.MeshParts)
            {
                // The stride is how big, in bytes, one vertex is in the vertex buffer
                // We have to use this as we do not know the make up of the vertex
                int stride = part.VertexBuffer.VertexDeclaration.VertexStride;

                VertexPositionNormalTexture[] vertexData = new VertexPositionNormalTexture[part.NumVertices];
                vertexPositions = new Vector3[part.NumVertices];

                part.VertexBuffer.GetData(part.VertexOffset * stride, vertexData, 0, part.NumVertices, stride);

                // Find minimum and maximum xyz values for this mesh part
                Vector3 vertPosition = new Vector3();

                for (int i = 0; i < vertexData.Length; i++)
                {
                    vertPosition       = vertexData[i].Position;
                    vertexPositions[i] = vertexData[i].Position;

                    // update our values from this vertex
                    meshMin = Vector3.Min(meshMin, vertPosition);
                    meshMax = Vector3.Max(meshMax, vertPosition);
                }
            }

            // Create the bounding box
            BoundingBox box = new BoundingBox(meshMin, meshMax);

            sphere = BoundingSphere.CreateFromBoundingBox(box);
            return(box);
        }
        /// <summary>
        /// Create the BoundingBox and BoundingSphere for this patch.
        /// </summary>

        private void SetBoundingVolumes(float terrainScale, float heightScale, Vector3 terrainPosition)
        {
            int left   = (int)mapOffset.X * TerrainPatch.patchSize;
            int right  = left + TerrainPatch.patchSize;
            int top    = (int)mapOffset.Y * TerrainPatch.patchSize;
            int bottom = top + TerrainPatch.patchSize;

            float minY = 1000000;
            float maxY = -1000000;

            for (int index = 0; index < meshes[0].vertices.Length; index++)
            {
                float height = meshes[0].vertices[index].VertexHeight;

                minY = (minY > height) ? height : minY;
                maxY = (maxY < height) ? height : maxY;
            }

            // Adjust bounding box extents
            bboxMin = new Vector3(left, minY * heightScale, top);
            bboxMax = new Vector3(right, maxY * heightScale, bottom);

            Vector3 scale = new Vector3(terrainScale);

            scale.Z = -scale.Z;

            // Transform bounding box to fit the actual terrain
            Matrix bboxTransform = Matrix.CreateScale(scale) *
                                   Matrix.CreateTranslation(terrainPosition);

            bboxMin = Vector3.Transform(bboxMin, bboxTransform);
            bboxMax = Vector3.Transform(bboxMax, bboxTransform);

            // Calculate the center point
            center = (bboxMin + bboxMax) / 2;

            boundingBox    = new BoundingBox(bboxMin, bboxMax);
            boundingSphere = BoundingSphere.CreateFromBoundingBox(boundingBox);
        }
Beispiel #28
0
        void CréerHitboxCaméra()
        {
            BoundingSphere temp            = new BoundingSphere();
            bool           firstTime       = true;
            int            soldatsComptées = 0;;

            for (int i = 0; i < Armés.GetLength(0); i++)
            {
                for (int j = 0; j < Armés.GetLength(1); j++)
                {
                    if (soldatsComptées <= NbVivants)
                    {
                        if (Armés[i, j] != null)
                        {
                            if (Armés[i, j].EstVivant)
                            {
                                if (EstDansLimiteTerrain(Armés[i, j]))
                                {
                                    if (firstTime)
                                    {
                                        temp      = BoundingSphere.CreateFromBoundingBox(Armés[i, j].HitBoxGénérale);
                                        firstTime = false;
                                        soldatsComptées++;
                                    }
                                    temp = BoundingSphere.CreateMerged(temp, BoundingSphere.CreateFromBoundingBox(Armés[i, j].HitBoxGénérale));
                                    soldatsComptées++;
                                }
                            }
                        }
                    }
                }
            }


            Caméra.DonnerBoundingSphere(BoundingSphere.CreateMerged(temp, Flag.ViewFlag));
        }
        private static void SetupReading(
            int lodIndex, ref Vector3I minInLod, ref Vector3I maxInLod,
            out float lodVoxelSizeHalf, out BoundingBox queryBox, out BoundingSphere querySphere)
        {
            ProfilerShort.Begin("SetupReading");
            lodVoxelSizeHalf = MyVoxelConstants.VOXEL_SIZE_IN_METRES_HALF * (1 << lodIndex);
            Vector3 localMin, localMax;

            {
                Vector3D localPositionD;
                var      min = minInLod << lodIndex;
                var      max = maxInLod << lodIndex;
                MyVoxelCoordSystems.VoxelCoordToLocalPosition(ref min, out localPositionD);
                localMin = localPositionD;
                MyVoxelCoordSystems.VoxelCoordToLocalPosition(ref max, out localPositionD);
                localMax = localPositionD;

                localMin -= lodVoxelSizeHalf;
                localMax += lodVoxelSizeHalf;
            }
            queryBox = new BoundingBox(localMin, localMax);
            BoundingSphere.CreateFromBoundingBox(ref queryBox, out querySphere);
            ProfilerShort.End();
        }
Beispiel #30
0
        public void Load()
        {
            CHeightmap heightmap = null;

            // for each heightmap component, create Model instance to enable Draw calls when rendering
            foreach (var renderable in Game1.Inst.Scene.GetComponents <C3DRenderable>())
            {
                if (renderable.Value.GetType() != typeof(CHeightmap))
                {
                    continue;
                }
                heightmap = (CHeightmap)renderable.Value;
                int key = renderable.Key;

                /* use each color channel for different data, e.g.
                 * R for height,
                 * G for texture/material/terrain type,
                 * B for fixed spawned models/entities (houses, trees etc.),
                 * A for additional data
                 */


                List <ModelMesh> meshes = new List <ModelMesh>();
                var bones = new List <ModelBone>();

                var indices  = new Dictionary <int, int[]>();
                var vertices = new Dictionary <int, VertexPositionNormalColor[]>();

                CreateIndicesChunk(heightmap, ref indices, 0);
                CalculateHeightData(heightmap, key);
                CreateVerticesChunks(heightmap, ref vertices, 0, 0);
                //basicEffect.Texture = heightmap.Image;
                basicEffect.DiffuseColor  = new Vector3(1, 1, 1);
                basicEffect.SpecularPower = 100;
                basicEffect.SpecularColor = new Vector3(0.25f);

                basicEffect.EnableDefaultLighting();
                basicEffect.LightingEnabled   = true;
                basicEffect.AmbientLightColor = Game1.Inst.Scene.LightConfig.AmbientColor;
                basicEffect.DirectionalLight0.SpecularColor = Game1.Inst.Scene.LightConfig.SpecularColor;
                basicEffect.DirectionalLight0.Direction     = Game1.Inst.Scene.LightConfig.Direction;
                basicEffect.DirectionalLight0.DiffuseColor  = Game1.Inst.Scene.LightConfig.DiffuseColor;
                basicEffect.DirectionalLight0.Enabled       = true;
                basicEffect.PreferPerPixelLighting          = true;


                for (int j = 0; j < vertices.Values.Count; j++)
                {
                    var vert = vertices[j];
                    var ind  = indices[j];
                    CalculateNormals(ref vert, ref ind);

                    /*
                     * for(int i = 0; i < vertices[j].Length; i++)
                     *  vertices[j][i].Color = Color.ForestGreen;
                     */
                    vertices[j] = vert;
                    indices[j]  = ind;

                    var modelpart = CreateModelPart(vert, ind);
                    List <ModelMeshPart> meshParts = new List <ModelMeshPart>();
                    meshParts.Add(modelpart);

                    ModelMesh modelMesh = new ModelMesh(mGraphicsDevice, meshParts);
                    modelMesh.BoundingSphere = new BoundingSphere();
                    ModelBone modelBone = new ModelBone();
                    modelBone.AddMesh(modelMesh);
                    modelBone.Transform = Matrix.CreateTranslation(new Vector3(0, 0, 0));                     // changing object world (frame) / origo

                    modelMesh.ParentBone = modelBone;
                    bones.Add(modelBone);
                    meshes.Add(modelMesh);
                    modelMesh.BoundingSphere = BoundingSphere.CreateFromBoundingBox(GenericUtil.BuildBoundingBoxForVertex(vert, Matrix.Identity));
                    modelpart.Effect         = basicEffect;
                }
                ModelMeshPart        ground          = buildGround(heightmap, 20);
                List <ModelMeshPart> groundMeshParts = new List <ModelMeshPart>();
                groundMeshParts.Add(ground);
                ModelMesh groundMesh = new ModelMesh(mGraphicsDevice, groundMeshParts);
                groundMesh.BoundingSphere = new BoundingSphere();
                ModelBone groundBone = new ModelBone();
                groundBone.AddMesh(groundMesh);
                groundBone.Transform  = Matrix.CreateTranslation(new Vector3(0, 0, 0));
                groundMesh.ParentBone = groundBone;
                groundMesh.Name       = "FrontFace";
                bones.Add(groundBone);
                meshes.Add(groundMesh);
                ground.Effect = basicEffect;

                heightmap.model = new Model(mGraphicsDevice, bones, meshes);

                heightmap.model.Tag = "Map";
            }
        }
Beispiel #31
0
        public void Load()
        {
            // for each heightmap component, create Model instance to enable Draw calls when rendering
            foreach (var renderable in Game1.Inst.Scene.GetComponents <C3DRenderable>())
            {
                if (renderable.Value.GetType() != typeof(CHeightmap))
                {
                    continue;
                }
                CHeightmap heightmap = (CHeightmap)renderable.Value;

                /* use each color channel for different data, e.g.
                 * R for height,
                 * G for texture/material/terrain type,
                 * B for fixed spawned models/entities (houses, trees etc.),
                 * A for additional data
                 */


                List <ModelMesh> meshes = new List <ModelMesh>();
                var bones = new List <ModelBone>();

                var indices  = new Dictionary <int, int[]>();
                var vertices = new Dictionary <int, VertexPositionNormalColor[]>();

                CreateIndicesChunk(heightmap, ref indices, 0);
                CalculateHeightData(heightmap);
                CreateVerticesChunks(heightmap, ref vertices, 0, 0);
                for (int j = 0; j < vertices.Values.Count; j++)
                {
                    var vert = vertices[j];
                    var ind  = indices[j];
                    CalculateNormals(ref vert, ref ind);
                    vertices[j] = vert;
                    indices[j]  = ind;

                    var modelpart = CreateModelPart(vert, ind);
                    List <ModelMeshPart> meshParts = new List <ModelMeshPart>();
                    meshParts.Add(modelpart);

                    ModelMesh modelMesh = new ModelMesh(mGraphicsDevice, meshParts);
                    modelMesh.BoundingSphere = new BoundingSphere();
                    ModelBone modelBone = new ModelBone();
                    modelBone.AddMesh(modelMesh);
                    modelBone.Transform = Matrix.CreateTranslation(new Vector3(0, 0, 0));                     // changing object world (frame) / origo

                    modelMesh.ParentBone = modelBone;
                    bones.Add(modelBone);
                    meshes.Add(modelMesh);
                    modelMesh.BoundingSphere = BoundingSphere.CreateFromBoundingBox(GenericUtil.BuildBoundingBoxForVertex(vert, Matrix.Identity));
                    modelpart.Effect         = basicEffect;
                }
                ModelMeshPart        ground          = buildGround(heightmap, 20);
                List <ModelMeshPart> groundMeshParts = new List <ModelMeshPart>();
                groundMeshParts.Add(ground);
                ModelMesh groundMesh = new ModelMesh(mGraphicsDevice, groundMeshParts);
                groundMesh.BoundingSphere = new BoundingSphere();
                ModelBone groundBone = new ModelBone();
                groundBone.AddMesh(groundMesh);
                groundBone.Transform  = Matrix.CreateTranslation(new Vector3(0, 0, 0));
                groundMesh.ParentBone = groundBone;
                groundMesh.Name       = "FrontFace";
                bones.Add(groundBone);
                meshes.Add(groundMesh);
                ground.Effect = basicEffect;

                heightmap.model     = new Model(mGraphicsDevice, bones, meshes);
                heightmap.model.Tag = "Map";
            }
        }