コード例 #1
0
ファイル: Version5.cs プロジェクト: Bigtalljosh/Devoxelation
        public override void Initialize()
        {
            // initiate the viewport
            ContentManager Content  = ScreenManager.Game.Content;
            Viewport       viewport = ScreenManager.GraphicsDevice.Viewport;

            staticVBRenderer = new StaticVBRenderer[(int)xychunks, (int)xychunks][];
            occlusionCull    = new OcclusionQuery(ScreenManager.GraphicsDevice);
            ScreenManager.Game.IsFixedTimeStep = false;

            raster = ScreenManager.GraphicsDevice.RasterizerState.ToString();

            //Textures
            kootenayFont   = Content.Load <SpriteFont>("Fonts\\Kootenay");
            staticVBEffect = Content.Load <Effect>("VertexBuffer");
            Textures[0]    = Content.Load <Texture2D>("Textures\\CubeTextures\\Stone");
            Textures[1]    = Content.Load <Texture2D>("Textures\\CubeTextures\\Grass");
            Textures[2]    = Content.Load <Texture2D>("Textures\\CubeTextures\\dirt");
            Textures[3]    = Content.Load <Texture2D>("Textures\\CubeTextures\\water_noborder");

            //Call map generation, at bottom
            GenerateMap();

            base.Initialize();
        }
コード例 #2
0
ファイル: LensFlare.cs プロジェクト: redchew-fork/C3DE
        public override void Start()
        {
            base.Start();

            _graphicsDevice = Application.GraphicsDevice;

            ColorWriteDisable = new BlendState()
            {
                ColorWriteChannels = ColorWriteChannels.None
            };

            _effect      = new BasicEffect(_graphicsDevice);
            _effect.View = Matrix.Identity;
            _effect.VertexColorEnabled = true;

            _queryVertices             = new VertexPositionColor[4];
            _queryVertices[0].Position = new Vector3(-QuerySize / 2, -QuerySize / 2, -1);
            _queryVertices[1].Position = new Vector3(QuerySize / 2, -QuerySize / 2, -1);
            _queryVertices[2].Position = new Vector3(-QuerySize / 2, QuerySize / 2, -1);
            _queryVertices[3].Position = new Vector3(QuerySize / 2, QuerySize / 2, -1);

            _occlusionQuery = new OcclusionQuery(_graphicsDevice);

            _spriteBatch = new SpriteBatch(_graphicsDevice);
            _light       = GetComponent <Light>();
        }
コード例 #3
0
ファイル: LensFlareComponent.cs プロジェクト: xgrommx/Ocean
        public LensFlareComponent(SpriteBatch sprite, ContentManager cont, GraphicsDevice device)
        {
            this.spriteBatch = sprite;
            glowSprite       = cont.Load <Texture2D>("Textures/glow");

            foreach (Flare flare in flares)
            {
                flare.Texture = cont.Load <Texture2D>("Textures/" + flare.TextureName);
            }


            basicEffect = new BasicEffect(device);

            basicEffect.View = Matrix.Identity;
            basicEffect.VertexColorEnabled = true;

            queryVertices = new VertexPositionColor[4];

            queryVertices[0].Position = new Vector3(-querySize / 2, -querySize / 2, -1);
            queryVertices[1].Position = new Vector3(querySize / 2, -querySize / 2, -1);
            queryVertices[2].Position = new Vector3(-querySize / 2, querySize / 2, -1);
            queryVertices[3].Position = new Vector3(querySize / 2, querySize / 2, -1);

            occlusionQuery = new OcclusionQuery(device);
        }
コード例 #4
0
        /// <summary>
        /// Initializes this instance.
        /// </summary>
        public virtual void Initialize(GraphicInfo ginfo, GraphicFactory factory, IObject obj)
        {
            #if !WINDOWS_PHONE && !REACH
            basicDraw             = factory.GetEffect("clippingPlane", false, true);
            getDepth              = factory.GetEffect("ShadowDepth", false, true);
            BasicDrawSamplerState = SamplerState.LinearWrap;
            #endif
            if (useOcclusionCulling)
            {
                if (Modelo == null)
                {
                    Modelo = new SimpleModel(factory, "block", true);
                }

                if (BasicEffect == null)
                {
                    BasicEffect = factory.GetBasicEffect();
                    BasicEffect.TextureEnabled     = false;
                    BasicEffect.VertexColorEnabled = false;
                }

                if (BlendState == null)
                {
                    BlendState = new Microsoft.Xna.Framework.Graphics.BlendState();
                    BlendState.ColorWriteChannels = ColorWriteChannels.None;
                }
                OcclusionQuery     = factory.CreateOcclusionQuery();
                OcclusionQuery.Tag = "Begin";
            }
            this.GraphicFactory = factory;
            isInitialized       = true;
        }
コード例 #5
0
ファイル: LensFlare.cs プロジェクト: sjb8100/C3DE
        public override void Start()
        {
            base.Start();

            m_GraphicsDevice = Application.GraphicsDevice;

            ColorWriteDisable = new BlendState()
            {
                ColorWriteChannels = ColorWriteChannels.None
            };

            m_Effect      = new BasicEffect(m_GraphicsDevice);
            m_Effect.View = Matrix.Identity;
            m_Effect.VertexColorEnabled = true;

            m_QueryVertices             = new VertexPositionColor[4];
            m_QueryVertices[0].Position = new Vector3(-QuerySize / 2, -QuerySize / 2, -1);
            m_QueryVertices[1].Position = new Vector3(QuerySize / 2, -QuerySize / 2, -1);
            m_QueryVertices[2].Position = new Vector3(-QuerySize / 2, QuerySize / 2, -1);
            m_QueryVertices[3].Position = new Vector3(QuerySize / 2, QuerySize / 2, -1);

            m_OcclusionQuery = new OcclusionQuery(m_GraphicsDevice);

            m_SpriteBatch = new SpriteBatch(m_GraphicsDevice);
            m_Camera      = GetComponent <Camera>();

            if (m_Camera == null)
            {
                throw new Exception("A LensFlare component have to be attached on a camera.");
            }
        }
コード例 #6
0
ファイル: CLensFlare.cs プロジェクト: slagusev/FPSDesigner
        /// <summary>
        /// Loads the content used by the lensflare component.
        /// </summary>
        public void LoadContent(ContentManager Content, GraphicsDevice _graphicsDevice, SpriteBatch _spriteBatch, Vector3 lightDirection)
        {
            spriteBatch = _spriteBatch;

            glowSprite = Content.Load <Texture2D>("Textures/LensFlare/glow");

            foreach (Flare flare in flares)
            {
                flare.Texture = Content.Load <Texture2D>("Textures/LensFlare/" + flare.TextureName);
            }

            basicEffect = new BasicEffect(_graphicsDevice);

            basicEffect.View = Matrix.Identity;
            basicEffect.VertexColorEnabled = true;

            queryVertices = new VertexPositionColor[4];

            queryVertices[0].Position = new Vector3(-querySize / 2, -querySize / 2, -1);
            queryVertices[1].Position = new Vector3(querySize / 2, -querySize / 2, -1);
            queryVertices[2].Position = new Vector3(-querySize / 2, querySize / 2, -1);
            queryVertices[3].Position = new Vector3(querySize / 2, querySize / 2, -1);

            graphicsDevice = _graphicsDevice;
            LightDirection = Vector3.Normalize(lightDirection);
            occlusionQuery = new OcclusionQuery(graphicsDevice);
        }
コード例 #7
0
        /// <summary>
        /// A private constructor.
        /// </summary>
        private iWearTracker()
        {
            identifier       = "iWearTracker";
            isAvailable      = false;
            stereoAvailable  = false;
            trackerAvailable = false;
            sensorAvailable  = false;
            productID        = iWearDllBridge.IWRProductID.IWR_PROD_NONE;
            rotation         = Quaternion.Identity;
            yaw              = 0;
            pitch            = 0;
            roll             = 0;
            magneticData     = Vector3.Zero;
            accelerationData = Vector3.Zero;
            gyroData         = Vector3.Zero;
            lbGyroData       = Vector3.Zero;
            sensorData       = new iWearDllBridge.IWRSensorData();
            isHiDef          = (State.Device.GraphicsProfile == GraphicsProfile.HiDef);

            stereoHandle = ((IntPtr)(-1));
            // Setup a query, to provide GPU syncing method.
            if (isHiDef)
            {
                g_QueryGPU = new OcclusionQuery(State.Device);
            }
            windowBottomLine = 0;
        }
コード例 #8
0
        protected override void LoadContent()
        {
            // Instantiate a SpriteBatch
            spriteBatch = ToDisposeContent(new SpriteBatch(GraphicsDevice));

            // Loads a sprite font
            // The [Arial16.xml] file is defined with the build action [ToolkitFont] in the project
            arial16Font = Content.Load <SpriteFont>("Arial16");

            // Creates a basic effect
            basicEffect = ToDisposeContent(new BasicEffect(GraphicsDevice));
            basicEffect.DiffuseColor           = Color.OrangeRed.ToVector4();
            basicEffect.PreferPerPixelLighting = true;
            basicEffect.EnableDefaultLighting();

            // Creates torus primitive
            sphere = ToDisposeContent(GeometricPrimitive.Sphere.New(GraphicsDevice, 1.75f));

            pixelTexture = Texture2D.New(GraphicsDevice, 1, 1, GraphicsDevice.BackBuffer.Format);
            pixelTexture.SetData <Color>(new Color[] { Color.Green });

            occlusionQuery = new OcclusionQuery(GraphicsDevice);

            offscreenBuffer = RenderTarget2D.New(GraphicsDevice, 128, 128, GraphicsDevice.BackBuffer.Format);

            base.LoadContent();
        }
コード例 #9
0
        /// <summary>
        /// Loads the content used by the lensflare component.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a SpriteBatch for drawing the glow and flare sprites.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // Load the glow and flare textures.
            glowSprite = Game.Content.Load <Texture2D>("glow");

            foreach (Flare flare in flares)
            {
                flare.Texture = Game.Content.Load <Texture2D>(flare.TextureName);
            }

            // Effect for drawing occlusion query polygons.
            basicEffect = new BasicEffect(GraphicsDevice);

            basicEffect.View = Matrix.Identity;
            basicEffect.VertexColorEnabled = true;

            // Create vertex data for the occlusion query polygons.
            queryVertices = new VertexPositionColor[4];

            queryVertices[0].Position = new Vector3(-querySize / 2, -querySize / 2, -1);
            queryVertices[1].Position = new Vector3(querySize / 2, -querySize / 2, -1);
            queryVertices[2].Position = new Vector3(-querySize / 2, querySize / 2, -1);
            queryVertices[3].Position = new Vector3(querySize / 2, querySize / 2, -1);

            // Create the occlusion query object.
            occlusionQuery = new OcclusionQuery(GraphicsDevice);
        }
コード例 #10
0
 /// <summary>
 /// Dispose the <see cref="OcclusionQuery"/>
 /// </summary>
 public void Dispose()
 {
     if (query != null)
     {
         query.Dispose();
     }
     query = null;
 }
コード例 #11
0
      public int VisiblePixels; // The number of visible pixels.

      public void Dispose()
      {
        if (OcclusionQuery != null)
        {
          OcclusionQuery.Dispose();
          OcclusionQuery = null;
          TotalPixels = 0;
          VisiblePixels = 0;
        }
      }
コード例 #12
0
        public void MismatchedBeginEnd()
        {
            var occlusionQuery = new OcclusionQuery(gd);

            Assert.Throws <InvalidOperationException>(() => occlusionQuery.End());

            occlusionQuery.Begin();
            Assert.Throws <InvalidOperationException>(() => occlusionQuery.Begin());

            occlusionQuery.Dispose();
        }
コード例 #13
0
ファイル: BatchGroup.cs プロジェクト: jli94/Fracture
        public void Initialize(IBatchContainer container, int layer, Action <DeviceManager, object> before, Action <DeviceManager, object> after, object userData, bool addToContainer = true)
        {
            base.Initialize(container, layer, null, addToContainer);

            RenderManager  = container.RenderManager;
            _Before        = before;
            _After         = after;
            _UserData      = userData;
            IsReleased     = false;
            OcclusionQuery = null;
        }
コード例 #14
0
        public void MismatchedBeginEnd()
        {
            Game.DrawWith += (sender, e) =>
            {
                var occlusionQuery = new OcclusionQuery(Game.GraphicsDevice);

                Assert.Throws <InvalidOperationException>(() => occlusionQuery.End());

                occlusionQuery.Begin();
                Assert.Throws <InvalidOperationException>(() => occlusionQuery.Begin());
            };
            Game.Run();
        }
コード例 #15
0
        public ChunkMesh(string name, ChunkEffect chunkEffect)
            : base(name)
        {
            if (chunkEffect == null)
            {
                throw new ArgumentNullException("chunkEffect");
            }

            this.chunkEffect    = chunkEffect;
            this.graphicsDevice = chunkEffect.GraphicsDevice;

            occlusionQuery = new OcclusionQuery(graphicsDevice);
        }
コード例 #16
0
        public void ConstructorsAndProperties()
        {
            Assert.Throws <ArgumentNullException>(() => new OcclusionQuery(null));

            var occlusionQuery = new OcclusionQuery(gd);

            Assert.IsFalse(occlusionQuery.IsComplete);

            Assert.Throws <InvalidOperationException>(
                () => { var n = occlusionQuery.PixelCount; },
                "PixelCount throws when query not yet started.");

            occlusionQuery.Dispose();
        }
コード例 #17
0
        public LensFlare(GraphicsDevice graphicsDevice, SpriteBatch spriteBatch, Texture2D glowSprite, Texture2D[] flareSprites)
        {
            if (graphicsDevice == null)
            {
                throw new ArgumentNullException("graphicsDevice");
            }
            if (spriteBatch == null)
            {
                throw new ArgumentNullException("spriteBatch");
            }
            if (glowSprite == null)
            {
                throw new ArgumentNullException("glowSprite");
            }
            if (flareSprites == null)
            {
                throw new ArgumentNullException("flareSprites");
            }

            Enabled = true;

            this.graphicsDevice = graphicsDevice;
            this.spriteBatch    = spriteBatch;
            this.glowSprite     = glowSprite;

            for (int i = 0; i < flares.Length; i++)
            {
                var index = flares[i].TextureIndex;
                if (index < 0 || flareSprites.Length <= index)
                {
                    throw new InvalidOperationException("Invalid index of flare sprite: " + index);
                }

                flares[i].Texture = flareSprites[index];
            }

            basicEffect      = new BasicEffect(graphicsDevice);
            basicEffect.View = Matrix.Identity;
            basicEffect.VertexColorEnabled = true;

            queryVertices             = new VertexPositionColor[4];
            queryVertices[0].Position = new Vector3(-querySize / 2, -querySize / 2, -1);
            queryVertices[1].Position = new Vector3(querySize / 2, -querySize / 2, -1);
            queryVertices[2].Position = new Vector3(-querySize / 2, querySize / 2, -1);
            queryVertices[3].Position = new Vector3(querySize / 2, querySize / 2, -1);

            occlusionQuery = new OcclusionQuery(graphicsDevice);
        }
コード例 #18
0
        public void ConstructorsAndProperties()
        {
            Game.DrawWith += (sender, e) =>
            {
                Assert.Throws <ArgumentNullException>(() => new OcclusionQuery(null));

                var occlusionQuery = new OcclusionQuery(Game.GraphicsDevice);

                Assert.IsFalse(occlusionQuery.IsComplete);

                Assert.Throws <InvalidOperationException>(
                    () => { var n = occlusionQuery.PixelCount; },
                    "PixelCount throws when query not yet started.");
            };
            Game.Run();
        }
コード例 #19
0
        protected override void Initialize()
        {
            GameUtilities.Content        = Content;
            GameUtilities.GraphicsDevice = GraphicsDevice;

            debug.Initialize();
            shapeDrawer.Initialize();

            mainCamera = new Camera("cam", new Vector3(0, 5, 10), new Vector3(0, 0, -1));
            mainCamera.Initialize();

            occQuery = new OcclusionQuery(GraphicsDevice);
            octTree  = new OctTree(100, Vector3.Zero, 5);

            base.Initialize();
        }
コード例 #20
0
        /// <summary>
        /// Tries to create an occlusion query. An occlusion query object cannot be created every frame, only in a specific frame (every fourth frame). Created object must used only in the current frame. If the pixels are drawn successfully, it will call callback.
        /// </summary>
        /// <param name="callback"></param>
        /// <param name="callbackParameter"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public static bool TryCreateOcclusionQuery(OcclusionQueryResult callback, object callbackParameter, out OcclusionQuery query)
        {
            if (canCreateOcclusionQueriesCounter == 0)
            {
                var item = new OcclusionQueryItem();
                item.query = OcclusionQuery.Create();
                item.query.SetCondition(true);
                item.callback          = callback;
                item.callbackParameter = callbackParameter;
                occlusionQueries.Add(item);

                query = item.query;
                return(true);
            }

            query = OcclusionQuery.Invalid;
            return(false);
        }
コード例 #21
0
ファイル: Game1.cs プロジェクト: Fearonz/3D-Graphics
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            GameUtilities.Content        = Content;
            GameUtilities.GraphicsDevice = GraphicsDevice;

            debug.Initialize();
            shapeDrawer.Initialize();

            mainCamera = new Camera("cam", new Vector3(0, 5, 20), new Vector3(0, 0, -1));
            mainCamera.Initialize();

            //quadTree = new QuadTree(100, Vector2.Zero, 5);
            octTree  = new OctTree(100, Vector3.Zero, 5);
            occQuery = new OcclusionQuery(GraphicsDevice);
            // TODO: Add your initialization logic here

            base.Initialize();
        }
コード例 #22
0
ファイル: BatchGroup.cs プロジェクト: jli94/Fracture
        protected override void OnReleaseResources()
        {
            IsReleased     = true;
            OcclusionQuery = null;

            for (int i = 0, c = _DrawCalls.Count; i < c; i++)
            {
                var batch = _DrawCalls[i];
                if (batch != null)
                {
                    batch.ReleaseResources();
                }
            }

            _DrawCalls.Clear();

            base.OnReleaseResources();
        }
コード例 #23
0
        /// <inheritdoc/>
        protected override void Dispose(bool disposing, bool disposeData)
        {
            if (!IsDisposed)
            {
                if (disposing)
                {
                    OcclusionQuery.SafeDispose();
                    OcclusionQuery = null;
                    SunOcclusion   = 0;

                    if (disposeData)
                    {
                        CloudMap.SafeDispose();
                    }
                }

                base.Dispose(disposing, disposeData);
            }
        }
コード例 #24
0
        /// <summary>
        /// Load your graphics content.
        /// </summary>
        protected override void LoadContent()
        {
            // Load the model.
            model       = Content.Load <Model>("dude");
            font        = Content.Load <SpriteFont>("font");
            spriteBatch = new SpriteBatch(this.graphics.GraphicsDevice);
            transforms  = new Matrix[model.Bones.Count];
            // Setup a query, to provide GPU syncing method.
            g_QueryGPU = new OcclusionQuery(GraphicsDevice);

            defaultVP = graphics.GraphicsDevice.Viewport;
            leftVP    = graphics.GraphicsDevice.Viewport;
            rightVP   = graphics.GraphicsDevice.Viewport;

            leftVP.Height = graphics.PreferredBackBufferHeight;
            leftVP.Width  = graphics.PreferredBackBufferWidth / 2;
            leftVP.X      = 0;
            leftVP.Y      = 0;

            rightVP.Height = graphics.PreferredBackBufferHeight;
            rightVP.Width  = graphics.PreferredBackBufferWidth / 2;
            rightVP.X      = graphics.PreferredBackBufferWidth / 2;
            rightVP.Y      = 0;

            // Look up our custom skinning information.
            SkinningData skinningData = model.Tag as SkinningData;

            if (skinningData == null)
            {
                throw new InvalidOperationException
                          ("This model does not contain a SkinningData tag.");
            }

            // Create an animation player, and start decoding an animation clip.
            animationPlayer = new AnimationPlayer(skinningData);

            AnimationClip clip = skinningData.AnimationClips["Take 001"];

            animationPlayer.StartClip(clip);
        }
コード例 #25
0
        protected override void LoadContent()
        {
            this.m_SpriteBatch = new SpriteBatch(this.GraphicsDevice);

            this.m_GlowSprite = this.Content.Load <Texture2D>(@"Content\LensFlare\glow");
            foreach (Flare flare in m_Flares)
            {
                flare.Texture = this.Content.Load <Texture2D>(@"Content\LensFlare\" + flare.TextureName);
            }

            this.m_BasicEffect      = new BasicEffect(this.GraphicsDevice, null);
            this.m_BasicEffect.View = Matrix.Identity;
            this.m_BasicEffect.VertexColorEnabled = true;

            this.m_VertexDeclaration = new VertexDeclaration(this.GraphicsDevice, VertexPositionColor.VertexElements);

            this.m_QueryVertices             = new VertexPositionColor[4];
            this.m_QueryVertices[0].Position = new Vector3(-QuerySize / 2, -QuerySize / 2, -1);
            this.m_QueryVertices[1].Position = new Vector3(QuerySize / 2, -QuerySize / 2, -1);
            this.m_QueryVertices[2].Position = new Vector3(QuerySize / 2, QuerySize / 2, -1);
            this.m_QueryVertices[3].Position = new Vector3(-QuerySize / 2, QuerySize / 2, -1);

            this.m_OcclusionQuery = new OcclusionQuery(this.GraphicsDevice);
        }
コード例 #26
0
        public void QueryOccludedSprites()
        {
            SpriteBatch    spriteBatch    = null;
            Texture2D      whiteTexture   = null;
            OcclusionQuery occlusionQuery = null;

            int state           = 0;
            int queryFrameCount = 0;

            Game.LoadContentWith += (sender, e) =>
            {
                spriteBatch  = new SpriteBatch(Game.GraphicsDevice);
                whiteTexture = Game.Content.Load <Texture2D>(Paths.Texture("white-64"));
            };

            Game.DrawWith += (sender, e) =>
            {
                if (occlusionQuery == null)
                {
                    occlusionQuery = new OcclusionQuery(Game.GraphicsDevice);
                }

                Game.GraphicsDevice.Clear(Color.CornflowerBlue);

                // White rectangle at depth 0.
                spriteBatch.Begin(SpriteSortMode.Immediate, null, null, DepthStencilState.Default, null);
                spriteBatch.Draw(whiteTexture, new Rectangle(100, 100, 100, 100), null, Color.White, 0, Vector2.Zero, SpriteEffects.None, 0);
                spriteBatch.End();

                if (state == 0)
                {
                    // Make query with red rectangle, 50% occluded.
                    occlusionQuery.Begin();
                    spriteBatch.Begin(SpriteSortMode.Immediate, null, null, DepthStencilState.Default, null);
                    spriteBatch.Draw(whiteTexture, new Rectangle(50, 100, 100, 100), null, Color.Red, 0, Vector2.Zero, SpriteEffects.None, 1);
                    spriteBatch.End();
                    occlusionQuery.End();
                    state           = 1;
                    queryFrameCount = 0;
                }
                else if (state == 1)
                {
                    queryFrameCount++;

                    if (queryFrameCount > 5)
                    {
                        Assert.Fail("Occlusion query did not complete.");
                    }

                    if (occlusionQuery.IsComplete)
                    {
                        Assert.AreEqual(100 * 100 / 2, occlusionQuery.PixelCount);
                        state = 2;
                    }
                }
                else if (state == 2)
                {
                    // Same results as last frame.
                    Assert.IsTrue(occlusionQuery.IsComplete);
                    Assert.AreEqual(100 * 100 / 2, occlusionQuery.PixelCount);

                    // Reuse query a second time, 10% occlusion.
                    occlusionQuery.Begin();
                    spriteBatch.Begin(SpriteSortMode.Immediate, null, null, DepthStencilState.Default, null);
                    spriteBatch.Draw(whiteTexture, new Rectangle(10, 100, 100, 100), null, Color.Red, 0, Vector2.Zero, SpriteEffects.None, 1);
                    spriteBatch.End();
                    occlusionQuery.End();
                    state           = 3;
                    queryFrameCount = 0;
                }
                else if (state == 3)
                {
                    queryFrameCount++;

                    if (queryFrameCount > 5)
                    {
                        Assert.Fail("Occlusion query did not complete.");
                    }

                    if (occlusionQuery.IsComplete)
                    {
                        Assert.AreEqual(100 * 100 * 9 / 10, occlusionQuery.PixelCount);
                        state = 4;
                    }
                }
            };

            Game.Run(until: frameInfo => state == 4 || frameInfo.DrawNumber > 15);
        }
コード例 #27
0
        /// <summary>
        /// Draw the predicate, and if the predicate draws at least <see cref="MinimumPixelCount"/> pixels, the 'complex' object will be drawn
        /// </summary>
        /// <param name="state"></param>
        public void Draw(DrawState state)
        {
            int frame = state.FrameIndex;

            if (!supported || frame == frameIndex)
            {
                if (item.CullTest(state))
                {
                    item.Draw(state);
                }
                return;
            }

            if (resetOnCullChange && frameIndex != frame - 1)
            {
                //XNA requires IsComplete to be checked.
                if (query != null)
                {
                    queryInProgress = query.IsComplete;
                }

                queryInProgress = false;                //reset the query
                queryPixelCount = ushort.MaxValue;
            }

            if (queryInProgress && query.IsComplete)
            {
                queryInProgress      = false;
                this.queryPixelCount = (ushort)query.PixelCount;
            }

            if (!queryInProgress)
            {
                GraphicsDevice device = state.BeginGetGraphicsDevice(Xen.Graphics.State.StateFlag.None);

                //run the query
                if (query == null)
                {
                    query = new OcclusionQuery(device);
                    if (query.IsSupported == false)
                    {
                        supported = false;
                        query.Dispose();
                        query = null;

                        if (item.CullTest(state))
                        {
                            item.Draw(state);
                        }
                        return;
                    }
                }

                query.Begin();

                state.PushRenderState();

                state.RenderState.DepthColourCull.DepthWriteEnabled = false;
                state.RenderState.DepthColourCull.ColourWriteMask   = ColorWriteChannels.None;
                state.RenderState.AlphaBlend = new AlphaBlendState();

                predicate.Draw(state);

                state.PopRenderState();

                query.End();

                queryInProgress = true;

                state.EndGetGraphicsDevice();
            }

            frameIndex = frame;

            if (queryPixelCount >= pixelCount && item.CullTest(state))
            {
                item.Draw(state);
            }
        }
コード例 #28
0
        public void QueryOccludedSprites()
        {
            var spriteBatch  = new SpriteBatch(gd);
            var whiteTexture = content.Load <Texture2D>(Paths.Texture("white-64"));

            var occlusionQuery = new OcclusionQuery(gd);

            var state           = 0;
            var queryFrameCount = 0;

            Action <int> action = frameNr =>
            {
                gd.Clear(Color.CornflowerBlue);

                // White rectangle at depth 0.
                spriteBatch.Begin(SpriteSortMode.Immediate, null, null, DepthStencilState.Default, null);
                spriteBatch.Draw(whiteTexture, new Rectangle(100, 100, 100, 100), null, Color.White, 0, Vector2.Zero,
                                 SpriteEffects.None, 0);
                spriteBatch.End();

                switch (state)
                {
                case 0:
                    // Make query with red rectangle, 50% occluded.
                    occlusionQuery.Begin();
                    spriteBatch.Begin(SpriteSortMode.Immediate, null, null, DepthStencilState.Default, null);
                    spriteBatch.Draw(whiteTexture, new Rectangle(50, 100, 100, 100), null, Color.Red, 0, Vector2.Zero,
                                     SpriteEffects.None, 1);
                    spriteBatch.End();
                    occlusionQuery.End();
                    state           = 1;
                    queryFrameCount = 0;
                    break;

                case 1:
                    queryFrameCount++;

                    if (queryFrameCount > 5)
                    {
                        Assert.Fail("Occlusion query did not complete.");
                    }

                    if (occlusionQuery.IsComplete)
                    {
                        Assert.AreEqual(100 * 100 / 2, occlusionQuery.PixelCount);
                        Console.WriteLine("First occlusionQuery completed in {0} frames", queryFrameCount);
                        state = 2;
                    }
                    break;

                case 2:
                    // Same results as last frame.
                    Assert.IsTrue(occlusionQuery.IsComplete);
                    Assert.AreEqual(100 * 100 / 2, occlusionQuery.PixelCount);

                    // Reuse query a second time, 10% occlusion.
                    occlusionQuery.Begin();
                    spriteBatch.Begin(SpriteSortMode.Immediate, null, null, DepthStencilState.Default, null);
                    spriteBatch.Draw(whiteTexture, new Rectangle(10, 100, 100, 100), null, Color.Red, 0, Vector2.Zero,
                                     SpriteEffects.None, 1);
                    spriteBatch.End();
                    occlusionQuery.End();
                    state           = 3;
                    queryFrameCount = 0;
                    break;

                case 3:
                    queryFrameCount++;

                    if (queryFrameCount > 5)
                    {
                        Assert.Fail("Occlusion query did not complete.");
                    }

                    if (occlusionQuery.IsComplete)
                    {
                        Assert.AreEqual(100 * 100 * 9 / 10, occlusionQuery.PixelCount);
                        Console.WriteLine("Second occlusionQuery completed in {0} frames", queryFrameCount);
                        state = 4;
                    }
                    break;
                }
            };

            Predicate <int> exitCondition = frame => state == 4 || frame > 15;

            DoGameLoop(action, exitCondition);

            spriteBatch.Dispose();
            whiteTexture.Dispose();
            occlusionQuery.Dispose();
        }
コード例 #29
0
ファイル: Bgfx.cs プロジェクト: prepare/SharpBgfx
 /// <summary>
 /// Submits the current batch of primitives for rendering.
 /// </summary>
 /// <param name="id">The index of the view to submit.</param>
 /// <param name="program">The program with which to render.</param>
 /// <param name="query">An occlusion query to use as a predicate during rendering.</param>
 /// <param name="depth">A depth value to use for sorting the batch.</param>
 /// <returns>The number of draw calls.</returns>
 public static int Submit(byte id, Program program, OcclusionQuery query, int depth = 0)
 {
     return NativeMethods.bgfx_submit_occlusion_query(id, program.handle, query.handle, depth);
 }
コード例 #30
0
ファイル: Stats.cs プロジェクト: ARLM-Attic/xna-xen
        /// <summary>
        /// Draw the statistics
        /// </summary>
        /// <param name="state"></param>
        public void Draw(DrawState state)
        {
#if DEBUG
            float fade = 8 - state.TotalTimeSeconds * 0.5f;
            if (fade > 1)
            {
                fade = 1;
            }
            if (fade < 0)
            {
                fade = 0;
            }


            if (!enabled)
            {
                if (toggleTextDisplay != null && fade > 0)
                {
                    this.toggleTextDisplay.ColourFloat = new Vector4(1, 1, 1, fade);
                    toggleTextDisplay.Draw(state);

                    AlignElements(state);
                }
                return;
            }

            if (fillRateQuery == null)
            {
                GraphicsDevice device = state.BeginGetGraphicsDevice(StateFlag.None);
                fillRateQuery = new OcclusionQuery(device);
                state.EndGetGraphicsDevice();

                if (fillRateQuery.IsSupported)
                {
                    fillRateQuery.Begin();
                    fillRateQueryActive = true;
                }
            }

            if (fillRateQuery.IsSupported)
            {
                if (fillRateQueryActive)
                {
                    fillRateQuery.End();
                    fillRateQueryActive = false;
                }
            }

            DrawStatistics stats;
            state.GetPreviousFrameStatistics(out stats);

            stats -= previousFrameOverhead;

            if (graphs == null)
            {
                const int   width       = 210;
                const int   height      = 128;
                const int   fontPix     = 20;
                List <Call> calls       = new List <Call>();
                List <bool> visibleList = new List <bool>();

                Callback <Graph, string, Call, bool, float> add         = delegate(string name, Call call, bool visible, float good) { calls.Add(call); visibleList.Add(visible); return(new Graph(name, width, height, width - fontPix / 2, fontPix, 0, font, -good)); };
                Callback <Graph, string, Call, bool, float> addHalf     = delegate(string name, Call call, bool visible, float good) { calls.Add(call); visibleList.Add(visible); return(new Graph(name, width / 2, height, width / 2 - fontPix / 2, fontPix, 0, font, -good)); };
                Callback <Graph, string, Call, bool, float> addHalfMin1 = delegate(string name, Call call, bool visible, float good) { calls.Add(call); visibleList.Add(visible); return(new Graph(name, width / 2, height, width / 2 - fontPix / 2, fontPix, 1, font, -good)); };

                graphs = new Graph[]
                {
                    add("Frame Rate (Approx)", delegate(ref DrawStatistics s, DrawState dstate)
                        { return((float)dstate.ApproximateFrameRate); }, true, -20),

                    add("Frame Draw Time (Ticks)", delegate(ref DrawStatistics s, DrawState dstate)
                        { return(s.ApproximateDrawTimeTicks); }, false, 1.0f / 20.0f),

                    addHalf("Draw Target Passes", delegate(ref DrawStatistics s, DrawState dstate)
                            { return((float)s.DrawTargetsPassCount); }, false, 10),

                    add("Primitives Drawn", delegate(ref DrawStatistics s, DrawState dstate)
                        { return((float)(s.TrianglesDrawn + s.LinesDrawn + s.PointsDrawn)); }, true, 1000000),

#if XBOX360
                    addHalf("Pixels Drawn\n(Approx)", delegate(ref DrawStatistics s, DrawState dstate)
                            { return(Math.Max(0, pixelsFillled - (float)s.XboxPixelFillBias)); }, true, 20000000),             // not accurate
#else
                    addHalf("Pixels Drawn", delegate(ref DrawStatistics s, DrawState dstate)
                            { return(Math.Max(0, pixelsFillled)); }, true, 18000000),
#endif

                    addHalf("Lines Drawn", delegate(ref DrawStatistics s, DrawState dstate)
                            { return((float)(s.LinesDrawn)); }, false, 1000000),
                    addHalf("Points Drawn", delegate(ref DrawStatistics s, DrawState dstate)
                            { return((float)(s.PointsDrawn)); }, false, 1000000),

                    addHalf("Draw Calls", delegate(ref DrawStatistics s, DrawState dstate)
                            { return((float)(s.DrawIndexedPrimitiveCallCount + s.DrawPrimitivesCallCount)); }, true, 300),
                    addHalf("Draw Calls (Indexed)", delegate(ref DrawStatistics s, DrawState dstate)
                            { return((float)(s.DrawIndexedPrimitiveCallCount)); }, false, 300),


                    addHalf("Instances Drawn", delegate(ref DrawStatistics s, DrawState dstate)
                            { return((float)(s.InstancesDrawn)); }, false, 1000),
                    addHalf("Inst.Batch Size (Avg)", delegate(ref DrawStatistics s, DrawState dstate)
                            { return(Avg(s.InstancesDrawn, s.InstancesDrawBatchCount)); }, false, 1000),



                    addHalf("Set Camera Count", delegate(ref DrawStatistics s, DrawState dstate)
                            { return((float)s.SetCameraCount); }, false, 1000),

                    addHalf("Shader Bind Count", delegate(ref DrawStatistics s, DrawState dstate)
                            { return((float)s.ShaderBindCount); }, false, 1000),

                    addHalf("Shader Constant Bytes", delegate(ref DrawStatistics s, DrawState dstate)
                            { return((float)(s.VertexShaderConstantBytesSetTotalCount + s.PixelShaderConstantBytesSetTotalCount)); }, false, 2000000),

                    addHalf("VS Constant Bytes (Avg)", delegate(ref DrawStatistics s, DrawState dstate)
                            { return(Avg(s.VertexShaderConstantBytesSetTotalCount, s.VertexShaderConstantBytesSetCount)); }, false, 1000),
                    addHalf("PS Constant Bytes (Avg)", delegate(ref DrawStatistics s, DrawState dstate)
                            { return(Avg(s.PixelShaderConstantBytesSetTotalCount, s.PixelShaderConstantBytesSetCount)); }, false, 1000),

                    addHalf("VS Complexity (Avg)", delegate(ref DrawStatistics s, DrawState dstate)
                            { return(Avg(s.VertexShaderApproximateInstructionsTotal, s.VertexShaderBoundWithKnownInstructionsCount)); }, false, 64),
                    addHalf("PS Complexity (Avg)", delegate(ref DrawStatistics s, DrawState dstate)
                            { return(Avg(s.PixelShaderApproximateInstructionsTotal, s.PixelShaderBoundWithKnownInstructionsCount)); }, false, 32),

                    addHalf("VS Preshader Complexity (Avg)", delegate(ref DrawStatistics s, DrawState dstate)
                            { return(Avg(s.VertexShaderApproximatePreshaderInstructionsTotal, s.VertexShaderBoundWithKnownInstructionsCount)); }, false, 512),
                    addHalf("PS Preshader Complexity (Avg)", delegate(ref DrawStatistics s, DrawState dstate)
                            { return(Avg(s.PixelShaderApproximatePreshaderInstructionsTotal, s.PixelShaderBoundWithKnownInstructionsCount)); }, false, 512),

                    addHalf("Dirty Render State Count", delegate(ref DrawStatistics s, DrawState dstate)
                            { return((float)s.DirtyRenderStateCount); }, false, 2),


                    add("Vertex Bytes Copied", delegate(ref DrawStatistics s, DrawState dstate)
                        { return((float)(s.VertexBufferByesCopied + s.DynamicVertexBufferByesCopied)); }, false, 1000000),
                    add("Index Bytes Copied", delegate(ref DrawStatistics s, DrawState dstate)
                        { return((float)(s.IndexBufferByesCopied + s.DynamicIndexBufferByesCopied)); }, false, 1000000),

                    add("Resource Device Bytes (Tracked)", delegate(ref DrawStatistics s, DrawState dstate)
                        { return((float)(Resource.GetAllAllocatedDeviceBytes())); }, false, 100000000),
                    addHalf("Resource Count (Tracked)", delegate(ref DrawStatistics s, DrawState dstate)
                            { return((float)(Resource.GetResourceCount())); }, false, 50),
                    addHalf("Resource Managed Bytes (Tracked)", delegate(ref DrawStatistics s, DrawState dstate)
                            { return((float)(Resource.GetAllAllocatedManagedBytes())); }, false, 100000000),
                    addHalf("Unused Resources (Tracked)", delegate(ref DrawStatistics s, DrawState dstate)
                            { return((float)(Resource.CountResourcesNotUsedByDevice())); }, false, 10),



                    addHalfMin1("Culler Efficiency (Sphere)", delegate(ref DrawStatistics s, DrawState dstate)
                                { return(1 - Avg(s.DefaultCullerTestSphereCulledCount, s.DefaultCullerTestSphereCount)); }, false, 1000),
                    addHalfMin1("Culler Efficiency (Box)", delegate(ref DrawStatistics s, DrawState dstate)
                                { return(1 - Avg(s.DefaultCullerTestBoxCulledCount, s.DefaultCullerTestBoxCount)); }, false, 1000),

                    addHalf("AlphaBlend State Changed", delegate(ref DrawStatistics s, DrawState dstate)
                            { return((float)(s.RenderStateAlphaBlendChangedCount)); }, false, 300),
                    addHalf("AlphaTest State Changed", delegate(ref DrawStatistics s, DrawState dstate)
                            { return((float)(s.RenderStateAlphaTestChangedCount)); }, false, 300),
                    addHalf("StencilTest State Changed", delegate(ref DrawStatistics s, DrawState dstate)
                            { return((float)(s.RenderStateStencilTestChangedCount)); }, false, 300),
                    addHalf("Depth/FrustumCull State Changed", delegate(ref DrawStatistics s, DrawState dstate)
                            { return((float)(s.RenderStateDepthColourCullChangedCount)); }, false, 300),

                    addHalf("Tex Sampler Address Changed", delegate(ref DrawStatistics s, DrawState dstate)
                            { return((float)(s.TextureSamplerAddressStateChanged)); }, false, 200),
                    addHalf("Tex Sampler Filter Changed", delegate(ref DrawStatistics s, DrawState dstate)
                            { return((float)(s.TextureSamplerFilterStateChanged)); }, false, 200),
                    addHalf("Texture Changed", delegate(ref DrawStatistics s, DrawState dstate)
                            { return((float)(s.TextureUnitTextureChanged)); }, false, 100),
                    addHalf("Vertex Texture Changed", delegate(ref DrawStatistics s, DrawState dstate)
                            { return((float)(s.VertexTextureUnitTextureChanged)); }, false, 50),

                    add("Bound Textures (Avg)", delegate(ref DrawStatistics s, DrawState dstate)
                        { return(Avg(s.BoundTextureCount, s.BoundTextureCountTotalSamples)); }, false, 4),
                    addHalf("Vertex Textures (Avg)", delegate(ref DrawStatistics s, DrawState dstate)
                            { return(Avg(s.BoundVertexTextureCount, s.BoundTextureCountTotalSamples)); }, false, 1),

                    addHalf("Garbage Collected", delegate(ref DrawStatistics s, DrawState dstate)
                    {
                        if (garbageTracker.Target == null)
                        {
                            garbageTracker.Target = new object(); return(1);
                        }
                        return(0);
                    }, true, 0),

#if XBOX360
                    addHalfMin1("CPU Usage\n(Primary)", delegate(ref DrawStatistics s, DrawState dstate)
                                { return(threads[0].Usage); }, true, -0.5f),
                    addHalfMin1("CPU Usage\n(Task Threads)", delegate(ref DrawStatistics s, DrawState dstate)
                                { return((threads[1].Usage + threads[2].Usage + threads[3].Usage) / 3.0f); }, true, -0.25f),
#endif
                };

                this.graphVisible  = visibleList.ToArray();
                this.setGraphCalls = calls.ToArray();
            }

            for (int i = 0; i < graphs.Length; i++)
            {
                if (graphVisible[i] || this.displayAll)
                {
                    graphs[i].SetGraphValue(setGraphCalls[i](ref stats, state));
                    graphs[i].Visible = true;
                }
                else
                {
                    graphs[i].Visible = false;
                }
            }

            AlignElements(state);


            DrawStatistics currentPreDraw;
            state.GetCurrentFrameStatistics(out currentPreDraw);


            for (int i = 0; i < graphs.Length; i++)
            {
                if (graphs[i].Visible)
                {
                    graphs[i].Draw(state);
                }
            }


            DrawStatistics currentPostDraw;
            state.GetCurrentFrameStatistics(out currentPostDraw);

            previousFrameOverhead = currentPostDraw - currentPreDraw;


            if (fillRateQuery.IsSupported)
            {
                if (fillRateQuery.IsComplete)
                {
                    pixelsFillled = (float)fillRateQuery.PixelCount;

                    fillRateQuery.Begin();
                    fillRateQueryActive = true;
                }
            }
            else
            {
                pixelsFillled = -1;
            }
#endif
        }
コード例 #31
0
 /// <summary>
 ///		Default constructor.
 /// </summary>
 /// <param name="device">Reference to a Direct3D device.</param>
 public XnaHardwareOcclusionQuery(GraphicsDevice device)
 {
     this.device = device;
     oQuery      = new OcclusionQuery(device);
 }