public void Render(ModelControl control, IFlatGuiGraphics graphics)
        {
            var instance = control.ModelInstance;

            if (control.VoxelEffect == null && control.CubeRenderer == null)
            {
                return;
            }

            var needToRender = control.VoxelEffect != null && control.ModelInstance != null || control.CubeRenderer != null && control.SelectedCube != null;

            if (!needToRender)
            {
                return;
            }

            var bounds      = control.GetAbsoluteBounds();
            var voxelEffect = control.VoxelEffect;
            var context     = graphics.Engine.ImmediateContext;

            float  aspectRatio = bounds.Width / bounds.Height;
            Matrix projection;
            var    fov = (float)Math.PI / 3.6f;

            Matrix.PerspectiveFovLH(fov, aspectRatio, 0.5f, 100f, out projection);
            Matrix view = Matrix.LookAtLH(new Vector3(0, 0, -1.9f), Vector3.Zero, Vector3.UnitY);

            //Set custom ViewPort
            graphics.Engine.SetCustomViewPort(new ViewportF(bounds.X, bounds.Y, bounds.Width, bounds.Height));

            //Rendering the Tool
            RenderStatesRepo.ApplyStates(context, DXStates.Rasters.Default, DXStates.Blenders.Enabled, DXStates.DepthStencils.DepthReadWriteEnabled);

            if (instance != null)
            {
                voxelEffect.Begin(context);
                voxelEffect.CBPerFrame.Values.LightDirection = Vector3.Zero;
                voxelEffect.CBPerFrame.Values.ViewProjection = Matrix.Transpose(view * projection);
                voxelEffect.CBPerFrame.IsDirty = true;

                var state = instance.VoxelModel.GetMainState();
                instance.SetState(state);
                var sphere = BoundingSphere.FromBox(state.BoundingBox);
                var rMax   = 2f * Math.Sin(fov / 2);
                var size   = state.BoundingBox.GetSize();
                var offset = -size / 2 - state.BoundingBox.Minimum;
                var scale  = (float)rMax / sphere.Radius;

                instance.World = Matrix.Translation(offset) * Matrix.Scaling(scale) *
                                 Matrix.RotationY(MathHelper.Pi + MathHelper.PiOver4) * control.AlterTransform *
                                 Matrix.RotationQuaternion(control.Rotation);
                control.VisualVoxelModel.Draw(context, control.VoxelEffect, instance);
            }
            else if (control.SelectedCube != null)
            {
                control.CubeRenderer.Render(context, control.AlterTransform * Matrix.RotationQuaternion(control.Rotation) * view, projection, new Color3(1, 1, 1));
            }

            graphics.Engine.SetScreenViewPort();
        }
Example #2
0
        public override BoundingSphere GetGizmoCenter()
        {
            BoundingSphere boundingSphere = BoundingSphere.FromBox(boundingBox);

            boundingSphere.Radius *= 0.9f;
            return(boundingSphere);
        }
Example #3
0
        static private Mesh CreateMesh(GraphicsDevice device, VertexPositionNormalTexture[] verts, uint[] indices)
        {
            /* now set up the GPU side stuff */
            var vbo = Xenko.Graphics.Buffer.Vertex.New(
                device,
                verts,                        /* allocated size of buffer inferred from the stored datatype and the length of the array */
                GraphicsResourceUsage.Default /* usage hint to the GPU for it to allocate it appropriately (explicit default in our case) */
                );

            /* NOTE: if resource usage here  is set to immutable (the default) you will encounter an error if you try to update it after creating it */
            var ibo = Xenko.Graphics.Buffer.Index.New(device, indices, GraphicsResourceUsage.Default);

            var newMesh = new Mesh()
            {
                Draw = new MeshDraw()
                {
                    PrimitiveType = PrimitiveType.TriangleList,
                    VertexBuffers = new[] {
                        new VertexBufferBinding(vbo, VertexPositionNormalTexture.Layout, verts.Length),
                    },
                    IndexBuffer = new IndexBufferBinding(ibo, is32Bit: true, count: indices.Length),
                    DrawCount   = indices.Length
                }
            };

            /* bounding box for culling */
            newMesh.BoundingBox    = Utils.FromPoints(verts);
            newMesh.BoundingSphere = BoundingSphere.FromBox(newMesh.BoundingBox);

            return(newMesh);
        }
        public void Build(RenderDrawContext context)
        {
            if (Mesh == null && TryGetHeightMapImageData(context.CommandList, out var data))
            {
                Data               = new GeometryBuilder(data).BuildTerrainData(Size, MaxHeight, UvScale);
                MeshBoundingBox    = Utils.FromPoints(Data.Vertices);
                MeshBoundingSphere = BoundingSphere.FromBox(MeshBoundingBox);
                BoundingBox        = new BoundingBoxExt(MeshBoundingBox);

                var vertexBuffer        = Buffer.Vertex.New(context.GraphicsDevice, Data.Vertices, GraphicsResourceUsage.Dynamic);
                var indexBuffer         = Buffer.Index.New(context.GraphicsDevice, Data.Indices);
                var vertexBufferBinding = new VertexBufferBinding(vertexBuffer, VertexPositionNormalTexture.Layout, vertexBuffer.ElementCount);
                var indexBufferBinding  = new IndexBufferBinding(indexBuffer, true, indexBuffer.ElementCount);

                MeshDraw = new MeshDraw
                {
                    StartLocation = 0,
                    PrimitiveType = PrimitiveType.TriangleList,
                    VertexBuffers = new[] { vertexBufferBinding },
                    IndexBuffer   = indexBufferBinding,
                    DrawCount     = indexBuffer.ElementCount
                };

                Mesh = new Mesh(MeshDraw, new ParameterCollection());
            }
        }
Example #5
0
        static private Mesh CreateMesh(GraphicsDevice device, VertexPositionNormalTexture[] verts)
        {
            /* now set up the GPU side stuff */
            var vbo = Xenko.Graphics.Buffer.Vertex.New(
                device,
                verts,                        /* allocated size of buffer inferred from the stored datatype and the length of the array */
                GraphicsResourceUsage.Default /* usage hint to the GPU for it to allocate it appropriately (explicit default in our case) */
                );

            var newMesh = new Mesh()
            {
                Draw = new MeshDraw()
                {
                    PrimitiveType = PrimitiveType.TriangleList,
                    VertexBuffers = new[] {
                        new VertexBufferBinding(vbo, VertexPositionNormalTexture.Layout, verts.Length)
                    },
                    DrawCount = verts.Length
                }
            };

            /* bounding box+sphere for culling */
            newMesh.BoundingBox    = Utils.FromPoints(verts);
            newMesh.BoundingSphere = BoundingSphere.FromBox(newMesh.BoundingBox);

            return(newMesh);
        }
Example #6
0
        /// <summary>
        /// Gets the actor bounding sphere (including child actors).
        /// </summary>
        /// <param name="actor">The actor.</param>
        /// <param name="sphere">The bounding sphere.</param>
        public static void GetActorEditorSphere(Actor actor, out BoundingSphere sphere)
        {
            BoundingBox box;

            Internal_GetEditorBoxWithChildren(actor.unmanagedPtr, out box);
            BoundingSphere.FromBox(ref box, out sphere);
            sphere.Radius = Math.Max(sphere.Radius, 15.0f);
        }
        private void UpdateBounds(bool transformOnly = false)
        {
            if (!transformOnly)
            {
                originalBound        = new BoundingBox(DomainBoundMin, DomainBoundMax);
                originalBoundsSphere = BoundingSphere.FromBox(originalBound);
                BoundingBox    newBound;
                BoundingSphere newBoundSphere;
                if (HasInstances)
                {
                    newBound       = OriginalBounds.Transform(Instances[0]);
                    newBoundSphere = OriginalBoundsSphere.TransformBoundingSphere(Instances[0]);
                    foreach (var instance in Instances)
                    {
                        var b = OriginalBounds.Transform(instance);
                        BoundingBox.Merge(ref newBound, ref b, out newBound);
                        var bs = OriginalBoundsSphere.TransformBoundingSphere(instance);
                        BoundingSphere.Merge(ref newBoundSphere, ref bs, out newBoundSphere);
                    }
                }
                else
                {
                    newBound       = OriginalBounds;
                    newBoundSphere = OriginalBoundsSphere;
                }

                var old = bounds;
                if (Set(ref bounds, newBound))
                {
                    RaiseOnBoundChanged(new BoundChangeArgs <BoundingBox>(ref bounds, ref old));
                }
                var oldS = boundsSphere;
                if (Set(ref boundsSphere, newBoundSphere))
                {
                    RaiseOnBoundSphereChanged(new BoundChangeArgs <BoundingSphere>(ref boundsSphere, ref oldS));
                }
            }

            var oldT = boundsWithTransform;

            if (Set(ref boundsWithTransform, bounds.Transform(ModelMatrix)))
            {
                RaiseOnTransformBoundChanged(new BoundChangeArgs <BoundingBox>(ref boundsWithTransform, ref oldT));
            }
            var oldTS = boundsSphereWithTransform;

            if (Set(ref boundsSphereWithTransform, boundsSphere.TransformBoundingSphere(ModelMatrix)))
            {
                RaiseOnTransformBoundSphereChanged(new BoundChangeArgs <BoundingSphere>(ref boundsSphereWithTransform, ref oldTS));
            }
        }
Example #8
0
        private void CreateMesh()
        {
            var vbo = Xenko.Graphics.Buffer.Vertex.New(
                GraphicsDevice,
                verts,
                GraphicsResourceUsage.Dynamic
                );

            var ibo = Xenko.Graphics.Buffer.Index.New(
                GraphicsDevice,
                tris,
                GraphicsResourceUsage.Dynamic
                );

            _vertexBufferBinding =
                new VertexBufferBinding(vbo, VertexPositionNormalTexture.Layout, verts.Length);
            _indexBufferBinding = new IndexBufferBinding(ibo, is32Bit: true, count: tris.Length);
            _mesh = new Mesh()
            {
                Draw = new MeshDraw()
                {
                    PrimitiveType = PrimitiveType.TriangleList,
                    VertexBuffers = new[]
                    {
                        _vertexBufferBinding
                    },
                    IndexBuffer = _indexBufferBinding,
                    DrawCount   = tris.Length
                }
            };

            _modelComponent = new ModelComponent()
            {
                Model = new Model()
                {
                    _mesh,
                    Material
                }
            };

            Entity.Add(_modelComponent);

            // Bounding box for culling (stops rendering the mesh when the camera isn't looking at it)
            _mesh.BoundingBox    = MathHelpers.FromPoints(verts);
            _mesh.BoundingSphere = BoundingSphere.FromBox(_mesh.BoundingBox);
            CreateCollider();
        }
Example #9
0
        private void CreateMesh()
        {
            var vbo = Xenko.Graphics.Buffer.Vertex.New(
                GraphicsDevice,
                vertices,
                GraphicsResourceUsage.Default
                );

            var ibo = Xenko.Graphics.Buffer.Index.New(
                GraphicsDevice,
                indices,
                GraphicsResourceUsage.Default
                );

            _vertexBufferBinding = new VertexBufferBinding(vbo, VertexPositionNormalColor.Layout, vertices.Length);
            _indexBufferBinding  = new IndexBufferBinding(ibo, is32Bit: true, count: indices.Length);

            _mesh = new Mesh()
            {
                Draw = new MeshDraw()
                {
                    PrimitiveType = PrimitiveType.TriangleList,
                    VertexBuffers = new[]
                    {
                        _vertexBufferBinding
                    },
                    IndexBuffer = _indexBufferBinding,
                    DrawCount   = indices.Length
                }
            };

            _modelComponent = new ModelComponent()
            {
                Model = new Model()
                {
                    _mesh,
                    material
                }
            };

            Entity.Add(_modelComponent);

            // Bounding box for culling
            _mesh.BoundingBox    = Helpers.FromPoints(vertices);
            _mesh.BoundingSphere = BoundingSphere.FromBox(_mesh.BoundingBox);
        }
Example #10
0
        /// <summary>
        /// Called when task calls <see cref="SceneRenderTask.Draw" /> event.
        /// </summary>
        /// <param name="collector">The draw calls collector.</param>
        public virtual void OnDraw(DrawCallsCollector collector)
        {
            if (_highlightMaterial == null)
            {
                return;
            }

            Matrix m1, m2, world;

            for (var i = 0; i < _highlights.Count; i++)
            {
                HighlightData highlight = _highlights[i];
                if (highlight.Target is StaticModel staticModel)
                {
                    if (staticModel.Model == null)
                    {
                        continue;
                    }

                    staticModel.Transform.GetWorld(out m1);
                    staticModel.Entries[highlight.EntryIndex].Transform.GetWorld(out m2);
                    Matrix.Multiply(ref m2, ref m1, out world);
                    BoundingSphere bounds = BoundingSphere.FromBox(staticModel.Box);

                    collector.AddDrawCall(staticModel.Model, highlight.EntryIndex, _highlightMaterial, ref bounds, ref world);
                }
            }

            if (_highlightTriangles.Count > 0)
            {
                var mesh = _highlightTrianglesModel.LODs[0].Meshes[0];
                if (!Utils.ArraysEqual(_highlightTrianglesSet, _highlightTriangles))
                {
                    _highlightIndicesSet = new int[_highlightTriangles.Count];
                    for (int i = 0; i < _highlightIndicesSet.Length; i++)
                    {
                        _highlightIndicesSet[i] = i;
                    }
                    _highlightTrianglesSet = _highlightTriangles.ToArray();
                    mesh.UpdateMesh(_highlightTrianglesSet, _highlightIndicesSet);
                }

                world = Matrix.Identity;
                collector.AddDrawCall(mesh, _highlightMaterial, ref world);
            }
        }
Example #11
0
        protected void CreateBoundingBox()
        {
            if (IsZone == 1 || _arenaRadius == -1f)
            {
                Vector3[] vertices = new Vector3[SharpRenderer.pyramidVertices.Count];

                for (int i = 0; i < SharpRenderer.pyramidVertices.Count; i++)
                {
                    vertices[i] = (Vector3)Vector3.Transform(SharpRenderer.pyramidVertices[i], world);
                }

                boundingBox    = BoundingBox.FromPoints(vertices);
                boundingSphere = BoundingSphere.FromBox(boundingBox);
            }
            else
            {
                boundingSphere = new BoundingSphere(_position, _arenaRadius);
                boundingBox    = BoundingBox.FromSphere(boundingSphere);
            }
        }
Example #12
0
        protected Mesh CreateMesh(IndexBufferBinding indexBuffer, IMeshData <TVertex> meshData)
        {
            Contracts.Requires.That(indexBuffer != null);
            Contracts.Requires.That(meshData != null);

            var vertexBuffers = new[]
            {
                new VertexBufferBinding(
                    Buffer.Vertex.New(this.GraphicsDevice, meshData.Vertices, GraphicsResourceUsage.Immutable),
                    this.Format.Layout,
                    meshData.VerticesCount),
            };

            var meshDraw = new MeshDraw()
            {
                IndexBuffer   = indexBuffer,
                VertexBuffers = vertexBuffers,
                DrawCount     = meshData.IndicesCount,
                PrimitiveType = PrimitiveType.TriangleList,
            };

            // create the bounding volumes
            var boundingBox = BoundingBox.Empty;

            for (int index = 0; index < meshData.VerticesCount; index++)
            {
                var position = this.Format.GetPosition(meshData.Vertices[index]);
                BoundingBox.Merge(ref boundingBox, ref position, out boundingBox);
            }

            var boundingSphere = BoundingSphere.FromBox(boundingBox);

            return(new Mesh
            {
                Draw = meshDraw,
                BoundingBox = boundingBox,
                BoundingSphere = boundingSphere,
            });
        }
Example #13
0
        /// <summary>
        /// Tries to get the bounding sphere for the given render-loop.
        /// Returns BoundingSphere.Empty, if it is not available.
        /// </summary>
        /// <param name="viewInfo">The ViewInformation for which to get the BoundingSphere.</param>
        public override BoundingSphere TryGetBoundingSphere(ViewInformation viewInfo)
        {
            GeometryResource geometryResource = m_localResources[viewInfo.Device.DeviceIndex];

            if ((geometryResource != null) &&
                (geometryResource.IsLoaded))
            {
                // Get BoundingBox object
                BoundingBox boundingBox = geometryResource.BoundingBox;

                // Calculate bounding sphare
                BoundingSphere result;
                BoundingSphere.FromBox(ref boundingBox, out result);

                result.Transform(this.Transform);

                return(result);
            }
            else
            {
                return(BoundingSphere.Empty);
            }
        }
Example #14
0
 protected override void CreateBoundingBox()
 {
     if (Shape == TriggerShape.Box)
     {
         boundingBox         = new BoundingBox(-Vector3.One, Vector3.One);
         boundingBox.Maximum = (Vector3)Vector3.Transform(boundingBox.Maximum, world);
         boundingBox.Minimum = (Vector3)Vector3.Transform(boundingBox.Minimum, world);
         boundingSphere      = BoundingSphere.FromBox(boundingBox);
     }
     else if (Shape == TriggerShape.Sphere)
     {
         boundingSphere = new BoundingSphere(_trigPos0, Radius);
         boundingBox    = BoundingBox.FromSphere(boundingSphere);
     }
     else
     {
         boundingBox = new BoundingBox
         {
             Maximum = new Vector3(Position0X, Position0Y, Position0Z) + new Vector3(Radius, Height * 2, Radius),
             Minimum = new Vector3(Position0X, Position0Y, Position0Z) - new Vector3(Radius, Height * 2, Radius)
         };
         boundingSphere = BoundingSphere.FromBox(boundingBox);
     }
 }
Example #15
0
        /// <summary>
        /// Calculate the bounding sphere of the entity's models.
        /// </summary>
        /// <param name="entity">The entity to measure</param>
        /// <param name="isRecursive">Indicate the child entities bounding spheres should be merged</param>
        /// <param name="meshSelector">Selects which meshes are considered for bounding box calculation.</param>
        /// <returns>The bounding sphere (world matrix included)</returns>
        public static BoundingSphere CalculateBoundSphere(this Entity entity, bool isRecursive = true, Func <Model, IEnumerable <Mesh> > meshSelector = null)
        {
            entity.Transform.UpdateWorldMatrix();
            var worldMatrix = entity.Transform.WorldMatrix;

            var boundingSphere = BoundingSphere.Empty;

            // calculate the bounding sphere of the model if any
            var modelComponent = entity.Get <ModelComponent>();
            var hasModel       = modelComponent?.Model != null;

            if (hasModel)
            {
                var hierarchy      = modelComponent.Skeleton;
                var nodeTransforms = new Matrix[hierarchy.Nodes.Length];

                // Calculate node transforms here, since there might not be a ModelProcessor running
                for (int i = 0; i < nodeTransforms.Length; i++)
                {
                    if (hierarchy.Nodes[i].ParentIndex == -1)
                    {
                        nodeTransforms[i] = worldMatrix;
                    }
                    else
                    {
                        Matrix localMatrix;

                        Matrix.Transformation(
                            ref hierarchy.Nodes[i].Transform.Scale,
                            ref hierarchy.Nodes[i].Transform.Rotation,
                            ref hierarchy.Nodes[i].Transform.Position, out localMatrix);

                        Matrix.Multiply(ref localMatrix, ref nodeTransforms[hierarchy.Nodes[i].ParentIndex], out nodeTransforms[i]);
                    }
                }

                // calculate the bounding sphere
                var boundingBox = BoundingBoxExt.Empty;

                var meshes         = modelComponent.Model.Meshes;
                var filteredMeshes = meshSelector == null ? meshes : meshSelector(modelComponent.Model);

                // Calculate skinned bounding boxes.
                // TODO: Cloned from ModelSkinningUpdater. Consolidate.
                foreach (var mesh in filteredMeshes)
                {
                    var skinning = mesh.Skinning;

                    if (skinning == null)
                    {
                        // For unskinned meshes, use the original bounding box
                        var boundingBoxExt = (BoundingBoxExt)mesh.BoundingBox;
                        boundingBoxExt.Transform(nodeTransforms[mesh.NodeIndex]);
                        BoundingBoxExt.Merge(ref boundingBox, ref boundingBoxExt, out boundingBox);
                    }
                    else
                    {
                        var bones = skinning.Bones;
                        var bindPoseBoundingBox = new BoundingBoxExt(mesh.BoundingBox);

                        for (var index = 0; index < bones.Length; index++)
                        {
                            var    nodeIndex = bones[index].NodeIndex;
                            Matrix boneMatrix;

                            // Compute bone matrix
                            Matrix.Multiply(ref bones[index].LinkToMeshMatrix, ref nodeTransforms[nodeIndex], out boneMatrix);

                            // Fast AABB transform: http://zeuxcg.org/2010/10/17/aabb-from-obb-with-component-wise-abs/
                            // Compute transformed AABB (by world)
                            var boundingBoxExt = bindPoseBoundingBox;
                            boundingBoxExt.Transform(boneMatrix);
                            BoundingBoxExt.Merge(ref boundingBox, ref boundingBoxExt, out boundingBox);
                        }
                    }
                }
                var halfSize    = boundingBox.Extent;
                var maxHalfSize = Math.Max(halfSize.X, Math.Max(halfSize.Y, halfSize.Z));
                boundingSphere = BoundingSphere.Merge(boundingSphere, new BoundingSphere(boundingBox.Center, maxHalfSize));
            }

            // Calculate the bounding sphere for the sprite component if any and merge the result
            var spriteComponent = entity.Get <SpriteComponent>();
            var hasSprite       = spriteComponent?.CurrentSprite != null;

            if (hasSprite && !(hasModel && meshSelector != null))
            {
                var spriteSize         = spriteComponent.CurrentSprite.Size;
                var spriteDiagonalSize = (float)Math.Sqrt(spriteSize.X * spriteSize.X + spriteSize.Y * spriteSize.Y);

                // Note: this is probably wrong, need to unify with SpriteComponentRenderer
                var center   = worldMatrix.TranslationVector;
                var scales   = new Vector3(worldMatrix.Row1.Length(), worldMatrix.Row2.Length(), worldMatrix.Row3.Length());
                var maxScale = Math.Max(scales.X, Math.Max(scales.Y, scales.Z));

                boundingSphere = BoundingSphere.Merge(boundingSphere, new BoundingSphere(center, maxScale * spriteDiagonalSize / 2f));
            }

            var spriteStudioComponent = entity.Get <SpriteStudioComponent>();

            if (spriteStudioComponent != null)
            {
                // Make sure nodes are prepared
                if (!SpriteStudioProcessor.PrepareNodes(spriteStudioComponent))
                {
                    return(new BoundingSphere());
                }

                // Update root nodes
                foreach (var node in spriteStudioComponent.Nodes)
                {
                    node.UpdateTransformation();
                }

                // Compute bounding sphere for each node
                foreach (var node in spriteStudioComponent.Nodes.SelectDeep(x => x.ChildrenNodes))
                {
                    if (node.Sprite == null || node.Hide != 0)
                    {
                        continue;
                    }

                    var nodeMatrix = node.ModelTransform * worldMatrix;

                    var spriteSize         = node.Sprite.Size;
                    var spriteDiagonalSize = (float)Math.Sqrt(spriteSize.X * spriteSize.X + spriteSize.Y * spriteSize.Y);

                    Vector3 pos, scale;
                    nodeMatrix.Decompose(out scale, out pos);

                    var center   = pos;
                    var maxScale = Math.Max(scale.X, scale.Y); //2d ignore Z

                    boundingSphere = BoundingSphere.Merge(boundingSphere, new BoundingSphere(center, maxScale * (spriteDiagonalSize / 2f)));
                }
            }

            var particleComponent = entity.Get <ParticleSystemComponent>();

            if (particleComponent != null)
            {
                var center = worldMatrix.TranslationVector;
                var sphere = particleComponent.ParticleSystem?.BoundingShape != null?BoundingSphere.FromBox(particleComponent.ParticleSystem.BoundingShape.GetAABB(center, Quaternion.Identity, 1.0f)) : new BoundingSphere(center, 2.0f);

                boundingSphere = BoundingSphere.Merge(boundingSphere, sphere);
            }

            var boundingBoxComponent = entity.Get <NavigationBoundingBoxComponent>();

            if (boundingBoxComponent != null)
            {
                var center = worldMatrix.TranslationVector;
                var scales = new Vector3(worldMatrix.Row1.Length(), worldMatrix.Row2.Length(), worldMatrix.Row3.Length()) * boundingBoxComponent.Size;
                boundingSphere = BoundingSphere.FromBox(new BoundingBox(-scales + center, scales + center));
            }

            // Extend the bounding sphere to include the children
            if (isRecursive)
            {
                foreach (var child in entity.GetChildren())
                {
                    boundingSphere = BoundingSphere.Merge(boundingSphere, child.CalculateBoundSphere(true, meshSelector));
                }
            }

            // If the entity does not contain any components having an impact on the bounding sphere, create an empty bounding sphere centered on the entity position.
            if (boundingSphere == BoundingSphere.Empty)
            {
                boundingSphere = new BoundingSphere(worldMatrix.TranslationVector, 0);
            }

            return(boundingSphere);
        }
Example #16
0
        /// <summary>
        /// Called when task calls <see cref="SceneRenderTask.CollectDrawCalls" /> event.
        /// </summary>
        /// <param name="renderContext">The rendering context.</param>
        public virtual void OnDraw(ref RenderContext renderContext)
        {
            if (_highlightMaterial == null ||
                (_highlights.Count == 0 && _highlightTriangles.Count == 0) ||
                renderContext.View.Pass == DrawPass.Depth
                )
            {
                return;
            }
            Profiler.BeginEvent("ViewportDebugDrawData.OnDraw");

            Matrix world;

            for (var i = 0; i < _highlights.Count; i++)
            {
                HighlightData highlight = _highlights[i];
                if (highlight.Target is StaticModel staticModel)
                {
                    var model = staticModel.Model;
                    if (model == null)
                    {
                        continue;
                    }
                    staticModel.Transform.GetWorld(out world);
                    var bounds = BoundingSphere.FromBox(staticModel.Box);

                    // Pick a proper LOD
                    int lodIndex = RenderTools.ComputeModelLOD(model, ref bounds.Center, bounds.Radius, ref renderContext);
                    var lods     = model.LODs;
                    if (lods == null || lods.Length < lodIndex || lodIndex < 0)
                    {
                        continue;
                    }
                    var lod = lods[lodIndex];

                    // Draw meshes
                    for (int meshIndex = 0; meshIndex < lod.Meshes.Length; meshIndex++)
                    {
                        if (lod.Meshes[meshIndex].MaterialSlotIndex == highlight.EntryIndex)
                        {
                            lod.Meshes[meshIndex].Draw(ref renderContext, _highlightMaterial, ref world);
                        }
                    }
                }
            }

            if (_highlightTriangles.Count > 0)
            {
                var mesh = _highlightTrianglesModel.LODs[0].Meshes[0];
                if (!Utils.ArraysEqual(_highlightTrianglesSet, _highlightTriangles))
                {
                    _highlightIndicesSet = new int[_highlightTriangles.Count];
                    for (int i = 0; i < _highlightIndicesSet.Length; i++)
                    {
                        _highlightIndicesSet[i] = i;
                    }
                    _highlightTrianglesSet = _highlightTriangles.ToArray();
                    mesh.UpdateMesh(_highlightTrianglesSet, _highlightIndicesSet);
                }

                world = Matrix.Identity;
                mesh.Draw(ref renderContext, _highlightMaterial, ref world);
            }

            Profiler.EndEvent();
        }
Example #17
0
 public static float Radius(BoundingBox bounding)
 {
     return(BoundingSphere.FromBox(bounding).Radius);
 }
Example #18
0
        public Texture2D CreateVoxelIcon(VisualVoxelModel visualVoxelModel, Size2 iconSize, VoxelModelState state = null, DeviceContext context = null, Matrix transform = default(Matrix))
        {
            if (context == null)
            {
                context = _d3DEngine.ImmediateContext;
            }

            //Create the render texture
            var texture = ToDispose(new RenderedTexture2D(_d3DEngine, iconSize.Width, iconSize.Height, Format.R8G8B8A8_UNorm)
            {
                BackGroundColor = new Color4(0, 0, 0, 0)
            });

            float  aspectRatio = IconSize / IconSize;
            Matrix projection;
            var    fov = (float)Math.PI / 3.6f;

            Matrix.PerspectiveFovLH(fov, aspectRatio, 0.5f, 100f, out projection);
            Matrix view = Matrix.LookAtLH(new Vector3(0, 0, -1.9f), Vector3.Zero, Vector3.UnitY);

            texture.Begin(context);

            RenderStatesRepo.ApplyStates(context, DXStates.Rasters.Default, DXStates.Blenders.Enabled, DXStates.DepthStencils.DepthReadWriteEnabled);

            _voxelEffect.Begin(context);

            _voxelEffect.CBPerFrame.Values.LightDirection = Vector3.Zero;
            _voxelEffect.CBPerFrame.Values.ViewProjection = Matrix.Transpose(view * projection);
            _voxelEffect.CBPerFrame.IsDirty = true;

            var instance = visualVoxelModel.VoxelModel.CreateInstance();

            if (state == null)
            {
                var iconState = visualVoxelModel.VoxelModel.States.FirstOrDefault(s => string.Equals(s.Name, "Icon", StringComparison.CurrentCultureIgnoreCase));
                state = iconState ?? visualVoxelModel.VoxelModel.GetMainState();
            }

            instance.SetState(state);

            var sphere = BoundingSphere.FromBox(state.BoundingBox);

            var rMax = 2f * Math.Sin(fov / 2);

            var size = state.BoundingBox.GetSize();

            var offset = -size / 2 - state.BoundingBox.Minimum;

            var scale = (float)rMax / sphere.Radius; // Math.Min(scaleFactor / size.X, Math.Min(scaleFactor / size.Y, scaleFactor / size.Z));

            if (transform == default(Matrix))
            {
                instance.World = Matrix.Translation(offset) * Matrix.Scaling(scale) * Matrix.RotationY(MathHelper.Pi + MathHelper.PiOver4) * Matrix.RotationX(-MathHelper.Pi / 5);
            }
            else
            {
                instance.World = transform;
            }

            visualVoxelModel.Draw(context, _voxelEffect, instance);

            texture.End(context, false);


            var tex2D = texture.CloneTexture(context, ResourceUsage.Default);

            tex2D = DrawOuterShadow(context, texture, tex2D, iconSize.Width);

            _d3DEngine.SetRenderTargetsAndViewPort(context);

            return(tex2D);
        }