//Creates a white 1*1 Texture that is used for the lines by scaling and rotating it
        public void CreatePixelTexture()
        {
            int TargetWidth = 1;
            int TargetHeight = 1;

            RenderTarget2D LevelRenderTarget = new RenderTarget2D(graphicsDevice, TargetWidth, TargetHeight, 1,
                graphicsDevice.PresentationParameters.BackBufferFormat, graphicsDevice.PresentationParameters.MultiSampleType,
                graphicsDevice.PresentationParameters.MultiSampleQuality, RenderTargetUsage.PreserveContents);

            DepthStencilBuffer stencilBuffer = new DepthStencilBuffer(graphicsDevice, TargetWidth, TargetHeight,
                graphicsDevice.DepthStencilBuffer.Format, graphicsDevice.PresentationParameters.MultiSampleType,
                graphicsDevice.PresentationParameters.MultiSampleQuality);

            graphicsDevice.SetRenderTarget(0, LevelRenderTarget);

            // Cache the current depth buffer
            DepthStencilBuffer old = graphicsDevice.DepthStencilBuffer;
            // Set our custom depth buffer
            graphicsDevice.DepthStencilBuffer = stencilBuffer;

            graphicsDevice.Clear(Color.White);

            graphicsDevice.SetRenderTarget(0, null);

            // Reset the depth buffer
            graphicsDevice.DepthStencilBuffer = old;
            pixel = LevelRenderTarget.GetTexture();
        }
Esempio n. 2
0
 protected override ShaderResourceView CreateShaderResourceView()
 {
     if (MultiSampleCount > 1)
     {
         return(new SharpDX.Direct3D11.ShaderResourceView
                    (GraphicsDevice._d3dDevice, _resolvedTexture.GetTexture()));
     }
     else
     {
         return(base.CreateShaderResourceView());
     }
 }
Esempio n. 3
0
        public void SetRenderTarget(int renderTargetIndex, RenderTarget2D renderTarget)
        {
            if (renderTargetIndex < 0 || renderTargetIndex >= renderTargets.Length)
            {
                throw new ArgumentOutOfRangeException("The specified index must be within the supported range.");
            }

            Gl.glBindFramebufferEXT(Gl.GL_FRAMEBUFFER_EXT, frameBufferIdentifier);

            if (renderTarget == null)
            {
                // Detach the texture and depth buffer
                Gl.glFramebufferTexture2DEXT(Gl.GL_FRAMEBUFFER_EXT, getColorAttachment(renderTargetIndex),
                                             Gl.GL_TEXTURE_2D, 0, 0);
                Gl.glFramebufferRenderbufferEXT(Gl.GL_FRAMEBUFFER_EXT, Gl.GL_DEPTH_ATTACHMENT_EXT,
                                                Gl.GL_RENDERBUFFER_EXT, 0);

                renderTargets[renderTargetIndex] = null;

                // Deactivate the frame buffer when no more targets are connected.
                if (--numActiveRenderTargets == 0)
                {
                    Gl.glBindFramebufferEXT(Gl.GL_FRAMEBUFFER_EXT, 0);
                }

                return;
            }

            if (renderTarget.IsDisposed)
            {
                throw new ObjectDisposedException("SetRenderTarget is called after the render target has been disposed.");
            }

            // Connect texture and depth buffer
            Gl.glFramebufferTexture2DEXT(Gl.GL_FRAMEBUFFER_EXT, getColorAttachment(renderTargetIndex), Gl.GL_TEXTURE_2D,
                                         renderTarget.GetTexture().textureId, 0);
            Gl.glFramebufferRenderbufferEXT(Gl.GL_FRAMEBUFFER_EXT, Gl.GL_DEPTH_ATTACHMENT_EXT,
                                            Gl.GL_RENDERBUFFER_EXT, renderTarget.renderBufferIdentifier);

            numActiveRenderTargets++;

            int status = Gl.glCheckFramebufferStatusEXT(Gl.GL_FRAMEBUFFER_EXT);

            if (status != Gl.GL_FRAMEBUFFER_COMPLETE_EXT)
            {
                throw new Exception("This should not occur.");
            }

            // Leave framebuffer active
        }
Esempio n. 4
0
 // Token: 0x06002540 RID: 9536
 // RVA: 0x000E0B84 File Offset: 0x000DED84
 private Texture2D method_11(Color color_3, Color color_4, Color color_5, Color color_6, float float_1)
 {
     RenderTarget2D renderTarget2D = new RenderTarget2D(base.method_8(), 128, 1, 1, 1);
     VertexPositionColor[] array = new VertexPositionColor[]
     {
         new VertexPositionColor(new Vector3(-0.5f, 0f, 0f), Color.get_TransparentBlack()),
         new VertexPositionColor(new Vector3(0f, 0f, 0f), Color.get_TransparentBlack()),
         new VertexPositionColor(new Vector3(0.078125f - float_1, 0f, 0f), color_3),
         new VertexPositionColor(new Vector3(0.078125f + float_1, 0f, 0f), color_4),
         new VertexPositionColor(new Vector3(0.1875f - float_1, 0f, 0f), color_4),
         new VertexPositionColor(new Vector3(0.1875f + float_1, 0f, 0f), color_6),
         new VertexPositionColor(new Vector3(1f, 0f, 0f), color_5),
         new VertexPositionColor(new Vector3(1.5f, 0f, 0f), color_5)
     };
     RenderTarget2D renderTarget2D2 = (RenderTarget2D)base.method_8().GetRenderTarget(0);
     base.method_8().SetRenderTarget(0, renderTarget2D);
     base.method_8().get_RenderState().set_AlphaBlendEnable(false);
     base.method_8().get_RenderState().set_DepthBufferEnable(false);
     base.method_8().get_RenderState().set_AlphaTestEnable(false);
     base.method_8().get_RenderState().set_BlendFunction(1);
     base.method_8().get_RenderState().set_AlphaBlendOperation(1);
     base.method_8().set_VertexDeclaration(new VertexDeclaration(base.method_8(), VertexPositionColor.VertexElements));
     base.method_8().Clear(Color.get_PaleVioletRed());
     base.method_9().set_World(Matrix.get_Identity());
     base.method_9().set_Projection(Matrix.CreateOrthographicOffCenter(0f, 1f, 1f, -1f, -1f, 1f));
     base.method_9().set_View(Matrix.get_Identity());
     base.method_9().set_TextureEnabled(false);
     base.method_9().set_Texture(null);
     base.method_9().set_VertexColorEnabled(true);
     base.method_9().Begin();
     base.method_9().get_CurrentTechnique().get_Passes().get_Item(0).Begin();
     base.method_8().DrawUserPrimitives<VertexPositionColor>(3, array, 0, 7);
     base.method_9().get_CurrentTechnique().get_Passes().get_Item(0).End();
     base.method_9().End();
     base.method_8().ResolveRenderTarget(0);
     Texture2D texture = renderTarget2D.GetTexture();
     base.method_8().SetRenderTarget(0, renderTarget2D2);
     return texture;
 }
        public Texture2D Generate2DNoise(NoiseParameters noiseParams, int width, int height, int mipCount)
        {
            Vector2 invRes = Vector2.One / new Vector2(width, height);
            noise2DShader.SetupShader();
            GFX.Device.SetVertexShaderConstant(0, invRes);
            GFX.Device.SetPixelShaderConstant(0, invRes);
            GFX.Device.SetPixelShaderConstant(1, new Vector4(noiseParams.Amplitude, noiseParams.Frequency, noiseParams.Persistance, noiseParams.Octaves));
            GFX.Device.Textures[0] = ComputeRandomTexture(width / 2, height / 2);

            RenderTarget2D rtNoise = new RenderTarget2D(GFX.Device, width, height, 1, SurfaceFormat.Color);
            DepthStencilBuffer dsOld = GFX.Device.DepthStencilBuffer;
            GFX.Device.DepthStencilBuffer = GFX.Inst.dsBufferLarge;
            GFX.Device.SetRenderTarget(0, rtNoise);
            GFXPrimitives.Quad.Render();
            GFX.Device.SetRenderTarget(0, null);
            GFX.Device.DepthStencilBuffer = dsOld;

            Color[] colorData = new Color[width * height];
            rtNoise.GetTexture().GetData<Color>(colorData);
            Texture2D noiseTexture = new Texture2D(GFX.Device, width, height, mipCount, TextureUsage.None, SurfaceFormat.Color);
            noiseTexture.SetData<Color>(colorData);
            noiseTexture.GenerateMipMaps(TextureFilter.GaussianQuad);
            return noiseTexture;
        }
Esempio n. 6
0
        Vector2 GetTerrainPosition(Texture2D heightmap, Vector2 shapeScale, Vector2 heightRange, out float heightAtPosition, out float thetaAtPosition, List<Vector3> placedShapes)
        {
            Vector2 invRes = new Vector2(1.0f / (float)heightmap.Width, 1.0f / (float)heightmap.Height);

            RenderTarget2D rtVariance = new RenderTarget2D(GFX.Device, heightmap.Width, heightmap.Height, 1, SurfaceFormat.Vector2);
            RenderTarget2D rtNormal = new RenderTarget2D(GFX.Device, heightmap.Width, heightmap.Height, 1, SurfaceFormat.Vector2);
            GFX.Device.Textures[0] = heightmap;
            varianceShader.SetupShader();
            GFX.Device.SetVertexShaderConstant(GFXShaderConstants.VC_INVTEXRES, invRes);
            GFX.Device.SetPixelShaderConstant(0, invRes);
            GFX.Device.SetRenderTarget(0, rtVariance);
            GFXPrimitives.Quad.Render();
            GFX.Device.SetRenderTarget(0, null);

            GFX.Device.SetRenderTarget(0, rtNormal);
            gradientShader.SetupShader();
            GFXPrimitives.Quad.Render();
            GFX.Device.SetRenderTarget(0, null);
            GFX.Device.Textures[0] = null;

            int bufferSize = heightmap.Width * heightmap.Height;
            float[] heightData = new float[bufferSize];
            Vector2[] varianceData = new Vector2[bufferSize];
            rtVariance.GetTexture().GetData<Vector2>(varianceData);
            Vector2[] gradientData = new Vector2[rtNormal.Width * rtNormal.Height];
            rtNormal.GetTexture().GetData<Vector2>(gradientData);

            switch (heightmap.Format)
            {
                case SurfaceFormat.Single:
                    heightmap.GetData<float>(heightData);
                    break;
                case SurfaceFormat.Color:
                    Color[] colorData = new Color[bufferSize];
                    heightmap.GetData<Color>(colorData);
                    float invScale = 1.0f / 255.0f;
                    for (int i = 0; i < colorData.Length; i++)
                        heightData[i] = (float)colorData[i].R * invScale;
                    break;
            }

            List<Int2D> availableSpots = new List<Int2D>();
            for (int x = 0; x < heightmap.Width; x++)
            {
                for (int y = 0; y < heightmap.Height; y++)
                {
                    int index = x + y * heightmap.Width;
                    if (varianceData[index].Y >= heightRange.X && varianceData[index].Y <= heightRange.Y)
                    {
                        /*
                        Vector2 currPos = new Vector2(x, y) * invRes * 2.0f - Vector2.One;
                        bool canPlace = true;
                        for(int i = 0; i < placedShapes.Count; i++)
                        {
                            if (Vector2.Distance(currPos, new Vector2(placedShapes[i].X, placedShapes[i].Y)) <= placedShapes[i].Z)
                            {
                                canPlace = false;
                                break;
                            }
                        }
                        if(canPlace)*/
                            availableSpots.Add(new Int2D(x, y));
                    }
                }
            }

            for (int i = 0; i < availableSpots.Count; i++)
            {
                Int2D temp = availableSpots[i];
                int randIndex = RandomHelper.RandomGen.Next(i, availableSpots.Count);
                availableSpots[i] = availableSpots[randIndex];
                availableSpots[randIndex] = temp;
            }

            PriorityQueue<float, Int2D> plantSpots = new PriorityQueue<float, Int2D>();
            for (int i = 0; i < availableSpots.Count; i++)
            {
                int index = availableSpots[i].X + availableSpots[i].Y * heightmap.Width;
                Vector2 currPos = new Vector2(availableSpots[i].X, availableSpots[i].Y) * invRes * 2.0f - Vector2.One;
                float netPriority = 0;
                for (int j = 0; j < placedShapes.Count; j++)
                {
                    float radius = Vector2.Distance(currPos, new Vector2(placedShapes[j].X, placedShapes[j].Y)) * placedShapes[j].Z;
                    if (radius == 0.0f)
                        radius = 0.001f;
                        netPriority += 1.0f / (radius * radius);

                }
                plantSpots.Enqueue(availableSpots[i], varianceData[index].X + netPriority);
            }

            Int2D randPos = plantSpots.ExtractMin();// availableSpots[RandomHelper.RandomGen.Next(0, availableSpots.Count)];
            Vector2 pos = new Vector2(randPos.X, randPos.Y) * invRes * 2.0f - Vector2.One;
            int placedIndex = randPos.X + randPos.Y * heightmap.Width;
            heightAtPosition = varianceData[placedIndex].Y;
            thetaAtPosition = (float)Math.Atan2(gradientData[placedIndex].Y, gradientData[placedIndex].X);
            return pos;
        }
Esempio n. 7
0
        public Texture2D CreateRoadAtlas(Texture2D[] input, SpriteBatch spriteBatch)
        {
            DepthStencilBuffer OldDSBuffer = m_GraphicsDevice.DepthStencilBuffer;

            RenderTarget2D RTarget = new RenderTarget2D(m_GraphicsDevice, 512, 512, 0, SurfaceFormat.Color,
                RenderTargetUsage.PreserveContents);
            DepthStencilBuffer DSBuffer = new DepthStencilBuffer(m_GraphicsDevice, 512, 512,
                OldDSBuffer.Format);

            m_GraphicsDevice.DepthStencilBuffer = DSBuffer;
            m_GraphicsDevice.SetRenderTarget(0, RTarget);

            m_GraphicsDevice.Clear(Color.TransparentBlack);

            spriteBatch.Begin();

            for (int i = 0; i < 16; i++)
            {
                spriteBatch.Draw(input[i], new Rectangle((i%4) * 128, (int)(i/4.0)*128, 128, 128), Color.White);
            }

            spriteBatch.End();

            m_GraphicsDevice.SetRenderTarget(0, null);
            m_GraphicsDevice.DepthStencilBuffer = OldDSBuffer;

            Texture2D Ret = RTarget.GetTexture();
            RTarget.Dispose(); //free up memory used by render target, as we have moved the data to a texture.
            return Ret;
        }
        public void DownsampleGlow(RenderTarget2D colorMap, RenderTarget2D lightMap, RenderTarget2D dataMap, RenderTarget2D emissiveMap)
        {
            bloomShader.SetupShader();
            for(int i = 0; i <= 2; i++)
                GFX.Inst.SetTextureFilter(i, TextureFilter.Linear);
            GFX.Device.Textures[0] = colorMap.GetTexture();
            GFX.Device.Textures[1] = lightMap.GetTexture();
            GFX.Device.Textures[2] = dataMap.GetTexture();
            Vector2 invRes = Vector2.One / new Vector2(colorMap.Width, colorMap.Height);
            GFX.Device.SetVertexShaderConstant(GFXShaderConstants.VC_INVTEXRES, invRes);
            GFX.Device.SetPixelShaderConstant(0, new Vector2(bloomBias, bloomMultiplier));
            GFX.Device.SetRenderTarget(0, emissiveMap);
            GFX.Device.Clear(Color.TransparentBlack);
            GFXPrimitives.Quad.Render();
            GFX.Device.SetRenderTarget(0, null);

            BlurRenderTarget(emissiveMap, BlurFilter.Box, 4);
        }
        public static Texture2D Scale(GraphicsDevice gd, Texture2D texture, float scaleX, float scaleY)
        {
            var newWidth = (int)(texture.Width * scaleX);
            var newHeight = (int)(texture.Height * scaleY);

            RenderTarget2D renderTarget = new RenderTarget2D(
                gd,
                newWidth, newHeight, 1,
                SurfaceFormat.Color);

            gd.SetRenderTarget(0, renderTarget);

            SpriteBatch batch = new SpriteBatch(gd);

            Rectangle destinationRectangle = new Rectangle(0, 0, newWidth, newHeight);

            batch.Begin();
            batch.Draw(texture, destinationRectangle, Color.White);
            batch.End();

            gd.SetRenderTarget(0, null);

            var newTexture = renderTarget.GetTexture();
            return newTexture;
        }
Esempio n. 10
0
        void PerformBlur(Texture2D heightmap)
        {
            Shader heightBlur2DShader = ResourceManager.Inst.GetShader("HeightmapBlurMinMax");
            RenderTarget2D paramTarget = new RenderTarget2D(GFX.Device, DensityFieldWidth, DensityFieldDepth, 1, SurfaceFormat.Vector4);
            GFX.Device.SetPixelShaderConstant(GFXShaderConstants.VC_INVTEXRES, Vector2.One / new Vector2(DensityFieldWidth, DensityFieldDepth));
            GFX.Device.SetPixelShaderConstant(0, Vector2.One / new Vector2(DensityFieldWidth, DensityFieldDepth));
            heightBlur2DShader.SetupShader();
            GFX.Device.Textures[0] = heightmap;

            GFX.Device.SetRenderTarget(0, paramTarget);
            GFXPrimitives.Quad.Render();
            GFX.Device.SetRenderTarget(0, null);

            Shader gradShader = ResourceManager.Inst.GetShader("GradientHeightmap");
            GFX.Device.Textures[0] = paramTarget.GetTexture();
            gradShader.SetupShader();

            RenderTarget2D gradTarget = new RenderTarget2D(GFX.Device, DensityFieldWidth, DensityFieldDepth, 1, SurfaceFormat.Single);
            GFX.Device.SetRenderTarget(0, gradTarget);
            GFXPrimitives.Quad.Render();
            GFX.Device.SetRenderTarget(0, null);

            GFX.Device.Textures[0] = null;

            Shader blurShader = ResourceManager.Inst.GetShader("VoxelBlur3x3x3");

            srcTarget = new RenderTarget2D(GFX.Device, DensityFieldWidth, DensityFieldHeight, 1, GFX.Inst.ByteSurfaceFormat);
            DepthStencilBuffer dsOld = GFX.Device.DepthStencilBuffer;
            GFX.Device.DepthStencilBuffer = GFX.Inst.dsBufferLarge;

            blurShader.SetupShader();
            GFX.Device.SetPixelShaderConstant(0, Vector3.One / new Vector3(DensityFieldWidth, DensityFieldHeight, DensityFieldDepth));

            GFX.Device.SamplerStates[0].AddressU = TextureAddressMode.Clamp;
            GFX.Device.SamplerStates[0].AddressV = TextureAddressMode.Clamp;
            GFX.Device.SamplerStates[0].AddressW = TextureAddressMode.Clamp;

            GFX.Device.RenderState.DepthBufferEnable = false;
            GFX.Device.RenderState.DepthBufferWriteEnable = false;

            //Here we generate our noise textures
            int nSize = 32;
            noiseTextures = new Texture3D[4];
            float[] noiseData = new float[nSize * nSize * nSize];
            Random rand = new Random();
            for (int i = 0; i < noiseTextures.Length; i++)
            {
                noiseTextures[i] = new Texture3D(GFX.Device, nSize, nSize, nSize, 1, TextureUsage.None, SurfaceFormat.Single);
                for (int j = 0; j < noiseData.Length; j++)
                {
                    noiseData[j] = (float)(rand.NextDouble() * 2 - 1);
                }
                noiseTextures[i].SetData<float>(noiseData);
            }

            noiseData = null;

            //Lets activate our textures
            for (int i = 0; i < noiseTextures.Length; i++)
                GFX.Device.Textures[i+3] = noiseTextures[i];

            //CopyDensityTextureData(ref DensityField, currDensityField);
            GFX.Device.Textures[0] = heightmap;
            GFX.Device.Textures[1] = paramTarget.GetTexture();
            GFX.Device.Textures[2] = gradTarget.GetTexture();
            for (int z = 0; z < DensityFieldDepth; z++)
            {
                Vector4 depth = Vector4.One * (float)z / (float)(DensityFieldDepth - 1);
                GFX.Device.SetVertexShaderConstant(0, depth); //Set our current depth

                GFX.Device.SetRenderTarget(0, srcTarget);
                //GFX.Device.Clear(Color.TransparentBlack);

                GFXPrimitives.Quad.Render();

                GFX.Device.SetRenderTarget(0, null);

                //Now the copying stage.
                ExtractDensityTextureData(ref DensityField, z);

            }
            GFX.Device.Textures[0] = null;
            /*
            Texture3D voxelTexture = new Texture3D(GFX.Device, DensityFieldWidth, DensityFieldHeight, DensityFieldDepth, 1, TextureUsage.None, GFX.Inst.ByteSurfaceFormat);
            switch (GFX.Inst.ByteSurfaceDataType)
            {
                case GFXTextureDataType.BYTE:
                    voxelTexture.SetData<byte>(DensityField);
                    break;
                case GFXTextureDataType.COLOR:
                    Color[] tempColor = new Color[DensityField.Length];
                    for(int i = 0; i < tempColor.Length; i++)
                        tempColor[i] = new Color(DensityField[i], DensityField[i], DensityField[i], DensityField[i]);
                    voxelTexture.SetData<Color>(tempColor);
                    tempColor = null;
                    break;
                case GFXTextureDataType.SINGLE:
                    float[] tempFloat = new float[DensityField.Length];
                    float invScale = 1.0f / 255.0f;
                    for (int i = 0; i < tempFloat.Length; i++)
                        tempFloat[i] = (float)DensityField[i] * invScale;
                    voxelTexture.SetData<float>(tempFloat);
                    tempFloat = null;
                    break;
            }

            Shader blurShaderGeneric = ResourceManager.Inst.GetShader("VoxelBlurGeneric");
            blurShaderGeneric.SetupShader();
            GFX.Device.Textures[0] = voxelTexture;
            for (int z = 0; z < DensityFieldDepth; z++)
            {
                Vector4 depth = Vector4.One * (float)z / (float)(DensityFieldDepth - 1);
                GFX.Device.SetVertexShaderConstant(0, depth); //Set our current depth

                GFX.Device.SetRenderTarget(0, srcTarget);

                GFXPrimitives.Quad.Render();

                GFX.Device.SetRenderTarget(0, null);

                //Now the copying stage.
                ExtractDensityTextureData(ref DensityField, z);

            }
            GFX.Device.Textures[0] = null;
            voxelTexture.Dispose();
            */

            GFX.Device.DepthStencilBuffer = dsOld;
            GFX.Device.RenderState.DepthBufferEnable = true;
            GFX.Device.RenderState.DepthBufferWriteEnable = true;
        }
Esempio n. 11
0
        void AssembleTextureAtlas(Texture3D target, Texture2D[] srcTextures, int textureSize, int mipCount)
        {
            Shader imageShader = ResourceManager.Inst.GetShader("Generic2D");
            RenderTarget2D rtTarget = new RenderTarget2D(GFX.Device, textureSize, textureSize, 1, SurfaceFormat.Color);
            target = new Texture3D(GFX.Device, textureSize, textureSize, srcTextures.Length, mipCount, TextureUsage.AutoGenerateMipMap, SurfaceFormat.Color);

            Color[] colorBuffer = new Color[textureSize * textureSize];

            GFX.Device.SamplerStates[0].MagFilter = TextureFilter.Linear;
            GFX.Device.SamplerStates[0].MinFilter = TextureFilter.Linear;
            GFX.Device.SamplerStates[0].MipFilter = TextureFilter.Linear;
            imageShader.SetupShader();
            for (int i = 0; i < srcTextures.Length; i++)
            {
                GFX.Device.SetVertexShaderConstant(GFXShaderConstants.VC_INVTEXRES, Vector2.One / new Vector2(srcTextures[i].Width, srcTextures[i].Height));
                GFX.Device.Textures[0] = srcTextures[i];
                GFX.Device.SetRenderTarget(0, rtTarget);
                GFXPrimitives.Quad.Render();
                GFX.Device.SetRenderTarget(0, null);
                rtTarget.GetTexture().GetData<Color>(colorBuffer);
                target.SetData<Color>(colorBuffer, colorBuffer.Length * i, colorBuffer.Length, SetDataOptions.None);
            }

            target.GenerateMipMaps(TextureFilter.Linear);
        }
Esempio n. 12
0
        public void SetText(string text)
        {
            this.text = text;
            width = (int)ServiceManager.Game.Font.MeasureString(text).X * 2;
            height = (int)ServiceManager.Game.Font.MeasureString(text).Y * 2;

            GraphicsDevice device = Renderer.GraphicOptions.graphics.GraphicsDevice;

            const int numberOfLevels = 1;
            const int multisampleQuality = 0;
            RenderTarget2D renderTarget = new RenderTarget2D(device, width,
                height, numberOfLevels, SurfaceFormat.Color,
                MultiSampleType.None, multisampleQuality, RenderTargetUsage.PreserveContents);

            device.SetRenderTarget(0, renderTarget);
            device.Clear(Color.TransparentWhite);
            ServiceManager.Game.Batch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Texture, SaveStateMode.SaveState);
            //ServiceManager.Game.Batch.Begin();
            ServiceManager.Game.Batch.DrawString(ServiceManager.Game.Font, text, Vector2.Zero, Color.Black, 0.0f, Vector2.Zero, 2.0f, SpriteEffects.None, 0f);
            ServiceManager.Game.Batch.End();

            device.SetRenderTarget(0, null);
            texture = renderTarget.GetTexture();

            //texture.Save("C:\\img.png", ImageFileFormat.Png);

            AdjustVertices();
            Ready();
        }
        void PopulateAtlas(Texture2D[] textures, Texture3D output)
        {
            RenderTarget2D rt = new RenderTarget2D(GFX.Device, output.Width, output.Height, 1, SurfaceFormat.Color);

            int stride = output.Width * output.Height;

            DepthStencilBuffer dsOld = GFX.Device.DepthStencilBuffer;
            GFX.Device.DepthStencilBuffer = GFX.Inst.dsBufferLarge;
            Shader drawImageShader = ResourceManager.Inst.GetShader("Generic2D");
            drawImageShader.SetupShader();

            GFX.Device.SamplerStates[0].AddressU = TextureAddressMode.Clamp;
            GFX.Device.SamplerStates[0].AddressV = TextureAddressMode.Clamp;
            GFX.Device.SamplerStates[0].AddressW = TextureAddressMode.Clamp;

            GFX.Device.RenderState.DepthBufferEnable = false;
            GFX.Device.RenderState.DepthBufferWriteEnable = false;

            Color[] colorDataAtlas = new Color[stride * output.Depth];

            for (int i = 0; i < textures.Length; i++)
            {
                GFX.Device.Textures[0] = textures[i];
                GFX.Device.SetVertexShaderConstant(0, new Vector2(1.0f / textures[i].Width, 1.0f / textures[0].Height));

                GFX.Device.SetRenderTarget(0, rt);

                GFXPrimitives.Quad.Render();

                GFX.Device.SetRenderTarget(0, null);

                rt.GetTexture().GetData<Color>(colorDataAtlas, i*stride, stride);
            }
            GFX.Device.Textures[0] = null;

            GFX.Device.DepthStencilBuffer = dsOld;
            GFX.Device.RenderState.DepthBufferEnable = true;
            GFX.Device.RenderState.DepthBufferWriteEnable = true;

            output.SetData<Color>(colorDataAtlas);
        }
 private void CopyTextureToRenderTarget(Texture2D src, RenderTarget2D rt, ref Texture2D dest)
 {
     var dsb = GraphicsDevice.DepthStencilBuffer;
     GraphicsDevice.DepthStencilBuffer = null;
     GraphicsDevice.SetRenderTarget(0, rt);
     spriteBatch.Begin(SpriteBlendMode.None, SpriteSortMode.Immediate, SaveStateMode.None);
     spriteBatch.Draw(src, new Rectangle(0, 0, src.Width, src.Height), Color.White);
     spriteBatch.End();
     GraphicsDevice.SetRenderTarget(0, null);
     GraphicsDevice.DepthStencilBuffer = dsb;
     dest = rt.GetTexture();
     dest.GenerateMipMaps(TextureFilter.Linear);
 }
        public void Process(GraphicsDevice g, RenderTarget2D sceneTarget)
        {
            // extract brightest parts of the scene
            g.SetRenderTarget(0, rTarget1);
            Texture2D sceneTexture = sceneTarget.GetTexture();
            ppManager.RenderScreenQuad(e, luminosityExtractTechnique, sceneTexture);

            // blur the luminosity extract horizontally
            g.SetRenderTarget(0, rTarget2);
            e.Parameters["fWeights"].SetValue(horizontalBlurParameters.Weights);
            e.Parameters["vOffsets"].SetValue(horizontalBlurParameters.Offsets);
            ppManager.RenderScreenQuad(e, gaussianBlurTechnique, rTarget1.GetTexture());

            // blur the luminosity extract vertically
            g.SetRenderTarget(0, rTarget1);
            e.Parameters["fWeights"].SetValue(verticalBlurParameters.Weights);
            e.Parameters["vOffsets"].SetValue(verticalBlurParameters.Offsets);
            ppManager.RenderScreenQuad(e, gaussianBlurTechnique, rTarget2.GetTexture());
            
            // combine blurred luminosity extract with scene
            g.SetRenderTarget(0, null);
            g.Textures[1] = sceneTexture;
            ppManager.RenderScreenQuad(e, compositeTechnique, rTarget1.GetTexture());
        }
Esempio n. 16
0
File: DText.cs Progetto: konlil/pipe
        protected override void DrawWithClipRect()
        {
            if (Visible)
            {
                Vector2 drawPos = new Vector2(AbsoluteTransform.X, AbsoluteTransform.Y);

                if (SourceRectangle.HasValue && IsPartiallyObscured)
                {
                    //Game.GraphicsDevice.ScissorRectangle = SourceRectangle.Value;
                    //Game.GraphicsDevice.RenderState.ScissorTestEnable = true;

                    //Game.GraphicsDevice.SetRenderTarget(0, null);
                    RenderTarget2D renderTarget = new RenderTarget2D(Game.GraphicsDevice,
                        SourceRectangle.Value.Width,
                        SourceRectangle.Value.Height,
                        1,
                        SurfaceFormat.Color,
                        RenderTargetUsage.PreserveContents);

                    Game.GraphicsDevice.SetRenderTarget(0, renderTarget);

                    Game.GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.TransparentWhite, 1, 0);

                    //draw the text!
                    SpriteBatch spriteBatch = new SpriteBatch(Game.GraphicsDevice);
                    spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Deferred, SaveStateMode.SaveState);
                    spriteBatch.DrawString(spriteFont,
                                            Text,
                                            new Vector2(SourceRectangle.Value.X, -SourceRectangle.Value.Y),
                                            fontColor,
                                            0,
                                            Origin,
                                            1,
                                            SpriteEffects.None,
                                            0);
                    spriteBatch.End();

                    Game.GraphicsDevice.SetRenderTarget(0, null);
                    //Game.GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.White, 1, 0);

                    _texture = renderTarget.GetTexture();

                    _guiManager.SpriteBatch.Draw(_texture,
                        drawPos + new Vector2(SourceRectangle.Value.X, SourceRectangle.Value.Y),
                        new Rectangle(0,0, SourceRectangle.Value.Width, SourceRectangle.Value.Height),
                        fontColor,
                        0f,
                        Vector2.Zero,
                        1f,
                        SpriteEffects.None,
                        0);

                }
                else if (!Parent.IsTotallyObscured)
                {
                    //draw the text!
                    _guiManager.SpriteBatch.DrawString(spriteFont,
                                            Text,
                                            drawPos,
                                            fontColor,
                                            0,
                                            Origin,
                                            1,
                                            SpriteEffects.None,
                                            0);
                }

                //Game.GraphicsDevice.RenderState.ScissorTestEnable = false;
            }
        }
Esempio n. 17
0
        void PerformHistogramEqualization(Texture2D heightmap)
        {
            Vector2 MinMax = GetMinMaxHeight(heightmap);
            RenderTarget2D rtHist = new RenderTarget2D(GFX.Device, heightmap.Width, heightmap.Height, 1, heightmap.Format);

            GFX.Device.SetRenderTarget(0, rtHist);

            GFX.Device.Textures[0] = heightmap;
            GFX.Device.SetVertexShaderConstant(GFXShaderConstants.VC_INVTEXRES, new Vector2(1.0f / (float)heightmap.Width, 1.0f / (float)heightmap.Height));
            GFX.Device.SetPixelShaderConstant(0, MinMax);
            histogramShader.SetupShader();

            GFXPrimitives.Quad.Render();

            GFX.Device.SetRenderTarget(0, null);
            GFX.Device.Textures[0] = null;

            CopyToTexture(rtHist.GetTexture(), heightmap);
        }
Esempio n. 18
0
        /// <summary>
        /// Returns a custom texture of Perlin Noise
        /// </summary>
        public static Texture2D GeneratePerlinNoise(int TextureWidth, int TextureHeight
            , Color[] NoiseData, int NoiseWidth, int NoiseHeight, float NoiseShift, float Sharpness)
        {
            isUsingGraphicsDevice = true;
            while (MyGame.isDrawing)
            {
                Thread.Sleep(10);
            }
            RenderTarget2D renderTarget = new RenderTarget2D(MyGame.graphics.GraphicsDevice
                , TextureWidth
                , TextureHeight
                , 1
                , MyGame.graphics.GraphicsDevice.DisplayMode.Format);
            MyGame.graphics.GraphicsDevice.SetRenderTarget(0, renderTarget);
            DepthStencilBuffer OriginalBuffer = MyGame.graphics.GraphicsDevice.DepthStencilBuffer;
            MyGame.graphics.GraphicsDevice.DepthStencilBuffer = new DepthStencilBuffer(MyGame.graphics.GraphicsDevice
                , renderTarget.Width
                , renderTarget.Height
                , MyGame.graphics.GraphicsDevice.DepthStencilBuffer.Format);

            Texture2D noiseMap = new Texture2D(MyGame.graphics.GraphicsDevice
                , NoiseWidth
                , NoiseHeight);
            noiseMap.SetData<Color>(NoiseData);

            PostProcessEffect.CurrentTechnique = PostProcessEffect.Techniques["GenerateNoise"];
            PostProcessEffect.Parameters["InputTexture"].SetValue(noiseMap);
            PostProcessEffect.Parameters["World"].SetValue(Matrix.Identity);
            PostProcessEffect.Parameters["NoiseShift"].SetValue(NoiseShift);
            PostProcessEffect.Parameters["Sharpness"].SetValue(Sharpness);
            spriteBatch.Begin(SpriteBlendMode.None, SpriteSortMode.Immediate, SaveStateMode.SaveState);
            PostProcessEffect.Begin();
            PostProcessEffect.CurrentTechnique.Passes.First<EffectPass>().Begin();
            spriteBatch.Draw(noiseMap
                , new Rectangle(0, 0, renderTarget.Width, renderTarget.Height)
                , Color.White);
            PostProcessEffect.CurrentTechnique.Passes.First<EffectPass>().End();
            PostProcessEffect.End();
            spriteBatch.End();

            MyGame.graphics.GraphicsDevice.SetRenderTarget(0, null);
            MyGame.graphics.GraphicsDevice.DepthStencilBuffer = OriginalBuffer;
            MyGame.graphics.GraphicsDevice.Clear(Color.Black);

            isUsingGraphicsDevice = false;
            return renderTarget.GetTexture();
        }
Esempio n. 19
0
        //Debugging methods
        public Texture2D GenTextureDebug(String text)
        {
            int w = (int)debugFont.MeasureString(text).X;
            int h = (int)debugFont.MeasureString(text).Y;

            RenderTarget2D render = new RenderTarget2D(GraphicsDevice, w, h, 1, GraphicsDevice.DisplayMode.Format
                                    , GraphicsDevice.PresentationParameters.MultiSampleType
                                    , GraphicsDevice.PresentationParameters.MultiSampleQuality
                                    , RenderTargetUsage.DiscardContents);

            GraphicsDevice.SetRenderTarget(0, render);

            spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.SaveState);
            spriteBatch.DrawString(debugFont, text, new Vector2(1, 1), Color.Black);
            spriteBatch.DrawString(debugFont, text, new Vector2(0, 0), Color.White);
            spriteBatch.End();

            GraphicsDevice.SetRenderTarget(0, null);
            return render.GetTexture();
        }
        void BuildBlendMap(Texture2D heightmap)
        {
            climate = ResourceManager.Inst.GetTerrainClimate("TestTerrain");

            DepthStencilBuffer dsOld = GFX.Device.DepthStencilBuffer;
            GFX.Device.DepthStencilBuffer = GFX.Inst.dsBufferLarge;

            Shader gradientShader = ResourceManager.Inst.GetShader("GradientHeightmap");
            gradientShader.SetupShader();
            GFX.Device.SetVertexShaderConstant(GFXShaderConstants.VC_INVTEXRES, Vector2.One / new Vector2(heightmap.Width, heightmap.Height));
            GFX.Device.SetPixelShaderConstant(0, Vector2.One / new Vector2(heightmap.Width, heightmap.Height));
            GFX.Device.Textures[0] = heightmap;

            RenderTarget2D rtGradient = new RenderTarget2D(GFX.Device, heightmap.Width, heightmap.Height, 1, SurfaceFormat.Single);
            GFX.Device.SetRenderTarget(0, rtGradient);
            GFXPrimitives.Quad.Render();
            GFX.Device.SetRenderTarget(0, null);
            GFX.Device.Textures[0] = rtGradient.GetTexture();
            RenderTarget2D rtCurvature = new RenderTarget2D(GFX.Device, heightmap.Width, heightmap.Height, 1, SurfaceFormat.Single);
            GFX.Device.SetRenderTarget(0, rtCurvature);
            GFXPrimitives.Quad.Render();
            GFX.Device.SetRenderTarget(0, null);

            Shader blendShader = ResourceManager.Inst.GetShader("BlendHeightmap");
            blendShader.SetupShader();
            GFX.Device.Textures[0] = heightmap;
            GFX.Device.Textures[1] = rtGradient.GetTexture();
            GFX.Device.Textures[2] = rtCurvature.GetTexture();

            Vector4[] climateParams = new Vector4[4];
            Vector4[] climateParams2 = new Vector4[4];

            int numBlendMapsNeeded = climate.blendZones.Length / 4;
            blendMaps = new RenderTarget2D[numBlendMapsNeeded];

            for (int i = 0; i < numBlendMapsNeeded; i++)
            {
                int offset = i * 4;
                for (int j = 0; j < 4; j++)
                {
                    int climateIndex = j + offset;
                    climateParams[j] = new Vector4(climate.heightCoeffs[climateIndex], climate.gradientCoeffs[climateIndex], climate.curvatureCoeffs[climateIndex], climate.baseScores[climateIndex]);
                    climateParams2[j] = Vector4.One * climate.blendZones[climateIndex];
                }

                GFX.Device.SetPixelShaderConstant(0, climateParams);
                GFX.Device.SetPixelShaderConstant(4, climateParams2);

                blendMaps[i] = new RenderTarget2D(GFX.Device, heightmap.Width, heightmap.Height, 1, SurfaceFormat.Color);
                GFX.Device.SetRenderTarget(0, blendMaps[i]);
                GFXPrimitives.Quad.Render();
                GFX.Device.SetRenderTarget(0, null);
            }

            NormalizeBlendWeights();
            GFX.Device.DepthStencilBuffer = dsOld;
        }
Esempio n. 21
0
        /*
        void InitializeMaterial()
        {

            terrainMaterial.SetTexture(0, climate.BaseMapAtlas);
            terrainMaterial.SetTexture(1, climate.NormalMapAtlas);
            TextureResource blendTex = new TextureResource();
            blendTex.SetTexture(TextureResourceType.Texture3D, blendTexture);
            TextureResource blendIDTex = new TextureResource();
            blendIDTex.SetTexture(TextureResourceType.Texture3D, blendIDTexture);
            terrainMaterial.SetTexture(2, blendTex);
            terrainMaterial.SetTexture(3, blendIDTex);
            terrainMaterial.kAmbient = climate.GetInverseResolution();
            terrainMaterial.kDiffuse = Vector3.One / new Vector3(blendMapWidth, blendMapHeight, blendMapDepth);

        }
        */
        void InitializeClimateMap()
        {
            Texture3D densityFieldTexture = new Texture3D(GFX.Device, DensityFieldWidth, DensityFieldHeight, DensityFieldDepth, 1, TextureUsage.None, GFX.Inst.ByteSurfaceFormat);
            CopyDensityTextureData(ref DensityField, densityFieldTexture);

            GFX.Device.Textures[0] = densityFieldTexture;

            RenderTarget2D rtClimateMap = new RenderTarget2D(GFX.Device, blendMapWidth, blendMapHeight, 1, SurfaceFormat.Color);
            RenderTarget2D rtIDMap = new RenderTarget2D(GFX.Device, blendMapWidth, blendMapHeight, 1, SurfaceFormat.Color);

            int stride = blendMapWidth * blendMapHeight;
            Color[] colorData = new Color[stride * blendMapDepth];
            Color[] blendIDData = new Color[stride * blendMapDepth];

            Vector4[] climateParams = new Vector4[4];
            Vector4[] climateParams2 = new Vector4[4];

            for (int i = 0; i < climate.heightCoeffs.Length; i++)
            {
                climateParams[i] = new Vector4(climate.heightCoeffs[i], climate.gradientCoeffs[i], climate.curvatureCoeffs[i], climate.baseScores[i]);
                climateParams2[i] = Vector4.One * climate.blendZones[i];
            }

            GFX.Device.SetPixelShaderConstant(0, Vector3.One / new Vector3(DensityFieldWidth, DensityFieldHeight, DensityFieldDepth));

            RenderTarget2D rtGradientMap = new RenderTarget2D(GFX.Device, DensityFieldWidth, DensityFieldHeight, 1, SurfaceFormat.Single);
            int gradStride = DensityFieldWidth * DensityFieldHeight;
            float[] gradientValues = new float[gradStride * DensityFieldDepth];
            Texture3D gradientTexture = new Texture3D(GFX.Device, DensityFieldWidth, DensityFieldHeight, DensityFieldDepth, 1, TextureUsage.None, SurfaceFormat.Single);
            Shader gradientShader = ResourceManager.Inst.GetShader("GradientShader");
            gradientShader.SetupShader();

            for (int z = 0; z < DensityFieldDepth; z++)
            {
                Vector4 depth = Vector4.One * (float)z / (float)(DensityFieldDepth - 1);
                GFX.Device.SetVertexShaderConstant(0, depth); //Set our current depth

                GFX.Device.SetRenderTarget(0, rtGradientMap);

                GFXPrimitives.Quad.Render();

                GFX.Device.SetRenderTarget(0, null);

                rtGradientMap.GetTexture().GetData<float>(gradientValues, z * gradStride, gradStride);
            }
            gradientTexture.SetData<float>(gradientValues);

            GFX.Device.Textures[1] = gradientTexture;
            GFX.Device.SetPixelShaderConstant(1, climateParams);
            GFX.Device.SetPixelShaderConstant(5, climateParams2);

            Shader climateShader = ResourceManager.Inst.GetShader("ClimateShader");
            climateShader.SetupShader();

            for (int z = 0; z < blendMapDepth; z++)
            {
                Vector4 depth = Vector4.One * (float)z / (float)(blendMapDepth - 1);
                GFX.Device.SetVertexShaderConstant(0, depth); //Set our current depth

                GFX.Device.SetRenderTarget(0, rtClimateMap);
                GFX.Device.SetRenderTarget(1, rtIDMap);

                GFXPrimitives.Quad.Render();

                GFX.Device.SetRenderTarget(0, null);
                GFX.Device.SetRenderTarget(1, null);

                rtClimateMap.GetTexture().GetData<Color>(colorData, z * stride, stride);
                rtIDMap.GetTexture().GetData<Color>(blendIDData, z * stride, stride);
            }
            GFX.Device.Textures[0] = null;
            GFX.Device.Textures[1] = null;

            gradientTexture.Dispose();

            blendTexture = new Texture3D(GFX.Device, blendMapWidth, blendMapHeight, blendMapDepth, 1, TextureUsage.None, SurfaceFormat.Color);
            blendTexture.SetData<Color>(colorData);

            blendIDTexture = new Texture3D(GFX.Device, blendMapWidth, blendMapHeight, blendMapDepth, 1, TextureUsage.None, SurfaceFormat.Color);
            blendIDTexture.SetData<Color>(blendIDData);

            blendTexture.Save("TestClimateMap.dds", ImageFileFormat.Dds);
            blendIDTexture.Save("TestClimateMapID.dds", ImageFileFormat.Dds);
        }
        void LoadHeightFromTexture()
        {
            Texture2D tex = Texture2D.FromFile(GFX.Device, heightmapFileName);
            width = tex.Width;
            depth = tex.Height;
            heightValues = new float[width * depth];

            byte[] data = new byte[width * depth];
            if (tex.Format != SurfaceFormat.Luminance8)
            {
                Color[] dataColor = new Color[tex.Width * tex.Height];
                tex.GetData<Color>(dataColor, 0, dataColor.Length);
                for (int i = 0; i < dataColor.Length; i++)
                    data[i] = dataColor[i].R;
            }
            else
            {
                tex.GetData<byte>(data);
            }
            float scale = (heightRange.Y - heightRange.X);
            for (int x = 0; x < width; x++)
            {
                for (int z = 0; z < depth; z++)
                {
                    int index = x + width * z;
                    heightValues[index] = (float)((data[index] / 255.0f) * scale) + heightRange.X;
                }
            }

            MaximumHeight = scale + heightRange.X;

            Shader basic2DShader = ResourceManager.Inst.GetShader("Generic2D");
            basic2DShader.SetupShader();
            GFX.Device.Textures[0] = tex;
            GFX.Device.SetVertexShaderConstant(0, Vector2.One / new Vector2(width - 1, depth - 1));
            GFX.Inst.SetTextureFilter(0, TextureFilter.Linear);
            RenderTarget2D heightmapSmaller = new RenderTarget2D(GFX.Device, width - 1, depth - 1, 1, SurfaceFormat.Color);
            DepthStencilBuffer dsOld = GFX.Device.DepthStencilBuffer;
            GFX.Device.DepthStencilBuffer = GFX.Inst.dsBufferLarge;
            GFX.Device.SetRenderTarget(0, heightmapSmaller);
            GFXPrimitives.Quad.Render();
            GFX.Device.SetRenderTarget(0, null);
            GFX.Device.DepthStencilBuffer = dsOld;

            BuildBlendMap(heightmapSmaller.GetTexture());
            GenerateNormalMap();
        }
Esempio n. 23
0
        /// <summary>
        /// Erases the corners and center of input texture and warps the rest into a spiral
        /// </summary>
        public static Texture2D SpiralWarp(Texture2D texture)
        {
            isUsingGraphicsDevice = true;
            while (MyGame.isDrawing)
            {
                Thread.Sleep(10);
            }
            RenderTarget2D renderTarget = new RenderTarget2D(MyGame.graphics.GraphicsDevice
                , texture.Width
                , texture.Width
                , 1
                , MyGame.graphics.GraphicsDevice.DisplayMode.Format);
            MyGame.graphics.GraphicsDevice.SetRenderTarget(0, renderTarget);
            DepthStencilBuffer OriginalBuffer = MyGame.graphics.GraphicsDevice.DepthStencilBuffer;
            MyGame.graphics.GraphicsDevice.DepthStencilBuffer = new DepthStencilBuffer(MyGame.graphics.GraphicsDevice
                , renderTarget.Width
                , renderTarget.Height
                , MyGame.graphics.GraphicsDevice.DepthStencilBuffer.Format);

            PostProcessEffect.CurrentTechnique = PostProcessEffect.Techniques["SpiralWarp"];
            PostProcessEffect.Parameters["InputTexture"].SetValue(texture);
            PostProcessEffect.Parameters["World"].SetValue(Matrix.Identity);
            PostProcessEffect.Parameters["WarpMagnitude"].SetValue(2.5f + 1.5f * (float)MyGame.random.NextDouble());
            spriteBatch.Begin(SpriteBlendMode.None, SpriteSortMode.Immediate, SaveStateMode.SaveState);
            PostProcessEffect.Begin();
            PostProcessEffect.CurrentTechnique.Passes.First<EffectPass>().Begin();
            spriteBatch.Draw(texture
                , new Rectangle(0, 0, renderTarget.Width, renderTarget.Height)
                , Color.White);
            PostProcessEffect.CurrentTechnique.Passes.First<EffectPass>().End();
            PostProcessEffect.End();
            spriteBatch.End();

            MyGame.graphics.GraphicsDevice.SetRenderTarget(0, null);
            MyGame.graphics.GraphicsDevice.DepthStencilBuffer = OriginalBuffer;
            MyGame.graphics.GraphicsDevice.Clear(Color.Black);

            isUsingGraphicsDevice = false;
            return renderTarget.GetTexture();
        }
Esempio n. 24
0
        void DrawBlur(float x, float y, Effect effectToUse,
            RenderTarget2D source, RenderTarget2D target)
        {
            SetBlurEffectParameters(x, y, effectToUse);

            GraphicsDevice.SetRenderTarget(0, target);

            spriteBatch.Begin(SpriteBlendMode.None,
                              SpriteSortMode.Immediate,
                              SaveStateMode.None);

            effectToUse.Begin();
            effectToUse.CurrentTechnique.Passes[0].Begin();

            spriteBatch.Draw(source.GetTexture(),
                new Rectangle(0, 0,
                    target.Width,
                    target.Height), Color.White);
            spriteBatch.End();

            effectToUse.CurrentTechnique.Passes[0].End();
            effectToUse.End();
        }
        void GenerateNormalMap()
        {
            Texture2D heightmap = new Texture2D(GFX.Device, width, depth, 1, TextureUsage.None, SurfaceFormat.Single);
            heightmap.SetData<float>(heightValues);

            Vector2 invRes = Vector2.One / new Vector2(heightmap.Width, heightmap.Height);
            Shader normalTangentShader = ResourceManager.Inst.GetShader("NormalTangentHeightmap");
            normalTangentShader.SetupShader();
            GFX.Device.SetVertexShaderConstant(0, invRes);
            GFX.Device.SetPixelShaderConstant(0, invRes);
            GFX.Device.SetPixelShaderConstant(1, Vector4.One / MaximumHeight);
            GFX.Device.Textures[0] = heightmap;
            GFX.Inst.SetTextureFilter(0, TextureFilter.Linear);

            RenderTarget2D normTanTarget = new RenderTarget2D(GFX.Device, heightmap.Width, heightmap.Height, 1, SurfaceFormat.Vector4);
            DepthStencilBuffer dsOld = GFX.Device.DepthStencilBuffer;
            DepthStencilBuffer dsNew = new DepthStencilBuffer(GFX.Device, heightmap.Width, heightmap.Height, dsOld.Format);
            GFX.Device.DepthStencilBuffer = dsNew;
            GFX.Device.SetRenderTarget(0, normTanTarget);
            GFXPrimitives.Quad.Render();
            GFX.Device.SetRenderTarget(0, null);
            GFX.Device.DepthStencilBuffer = dsOld;

            normalTexture = normTanTarget.GetTexture();
        }
Esempio n. 26
0
        void ApplyErosion(Texture2D heightmap, int iterations, float initialParticleCoverage)
        {
            Color[] heightDataOrig = new Color[heightmap.Width * heightmap.Height];
            heightmap.GetData<Color>(heightDataOrig);

            float[] heightValues = new float[heightDataOrig.Length];
            for (int i = 0; i < heightDataOrig.Length; i++)
                heightValues[i] = (float)heightDataOrig[i].R / 255.0f;

            RenderTarget2D normalTarget = new RenderTarget2D(GFX.Device, heightmap.Width, heightmap.Height, 1, SurfaceFormat.Vector2);

            int numParticles = (int)(initialParticleCoverage * heightmap.Width * heightmap.Height);
            ErosionParticle[] particles = new ErosionParticle[numParticles];
            for (int k = 0; k < iterations; k++)
            {
                Vector2 invRes = new Vector2(1.0f / (float)heightmap.Width, 1.0f / (float)heightmap.Height);

                GFX.Device.SetRenderTarget(0, normalTarget);
                gradientShader.SetupShader();

                GFX.Device.Textures[0] = heightmap;
                GFX.Device.SetVertexShaderConstant(GFXShaderConstants.VC_INVTEXRES, invRes);
                GFX.Device.SetPixelShaderConstant(0, invRes);

                GFXPrimitives.Quad.Render();
                GFX.Device.SetRenderTarget(0, null);

                Vector2[] gradientData = new Vector2[normalTarget.Width * normalTarget.Height];
                normalTarget.GetTexture().GetData<Vector2>(gradientData);

                for (int i = 0; i < numParticles; i++)
                {
                    particles[i].x = RandomHelper.RandomGen.Next(heightmap.Width - 1);
                    particles[i].y = RandomHelper.RandomGen.Next(heightmap.Height - 1);
                    particles[i].sediment = 0;

                    int oldX = particles[i].x;
                    int oldY = particles[i].y;
                    while (true)
                    {
                        int index = particles[i].x + particles[i].y * heightmap.Width;
                        float oldHeight = heightValues[index];
                        float heightAmount = heightValues[index] * 0.035f;
                        heightValues[index] -= heightAmount;
                        particles[i].sediment += heightAmount;
                        Vector2 gradient = gradientData[index];
                        int shiftX = (gradient.X < 0.25f) ? -1 : (gradient.X > 0.25f) ? 1 : 0;
                        int shiftY = (gradient.Y < 0.25f) ? -1 : (gradient.Y > 0.25f) ? 1 : 0;
                        int newX = (int)(particles[i].x + shiftX);
                        int newY = (int)(particles[i].y + shiftY);
                        if (newX < 0 || newY < 0 || newX >= heightmap.Width || newY >= heightmap.Height)
                            break;
                        if (heightValues[newX + newY * heightmap.Width] > heightValues[index] || (newX == oldX && newY == oldY))
                        {
                            heightValues[index] += particles[i].sediment;
                            break;
                        }
                        oldX = particles[i].x;
                        oldY = particles[i].y;
                        particles[i].x = newX;
                        particles[i].y = newY;
                    }
                }

                GFX.Device.Textures[0] = null;
                for (int i = 0; i < heightDataOrig.Length; i++)
                {
                    byte value = (byte)(heightValues[i] * 255.0f);
                    heightDataOrig[i].R = value;
                    heightDataOrig[i].G = value;
                    heightDataOrig[i].B = value;
                    heightDataOrig[i].A = value;
                }
                heightmap.SetData<Color>(heightDataOrig);
            }
        }
Esempio n. 27
0
        public static Texture2D Resize(GraphicsDevice gd, Texture2D texture, int newWidth, int newHeight)
        {
            RenderTarget2D renderTarget = new RenderTarget2D(
                gd,
                newWidth, newHeight, 1,
                SurfaceFormat.Color);

            SpriteBatch batch = new SpriteBatch(gd);

            Rectangle destinationRectangle = new Rectangle(0, 0, newWidth, newHeight);
            lock (gd)
            {
                gd.SetRenderTarget(0, renderTarget);
                batch.Begin();
                batch.Draw(texture, destinationRectangle, Color.White);
                batch.End();
                gd.SetRenderTarget(0, null);
            }
            var newTexture = renderTarget.GetTexture();
            return newTexture;
        }
Esempio n. 28
0
        void CreateConstraints(Texture2D heightmap, out SortedList<int, Vector4> landmarks)
        {
            RenderTarget2D rtHeightmap = new RenderTarget2D(GFX.Device, heightmap.Width, heightmap.Height, 1, heightmap.Format);

            float[] numDirs = new float[4] { 0, MathHelper.PiOver2, MathHelper.Pi, 3.0f * MathHelper.PiOver2 };
            GFX.Device.SetRenderTarget(0, rtHeightmap);
            float randomRot = numDirs[RandomHelper.RandomGen.Next(0, numDirs.Length)];
            CreateLerpLayer(heightmap, GetRandomIsland(), false, 0, 0.28f, Vector2.One, randomRot, Vector2.Zero);
            GFX.Device.SetRenderTarget(0, null);

            CopyToTexture(rtHeightmap.GetTexture(), heightmap);

            List<Vector3> placedLocations = new List<Vector3>();
            landmarks = new SortedList<int, Vector4>();
            for(int i = 0; i < creationDatablock.MapLocations.Length; i++)
            {
                TerrainCreationParameters currParams = creationDatablock.MapLocations[i];
                if(currParams !=  null)
                {
                    float baseHeight;
                    float theta = 0;
                    Vector2 position = GetTerrainPosition(heightmap, currParams.Scale, currParams.HeightRange, out baseHeight, out theta, placedLocations);
                    switch (currParams.Rotation)
                    {
                        case RotationParameters.Fixed:
                            theta = 0;
                            break;
                        case RotationParameters.FourAngles:
                            theta = numDirs[RandomHelper.RandomGen.Next(0, numDirs.Length)];
                            break;
                        case RotationParameters.Random:
                            theta = (float)RandomHelper.RandomGen.NextDouble() * MathHelper.TwoPi;
                            break;
                    }

                    GFX.Device.SetRenderTarget(0, rtHeightmap);
                    DrawImage(heightmap);
                    CreateLerpLayer(heightmap, currParams.Mask.GetTexture() as Texture2D, true, baseHeight, currParams.Intensity, currParams.Scale, theta, position);
                    GFX.Device.SetRenderTarget(0, null);
                    CopyToTexture(rtHeightmap.GetTexture(), heightmap);
                    landmarks.Add(i, new Vector4(position.X, position.Y, baseHeight, theta));
                    placedLocations.Add(new Vector3(position.X, position.Y, currParams.RepulsionFactor));
                    //placedLocations.Add(new Vector3(position.X, position.Y, currParams.Scale.Length() * currParams.RepulsionFactor));
                }
            }
        }
        public void BlurRenderTarget(RenderTarget2D target, BlurFilter filterType, int blurPasses)
        {
            Vector2 invRes = Vector2.One / new Vector2(target.Width, target.Height);
            GFX.Device.SetVertexShaderConstant(GFXShaderConstants.VC_INVTEXRES, invRes);
            GFX.Device.SetPixelShaderConstant(1, Vector4.One * 0.015f);
            GFX.Device.SetPixelShaderConstant(0, invRes);

            Shader activeHShader = boxBlurHShader;
            Shader activeVShader = boxBlurVShader;
            switch (filterType)
            {
                case BlurFilter.Gauss:
                    activeHShader = gaussBlurHShader;
                    activeVShader = gaussBlurVShader;
                    break;
            }

            for (int i = 0; i < blurPasses; i++)
            {
                GFX.Device.Textures[0] = target.GetTexture();
                GFX.Device.SetRenderTarget(0, target);
                activeHShader.SetupShader();
                GFXPrimitives.Quad.Render();
                GFX.Device.SetRenderTarget(0, null);

                GFX.Device.Textures[0] = target.GetTexture();

                GFX.Device.SetRenderTarget(0, target);
                activeVShader.SetupShader();
                GFXPrimitives.Quad.Render();
                GFX.Device.SetRenderTarget(0, null);
            }
        }
Esempio n. 30
0
        void CreateLayer(Texture2D heightmap, LayerMode mode, BlendMode blendMode, PlacementParameters parameters)
        {
            RenderTarget2D rtPeaks = new RenderTarget2D(GFX.Device, heightmap.Width, heightmap.Height, 1, heightmap.Format);

            GFX.Device.SetRenderTarget(0, rtPeaks);
            DrawImage(heightmap);

            GFX.Device.RenderState.AlphaBlendEnable = true;

            switch (blendMode)
            {
                case BlendMode.Additive:
                    GFX.Device.RenderState.SourceBlend = Blend.One;
                    GFX.Device.RenderState.DestinationBlend = Blend.One;
                    break;
                case BlendMode.SoftAdditive:
                    GFX.Device.RenderState.SourceBlend = Blend.InverseDestinationColor;
                    GFX.Device.RenderState.DestinationBlend = Blend.One;
                    break;
                case BlendMode.Multiply:
                    GFX.Device.RenderState.SourceBlend = Blend.DestinationColor;
                    GFX.Device.RenderState.DestinationBlend = Blend.Zero;
                    break;
                case BlendMode.Interpolate:
                    GFX.Device.RenderState.SourceBlend = Blend.SourceAlpha;
                    GFX.Device.RenderState.DestinationBlend = Blend.InverseSourceAlpha;
                    break;
            }

            peakShader.SetupShader();
            int count = RandomHelper.RandomGen.Next(parameters.MinCount, parameters.MaxCount);
            for (int i = 0; i < count; i++)
            {
                Vector2 res = Vector2.One;
                switch (mode)
                {
                    case LayerMode.Peaks:
                        GFX.Device.Textures[0] = whiteTexture;
                        break;
                    case LayerMode.Mountains:
                        Texture2D mountainMap = GFX.Inst.PerlinNoiseGen.Generate2DNoise(mountainParams, mountainRes, mountainRes, 1);
                        GFX.Device.Textures[0] = mountainMap;
                        res = new Vector2(mountainRes, mountainRes);
                        break;
                }
                float amplitude = MathHelper.Lerp(parameters.MinAmplitude, parameters.MaxAmplitude, (float)RandomHelper.RandomGen.NextDouble());
                float falloff = MathHelper.Lerp(parameters.MinFalloff, parameters.MaxFalloff, (float)RandomHelper.RandomGen.NextDouble());
                Vector4 peakParameters = new Vector4(amplitude, falloff, 0, 0);
                Vector2 randPos = new Vector2((float)RandomHelper.RandomGen.NextDouble(), (float)RandomHelper.RandomGen.NextDouble()) * 2.0f - Vector2.One;

                Vector2 randRadius = Vector2.Lerp(parameters.MinSize, parameters.MaxSize, (float)RandomHelper.RandomGen.NextDouble());
                randPos = Vector2.Clamp(randPos, Vector2.One * -1 + randRadius, Vector2.One - randRadius);
                GFX.Device.SetPixelShaderConstant(0, peakParameters);
                GFX.Device.SetVertexShaderConstant(0, new Vector4(randRadius.X, randRadius.Y, randPos.X, randPos.Y));
                GFX.Device.SetVertexShaderConstant(1, Vector4.Zero);
                GFX.Device.SetVertexShaderConstant(2, Vector2.One / res);
            }

            GFX.Device.RenderState.AlphaBlendEnable = false;

            GFX.Device.SetRenderTarget(0, null);
            GFX.Device.Textures[0] = null;

            CopyToTexture(rtPeaks.GetTexture(), heightmap);
        }
Esempio n. 31
0
        void CreateTerraces(Texture2D heightmap)
        {
            RenderTarget2D rtTerrace = new RenderTarget2D(GFX.Device, heightmap.Width, heightmap.Height, 1, heightmap.Format);

            GFX.Device.SetRenderTarget(0, rtTerrace);

            GFX.Device.Textures[0] = heightmap;
            GFX.Device.SetVertexShaderConstant(GFXShaderConstants.VC_INVTEXRES, new Vector2(1.0f / (float)heightmap.Width, 1.0f / (float)heightmap.Height));
            GFX.Device.SetPixelShaderConstant(0, new Vector4(terraceCount, terraceExp, 0, 0));
            terraceShader.SetupShader();

            GFXPrimitives.Quad.Render();

            GFX.Device.SetRenderTarget(0, null);
            GFX.Device.Textures[0] = null;

            CopyToTexture(rtTerrace.GetTexture(), heightmap);
        }
Esempio n. 32
0
        /// <summary>
        /// Creates a transparency atlas with which to texture the terrain.
        /// </summary>
        /// <param name="spriteBatch">A spritebatch to draw with.</param>
        public void CreateTransparencyAtlas(SpriteBatch spriteBatch)
        {
            DepthStencilBuffer OldDSBuffer = m_GraphicsDevice.DepthStencilBuffer;

            RenderTarget2D RTarget = new RenderTarget2D(m_GraphicsDevice, 1024, 256, 0, SurfaceFormat.Color,
                RenderTargetUsage.PreserveContents);
            DepthStencilBuffer DSBuffer = new DepthStencilBuffer(m_GraphicsDevice, 1024, 256,
                OldDSBuffer.Format);

            m_GraphicsDevice.DepthStencilBuffer = DSBuffer;
            m_GraphicsDevice.SetRenderTarget(0, RTarget);

            m_GraphicsDevice.Clear(Color.CornflowerBlue);

            spriteBatch.Begin();

            for (int i = 0; i < 30; i = i + 2)
            {
                spriteBatch.Draw(m_TransA[i], new Rectangle(i*32, 0, m_TransA[i].Width, m_TransA[i].Height), Color.White);
                spriteBatch.Draw(m_TransA[i + 1], new Rectangle(i*32, 64, m_TransA[i + 1].Width, m_TransA[i + 1].Height), Color.White);
            }

            for (int i = 0; i < 30; i = i + 2)
            {
                spriteBatch.Draw(TransB[i], new Rectangle(i*32, 128, m_TransA[i].Width, m_TransA[i].Height), Color.White);
                spriteBatch.Draw(TransB[i + 1], new Rectangle(i*32, 192, m_TransA[i + 1].Width, m_TransA[i + 1].Height), Color.White);
            }

            Texture2D black = new Texture2D(m_GraphicsDevice, 1, 1);
            black.SetData<Color>(new Color[] { Color.Black });
            spriteBatch.Draw(black, new Rectangle(1024-64, 0, 64, 256), Color.Black);
            //fill far end with black to cause no blend if adjacency bitmask is "0000"

            spriteBatch.End();

            m_GraphicsDevice.SetRenderTarget(0, null);
            m_GraphicsDevice.DepthStencilBuffer = OldDSBuffer;

            TransAtlas = RTarget.GetTexture();
            RTarget.Dispose(); //free up memory used by render target, as we have moved the data to a texture.
        }