public void CullMeshes(ref ChunkCoordinate current, ref BoundingFrustum frustum) { BoundingBox box; if (!current.Equals(ref _previous)) { _solidMeshes.Sort((x, y) => x.Position.LengthSquared().CompareTo(y.Position.LengthSquared())); _transparentMeshes.Sort((x, y) => -x.Position.LengthSquared().CompareTo(y.Position.LengthSquared())); } for (int i = 0; i < _solidMeshes.Count; i++) { _solidMeshes[i].GetBoundingBox(out box); if (frustum.Contains(box) != ContainmentType.Disjoint) { _solidMeshRenderQueue.Enqueue(_solidMeshes[i]); } } for (int i = 0; i < _transparentMeshes.Count; i++) { _transparentMeshes[i].GetBoundingBox(out box); if (frustum.Contains(box) != ContainmentType.Disjoint) { _transparentMeshRenderQueue.Enqueue(_transparentMeshes[i]); } } }
/// <summary> /// Vykreslí jeden snímek trojrozměrného světa. /// </summary> public void Draw() { if (_body3Ds.Count > 0 || _backdrop3Ds.Count > 0) { _boundingFrustum = new BoundingFrustum(Camera3D.View * Camera3D.Projection); } if (_body3Ds.Count > 0) { for (int i = 0; i < _body3Ds.Count; i++) { _body3Ds[i].Update3DPosition(); if (_boundingFrustum.Contains(_body3Ds[i].BoundingSphere) != ContainmentType.Disjoint) { //Těleso je uvnitř promítacího kuželu, potom se vždy simuluje a vykresluje _body3Ds[i].EnableSimulation(); _body3Ds[i].Draw(Camera3D); } else { //Těleso není uvnitř promítacího kuželu //Chce uživatel v této situaci neprovádět simulaci? if (DisableSimulationWhenOutOfBoundingFrustum) { _body3Ds[i].DisableSimulation(); } } } } if (_backdrop3Ds.Count > 0) { for (int i = 0; i < _backdrop3Ds.Count; i++) { if (_boundingFrustum.Contains(_backdrop3Ds[i].BoundingSphere) != ContainmentType.Disjoint) { _backdrop3Ds[i].Draw(Camera3D); } } } }
public bool IsInVolume(BoundingFrustum frustum) { if (frustum.Contains(masterRegion.RegionBox) != ContainmentType.Disjoint) { return(true); } else { return(false); } }
public IEnumerable <VoxelChunk> EnumerateChunksInBounds(BoundingFrustum Frustum) { return(EnumerateChunksInBounds(MathFunctions.GetBoundingBox(Frustum.GetCorners())) .Where(c => { var min = new GlobalVoxelCoordinate(c.ID, new LocalVoxelCoordinate(0, 0, 0)); var box = new BoundingBox(min.ToVector3(), min.ToVector3() + new Vector3(VoxelConstants.ChunkSizeX, VoxelConstants.ChunkSizeY, VoxelConstants.ChunkSizeZ)); var r = Frustum.Contains(box) != ContainmentType.Disjoint; return r; })); }
public bool InScreen(Vector3 p, BoundingFrustum bf) { if (bf.Contains(p) != ContainmentType.Disjoint) { return(true); } else { return(false); } }
private bool Contains(BoundingFrustum bf, Vector3[] pts) { foreach (Vector3 p in pts) { if (bf.Contains(p) != ContainmentType.Contains) { return(false); } } return(true); }
public static bool IntersectObject(BoundingFrustum boundingFrustum, IGeometry geometry, Matrix matrix) { for (int i = 0; i < geometry.VertexCount(); i++) { if (boundingFrustum.Contains(Vector3.Transform(geometry.GetVertexById(i), matrix)) != ContainmentType.Disjoint) { return(true); } } return(false); }
public void EnumerateItems(BoundingFrustum SearchBounds, HashSet <T> Into, Func <T, bool> Filter) { lock (this) { switch (SearchBounds.Contains(Bounds)) { case ContainmentType.Disjoint: return; case ContainmentType.Intersects: if (Children == null) { for (var i = 0; i < Items.Count; ++i) { if (Filter(Items[i].Body) && FastIntersects(SearchBounds, Items[i].BoundingBox)) { Into.Add(Items[i].Body); } } } else { for (var i = 0; i < 8; ++i) { Children[i].EnumerateItems(SearchBounds, Into, Filter); } } break; case ContainmentType.Contains: if (Children == null) { foreach (var item in Items) { if (Filter(item.Body)) { Into.Add(item.Body); } } } else { for (var i = 0; i < 8; ++i) { Children[i].EnumerateItems(Into, Filter); } } break; } } }
public virtual void Render(GraphicsDevice graphics, Effect effect, EffectPass pass, BoundingFrustum viewFrustum, bool isInstanced) { if (!isInstanced) { if (viewFrustum.Contains(Bounds) == ContainmentType.Disjoint) { return; } effect.Parameters["World"].SetValue(WorldTransform); effect.Parameters["WorldInverseTranspose"].SetValue(Matrix.Transpose(Matrix.Invert(WorldTransform))); Geometry.Render(graphics, effect, pass); } }
public void BoundingFrustum_CalculatesContainsBoundingFrustumCorrectly() { var view1 = Matrix.CreateLookAt(new Vector3(0, 0, 5), Vector3.Zero, Vector3.Up); var proj1 = Matrix.CreatePerspectiveFieldOfView((float)Math.PI / 4f, 4f / 3f, 1f, 1000f); var frustum1 = new BoundingFrustum(view1 * proj1); var view2 = Matrix.CreateLookAt(new Vector3(0, 0, 5), new Vector3(0, 0, 10), Vector3.Up); var proj2 = Matrix.CreatePerspectiveFieldOfView((float)Math.PI / 4f, 4f / 3f, 1f, 1000f); var frustum2 = new BoundingFrustum(view2 * proj2); var view3 = Matrix.CreateLookAt(new Vector3(0, 0, 5), new Vector3(2, 0, 0), Vector3.Up); var proj3 = Matrix.CreatePerspectiveFieldOfView((float)Math.PI / 4f, 4f / 3f, 1f, 1000f); var frustum3 = new BoundingFrustum(view3 * proj3); var r1 = frustum1.Contains(frustum2); var r2 = frustum1.Contains(frustum3); var r3 = frustum1.Contains(frustum1); TheResultingValue(r1).ShouldBe(ContainmentType.Disjoint); TheResultingValue(r2).ShouldBe(ContainmentType.Intersects); TheResultingValue(r3).ShouldBe(ContainmentType.Contains); }
/// <summary> /// Draws all particles /// </summary> /// <param name="gt">The gt.</param> /// <param name="view">The view.</param> /// <param name="Projection">The projection.</param> /// <param name="render">The render.</param> protected override void Draw(GameTime gt, Matrix view, Matrix Projection, RenderHelper render) { //manager.DrawAllParticleSystems(); BoundingFrustum bf = new BoundingFrustum(view * Projection); foreach (var item in ParticleSystem.Values) { if (item.BoundingBox == null || (bf.Contains(item.BoundingBox.Value) == ContainmentType.Disjoint)) { item.IDPSFParticleSystem.Draw(); } } }
public void BoundingFrustumToBoundingBoxTests() { var view = Matrix.CreateLookAt(new Vector3(0, 0, 5), Vector3.Zero, Vector3.Up); var projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, 1, 1, 100); var testFrustum = new BoundingFrustum(view * projection); var bbox1 = new BoundingBox(new Vector3(0, 0, 0), new Vector3(1, 1, 1)); Assert.That(testFrustum.Contains(bbox1), Is.EqualTo(ContainmentType.Contains)); Assert.That(testFrustum.Intersects(bbox1), Is.True); var bbox2 = new BoundingBox(new Vector3(-1000, -1000, -1000), new Vector3(1000, 1000, 1000)); Assert.That(testFrustum.Contains(bbox2), Is.EqualTo(ContainmentType.Intersects)); Assert.That(testFrustum.Intersects(bbox2), Is.True); var bbox3 = new BoundingBox(new Vector3(-1000, -1000, -1000), new Vector3(0, 0, 0)); Assert.That(testFrustum.Contains(bbox3), Is.EqualTo(ContainmentType.Intersects)); Assert.That(testFrustum.Intersects(bbox3), Is.True); var bbox4 = new BoundingBox(new Vector3(-1000, -1000, -1000), new Vector3(-500, -500, -500)); Assert.That(testFrustum.Contains(bbox4), Is.EqualTo(ContainmentType.Disjoint)); Assert.That(testFrustum.Intersects(bbox4), Is.False); }
public override void Update(GameTime gameTime) { base.Update(gameTime); if (!Visible) { BoundingFrustum bf = new BoundingFrustum(((Renderer3D)Renderer).Cam.View * ((Renderer3D)Renderer).Cam.Projection); ContainmentType containment = bf.Contains(BoundingBox); if (containment != ContainmentType.Disjoint) { Visible = true; } } }
private TraverseOptions FindAllBoundingFrustum(QuadTreeNode <QuadTreeSceneManagerNodeData <ISpatialQueryable> > node) { if (!node.value.Initialized) { return(TraverseOptions.Skip); } var nodeContainment = ContainmentType.Intersects; var nodeBounds = new BoundingBox(new Vector3(node.bounds.X, node.bounds.Y, node.value.MinHeight), new Vector3(node.bounds.X + node.bounds.Width, node.bounds.Y + node.bounds.Height, node.value.MaxHeight)); boundingFrustum.Contains(ref boundingBox, out nodeContainment); if (nodeContainment == ContainmentType.Disjoint) { return(TraverseOptions.Skip); } if (nodeContainment == ContainmentType.Contains) { AddAllDesedents(node); return(TraverseOptions.Skip); } if (node.value.List != null) { var count = node.value.List.Count; for (int i = 0; i < count; ++i) { var val = node.value.List[i]; if (boundingFrustum.Contains(val.BoundingBox) != ContainmentType.Disjoint) { result.Add(val); } } } return(TraverseOptions.Continue); }
public void Render(GraphicsDevice graphicsDevice, GameTime gameTime) { RegenerateDirtyVertexLists(); graphicsDevice.BlendState = BlendState.Opaque; graphicsDevice.DepthStencilState = DepthStencilState.Default; for (BlockTexture blockTexture = BlockTexture.None + 1; blockTexture < BlockTexture.MAXIMUM; blockTexture++) { for (uint r = 0; r < NUMREGIONS; r++) { // Figure out if we should be rendering translucently. bool renderTranslucent = false; if (blockTexture == BlockTexture.TransRed || blockTexture == BlockTexture.TransBlue) { renderTranslucent = true; } // If this is empty, don't render it. DynamicVertexBuffer regionBuffer = vertexBuffers[(byte)blockTexture, r]; if (regionBuffer == null) { continue; } // If this isn't in our view frustum, don't render it. BoundingSphere regionBounds = new BoundingSphere(GetRegionCenter(r), REGIONSIZE); BoundingFrustum boundingFrustum = new BoundingFrustum(gameInstance.propertyBag.playerCamera.ViewMatrix * gameInstance.propertyBag.playerCamera.ProjectionMatrix); if (boundingFrustum.Contains(regionBounds) == ContainmentType.Disjoint) { continue; } // Make sure our vertex buffer is clean. if (vertexListDirty[(byte)blockTexture, r]) { continue; } // Actually render. RenderVertexList(graphicsDevice, regionBuffer, blockTextures[(byte)blockTexture].Texture, blockTextures[(byte)blockTexture].LODColor, renderTranslucent, blockTexture == BlockTexture.Lava, (float)gameTime.TotalGameTime.TotalSeconds); } } // Apply posteffects. if (bloomPosteffect != null) { bloomPosteffect.Draw(graphicsDevice); } }
public void GetVisibleEntities(PerspectiveCamera camera, IList <Pose> outVisible) { var frustum = new BoundingFrustum(camera.ViewProjection); for (var i = 0; i < this.Entries.Count; i++) { var entry = this.Entries[i]; var bounds = entry.Bounds.Transform(entry.Transform.Matrix); if (frustum.Contains(bounds) != ContainmentType.Disjoint) { outVisible.Add(entry); } } }
/// <summary> /// Provides the behavior for the Arrange pass of Silverlight layout. /// </summary> /// <param name="finalSize">The final area within the parent that this /// object should use to arrange itself and its children.</param> /// <returns> /// The actual size that is used after the element is arranged in layout. /// </returns> protected override Size ArrangeOverride(Size finalSize) { if (ActualWidth > 0 && ActualHeight > 0 && (motion != null && motion.IsDataValid || IsDesignMode)) { this.FirsVectorInView = null; BoundingFrustum viewFrustum = new BoundingFrustum(Attitude * view * CameraProjection); foreach (var child in Children) { object posObj = child.GetValue(DirectionProperty); if (posObj is Point && !double.IsNaN(((Point)posObj).X)) { Point p = (Point)posObj; Vector3 direction = PolarToVector(p.X, p.Y, 10); var size = child.DesiredSize; //Create a bounding sphere around the element for hittesting against the current frustum //This size is not entirely right... size we have is screen size but we use the world size. //*.008 seems to roughly fit as conversion factor for now var box = new BoundingSphere(direction, (float)Math.Max(size.Width, size.Height) * .008f); if (viewFrustum.Contains(box) != ContainmentType.Disjoint) //partially or fully inside camera frustum { Vector3 projected = Project(direction); if (this.FirsVectorInView == null) { this.FirsVectorInView = projected; } if (!float.IsNaN(projected.X) && !float.IsNaN(projected.Y)) { //Arrange element centered on projected coordinate double x = projected.X - size.Width * .5; double y = projected.Y - size.Height * .5; child.Arrange(new Rect(x, y, size.Width, size.Height)); continue; } } } //if we fall through to here, it's because the element is outside the view, //or placement can't be calculated child.Arrange(new Rect(0, 0, 0, 0)); } return(finalSize); } else { return(base.ArrangeOverride(finalSize)); } }
public override void StartFrame(ref Matrix view, ref Matrix projection, BoundingFrustum frustrum) { forward.Clear(); deferred.Clear(); foreach (var item in world.Objects) { if (item.Material.MaterialType == MaterialType.DEFERRED) { if ((item.PhysicObject.PhysicObjectTypes == PhysicObjectTypes.GHOST && item.PhysicObject.BoundingBox.HasValue == false) || item.PhysicObject.PhysicObjectTypes == PhysicObjectTypes.NONE) { deferred.Add(item); continue; } if (frustrum.Contains(item.PhysicObject.BoundingBox.Value) != Microsoft.Xna.Framework.ContainmentType.Disjoint) { deferred.Add(item); } } else { if ((item.PhysicObject.PhysicObjectTypes == PhysicObjectTypes.GHOST && item.PhysicObject.BoundingBox.HasValue == false) || item.PhysicObject.PhysicObjectTypes == PhysicObjectTypes.NONE) { forward.Add(item); continue; } if (frustrum.Contains(item.PhysicObject.BoundingBox.Value) != Microsoft.Xna.Framework.ContainmentType.Disjoint) { forward.Add(item); } } } num = forward.Count + deferred.Count; }
public void Render(GraphicsDevice gd, BasicEffect be) { BoundingFrustum frustum = new BoundingFrustum(be.View * be.Projection); ComponentManager cm = ComponentManager.GetInstance(); foreach (var(_, mic, box) in cm.GetComponentsOfType <ModelInstanceComponent, BoundingBoxComponent>()) { ModelComponent mc = cm.GetComponentForEntity <ModelComponent>(mic.ModelEntityId); if (frustum.Contains(box.BoundingBox) != ContainmentType.Disjoint) { ModelHelper.Render(be, mc, mic.Instance); } } }
public override void StartFrame(ref Matrix view, ref Matrix projection, BoundingFrustum frustrum) { forward.Clear(); deferred.Clear(); foreach (var item in world.Objects) { if (item.Material.MaterialType == MaterialType.DEFERRED) { if ( (item.PhysicObject.PhysicObjectTypes == PhysicObjectTypes.GHOST && item.PhysicObject.BoundingBox.HasValue == false ) || item.PhysicObject.PhysicObjectTypes == PhysicObjectTypes.NONE) { deferred.Add(item); continue; } if (frustrum.Contains(item.PhysicObject.BoundingBox.Value) != Microsoft.Xna.Framework.ContainmentType.Disjoint) { deferred.Add(item); } } else { if ( (item.PhysicObject.PhysicObjectTypes == PhysicObjectTypes.GHOST && item.PhysicObject.BoundingBox.HasValue == false ) || item.PhysicObject.PhysicObjectTypes == PhysicObjectTypes.NONE) { forward.Add(item); continue; } if (frustrum.Contains(item.PhysicObject.BoundingBox.Value) != Microsoft.Xna.Framework.ContainmentType.Disjoint) { forward.Add(item); } } } num = forward.Count + deferred.Count; }
//IF a submesh belongs to an entity that has moved we need to update the BoundingBoxWorld Position! //returns the mean distance of all objects iwth that material public float?UpdatePositionAndCheckRender(bool cameraHasChanged, BoundingFrustum viewFrustum, Vector3 cameraPosition, BoundingSphere sphere) { float?distance = null; bool hasAnythingChanged = false; for (var i = 0; i < Index; i++) { TransformMatrix trafoMatrix = _worldMatrices[i]; if (trafoMatrix.HasChanged) { _worldBoundingCenters[i] = trafoMatrix.TransformMatrixSubModel(MeshBoundingSphere.Center); } //If either the trafomatrix or the camera has changed we need to check visibility if (trafoMatrix.HasChanged || cameraHasChanged) { sphere.Center = _worldBoundingCenters[i]; sphere.Radius = MeshBoundingSphere.Radius * trafoMatrix.Scale.X; if (viewFrustum.Contains(sphere) == ContainmentType.Disjoint) { Rendered[i] = false; } else { Rendered[i] = true; } //we just register that something has changed hasAnythingChanged = true; } } //We need to calcualte a new average distance if (hasAnythingChanged && GameSettings.g_CPU_Sort) { distance = 0; for (var i = 0; i < Index; i++) { distance += Vector3.DistanceSquared(cameraPosition, _worldBoundingCenters[i]); } } return(distance); }
public void EnumerateItems(BoundingFrustum SearchBounds, HashSet <Body> Into) { lock (this) { switch (SearchBounds.Contains(Bounds)) { case ContainmentType.Disjoint: return; case ContainmentType.Intersects: if (Children == null) { for (var i = 0; i < Items.Count; ++i) { if (Items[i].BoundingBox.Intersects(SearchBounds)) { Into.Add(Items[i].Body); } } } else { for (var i = 0; i < 8; ++i) { Children[i].EnumerateItems(SearchBounds, Into); } } break; case ContainmentType.Contains: if (Children == null) { for (var i = 0; i < Items.Count; ++i) { Into.Add(Items[i].Body); } } else { for (var i = 0; i < 8; ++i) { Children[i].EnumerateItems(Into); } } break; } } }
/// <summary> /// Draw the current state of the <c>GameLayer3D</c>. /// </summary> /// <param name="gameTime">Global time of the game.</param> /// <param name="customEffect">Custom effect to be applied in the <c>GameLayer3D</c>.</param> public void Draw(GameTime gameTime, Effect customEffect) { Dictionary <string, Matrix> dictionary = new Dictionary <string, Matrix>(); BoundingFrustum boundingFrustum = new BoundingFrustum( CameraManager.ActiveCamera.View * CameraManager.ActiveCamera.Projection); foreach (DrawableModel model in _modelList) { ContainmentType cameraNodeContainment = boundingFrustum.Contains(model.BSphere);//boundingFrustum.Contains(model.GetBoundingBox()); if (!_checkFrustum || (_checkFrustum && cameraNodeContainment != ContainmentType.Disjoint)) { model.Draw(CameraManager.ActiveCamera.View, CameraManager.ActiveCamera.Projection, DrawingMethod.HardwareInstancing, dictionary, customEffect); } } }
public void addLeavesInsideFrustum(BoundingFrustum frustum) { if (frustum.Contains(boundingBox) != ContainmentType.Disjoint) { if (topLeft == null) { leavesInsideBound.Add(this); } else { topLeft.addLeavesInsideFrustum(frustum); topRight.addLeavesInsideFrustum(frustum); bottomLeft.addLeavesInsideFrustum(frustum); bottomRight.addLeavesInsideFrustum(frustum); } } }
public void Process(BoundingFrustum frustum, ref List <GameObject3D> foundObjects) { if (foundObjects == null) { foundObjects = new List <GameObject3D>(); } if (frustum.Contains(Bounds) != ContainmentType.Disjoint) { foundObjects.AddRange(Objects); foreach (Octree node in Nodes) { node.Process(frustum, ref foundObjects); } } }
public override void Do() { Mesh mesh = Instantiate(meshFilter.sharedMesh); BoundingFrustum boundingFrustum = new BoundingFrustum(); boundingFrustum.Update(camera, camera.GetComponent <Transform>()); Color[] meshColors = mesh.colors; if (meshColors == null || meshColors.Length != mesh.vertexCount) { meshColors = new Color[mesh.vertexCount]; for (int i = 0; i < mesh.vertexCount; i++) { meshColors[i] = defaultColor; } } for (int i = 0; i < mesh.vertexCount; i++) { MeshExtensions.MeshVertex meshVertex = new MeshExtensions.MeshVertex(mesh, trs, i, null); if (boundingFrustum.Contains(ref meshVertex.point)) { if (paintType == PaintType.Both || paintType == PaintType.Inside) { meshColors[i] = insideFrustumColor; } } else if (paintType == PaintType.Both || paintType == PaintType.Outside) { meshColors[i] = outsideFrustumColor; } } mesh.colors = meshColors; meshFilter.sharedMesh = mesh; if (makeAsset) { if (autoNameAssetPath) { string newAssetPath = saveAssetAtPath; while (File.Exists(newAssetPath)) { newAssetPath = newAssetPath.Replace(".asset", "1.asset"); } } AssetDatabase.CreateAsset(meshFilter.sharedMesh, saveAssetAtPath); AssetDatabase.SaveAssets(); } }
//TODO: Actually use raytracing... private void Raytrace() { BoundingFrustum frustum = new BoundingFrustum(_effect.View * _effect.Projection); List <Group> renderable = new List <Group>(); List <Group> renderableAlpha = new List <Group>(); foreach (var g in Groups) { bool hasRenderable = false; bool transparent = false; foreach (var area in g.Areas) { if (frustum.Contains(area.Box.Transform(_effect.World)) == ContainmentType.Disjoint) { area.Render = false; } else { area.Render = true; hasRenderable = true; } if (area.HasTransparency || area.Material.TextureMapAlpha != null) { transparent = true; } } if (hasRenderable) { if (transparent) { renderableAlpha.Add(g); } else { renderable.Add(g); } } } _renderedGroups = renderable; _renderedAlphaGroups = renderableAlpha; }
public void Process(BoundingFrustum frustum, ref List <GameObject3D> passedObjects) { if (passedObjects == null) { passedObjects = new List <GameObject3D>(); } if (frustum.Contains(Bounds) != ContainmentType.Disjoint) { passedObjects.AddRange(Objects); foreach (QuadTree node in Nodes) { //Process(frustum, ref passedObjects); node.Process(frustum, ref passedObjects); } } }
public void CullRenderables(BoundingFrustum frustum) { for (int i = 0; i < SYSTEM_SIZE; i++) { if (!cVisible[i]._valid) { continue; } var intersect = frustum.Contains(ref cBounds[i]); if (intersect == ContainmentType.Contains || intersect == ContainmentType.Intersects) { cCulled[i] = !cVisible[i]._valid || !cVisible[i]._visible; } else { cCulled[i] = true; } } }
public static bool BoundingFrustumIntersection(AEntity e1) { //var tempCamera = new Camera(Global.GraphicsManager.GraphicsDevice.DisplayMode.AspectRatio, 10000f, MathHelper.ToRadians(45), 1f, new Vector3(0, 250, 250), new Vector3(0, 0, 0), Vector3.Up); //BoundingFrustum boundingFrustum = new BoundingFrustum(tempCamera.ViewMatrix * tempCamera.ProjectionMatrix); BoundingFrustum boundingFrustum = new BoundingFrustum(Global.Camera.ViewMatrix * Global.Camera.ProjectionMatrix); for (var i = 0; i < e1.Model.Meshes.Count; i++) { var e1BoundingSphere = e1.Model.Meshes[i].BoundingSphere; e1BoundingSphere.Center += e1.Position; if (boundingFrustum.Contains(e1BoundingSphere) != ContainmentType.Disjoint) { return(true); } } return(false); }
public PolygonDrawCommand(List <Vector3> points, bool isClosed, Color lineColor, int lineWidth) { Points = new List <Vector2>(); BoundingFrustum cameraFrustrum = PlayState.Camera.GetFrustrum(); foreach (Vector3 point in points) { if (cameraFrustrum.Contains(point) == ContainmentType.Contains) { Vector3 screenVec = GameState.Game.GraphicsDevice.Viewport.Project(point, PlayState.Camera.ProjectionMatrix, PlayState.Camera.ViewMatrix, Matrix.Identity); Points.Add(new Vector2(screenVec.X, screenVec.Y)); } } IsClosed = isClosed; LineColor = lineColor; LineWidth = lineWidth; }
public PolygonDrawCommand(Camera camera, IEnumerable <Vector3> points, bool isClosed, Color lineColor, int lineWidth, Viewport viewport) { Points = new List <Vector2>(); BoundingFrustum cameraFrustrum = camera.GetFrustum(); foreach (Vector3 point in points) { if (cameraFrustrum.Contains(point) == ContainmentType.Contains) { Vector3 screenVec = viewport.Project(point, camera.ProjectionMatrix, camera.ViewMatrix, Matrix.Identity); Points.Add(new Vector2(screenVec.X, screenVec.Y)); } } IsClosed = isClosed; LineColor = lineColor; LineWidth = lineWidth; }
public void Draw(Effect GBuffer, BoundingFrustum cameraFrustrum) { BoundingBox transformedBox = XNAUtils.TransformBoundingBox(nodeBoundingBox, Matrix.Identity); ContainmentType cameraNodeContainment = cameraFrustrum.Contains(transformedBox); if (cameraNodeContainment != ContainmentType.Disjoint) { if (isEndNode) { DrawCurrentNode(Matrix.Identity, Camera.viewMatrix, Camera.projectionMatrix, GBuffer); } else { nodeUL.Draw(GBuffer, cameraFrustrum); nodeUR.Draw(GBuffer, cameraFrustrum); nodeLL.Draw(GBuffer, cameraFrustrum); nodeLR.Draw(GBuffer, cameraFrustrum); } } }
protected override void Draw(GameTime gameTime) { device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.CornflowerBlue, 1, 0); int modelsDrawn = 0; BoundingFrustum cameraSight = new BoundingFrustum(fpsCam.ViewMatrix * fpsCam.ProjectionMatrix); for (int x = 0; x < 5; x++) { for (int z = 0; z < 5; z++) { Matrix worldMatrix = Matrix.CreateScale(0.001f) * Matrix.CreateTranslation(x * 5 - 10, 0, z * 5 - 10); BoundingSphere origSphere = (BoundingSphere)myModel.Tag; BoundingSphere transSphere = origSphere.Transform(worldMatrix); ContainmentType containmentType = cameraSight.Contains(transSphere); if (containmentType != ContainmentType.Disjoint) { modelsDrawn++; //draw model myModel.CopyAbsoluteBoneTransformsTo(modelTransforms); foreach (ModelMesh mesh in myModel.Meshes) { foreach (BasicEffect effect in mesh.Effects) { effect.EnableDefaultLighting(); effect.World = modelTransforms[mesh.ParentBone.Index] * worldMatrix; effect.View = fpsCam.ViewMatrix; effect.Projection = fpsCam.ProjectionMatrix; } mesh.Draw(); } } } } Window.Title = string.Format("Models actually drawn: {0}", modelsDrawn); //draw coordcross cCross.Draw(fpsCam.ViewMatrix, fpsCam.ProjectionMatrix); base.Draw(gameTime); }
public bool Contains(BoundingBox bbox) { var frustum = new BoundingFrustum(_View * _Projection); return frustum.Contains(bbox) != ContainmentType.Disjoint; }
public void DrawText(Matrix viewMatrix, Matrix projectionMatrix, Vector3 drawPosition, string hoverText, Color color) { // Don't draw text if it's not within our frustum. BoundingSphere regionBounds = new BoundingSphere(drawPosition, 0.1f); BoundingFrustum boundingFrustum = new BoundingFrustum(viewMatrix * projectionMatrix); if (boundingFrustum.Contains(regionBounds) == ContainmentType.Disjoint) return; // Draw our text over the player. SpriteBatch spriteBatch = new SpriteBatch(graphicsDevice); spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.SaveState); Vector3 screenSpace = graphicsDevice.Viewport.Project(Vector3.Zero, projectionMatrix, viewMatrix, Matrix.CreateTranslation(drawPosition + new Vector3(0, 1.7f, 0))); Vector2 textPosition = new Vector2(screenSpace.X, screenSpace.Y) - nameFont.MeasureString(hoverText) * 0.5f; textPosition.X = (int)textPosition.X; textPosition.Y = (int)textPosition.Y; spriteBatch.DrawString(nameFont, hoverText, textPosition, Color.Black); textPosition.X -= 2; textPosition.Y -= 2; spriteBatch.DrawString(nameFont, hoverText, textPosition, color);//Color.White); spriteBatch.End(); }
public void Render(GraphicsDevice graphicsDevice, GameTime gameTime) { RegenerateDirtyVertexLists(); for (BlockTexture blockTexture = BlockTexture.None+1; blockTexture < BlockTexture.MAXIMUM; blockTexture++) for (uint r = 0; r < NUMREGIONS; r++) { // Figure out if we should be rendering translucently. bool renderTranslucent = false; if (blockTexture == BlockTexture.TransRed || blockTexture == BlockTexture.TransBlue) renderTranslucent = true; // If this is empty, don't render it. DynamicVertexBuffer regionBuffer = vertexBuffers[(byte)blockTexture, r]; if (regionBuffer == null) continue; // If this isn't in our view frustum, don't render it. BoundingSphere regionBounds = new BoundingSphere(GetRegionCenter(r), REGIONSIZE); BoundingFrustum boundingFrustum = new BoundingFrustum(gameInstance.propertyBag.playerCamera.ViewMatrix * gameInstance.propertyBag.playerCamera.ProjectionMatrix); if (boundingFrustum.Contains(regionBounds) == ContainmentType.Disjoint) continue; // Make sure our vertex buffer is clean. if (vertexListDirty[(byte)blockTexture, r]) continue; // Actually render. RenderVertexList(graphicsDevice, regionBuffer, blockTextures[(byte)blockTexture].Texture, blockTextures[(byte)blockTexture].LODColor, renderTranslucent, blockTexture == BlockTexture.Lava, (float)gameTime.TotalRealTime.TotalSeconds); } // Apply posteffects. if (bloomPosteffect != null) bloomPosteffect.Draw(graphicsDevice); }
private int TestFrustum(BoundingBox BB, BoundingFrustum BF) { ContainmentType CT = BF.Contains(BB); if (CT == ContainmentType.Contains) return 2; if (CT == ContainmentType.Intersects) return 1; return 0; //0 - нет //1 - частично //2 - полностью }
public List<SimpleModel> Process(BoundingFrustum frustum) { List<SimpleModel> drawnObjects = new List<SimpleModel>(); if (frustum.Contains(BoundingBox) != ContainmentType.Disjoint) { drawnObjects.AddRange(Objects); foreach (var node in childNodes) { drawnObjects.AddRange(node.Process(frustum)); } } return drawnObjects; }
public void Render(BoundingFrustum frustum) { int vertices = 0; uint cx = x; uint cy = y; //cache = anti-earthquake uint cz = z; Matrix world = Matrix.Identity; Vector3 middle = new Vector3(8, 8, 8); foreach (var node in vertexBuffers.AsEnumerable) { if (node.Value == null) continue; world.Translation = new Vector3((int)(node.Key.X - cx), (int)(node.Key.Y - cy), (int)(node.Key.Z - cz)); bs.Center = middle + world.Translation; if (ContainmentType.Disjoint == frustum.Contains(bs)) continue; effect.WMatrix = world; effect.BeginPass3D(); device.Indices = Static.Indices; device.Vertices[0].SetSource(node.Value.VertexBuffer, 0, VertexAwesome.SizeInBytes); Action<int> draw = i => { if (node.Value.Count[i] != 0) { device.DrawIndexedPrimitives(PrimitiveType.TriangleList, node.Value.Offset[i], 0, node.Value.Count[i], 0, node.Value.Count[i] / 2); vertices += node.Value.Count[i]; } }; if (node.Key.Z - cz - 1 > 0x80000000) draw(0); if (node.Key.Z - cz + 16 < 0x80000000) draw(1); if (node.Key.X - cx - 1 > 0x80000000) draw(2); if (node.Key.X - cx + 16 < 0x80000000) draw(3); if (node.Key.Y - cy - 1 > 0x80000000) draw(4); if (node.Key.Y - cy + 16 < 0x80000000) draw(5); if (node.Value.Count[6] != 0) { device.DrawPrimitives(PrimitiveType.TriangleList, node.Value.Offset[6], node.Value.Count[6] / 3); vertices += node.Value.Count[6]; } effect.EndPass3D(); } this.Vertices = vertices; }
public bool CheckFrustumIntersection(BoundingFrustum boundingFrustum) { ContainmentType con = boundingFrustum.Contains(model.BoundingSphere); if (con == ContainmentType.Contains || con == ContainmentType.Intersects) return true; return false; }
public void Render(Camera camera) { // If this node should be split, then render the four children instead if (splitIntoChildren) { foreach (TerrainChunk child in children) { child.Render(camera); } } else { IGraphicsDeviceService igs = (IGraphicsDeviceService)quadTree.Game.Services.GetService(typeof(IGraphicsDeviceService)); GraphicsDevice graphicsDevice = igs.GraphicsDevice; // Do frustum culling BoundingFrustum frustum = new BoundingFrustum(camera.ViewMatrix * camera.ProjMatrix); ContainmentType containment; frustum.Contains(ref boundingBox, out containment); if (containment == ContainmentType.Disjoint) return; // Prepare the effect quadTree.TerrainShader.Parameters["world"].SetValue(worldTransform); quadTree.TerrainShader.Parameters["view"].SetValue(camera.ViewMatrix); quadTree.TerrainShader.Parameters["proj"].SetValue(camera.ProjMatrix); quadTree.TerrainShader.Parameters["maxHeight"].SetValue(quadTree.Parameters.MaxHeight); quadTree.TerrainShader.Parameters["textureSize"].SetValue(quadTree.HeightMap.Width); quadTree.TerrainShader.Parameters["heightMap"].SetValue(quadTree.HeightMap); quadTree.TerrainShader.Parameters["grassMap"].SetValue(quadTree.LayerMap0); quadTree.TerrainShader.Parameters["rockMap"].SetValue(quadTree.LayerMap1); quadTree.TerrainShader.Parameters["snowMap"].SetValue(quadTree.LayerMap2); quadTree.TerrainShader.Parameters["normalMap"].SetValue(quadTree.NormalMap); quadTree.TerrainShader.Parameters["uStart"].SetValue(textureCoordinates.UStart); quadTree.TerrainShader.Parameters["uEnd"].SetValue(textureCoordinates.UEnd); quadTree.TerrainShader.Parameters["vStart"].SetValue(textureCoordinates.VStart); quadTree.TerrainShader.Parameters["vEnd"].SetValue(textureCoordinates.VEnd); // Render it! quadTree.TerrainShader.CurrentTechnique = quadTree.TerrainShader.Techniques["TerrainDraw"]; quadTree.TerrainShader.Begin(); foreach (EffectPass pass in quadTree.TerrainShader.CurrentTechnique.Passes) { pass.Begin(); quadTree.CommonGrid.Draw(); pass.End(); } quadTree.TerrainShader.End(); } }
public void Draw(Layer layer) { if (activeItem != null) { switch (activeItem.NextItem) { case TriggerType.MessageClose : break; default : SpriteBatch spriteBatch = GameState.spriteBatch; spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, null, Settings.spriteScale); foreach (TutorialPair pair in activeItem.PairList) { if (pair.Kind == PositionKind.POS_2D && layer == Layer.Layer3) { TextWrapping.DrawStringOnScreen(pair.Text, font, Settings.colorMainText, pair.Position.X, pair.Position.Y, spriteBatch, 50f); } else if (pair.Kind == PositionKind.POS_3D && layer == Layer.Layer1) { BoundingFrustum frustum = new BoundingFrustum(GameState.view * GameState.projection); ContainmentType containmentType = frustum.Contains(Vector3.Transform(new Vector3(0.0f, 0.0f, 0.0f), pair.World)); if (containmentType != ContainmentType.Disjoint) { Vector3 point3D = GameState.game.GraphicsDevice.Viewport.Project(new Vector3(0.0f, 0.0f, 0.0f), GameState.projection, GameState.view, pair.World); TextWrapping.DrawStringOnScreen(pair.Text, font, Settings.colorMainText, Settings.UnScaleW(point3D.X) + pair.Position.X, Settings.UnScaleH(point3D.Y) + pair.Position.Y, spriteBatch, 50f); } } } spriteBatch.End(); break; } } }
internal static void PrepareEntitiesForDraw(ref BoundingFrustum frustum, Vector3 cameraPosition, float cameraZoomDivider, MyOcclusionQueryID queryID, List<MyElement> renderObjectListForDraw, List<MyElement> cullObjectListForDraw, List<MyOcclusionQueryIssue> renderOcclusionQueries, ref int occludedItemsStats) { m_renderProfiler.StartProfilingBlock("PrepareEntitiesForDrawFr()"); if (queryID != MyOcclusionQueryID.MAIN_RENDER) { m_shadowPrunningStructure.OverlapAllFrustum(ref frustum, renderObjectListForDraw); m_renderProfiler.EndProfilingBlock(); return; } m_renderProfiler.StartProfilingBlock("m_cullingStructure.OverlapAllFrustum"); m_cullingStructure.OverlapAllFrustum(ref frustum, cullObjectListForDraw); m_renderProfiler.EndProfilingBlock(); if (renderOcclusionQueries != null) { //Process only big cull object for queries renderOcclusionQueries.Clear(); m_renderProfiler.StartProfilingBlock("PrepareObjectQueries"); PrepareObjectQueries(queryID, cullObjectListForDraw, renderOcclusionQueries, ref occludedItemsStats); m_renderProfiler.EndProfilingBlock(); } renderObjectListForDraw.Clear(); m_renderProfiler.StartProfilingBlock("m_prunningStructure.OverlapAllFrustum"); m_prunningStructure.OverlapAllFrustum(ref frustum, renderObjectListForDraw); //AssertRenderObjects(renderObjectListForDraw); m_renderProfiler.EndProfilingBlock(); m_renderProfiler.StartProfilingBlock("Get from cullobjects - part 1"); //int i = 1; if (queryID == MyOcclusionQueryID.MAIN_RENDER) { foreach (MyCullableRenderObject cullableObject in cullObjectListForDraw) { if (frustum.Contains(cullableObject.GetWorldSpaceAABB()) == MinerWarsMath.ContainmentType.Contains) { cullableObject.CulledObjects.GetAll(renderObjectListForDraw, false); } else { cullableObject.CulledObjects.OverlapAllFrustum(ref frustum, renderObjectListForDraw, false); // i++; } //AssertRenderObjects(renderObjectListForDraw); //BoundingBox aabb = new BoundingBox(new Vector3(float.MinValue), new Vector3(float.MaxValue)); //cullableObject.CulledObjects.OverlapAllBoundingBox(ref aabb, renderObjectListForDraw, false); //cullableObject.CulledObjects.GetAll(renderObjectListForDraw, false); } } else { foreach (MyCullableRenderObject cullableObject in cullObjectListForDraw) { if (frustum.Contains(cullableObject.GetWorldSpaceAABB()) == MinerWarsMath.ContainmentType.Contains) { cullableObject.CulledObjects.GetAll(renderObjectListForDraw, false); } else { cullableObject.CulledObjects.OverlapAllFrustum(ref frustum, renderObjectListForDraw, false); } //cullableObject.CulledObjects.OverlapAllFrustum(ref frustum, renderObjectListForDraw, false); //cullableObject.CulledObjects.GetAll(renderObjectListForDraw, false); } } m_renderProfiler.EndProfilingBlock(); m_renderProfiler.StartProfilingBlock("Get from cullobjects - part 2"); int c = 0; if (queryID == MyOcclusionQueryID.MAIN_RENDER) { //int ii = 0; while (c < renderObjectListForDraw.Count) { MyRenderObject ro = renderObjectListForDraw[c] as MyRenderObject; if (!ro.SkipIfTooSmall) { c++; continue; } Vector3 entityPosition = ro.Entity.GetPosition(); Vector3.Distance(ref cameraPosition, ref entityPosition, out ro.Distance); ro.Distance = MyCamera.GetDistanceWithFOV(ro.Distance); float cullRatio = ro.Entity is MyStaticAsteroid ? 75 : MyRenderConstants.DISTANCE_CULL_RATIO; if (ro.Entity is MinerWars.AppCode.Game.Entities.SubObjects.MyPrefabLargeWeapon || ro.Entity is MinerWars.AppCode.Game.Entities.Weapons.MyLargeShipBarrelBase || ro.Entity is MinerWars.AppCode.Game.Entities.Weapons.MyLargeShipGunBase) { cullRatio = 250; } if (ro.Entity.WorldVolume.Radius < ro.Distance / cullRatio) { renderObjectListForDraw.RemoveAtFast(c); continue; } //float f = ro.Distance / (2 * (float)Math.Tan(Math.PI * MyCamera.FieldOfView)); //if (f > ro.Entity.LocalVolume.Radius * 100) //{ // renderObjectListForDraw.RemoveAtFast(c); // continue; //} c++; } } m_renderProfiler.EndProfilingBlock(); m_renderProfiler.EndProfilingBlock(); }
public void DrawObjects() { try { lock (gameObjects) { ObjectsDrawn = 0; foreach (Gobject go in gameObjects.Values) { BoundingFrustum frustum = new BoundingFrustum(view * proj); if (frustum.Contains(go.Skin.WorldBoundingBox) != ContainmentType.Disjoint) { ObjectsDrawn++; if (DrawingEnabled) { if (go is Terrain) { (go as Terrain).Draw(GraphicsDevice, view, proj); } else if (go is Planet) { (go as Planet).Draw(GraphicsDevice, view, proj); } else go.Draw(ref view, ref proj); } if (game.DebugPhysics) go.DrawWireframe(GraphicsDevice, view, proj); } } } } catch (Exception E) { System.Diagnostics.Debug.WriteLine(E.StackTrace); } }
/// <summary> /// Provides the behavior for the Arrange pass of Silverlight layout. /// </summary> /// <param name="finalSize">The final area within the parent that this /// object should use to arrange itself and its children.</param> /// <returns> /// The actual size that is used after the element is arranged in layout. /// </returns> protected override Size ArrangeOverride(Size finalSize) { if (ActualWidth > 0 && ActualHeight > 0 && (motion != null && motion.IsDataValid || IsDesignMode)) { this.FirsVectorInView = null; BoundingFrustum viewFrustum = new BoundingFrustum(Attitude * view * CameraProjection); foreach (var child in Children) { object posObj = child.GetValue(DirectionProperty); if (posObj is Point && !double.IsNaN(((Point)posObj).X)) { Point p = (Point)posObj; Vector3 direction = PolarToVector(p.X, p.Y, 10); var size = child.DesiredSize; //Create a bounding sphere around the element for hittesting against the current frustum //This size is not entirely right... size we have is screen size but we use the world size. //*.008 seems to roughly fit as conversion factor for now var box = new BoundingSphere(direction, (float)Math.Max(size.Width, size.Height) * .008f); if (viewFrustum.Contains(box) != ContainmentType.Disjoint) //partially or fully inside camera frustum { Vector3 projected = Project(direction); if (this.FirsVectorInView == null) { this.FirsVectorInView = projected; } if (!float.IsNaN(projected.X) && !float.IsNaN(projected.Y)) { //Arrange element centered on projected coordinate double x = projected.X - size.Width * .5; double y = projected.Y - size.Height * .5; child.Arrange(new Rect(x, y, size.Width, size.Height)); continue; } } } //if we fall through to here, it's because the element is outside the view, //or placement can't be calculated child.Arrange(new Rect(0, 0, 0, 0)); } return finalSize; } else return base.ArrangeOverride(finalSize); }
public bool IsInView(Point directionPoint) { BoundingFrustum viewFrustum = new BoundingFrustum(Attitude * view * CameraProjection); object posObj = directionPoint; if (posObj is Point && !double.IsNaN(((Point)posObj).X)) { Point p = (Point)posObj; Vector3 direction = PolarToVector(p.X, p.Y, 10); //Create a bounding sphere around the element for hittesting against the current frustum //This size is not entirely right... size we have is screen size but we use the world size. //*.008 seems to roughly fit as conversion factor for now var box = new BoundingSphere(direction, 10 * .008f); if (viewFrustum.Contains(box) != ContainmentType.Disjoint) //partially or fully inside camera frustum { return true; } } return false; }
public static void Intersects(ref Ray ray, ref BoundingFrustum boundingFrustum, out float? result) { // TODO: Make test case of this if (boundingFrustum.Contains(ray.Position) == ContainmentType.Contains) { // the ray is inside the frustum result = 0.0f; } else { result = null; var corners = boundingFrustum.GetCorners(); for (int i = 0; i < (BoundingFrustum.PlaneCount * 2); i++) { var v1 = corners[Geometry.TriangleIndices[i + 0]]; var v2 = corners[Geometry.TriangleIndices[i + 1]]; var v3 = corners[Geometry.TriangleIndices[i + 2]]; Intersects(ref ray, ref v1, ref v2, ref v3, out result); if (result.HasValue) break; } } }
public void Render(BoundingFrustum frustum) { int vertices = 0; BoundingSphere bs = new BoundingSphere(); uint cx = x; uint cy = y; //cache = anti-earthquake uint cz = z; foreach (var node in vertexBuffers.AsEnumerable) { if (node.Value == null) continue; var world = Matrix.CreateTranslation((int)(node.Key.X - cx), (int)(node.Key.Y - cy), (int)(node.Key.Z - cz)); bs.Radius = 16; bs.Center = Vector3.Transform(new Vector3(8, 8, 8), world); if (ContainmentType.Disjoint == frustum.Contains(bs)) continue; effect.WMatrix = world; effect.BeginPass3D(); if (node.Value[0] != null && node.Key.Z - cz - 1 > 0x80000000) { device.Vertices[0].SetSource(node.Value[0], 0, VertexAwesome.SizeInBytes); device.DrawPrimitives(PrimitiveType.TriangleList, 0, node.Value[0].SizeInBytes / VertexAwesome.SizeInBytes / 3); vertices += node.Value[0].SizeInBytes / VertexAwesome.SizeInBytes; } if (node.Value[1] != null && node.Key.Z - cz + 16 < 0x80000000) { device.Vertices[0].SetSource(node.Value[1], 0, VertexAwesome.SizeInBytes); device.DrawPrimitives(PrimitiveType.TriangleList, 0, node.Value[1].SizeInBytes / VertexAwesome.SizeInBytes / 3); vertices += node.Value[1].SizeInBytes / VertexAwesome.SizeInBytes; } if (node.Value[2] != null && node.Key.X - cx - 1 > 0x80000000) { device.Vertices[0].SetSource(node.Value[2], 0, VertexAwesome.SizeInBytes); device.DrawPrimitives(PrimitiveType.TriangleList, 0, node.Value[2].SizeInBytes / VertexAwesome.SizeInBytes / 3); vertices += node.Value[2].SizeInBytes / VertexAwesome.SizeInBytes; } if (node.Value[3] != null && node.Key.X - cx + 16 < 0x80000000) { device.Vertices[0].SetSource(node.Value[3], 0, VertexAwesome.SizeInBytes); device.DrawPrimitives(PrimitiveType.TriangleList, 0, node.Value[3].SizeInBytes / VertexAwesome.SizeInBytes / 3); vertices += node.Value[3].SizeInBytes / VertexAwesome.SizeInBytes; } if (node.Value[4] != null && node.Key.Y - cy - 1 > 0x80000000) { device.Vertices[0].SetSource(node.Value[4], 0, VertexAwesome.SizeInBytes); device.DrawPrimitives(PrimitiveType.TriangleList, 0, node.Value[4].SizeInBytes / VertexAwesome.SizeInBytes / 3); vertices += node.Value[4].SizeInBytes / VertexAwesome.SizeInBytes; } if (node.Value[5] != null && node.Key.Y - cy + 16 < 0x80000000) { device.Vertices[0].SetSource(node.Value[5], 0, VertexAwesome.SizeInBytes); device.DrawPrimitives(PrimitiveType.TriangleList, 0, node.Value[5].SizeInBytes / VertexAwesome.SizeInBytes / 3); vertices += node.Value[5].SizeInBytes / VertexAwesome.SizeInBytes; } if (node.Value[6] != null) { device.Vertices[0].SetSource(node.Value[6], 0, VertexAwesome.SizeInBytes); device.DrawPrimitives(PrimitiveType.TriangleList, 0, node.Value[6].SizeInBytes / VertexAwesome.SizeInBytes / 3); vertices += node.Value[6].SizeInBytes / VertexAwesome.SizeInBytes; } effect.EndPass3D(); } this.Vertices = vertices; }
public void DrawShadows(Effect depthWriter, BoundingFrustum cameraFrustrum) { BoundingBox transformedBox = XNAUtils.TransformBoundingBox(nodeBoundingBox, Matrix.Identity); ContainmentType cameraNodeContainment = cameraFrustrum.Contains(transformedBox); if (cameraNodeContainment != ContainmentType.Disjoint) { if (isEndNode) { DrawShadow(depthWriter); } else { nodeUL.DrawShadows(depthWriter, cameraFrustrum); nodeUR.DrawShadows(depthWriter, cameraFrustrum); nodeLL.DrawShadows(depthWriter, cameraFrustrum); nodeLR.DrawShadows(depthWriter, cameraFrustrum); } } }
/// <summary> /// Randomly calculates a few Bodies' distances to the Focus /// Then sorts the resulting list /// Then calculates the screen size of the closest items /// In the Process, a list of active Bodies and their containers is made /// </summary> /// <param name="Focus">Unprojection of the middle of the screen into a ray</param> /// <param name="Bodies">Will be rearranged</param> /// <param name="VisibleBodies">Should be cleared before input from Manager</param> /// <param name="ContainingBodies">Should be cleared before input from Manager</param> public static void PartiallySortBodies(Ray Focus, BoundingFrustum VisibleArea, ref List<Body> Bodies , ref List<Body> VisibleBodies, ref List<Body> ContainingBodies) { List<Body> CalculatorBodies = new List<Body>(); int calculators = (int)Math.Sqrt(Bodies.Count); for (int i = 0; i < calculators && Bodies.Count > 0; i++) { int index = MyGame.random.Next(Bodies.Count); CalculatorBodies.Add(Bodies[index]); Bodies.RemoveAt(index); Vector3 FocusToBody = CalculatorBodies[i].Transforms.Position - Focus.Position; CalculatorBodies[i].DistanceToCenter = (FocusToBody - Focus.Direction * Vector3.Dot(FocusToBody, Focus.Direction)).Length(); } Bodies.AddRange(CalculatorBodies); CalculatorBodies.Clear(); //Merge Sort with two lists List<List<Body>> MergeBodies = new List<List<Body>>(); for (int i = 0; i < Bodies.Count; i++) { MergeBodies.Add(new List<Body>()); MergeBodies[i].Add(Bodies[i]); } while (MergeBodies.Count > 1) { for (int i = 0; i < MergeBodies.Count - 1; i++) { for (int a = 0; a < MergeBodies[i].Count; a++) { for (int b = 0; b < MergeBodies[i + 1].Count; b++) { if (MergeBodies[i + 1][b].DistanceToCenter < MergeBodies[i][a].DistanceToCenter) { MergeBodies[i].Insert(a++, MergeBodies[i + 1][b]); MergeBodies[i + 1].RemoveAt(b--); } } } MergeBodies[i].AddRange(MergeBodies[i + 1]); MergeBodies.RemoveAt(i + 1); } } Bodies = MergeBodies[0]; //Screen size calculation for (int i = 0; i < Bodies.Count; i++) { Bodies[i].ScreenPosition = Cursor.Project(VisibleArea , Bodies[i].Bounds.Center); Bodies[i].ScreenScale = (float)Math.Atan2( Bodies[i].Bounds.Radius , (Bodies[i].Bounds.Center - Manager.CameraFocus - Manager.CameraLocation).Length()) * Manager.GameWindow.Width / 2.0f; if (VisibleArea.Contains(Bodies[i].Bounds) != ContainmentType.Disjoint) { if (Bodies[i].ScreenScale / 10 > 1.0f) { Bodies[i].InitializeNestedBodies(); } else { Bodies[i].DisposeNextedBodies(); } if (Bodies[i].ScreenScale > Manager.GameWindow.Width / 10.0f) { if (Bodies[i].NestedBodies.Count > 0) { PartiallySortBodies(Focus, VisibleArea, ref Bodies[i].NestedBodies, ref VisibleBodies, ref ContainingBodies); float DisplayOpacity = Bodies[i].ScreenScale / Manager.GameWindow.Width * 10.0f - 1.0f; if (DisplayOpacity > 1.0f) { DisplayOpacity = 1.0f; } for (int j = 0; j < Bodies[i].NestedBodies.Count; j++) { Bodies[i].NestedBodies[j].DisplayOpacity = DisplayOpacity; } Bodies[i].DisplayOpacity = 1.0f - DisplayOpacity; ContainingBodies.Add(Bodies[i]); } else { VisibleBodies.Add(Bodies[i]); } } else { VisibleBodies.Add(Bodies[i]); } } } }
internal IEnumerable<Entity> GetEntitiesInView(BoundingFrustum bf) { return entities.Where(x => bf.Contains(x.Box) == ContainmentType.Contains).Except(new[]{player}); }
public void Render(BoundingFrustum frustum, WorldPosition hoverBox) { int vertices = 0; uint cx = x; uint cy = y; //cache = anti-earthquake uint cz = z; Matrix world = Matrix.Identity; Vector3 middle = new Vector3(8, 8, 8); foreach (var node in vertexBuffers.AsEnumerable) { if (node.Value == null) continue; world.Translation = new Vector3((int)(node.Key.X - cx), (int)(node.Key.Y - cy), (int)(node.Key.Z - cz)); bs.Center = middle + world.Translation; if (ContainmentType.Disjoint == frustum.Contains(bs)) continue; effect.WMatrix = world; effect.BeginPass3D(); device.Indices = Static.Indices; VBuffer7 vbuffer = node.Value; device.Vertices[0].SetSource(vbuffer.VertexBuffer, 0, VertexAwesome.SizeInBytes); Action<int> draw = i => { if (vbuffer.Count[i] != 0) { device.DrawIndexedPrimitives(PrimitiveType.TriangleList, vbuffer.Offset[i], 0, vbuffer.Count[i], 0, vbuffer.Count[i] / 2); vertices += vbuffer.Count[i]; } }; if (node.Key.Z - cz - 1 > 0x80000000) draw(0); if (node.Key.Z - cz + 16 < 0x80000000) draw(1); if (node.Key.X - cx - 1 > 0x80000000) draw(2); if (node.Key.X - cx + 16 < 0x80000000) draw(3); if (node.Key.Y - cy - 1 > 0x80000000) draw(4); if (node.Key.Y - cy + 16 < 0x80000000) draw(5); draw(6); effect.EndPass3D(); } this.Vertices = vertices; //hovered box: if (hoverBox != null) { Static.Effect.LightDirection = Vector3.Backward; Static.Effect.AmbientLightColor = Color.LightGreen.ToVector4(); hoverBoxMesh.Draw(Matrix.CreateTranslation((int)(hoverBox.X - cx), (int)(hoverBox.Y - cy), (int)(hoverBox.Z - cz))); } }
public void BoundingFrustumToBoundingFrustumTests() { var view = Matrix.CreateLookAt(new Vector3(0, 0, 5), Vector3.Zero, Vector3.Up); var projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, 1, 1, 100); var testFrustum = new BoundingFrustum(view * projection); // Same frustum. Assert.That(testFrustum.Contains(testFrustum), Is.EqualTo(ContainmentType.Contains)); Assert.That(testFrustum.Intersects(testFrustum), Is.True); var otherFrustum = new BoundingFrustum(Matrix.Identity); // Smaller frustum contained entirely inside. var view2 = Matrix.CreateLookAt(new Vector3(0, 0, 4), Vector3.Zero, Vector3.Up); var projection2 = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, 1, 1, 50); otherFrustum.Matrix = view2 * projection2; Assert.That(testFrustum.Contains(otherFrustum), Is.EqualTo(ContainmentType.Contains)); Assert.That(testFrustum.Intersects(otherFrustum), Is.True); // Same size frustum, pointing in the same direction and offset by a small amount. otherFrustum.Matrix = view2 * projection; Assert.That(testFrustum.Contains(otherFrustum), Is.EqualTo(ContainmentType.Intersects)); Assert.That(testFrustum.Intersects(otherFrustum), Is.True); // Same size frustum, pointing in the opposite direction and not overlapping. var view3 = Matrix.CreateLookAt(new Vector3(0, 0, 6), new Vector3(0, 0, 7), Vector3.Up); otherFrustum.Matrix = view3 * projection; Assert.That(testFrustum.Contains(otherFrustum), Is.EqualTo(ContainmentType.Disjoint)); Assert.That(testFrustum.Intersects(otherFrustum), Is.False); // Larger frustum, entirely containing test frustum. var view4 = Matrix.CreateLookAt(new Vector3(0, 0, 10), Vector3.Zero, Vector3.Up); var projection4 = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, 1, 1, 1000); otherFrustum.Matrix = view4 * projection4; Assert.That(testFrustum.Contains(otherFrustum), Is.EqualTo(ContainmentType.Intersects)); Assert.That(testFrustum.Intersects(otherFrustum), Is.True); }
/// /// Draws the octree. /// /// The viewing matrix. /// The projection matrix. /// The objects in the octree. /// The number of octrees drawn. public int Draw(Matrix view, Matrix projection, List objects) { BoundingFrustum frustum = new BoundingFrustum(view * projection); ContainmentType containment = frustum.Contains(this.bounds); return this.Draw(frustum, view, projection, containment, objects); }
/// /// Draws the octree. /// /// The viewing frustum used to determine if the octree is in view. /// The viewing matrix. /// The projection matrix. /// Determines how much of the octree is visible. /// The objects in the octree. /// The number of octrees drawn. private int Draw(BoundingFrustum frustum, Matrix view, Matrix projection, ContainmentType containment, List objects) { int count = 0; if (containment != ContainmentType.Contains) { containment = frustum.Contains(this.bounds); } // Draw the octree only if it is atleast partially in view. if (containment != ContainmentType.Disjoint) { // Draw the octree's bounds if there are objects in the octree. if (this.objects.Count > 0) { if (DebugDraw != null) DebugDraw.AddShape(new DebugBox(this.bounds, Color.White)); objects.AddRange(this.objects); count++; } // Draw the octree's children. if (this.children != null) { foreach (Octree child in this.children) { count += child.Draw(frustum, view, projection, containment, objects); } } } return count; }
public void Draw2D() { BoundingFrustum frustum = new BoundingFrustum(GameState.view * GameState.projection); ContainmentType containmentType = frustum.Contains(Vector3.Transform(new Vector3(0.0f, 0.0f, 0.0f), world)); centerOnScreen = containmentType != ContainmentType.Disjoint; if (kind == HexaKind.Water) { return; } if (containmentType != ContainmentType.Disjoint) { Vector3 point3D = GameState.game.GraphicsDevice.Viewport.Project(new Vector3(0.0f, 0.0f, 0.0f), GameState.projection, GameState.view, world); Vector2 point2D = new Vector2(); Vector2 posHexaIcon = new Vector2(); point2D.X = point3D.X; point2D.Y = point3D.Y; posHexaIcon = point2D; Texture2D playerIcon = GameResources.Inst().GetHudTexture(HUDTexture.PlayerColor); Rectangle playerIconRect = new Rectangle((int)point2D.X - playerIcon.Width / 2, (int)point2D.Y - playerIcon.Height / 2, playerIcon.Width, playerIcon.Height); SpriteBatch spriteBatch = GameState.spriteBatch; Vector2 stringCenter = GameResources.Inst().GetFont(EFont.MedievalMedium).MeasureString(model.GetCurrentSource() + "") * 0.5f; /* x, y coord Vector2 stringCenter = GameResources.Inst().GetFont(EFont.MedievalMedium).MeasureString("[" + x + ";" + y + "]") * 0.5f; */ // now subtract the string center from the text position to find correct position point2D.X = (int)(point2D.X - stringCenter.X); point2D.Y = (int)(point2D.Y - stringCenter.Y); spriteBatch.Begin(); /* x, y coord if (kind == HexaKind.Water) { DrawHexaNumber(spriteBatch, point2D); spriteBatch.End(); return; }*/ bool drawNumber = true; TownModel tempTown = null; if (GameMaster.Inst().GetFortState() == EFortState.Normal) { foreach (TownView town in townView) { if (town.getIsMarked()) { tempTown = town.getTownModel(); if (tempTown.GetBuildingKind(hexaID) != BuildingKind.NoBuilding || tempTown.GetOwner() == GameMaster.Inst().GetActivePlayer()) drawNumber = false; break; } } if (drawNumber && pickVars.pickActive) { HUDTexture texture = HUDTexture.HUDCount; switch (kind) { case HexaKind.Cornfield: texture = HUDTexture.SmallCorn; break; case HexaKind.Forest: texture = HUDTexture.SmallWood; break; case HexaKind.Mountains: texture = HUDTexture.SmallOre; break; case HexaKind.Pasture: texture = HUDTexture.SmallMeat; break; case HexaKind.Stone: texture = HUDTexture.SmallStone; break; } if(texture != HUDTexture.HUDCount) DrawHexaIcon(spriteBatch, posHexaIcon, texture, texture); } } else { if (!IsInFortRadius())// || (GameMaster.Inst().GetFortState() == EFortState.DestroyingHexa && model.GetDestroyed())) drawNumber = false; } if (GameMaster.Inst().GetFortState() != EFortState.Normal)// && //(GameMaster.Inst().GetFortState() != EFortState.DestroyingHexa || !model.GetDestroyed())) { HUDTexture textPassive = HUDTexture.DestroyPassive, textActive = HUDTexture.DestroyActive; if (IsInFortRadius()) { switch(GameMaster.Inst().GetFortState()) { case EFortState.CapturingHexa: textPassive = HUDTexture.SwordsPassive; textActive = HUDTexture.SwordsActive; break; case EFortState.DestroyingHexa: textPassive = HUDTexture.DestroyPassive; textActive = HUDTexture.DestroyActive; break; } DrawHexaIcon(spriteBatch, posHexaIcon, textPassive, textActive); } } if (model.GetCaptured()) { spriteBatch.Draw(playerIcon, playerIconRect, model.GetCapturedPlayer().GetColor()); } if (drawNumber) { DrawHexaNumber(spriteBatch, point2D); } else if(GameMaster.Inst().GetFortState() == EFortState.Normal) { if (tempTown.GetBuildingKind(hexaID) == BuildingKind.NoBuilding && tempTown.GetOwner() == GameMaster.Inst().GetActivePlayer()) { DrawHexaIcon(spriteBatch, posHexaIcon, HUDTexture.HammersPassive, HUDTexture.HammersActive); DrawHexaNumber(spriteBatch, point2D); } else { DrawHexaIcon(spriteBatch, posHexaIcon, tempTown.GetSpecialBuilding(hexaID).GetIconPassive(), tempTown.GetSpecialBuilding(hexaID).GetIconActive()); if (model.GetCaptured()) { spriteBatch.Draw(playerIcon, playerIconRect, model.GetCapturedPlayer().GetColor()); } if(tempTown.GetBuildingKind(hexaID) == BuildingKind.SourceBuilding) DrawHexaNumber(spriteBatch, point2D); } } spriteBatch.End(); } }
/// <summary> /// Draws every mesh within the model using ScalePositionRotation properties /// Draws all Nested Bodies with an Offset of Position /// </summary> public virtual void Draw(BoundingFrustum VisibleArea, Vector3 Position) { if (VisibleArea.Contains(Bounds) != ContainmentType.Disjoint) { if (ModelVertices != null) { Matrix transform = transforms.Rotation * Matrix.CreateScale(transforms.Scale) * Matrix.CreateTranslation(transforms.Position + Position); effect.Parameters["World"].SetValue(transform); MyGame.graphics.GraphicsDevice.VertexDeclaration = DefaultDeclaration; effect.Begin(); effect.CurrentTechnique.Passes.First<EffectPass>().Begin(); MyGame.graphics.GraphicsDevice.DrawUserIndexedPrimitives<VertexPositionTexture>( PrimitiveType.TriangleList , ModelVertices , 0 , ModelVertices.Length , ModelIndices , 0 , ModelIndices.Length / 3); effect.CurrentTechnique.Passes.First<EffectPass>().End(); effect.End(); } for (int i = 0; i < NestedBodies.Count; i++) { NestedBodies[i].Draw(VisibleArea, transforms.Position + Position); } } }
/// <summary> /// Helper Draw function. Determines what objects are fully visible and what objects are transparent. /// </summary> private void FindVisible() { currentFrustum = new BoundingFrustum(CurrentCamera.View * CurrentCamera.Projection); Matrix transView = Matrix.CreateLookAt(CurrentCamera.Position, CurrentCamera.TargetPosition - Vector3.UnitZ * 30, Vector3.UnitZ); Matrix trans1Proj = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4 / 15, (float)GraphicOptions.graphics.GraphicsDevice.Viewport.Width / (float)GraphicOptions.graphics.GraphicsDevice.Viewport.Height, 10f, 475f); transparent1Frustum = new BoundingFrustum(transView * trans1Proj); //this section updates each entity and then determines if they are within the bounding frustum drawableEntities.Clear(); transparentEntities.Clear(); int i = 0; foreach (SceneLayer layer in layers) { drawableEntities.Add(new SceneLayer()); transparentEntities.Add(new SceneLayer()); drawableEntities[i].DrawLayer = layer.DrawLayer; transparentEntities[i].DrawLayer = layer.DrawLayer; foreach (KeyValuePair<int, Object3> ent in layer.entityDictionary3D) { if (currentFrustum.Contains(ent.Value.BoundingSphere) != ContainmentType.Disjoint) { if (transparent1Frustum.Contains(ent.Value.BoundingSphere) != ContainmentType.Disjoint && ent.Value.TransparencyEnabled && GraphicOptions.TransparentWalls) { transparentEntities[i].Add(ent); } if (transparent1Frustum.Contains(ent.Value.BoundingSphere) != ContainmentType.Contains || !ent.Value.TransparencyEnabled || !GraphicOptions.TransparentWalls) { drawableEntities[i].Add(ent); } } } foreach (KeyValuePair<int, VertexGroup> ent in layer.entityDictionaryVertex) { drawableEntities[i].Add(ent); } foreach (KeyValuePair<int, ParticleEmitter> ent in layer.entityDictionaryEmitter) { if (currentFrustum.Contains(ent.Value.BoundingSphere) != ContainmentType.Disjoint) { drawableEntities[i].Add(ent); } else { ent.Value.OutOfFrustumDraw(); } } foreach (KeyValuePair<int, VertexColorGroup> ent in layer.entityDictionaryVertexColor) { // if (currentFrustum.Contains(ent.Value.BoundingSphere) != ContainmentType.Disjoint) // { drawableEntities[i].Add(ent); // } } foreach (KeyValuePair<int, VertexPositionColorTextureGroup> ent in layer.entityDictionaryVPCT) { // if (currentFrustum.Contains(ent.Value.BoundingSphere) != ContainmentType.Disjoint) // { drawableEntities[i].Add(ent); // } } i++; } }
public void GetChunksIntersecting(BoundingFrustum frustum, HashSet<VoxelChunk> chunks) { chunks.Clear(); BoundingBox frustumBox = MathFunctions.GetBoundingBox(frustum.GetCorners()); GetChunksIntersecting(frustumBox, chunks); chunks.RemoveWhere(chunk => frustum.Contains(chunk.GetBoundingBox()) == ContainmentType.Disjoint); }