Пример #1
0
		public static Texture BeginGetTempTexture(Type type)
		{
			if (type == typeof(Texture))
				type = typeof(Texture2D);

			for (int i = 0; i < textureCache.Count; i++)
			{
				if (textureCache[i].GetType() == type)
				{
					Texture t = textureCache[i];
					textureCache.RemoveAt(i);
					return t;
				}
			}

			//create.
			SurfaceFormat format = SurfaceFormat.HalfSingle;

			Texture texture = null;

			if (type == typeof(Texture2D))
				texture = new Texture2D(GraphicsDevice, 2, 2, false, format);
			if (type == typeof(Texture3D))
				texture = new Texture3D(GraphicsDevice, 2, 2, 2, false, format);
			if (type == typeof(TextureCube))
				texture = new TextureCube(GraphicsDevice, 2, false, format);

			return texture;
		}
        public ShaderResourceView GenerateNoiseTexture(Buffer constantBuffer, DirectComputeConstantBuffer container)
        {
            Texture3D noiseTexture = new Texture3D(graphicsDevice, new Texture3DDescription()
            {
                BindFlags = BindFlags.ShaderResource | BindFlags.UnorderedAccess,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = Format.R32_Float,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                Usage = ResourceUsage.Default,
                Width = container.Width,
                Height = container.Height,
                Depth = container.Depth
            });

            UnorderedAccessView noiseTextureUAV = new UnorderedAccessView(graphicsDevice, noiseTexture);

            DataBox data = graphicsDevice.ImmediateContext.MapSubresource(constantBuffer, MapMode.WriteDiscard, MapFlags.None);
            data.Data.Write<DirectComputeConstantBuffer>(container);
            graphicsDevice.ImmediateContext.UnmapSubresource(constantBuffer, 0);

            graphicsDevice.ImmediateContext.ComputeShader.Set(computeFillNoiseTexture);
            graphicsDevice.ImmediateContext.ComputeShader.SetConstantBuffer(constantBuffer, 0);
            graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(noiseTextureUAV, 0);

            Vector3 gridDim = new Vector3((float)Math.Ceiling(container.Width / 8.0f), (float)Math.Ceiling(container.Height / 8.0f), (float)Math.Ceiling(container.Depth / 8.0f));

            graphicsDevice.ImmediateContext.Dispatch((int)gridDim.X, (int)gridDim.Y, (int)gridDim.Z);

            noiseTextureUAV.Dispose();

            return new ShaderResourceView(graphicsDevice, noiseTexture);
        }
Пример #3
0
        //        Primitive						m_Prim_Cube;
        public ViewerForm( BImage _Image )
        {
            InitializeComponent();

            //TransparencyKey = SystemColors.Control;

            // Setup device
            m_Device = new Device();
            m_Device.Init( Handle, false, true );

            m_CB_Global = new ConstantBuffer< CB_Global >( m_Device, 0 );

            // Create shaders
            m_Shader_Render2D = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( @"./Shaders/Render2D.hlsl" ) ), VERTEX_FORMAT.Pt4, "VS", null, "PS", null );

            // Create the texture
            try
            {
                if ( _Image.m_Opts.m_type == BImage.ImageOptions.TYPE.TT_2D ) {
                    m_Tex2D = _Image.CreateTexture2D( m_Device );

                    m_CB_Global.m.m_ImageWidth = (uint) m_Tex2D.Width;
                    m_CB_Global.m.m_ImageHeight = (uint) m_Tex2D.Height;
                    m_CB_Global.m.m_ImageDepth = (uint) m_Tex2D.ArraySize;
                    m_CB_Global.m.m_ImageType = 0;

                    integerTrackbarControlMipLevel.RangeMax = m_Tex2D.MipLevelsCount;
                    integerTrackbarControlMipLevel.VisibleRangeMax = m_Tex2D.MipLevelsCount;

                } else if ( _Image.m_Opts.m_type == BImage.ImageOptions.TYPE.TT_CUBIC ) {
                    m_TexCube = _Image.CreateTextureCube( m_Device );

                    m_CB_Global.m.m_ImageWidth = (uint) m_TexCube.Width;
                    m_CB_Global.m.m_ImageHeight = (uint) m_TexCube.Height;
                    m_CB_Global.m.m_ImageDepth = (uint) m_TexCube.ArraySize;
                    m_CB_Global.m.m_ImageType = 1;

                    integerTrackbarControlMipLevel.RangeMax = m_TexCube.MipLevelsCount;
                    integerTrackbarControlMipLevel.VisibleRangeMax = m_TexCube.MipLevelsCount;

                } else if ( _Image.m_Opts.m_type == BImage.ImageOptions.TYPE.TT_3D ) {
                    m_Tex3D = _Image.CreateTexture3D( m_Device );
                }

                // Enable EV manipulation for HDR images
                bool	showExposure = _Image.m_Opts.m_format.m_type == BImage.PixelFormat.Type.FLOAT;
                labelEV.Visible = showExposure;
                floatTrackbarControlEV.Visible = showExposure;

            }
            catch ( Exception _e )
            {
                MessageBox.Show( this, "Failed to create a valid texture from the image:\r\n\r\n" + _e.Message, "BImage Viewer", MessageBoxButtons.OK, MessageBoxIcon.Error );
            }

            Application.Idle += new EventHandler( Application_Idle );
        }
Пример #4
0
        public DX11RenderTexture3D(DX11RenderContext context, Texture3D tex, ShaderResourceView srv, UnorderedAccessView uav)
            : base(context)
        {
            this.Resource = tex;

            this.SRV = srv;

            this.UAV = uav;
        }
Пример #5
0
        public DX11RenderTexture3D(DX11RenderContext context, Texture3D tex)
            : base(context)
        {
            this.Resource = tex;

            this.SRV = new ShaderResourceView(context.Device, tex);

            this.UAV = new UnorderedAccessView(context.Device, tex);
        }
Пример #6
0
 public cFlameEffect(GraphicsDevice gd, ContentManager cm, int w, int h)
     : base(w, h, 1)
 {
     this.RigidBody.IsStatic = true;
     Width = w;
     Height = h;
     _effect = cm.Load<Effect>(@"Resources/Shaders/Fire/FlameEffect");
     _flameTex = cm.Load<Texture2D>(@"Resources/Textures/flame2");
     _noiseTex = Texture3D.FromFile(gd, @"Resources/Textures/NoiseVolume.dds");
     this.RigidBody.setCollisionListner(this, "fire");
 }
 void IResource.Destroy()
 {
     if (texture2D != null)
         texture2D.Dispose();
     texture2D = null;
     if (texture3D != null)
         texture3D.Dispose();
     texture3D = null;
     if (textureCube != null)
         textureCube.Dispose();
     textureCube = null;
 }
        public static Texture3D CreateRotatedPoissonDiskTexture(GraphicsDevice graphicsDevice)
        {
            const int size = 32;

            var result = new Texture3D(graphicsDevice, 
                size, size, size, false, 
                SurfaceFormat.Rg32);

            result.SetData(CreateRandomRotations(size * size * size).ToArray());

            return result;
        }
Пример #9
0
        public VolumeRaycaster(Game game, Volume<byte> volume)
            : base(game)
        {
            _bbox = new BoundingBox(new Vector3(-1), new Vector3(1));
            _volume = volume;
            _alpha = 1.0f;

            IGraphicsDeviceService graphicsservice = Game.Services.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService;
            _graphicDevice = graphicsservice.GraphicsDevice;
            _volTexture = new Texture3D(_graphicDevice, _volume.Dim.Width, _volume.Dim.Height, _volume.Dim.Depth, 1, TextureUsage.None, SurfaceFormat.Alpha8);
            _tfTexture = new Texture2D(_graphicDevice, 256, 1, 1, TextureUsage.None, SurfaceFormat.Color);
            _tfPreIntTexture = new Texture2D(_graphicDevice, 256, 256, 1, TextureUsage.None, SurfaceFormat.Color);

            Viewport viewport = _graphicDevice.Viewport;
            _entryPointRt = new RenderTarget2D(_graphicDevice, viewport.Width, viewport.Height, 1, SurfaceFormat.Vector4);
            _exitPointRt = new RenderTarget2D(_graphicDevice, viewport.Width, viewport.Height, 1, SurfaceFormat.Vector4);
            _tempRt = new RenderTarget2D(_graphicDevice, viewport.Width, viewport.Height, 1, SurfaceFormat.Vector4);
        }
Пример #10
0
        // Functions
        public TextureObject()
        {
            m_Width = m_Height = 1;
            m_Mips = 1;
            m_Depth = 1;
            m_ArraySize = 1;
            m_IsCube = false;
            m_TexFormat = Format.Unknown;
            m_TextureObject2D = null;
            m_TextureObject3D = null;
            m_RenderTargetView = null;
            m_ShaderResourceView = null;
            m_DepthStencilView = null;
            m_UnorderedAccessView = null;

            m_ArrayRenderTargetViews = null;
            m_ArrayShaderResourceViews = null;
            m_ArrayDepthStencilViews = null;
            m_ArrayUnorderedAccessViews = null;
        }
Пример #11
0
        public void ShouldSetAndGetData(int width, int height, int depth)
        {
            Game.DrawWith += (sender, e) =>
            {
                var dataSize = width * height * depth;
                var texture3D = new Texture3D(Game.GraphicsDevice, width, height, depth, false, SurfaceFormat.Color);
                var savedData = new Color[dataSize];
                for (var index = 0; index < dataSize; index++) savedData[index] = new Color(index, index, index);
                texture3D.SetData(savedData);

                var readData = new Color[dataSize];
                texture3D.GetData(readData);

                Assert.AreEqual(savedData, readData);
            };
            Game.RunOneFrame();
        }
Пример #12
0
		private static void Internal_Create(Texture3D mono, int width, int height, int depth, TextureFormat format, bool mipmap){}
Пример #13
0
        /// <summary>
        /// Open a dds from a stream.
        /// (Supported formats : Dxt1,Dxt2,Dxt3,Dxt4,Dxt5,A8R8G8B8/Color,X8R8G8B8,R8G8B8,A4R4G4B4,A1R5G5B5,R5G6B5,A8,
        /// FP32/Single,FP16/HalfSingle,FP32x4/Vector4,FP16x4/HalfVector4,CxV8U8/NormalizedByte2/CxVU,Q8VW8V8U8/NormalizedByte4/8888QWVU
        /// ,HalfVector2/G16R16F/16.16fGR,Vector2/G32R32F,G16R16/RG32/1616GB,B8G8R8,X8B8G8R8,A8B8G8R8/Color,L8,A2B10G10R10/Rgba1010102,A16B16G16R16/Rgba64)
        /// </summary>
        /// <param name="stream">Stream containing the data.</param>
        /// <param name="device">Graphic device where you want the texture to be loaded.</param>
        /// <param name="texture">The reference to the loaded texture.</param>
        /// <param name="streamOffset">Offset in the stream to where the DDS is located.</param>
        /// <param name="loadMipMap">If true it will load the mip-map chain for this texture.</param>
        public static void DDSFromStream(Stream stream, GraphicsDevice device, int streamOffset, bool loadMipMap, out Texture3D texture)
        {
            Texture tex;
            InternalDDSFromStream(stream, device, streamOffset, loadMipMap, out tex);

            texture = tex as Texture3D;
            if (texture == null)
            {
                throw new Exception("The data in the stream contains a Texture2D not TextureCube");
            }
        }
Пример #14
0
        static void loadTextures()
        {
            groundTexture = new Dictionary<BiomeType, Texture2D>();
            elementInterface = new Dictionary<string, Texture2D>();

            groundTexture.Add(BiomeType.None, content.Load<Texture2D>("Textures/Sand"));
            groundTexture.Add(BiomeType.Water, content.Load<Texture2D>("Textures/Sand"));
            groundTexture.Add(BiomeType.SubtropicalDesert, content.Load<Texture2D>("Textures/Sand"));
            groundTexture.Add(BiomeType.GrasslandDesert, content.Load<Texture2D>("Textures/Grass"));
            groundTexture.Add(BiomeType.Savanna, content.Load<Texture2D>("Textures/Gravel"));
            groundTexture.Add(BiomeType.Shrubland, content.Load<Texture2D>("Textures\\dirt3"));
            groundTexture.Add(BiomeType.Taiga, content.Load<Texture2D>("Textures/stone"));
            groundTexture.Add(BiomeType.Tundra, content.Load<Texture2D>("Textures/stone2"));
            groundTexture.Add(BiomeType.TemperateForest, content.Load<Texture2D>("Textures/Grass2"));
            groundTexture.Add(BiomeType.TropicalRainforest, content.Load<Texture2D>("Textures/Grass2"));
            groundTexture.Add(BiomeType.TemperateRainforest, content.Load<Texture2D>("Textures/Grass2"));

            biomeTextures = new Texture2D[groundTexture.Count];
            biome3D = new Texture3D(device, 256, 256, groundTexture.Count, false, groundTexture[0].Format);
            Color[] texData = new Color[256 * 256*11];

            foreach (BiomeType t in groundTexture.Keys)
            {
                biomeTextures[(int)t] = groundTexture[t];

                biomeTextures[(int)t].GetData(texData, 256*256*((int)t), 256*256);

            }

            biome3D.SetData(texData);

            //biomeAtlas = content.Load<Texture2D>("Texture/biomeAtlas");
        }
Пример #15
0
            /// <summary>
            /// Generates the mip maps.
            /// </summary>
            /// <param name="device">The device.</param>
            /// <param name="texture">The texture.</param>
            /// <param name="textMip">Returns a new texture with mipmaps if succeeded. Otherwise returns the input texture</param>
            /// <returns>True succeed. False: Format not supported.</returns>
            /// <exception cref="InvalidDataException">Input texture is invalid.</exception>
            public static bool GenerateMipMaps(Device device, global::SharpDX.Toolkit.Graphics.Texture texture, out Resource textMip)
            {
                textMip = null;
                //Check texture format support: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476426(v=vs.85).aspx
                switch (texture.Description.Format)
                {
                case global::SharpDX.DXGI.Format.R8G8B8A8_UNorm:
                case global::SharpDX.DXGI.Format.R8G8B8A8_UNorm_SRgb:
                case global::SharpDX.DXGI.Format.B5G6R5_UNorm:
                case global::SharpDX.DXGI.Format.B8G8R8A8_UNorm:
                case global::SharpDX.DXGI.Format.B8G8R8A8_UNorm_SRgb:
                case global::SharpDX.DXGI.Format.B8G8R8X8_UNorm:
                case global::SharpDX.DXGI.Format.B8G8R8X8_UNorm_SRgb:
                case global::SharpDX.DXGI.Format.R16G16B16A16_Float:
                case global::SharpDX.DXGI.Format.R16G16B16A16_UNorm:
                case global::SharpDX.DXGI.Format.R16G16_Float:
                case global::SharpDX.DXGI.Format.R16G16_UNorm:
                case global::SharpDX.DXGI.Format.R32_Float:
                case global::SharpDX.DXGI.Format.R32G32B32A32_Float:
                case global::SharpDX.DXGI.Format.B4G4R4A4_UNorm:
                case global::SharpDX.DXGI.Format.R32G32B32_Float:
                case global::SharpDX.DXGI.Format.R16G16B16A16_SNorm:
                case global::SharpDX.DXGI.Format.R32G32_Float:
                case global::SharpDX.DXGI.Format.R10G10B10A2_UNorm:
                case global::SharpDX.DXGI.Format.R11G11B10_Float:
                case global::SharpDX.DXGI.Format.R8G8B8A8_SNorm:
                case global::SharpDX.DXGI.Format.R16G16_SNorm:
                case global::SharpDX.DXGI.Format.R8G8_UNorm:
                case global::SharpDX.DXGI.Format.R8G8_SNorm:
                case global::SharpDX.DXGI.Format.R16_Float:
                case global::SharpDX.DXGI.Format.R16_UNorm:
                case global::SharpDX.DXGI.Format.R16_SNorm:
                case global::SharpDX.DXGI.Format.R8_UNorm:
                case global::SharpDX.DXGI.Format.R8_SNorm:
                case global::SharpDX.DXGI.Format.A8_UNorm:
                case global::SharpDX.DXGI.Format.B5G5R5A1_UNorm:
                    break;

                default:
                    textMip = texture.Resource.QueryInterface <Resource>();   //Format not support, return the original texture.
                    return(false);
                }
                var sliceCount = 1;
                var mipLevels  = 0;

                switch (texture.Description.Dimension)
                {
                case global::SharpDX.Toolkit.Graphics.TextureDimension.Texture1D:
                    var desc1D = new Texture1DDescription()
                    {
                        Width          = texture.Description.Width,
                        MipLevels      = 0,
                        ArraySize      = 1,
                        BindFlags      = BindFlags.RenderTarget | BindFlags.ShaderResource,
                        CpuAccessFlags = CpuAccessFlags.None,
                        Usage          = ResourceUsage.Default,
                        OptionFlags    = ResourceOptionFlags.GenerateMipMaps,
                        Format         = texture.Description.Format
                    };
                    textMip   = new Texture1D(device, desc1D);
                    mipLevels = (textMip as Texture1D).Description.MipLevels;
                    break;

                case global::SharpDX.Toolkit.Graphics.TextureDimension.Texture2D:
                    var desc2D = new Texture2DDescription()
                    {
                        Width             = texture.Description.Width,
                        Height            = texture.Description.Height,
                        MipLevels         = 0,
                        ArraySize         = 1,
                        BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                        CpuAccessFlags    = CpuAccessFlags.None,
                        Usage             = ResourceUsage.Default,
                        SampleDescription = texture.Description.SampleDescription,
                        OptionFlags       = ResourceOptionFlags.GenerateMipMaps,
                        Format            = texture.Description.Format
                    };
                    textMip   = new Texture2D(device, desc2D);
                    mipLevels = (textMip as Texture2D).Description.MipLevels;
                    break;

                case global::SharpDX.Toolkit.Graphics.TextureDimension.Texture3D:
                    var desc3D = new Texture3DDescription()
                    {
                        Width          = texture.Description.Width,
                        Height         = texture.Description.Height,
                        Depth          = texture.Description.Depth,
                        MipLevels      = 0,
                        BindFlags      = BindFlags.RenderTarget | BindFlags.ShaderResource,
                        CpuAccessFlags = CpuAccessFlags.None,
                        Usage          = ResourceUsage.Default,
                        OptionFlags    = ResourceOptionFlags.GenerateMipMaps,
                        Format         = texture.Description.Format
                    };
                    textMip    = new Texture3D(device, desc3D);
                    sliceCount = texture.Description.Depth;
                    mipLevels  = (textMip as Texture3D).Description.MipLevels;
                    break;

                case global::SharpDX.Toolkit.Graphics.TextureDimension.TextureCube:
                    var descCube = new Texture2DDescription()
                    {
                        Width             = texture.Description.Width,
                        Height            = texture.Description.Height,
                        ArraySize         = texture.Description.ArraySize,
                        MipLevels         = 0,
                        BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                        CpuAccessFlags    = CpuAccessFlags.None,
                        SampleDescription = new global::SharpDX.DXGI.SampleDescription(1, 0),
                        Usage             = ResourceUsage.Default,
                        OptionFlags       = ResourceOptionFlags.GenerateMipMaps | ResourceOptionFlags.TextureCube,
                        Format            = texture.Description.Format
                    };
                    textMip    = new Texture2D(device, descCube);
                    sliceCount = texture.Description.ArraySize;
                    mipLevels  = (textMip as Texture2D).Description.MipLevels;
                    break;

                default:
                    throw new InvalidDataException("Input texture is invalid.");
                }

                using (var shaderRes = new ShaderResourceView(device, textMip))
                {
                    for (var i = 0; i < sliceCount; ++i)
                    {
                        var idx       = texture.GetSubResourceIndex(i, 0);
                        var targetIdx = GetSubResourceIndex(i, mipLevels, 0);
                        device.ImmediateContext.CopySubresourceRegion(texture, idx, null, textMip, targetIdx);
                    }
                    device.ImmediateContext.GenerateMips(shaderRes);
                }
                return(true);
            }
Пример #16
0
        void GenerateFloatingIslands(int size)
        {
            DensityFieldWidth = size + 1;
            DensityFieldHeight = size/2 + 1;
            DensityFieldDepth = DensityFieldWidth;

            InitializeFieldData();

            //Here we generate our noise textures
            int nSize = 16;
            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;

            //The program we'll be using
            Shader islandShader = ResourceManager.Inst.GetShader("ProceduralIsland");
            islandShader.SetupShader();

            GFX.Device.SetPixelShaderConstant(0, Vector3.One / new Vector3(DensityFieldWidth, DensityFieldHeight, DensityFieldDepth));
            //Lets activate our textures
            for (int i = 0; i < noiseTextures.Length; i++)
                GFX.Device.Textures[i] = noiseTextures[i];

            GFX.Device.SetVertexShaderConstant(1, textureMatrix);

            //Set swizzle axis to the z axis
            GFX.Device.SetPixelShaderConstant(1, Vector4.One * 2);

            //Here we setup our render target.
            //This is used to fetch what is rendered to our screen and store it in a texture.
            srcTarget = new RenderTarget2D(GFX.Device, DensityFieldWidth, DensityFieldHeight, 1, GFX.Inst.ByteSurfaceFormat);
            DepthStencilBuffer dsOld = GFX.Device.DepthStencilBuffer;
            GFX.Device.DepthStencilBuffer = GFX.Inst.dsBufferLarge;

            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.DepthStencilBuffer = dsOld;

            InitializeSurfaceIndices();

            InitializeVoxels();
        }
Пример #17
0
        ///<summary>
        ///    Call this to associate a Xna Texture3D with this pixel buffer
        ///</summary>
        public void Bind( GraphicsDevice device, Texture3D volume, bool update )
        {
            this.device = device;
            this.volume = volume;

            width = volume.Width;
            height = volume.Height;
            depth = volume.Depth;
            format = XnaHelper.Convert( volume.Format );
            // Default
            rowPitch = Width;
            slicePitch = Height*Width;
            sizeInBytes = PixelUtil.GetMemorySize( Width, Height, Depth, Format );

            if ( ( (int)usage & (int)TextureUsage.RenderTarget ) != 0 )
                CreateRenderTextures( update );
        }
Пример #18
0
 public void RemakeTexture()
 {
     GetData();
     _texture = MakeTexture(values);
 }
        /// <summary>
        /// Bind to a pixel shader for rendering.
        /// </summary>
        public void BindToMaterial(Material mat)
        {
            if (UseLuminance == LUMINANCE.NONE)
            {
                mat.EnableKeyword("RADIANCE_API_ENABLED");
            }
            else
            {
                mat.DisableKeyword("RADIANCE_API_ENABLED");
            }

            if (CombineScatteringTextures)
            {
                mat.EnableKeyword("COMBINED_SCATTERING_TEXTURES");
            }
            else
            {
                mat.DisableKeyword("COMBINED_SCATTERING_TEXTURES");
            }

            string path = "Assets/BrunetonsImprovedAtmosphere/Textures/";

            Texture2D t = TransmittanceTexture.ToTexture2D();

            AssetDatabase.CreateAsset(t, path + "transmittance.Texture2D");

            Texture3D s = ScatteringTexture.ToTexture3D();

            AssetDatabase.CreateAsset(s, path + "scattering.Texture3D");

            Texture2D i = IrradianceTexture.ToTexture2D();

            AssetDatabase.CreateAsset(i, path + "irradiance.Texture2D");

            mat.SetTexture("transmittance_texture", t);
            mat.SetTexture("scattering_texture", s);
            mat.SetTexture("irradiance_texture", i);

            if (CombineScatteringTextures)
            {
                mat.SetTexture("single_mie_scattering_texture", TextureUtilities.blackTexture3D());
            }
            else
            {
                Texture3D m = OptionalSingleMieScatteringTexture.ToTexture3D();
                AssetDatabase.CreateAsset(m, path + "optional_mie.Texture3D");
                mat.SetTexture("single_mie_scattering_texture", m);
            }

            mat.SetInt("TRANSMITTANCE_TEXTURE_WIDTH", CONSTANTS.TRANSMITTANCE_WIDTH);
            mat.SetInt("TRANSMITTANCE_TEXTURE_HEIGHT", CONSTANTS.TRANSMITTANCE_HEIGHT);
            mat.SetInt("SCATTERING_TEXTURE_R_SIZE", CONSTANTS.SCATTERING_R);
            mat.SetInt("SCATTERING_TEXTURE_MU_SIZE", CONSTANTS.SCATTERING_MU);
            mat.SetInt("SCATTERING_TEXTURE_MU_S_SIZE", CONSTANTS.SCATTERING_MU_S);
            mat.SetInt("SCATTERING_TEXTURE_NU_SIZE", CONSTANTS.SCATTERING_NU);
            mat.SetInt("SCATTERING_TEXTURE_WIDTH", CONSTANTS.SCATTERING_WIDTH);
            mat.SetInt("SCATTERING_TEXTURE_HEIGHT", CONSTANTS.SCATTERING_HEIGHT);
            mat.SetInt("SCATTERING_TEXTURE_DEPTH", CONSTANTS.SCATTERING_DEPTH);
            mat.SetInt("IRRADIANCE_TEXTURE_WIDTH", CONSTANTS.IRRADIANCE_WIDTH);
            mat.SetInt("IRRADIANCE_TEXTURE_HEIGHT", CONSTANTS.IRRADIANCE_HEIGHT);

            mat.SetFloat("sun_angular_radius", (float)SunAngularRadius);
            mat.SetFloat("bottom_radius", (float)(BottomRadius / LengthUnitInMeters));
            mat.SetFloat("top_radius", (float)(TopRadius / LengthUnitInMeters));
            mat.SetFloat("mie_phase_function_g", (float)MiePhaseFunctionG);
            mat.SetFloat("mu_s_min", (float)Math.Cos(MaxSunZenithAngle));

            Vector3 skySpectralRadianceToLuminance, sunSpectralRadianceToLuminance;

            SkySunRadianceToLuminance(out skySpectralRadianceToLuminance, out sunSpectralRadianceToLuminance);

            mat.SetVector("SKY_SPECTRAL_RADIANCE_TO_LUMINANCE", skySpectralRadianceToLuminance);
            mat.SetVector("SUN_SPECTRAL_RADIANCE_TO_LUMINANCE", sunSpectralRadianceToLuminance);

            double[] lambdas = new double[] { kLambdaR, kLambdaG, kLambdaB };

            Vector3 solarIrradiance = ToVector(Wavelengths, SolarIrradiance, lambdas, 1.0);

            mat.SetVector("solar_irradiance", solarIrradiance);

            Vector3 rayleighScattering = ToVector(Wavelengths, RayleighScattering, lambdas, LengthUnitInMeters);

            mat.SetVector("rayleigh_scattering", rayleighScattering);

            Vector3 mieScattering = ToVector(Wavelengths, MieScattering, lambdas, LengthUnitInMeters);

            mat.SetVector("mie_scattering", mieScattering);
        }
Пример #20
0
    void GenerateNoise_3D()
    {
        Texture3D tex3D = new Texture3D(mTexSize, mTexSize, mTexSize, TextureFormat.RGBA32, false);

        Color[] cols = tex3D.GetPixels();

        var buffer = new ComputeBuffer(mTexSize * mTexSize * mTexSize, sizeof(float));

        float[] datas = new float[mTexSize * mTexSize * mTexSize];


        if (SetNoiseCS_3D(noises[0], buffer) == true)
        {
            buffer.GetData(datas);

            for (int i = 0; i < datas.Length; ++i)
            {
                cols[i].r = datas[i];
            }
        }
        else
        {
            for (int i = 0; i < datas.Length; ++i)
            {
                cols[i].r = 0f;
            }
        }

        if (SetNoiseCS_3D(noises[1], buffer) == true)
        {
            buffer.GetData(datas);

            for (int i = 0; i < datas.Length; ++i)
            {
                cols[i].g = datas[i];
            }
        }
        else
        {
            for (int i = 0; i < datas.Length; ++i)
            {
                cols[i].g = 0f;
            }
        }

        if (SetNoiseCS_3D(noises[2], buffer) == true)
        {
            buffer.GetData(datas);

            for (int i = 0; i < datas.Length; ++i)
            {
                cols[i].b = datas[i];
            }
        }
        else
        {
            for (int i = 0; i < datas.Length; ++i)
            {
                cols[i].b = 0f;
            }
        }

        if (SetNoiseCS_3D(noises[3], buffer) == true)
        {
            buffer.GetData(datas);

            for (int i = 0; i < datas.Length; ++i)
            {
                cols[i].a = datas[i];
            }
        }
        else
        {
            for (int i = 0; i < datas.Length; ++i)
            {
                cols[i].a = 0f;
            }
        }

        buffer.Release();

        tex3D.SetPixels(cols);
        tex3D.Apply();

        SaveTexture <Texture3D>(tex3D);
    }
Пример #21
0
 void Start()
 {
     texture = CreateTexture3D(256);
 }
        public void VolumeVoxelizationPass(HDCamera hdCamera, CommandBuffer cmd, uint frameIndex, DensityVolumeList densityVolumes, LightLoop lightLoop)
        {
            if (!hdCamera.frameSettings.enableVolumetrics)
            {
                return;
            }

            var visualEnvironment = VolumeManager.instance.stack.GetComponent <VisualEnvironment>();

            if (visualEnvironment.fogType.value != FogType.Volumetric)
            {
                return;
            }

            using (new ProfilingSample(cmd, "Volume Voxelization"))
            {
                int  numVisibleVolumes = m_VisibleVolumeBounds.Count;
                bool tiledLighting     = hdCamera.frameSettings.lightLoopSettings.enableBigTilePrepass;
                bool highQuality       = preset == VolumetricLightingPreset.High;

                int kernel = (tiledLighting ? 1 : 0) | (highQuality ? 2 : 0);

                var currFrameParams = hdCamera.vBufferParams[0];
                var cvp             = currFrameParams.viewportSize;

                Vector4 resolution = new Vector4(cvp.x, cvp.y, 1.0f / cvp.x, 1.0f / cvp.y);
#if UNITY_2019_1_OR_NEWER
                var vFoV      = hdCamera.camera.GetGateFittedFieldOfView() * Mathf.Deg2Rad;
                var lensShift = hdCamera.camera.GetGateFittedLensShift();
#else
                var vFoV      = hdCamera.camera.fieldOfView * Mathf.Deg2Rad;
                var lensShift = Vector2.zero;
#endif

                // Compose the matrix which allows us to compute the world space view direction.
                Matrix4x4 transform = HDUtils.ComputePixelCoordToWorldSpaceViewDirectionMatrix(vFoV, lensShift, resolution, hdCamera.viewMatrix, false);

                // Compute texel spacing at the depth of 1 meter.
                float unitDepthTexelSpacing = HDUtils.ComputZPlaneTexelSpacing(1.0f, vFoV, resolution.y);

                Texture3D volumeAtlas           = DensityVolumeManager.manager.volumeAtlas.GetAtlas();
                Vector4   volumeAtlasDimensions = new Vector4(0.0f, 0.0f, 0.0f, 0.0f);

                if (volumeAtlas != null)
                {
                    volumeAtlasDimensions.x = (float)volumeAtlas.width / volumeAtlas.depth; // 1 / number of textures
                    volumeAtlasDimensions.y = volumeAtlas.width;
                    volumeAtlasDimensions.z = volumeAtlas.depth;
                    volumeAtlasDimensions.w = Mathf.Log(volumeAtlas.width, 2);              // Max LoD
                }
                else
                {
                    volumeAtlas = CoreUtils.blackVolumeTexture;
                }

                if (hdCamera.frameSettings.VolumeVoxelizationRunsAsync())
                {
                    // We explicitly set the big tile info even though it is set globally, since this could be running async before the PushGlobalParams
                    cmd.SetComputeIntParam(m_VolumeVoxelizationCS, HDShaderIDs._NumTileBigTileX, lightLoop.GetNumTileBigTileX(hdCamera));
                    cmd.SetComputeIntParam(m_VolumeVoxelizationCS, HDShaderIDs._NumTileBigTileY, lightLoop.GetNumTileBigTileY(hdCamera));
                    if (hdCamera.frameSettings.lightLoopSettings.enableBigTilePrepass)
                    {
                        cmd.SetComputeBufferParam(m_VolumeVoxelizationCS, kernel, HDShaderIDs.g_vBigTileLightList, lightLoop.GetBigTileLightList());
                    }
                }

                cmd.SetComputeTextureParam(m_VolumeVoxelizationCS, kernel, HDShaderIDs._VBufferDensity, m_DensityBufferHandle);
                cmd.SetComputeBufferParam(m_VolumeVoxelizationCS, kernel, HDShaderIDs._VolumeBounds, s_VisibleVolumeBoundsBuffer);
                cmd.SetComputeBufferParam(m_VolumeVoxelizationCS, kernel, HDShaderIDs._VolumeData, s_VisibleVolumeDataBuffer);
                cmd.SetComputeTextureParam(m_VolumeVoxelizationCS, kernel, HDShaderIDs._VolumeMaskAtlas, volumeAtlas);

                // TODO: set the constant buffer data only once.
                cmd.SetComputeMatrixParam(m_VolumeVoxelizationCS, HDShaderIDs._VBufferCoordToViewDirWS, transform);
                cmd.SetComputeFloatParam(m_VolumeVoxelizationCS, HDShaderIDs._VBufferUnitDepthTexelSpacing, unitDepthTexelSpacing);
                cmd.SetComputeIntParam(m_VolumeVoxelizationCS, HDShaderIDs._NumVisibleDensityVolumes, numVisibleVolumes);
                cmd.SetComputeVectorParam(m_VolumeVoxelizationCS, HDShaderIDs._VolumeMaskDimensions, volumeAtlasDimensions);

                int w = (int)resolution.x;
                int h = (int)resolution.y;

                // The shader defines GROUP_SIZE_1D = 8.
                cmd.DispatchCompute(m_VolumeVoxelizationCS, kernel, (w + 7) / 8, (h + 7) / 8, 1);
            }
        }
 public int GetTextureIndex(Texture3D tex)
 {
     return(textures.IndexOf(tex));
 }
    public Texture3D Convert(Texture2D temp2DTex, Texture3D cv3D)
    {
        int dim = 256 * 16;

        if (temp2DTex)
        {
            dim = temp2DTex.width * temp2DTex.height;
            dim = temp2DTex.height;

            if (!ValidDimensions(temp2DTex))
            {
                Debug.LogWarning("The given 2D texture " + temp2DTex.name + " cannot be used as a 3D LUT.");
                return(cv3D);
            }
        }
#if UNITY_EDITOR
        if (Application.isPlaying != true)
        {
            string path = AssetDatabase.GetAssetPath(LutTexture);
            MemoPath = path;
            TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
            if (!textureImporter.isReadable)
            {
                textureImporter.isReadable    = true;
                textureImporter.mipmapEnabled = false;
                AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
            }
            string path2 = AssetDatabase.GetAssetPath(LutTexture2);
            MemoPath2 = path2;
            TextureImporter textureImporter2 = AssetImporter.GetAtPath(path2) as TextureImporter;
            if (!textureImporter2.isReadable)
            {
                textureImporter2.isReadable    = true;
                textureImporter2.mipmapEnabled = false;
                AssetDatabase.ImportAsset(path2, ImportAssetOptions.ForceUpdate);
            }
        }
#endif

        var c    = temp2DTex.GetPixels();
        var newC = new Color[c.Length];

        for (int i = 0; i < dim; i++)
        {
            for (int j = 0; j < dim; j++)
            {
                for (int k = 0; k < dim; k++)
                {
                    int j_ = dim - j - 1;
                    newC[i + (j * dim) + (k * dim * dim)] = c[k * dim + i + j_ * dim * dim];
                }
            }
        }


        if (cv3D)
        {
            DestroyImmediate(cv3D);
        }
        cv3D = new Texture3D(dim, dim, dim, TextureFormat.ARGB32, false);
        cv3D.SetPixels(newC);
        cv3D.Apply();

        return(cv3D);
    }
        protected override void LoadContent()
        {
            base.LoadContent();

            // Create a step size based on the largest side length and create a scale factor
            // for the shader
            float maxSideLength = (float)Math.Max(width, Math.Max(height, depth));
            Vector3 stepSize = new Vector3(1.0f / maxSideLength, 1.0f / maxSideLength, 1.0f / maxSideLength);

            effect.Parameters["StepSize"].SetValue(stepSize * stepScale);
            effect.Parameters["ActualSampleDist"].SetValue(stepScale);
            effect.Parameters["Iterations"].SetValue((int)maxSideLength * (1.0f / stepScale) * 2.0f);

            Vector3 sizes = new Vector3(width, height, depth);
            Vector3 scaleFactor = Vector3.One / ((Vector3.One * maxSideLength) / (sizes * Vector3.One));
            effect.Parameters["ScaleFactor"].SetValue(new Vector4(scaleFactor, 1.0f));

            // Get the scaled volume data.
            float[] volumeData;
            RawFileReader tempFileReader = new RawFileReader();
            tempFileReader.Open(volumeAssetName, width, height, depth);
            tempFileReader.GetRawData(out volumeData);
            tempFileReader.Close();

            // Compute the gradient at each voxel and combine them with the isovalues.
            HalfVector4[] textureData;
            CreateTextureData(volumeData, out textureData);

            // Set the data into our Texture3D object, for use in the shader.
            volumeTexture = new Texture3D(VolumetricRenderer.Game.GraphicsDevice, width, height, depth, 0,
                TextureUsage.None, SurfaceFormat.HalfVector4);
            volumeTexture.SetData<HalfVector4>(textureData);

            effect.Parameters["Volume"].SetValue(volumeTexture);

            if (transfer2DTex != null)
            {
                effect.Parameters["Transfer"].SetValue(transfer2DTex);
            }
        }
Пример #26
0
        public void VolumeVoxelizationPass(HDCamera hdCamera, CommandBuffer cmd, uint frameIndex, DensityVolumeList densityVolumes)
        {
            if (!hdCamera.frameSettings.enableVolumetrics)
            {
                return;
            }

            var visualEnvironment = VolumeManager.instance.stack.GetComponent <VisualEnvironment>();

            if (visualEnvironment.fogType.value != FogType.Volumetric)
            {
                return;
            }

            using (new ProfilingSample(cmd, "Volume Voxelization"))
            {
                int numVisibleVolumes = m_VisibleVolumeBounds.Count;

                bool highQuality     = preset == VolumetricLightingPreset.High;
                bool enableClustered = hdCamera.frameSettings.lightLoopSettings.enableTileAndCluster;

                int kernel;

                if (highQuality)
                {
                    kernel = m_VolumeVoxelizationCS.FindKernel(enableClustered ? "VolumeVoxelizationClusteredHQ"
                                                                               : "VolumeVoxelizationBruteforceHQ");
                }
                else
                {
                    kernel = m_VolumeVoxelizationCS.FindKernel(enableClustered ? "VolumeVoxelizationClusteredMQ"
                                                                               : "VolumeVoxelizationBruteforceMQ");
                }

                var     frameParams = hdCamera.vBufferParams[0];
                Vector4 resolution  = frameParams.resolution;
                float   vFoV        = hdCamera.camera.fieldOfView * Mathf.Deg2Rad;

                // Compose the matrix which allows us to compute the world space view direction.
                Matrix4x4 transform = HDUtils.ComputePixelCoordToWorldSpaceViewDirectionMatrix(vFoV, resolution, hdCamera.viewMatrix, false);

                Texture3D volumeAtlas           = DensityVolumeManager.manager.volumeAtlas.volumeAtlas;
                Vector4   volumeAtlasDimensions = new Vector4(0.0f, 0.0f, 0.0f, 0.0f);

                if (volumeAtlas != null)
                {
                    volumeAtlasDimensions.x = (float)volumeAtlas.width / volumeAtlas.depth; // 1 / number of textures
                    volumeAtlasDimensions.y = volumeAtlas.width;
                    volumeAtlasDimensions.z = volumeAtlas.depth;
                    volumeAtlasDimensions.w = Mathf.Log(volumeAtlas.width, 2);              // Max LoD
                }
                else
                {
                    volumeAtlas = CoreUtils.blackVolumeTexture;
                }

                cmd.SetComputeTextureParam(m_VolumeVoxelizationCS, kernel, HDShaderIDs._VBufferDensity, m_DensityBufferHandle);
                cmd.SetComputeBufferParam(m_VolumeVoxelizationCS, kernel, HDShaderIDs._VolumeBounds, s_VisibleVolumeBoundsBuffer);
                cmd.SetComputeBufferParam(m_VolumeVoxelizationCS, kernel, HDShaderIDs._VolumeData, s_VisibleVolumeDataBuffer);
                cmd.SetComputeTextureParam(m_VolumeVoxelizationCS, kernel, HDShaderIDs._VolumeMaskAtlas, volumeAtlas);

                // TODO: set the constant buffer data only once.
                cmd.SetComputeMatrixParam(m_VolumeVoxelizationCS, HDShaderIDs._VBufferCoordToViewDirWS, transform);
                cmd.SetComputeIntParam(m_VolumeVoxelizationCS, HDShaderIDs._NumVisibleDensityVolumes, numVisibleVolumes);
                cmd.SetComputeVectorParam(m_VolumeVoxelizationCS, HDShaderIDs._VolumeMaskDimensions, volumeAtlasDimensions);

                int w = (int)resolution.x;
                int h = (int)resolution.y;

                // The shader defines GROUP_SIZE_1D = 8.
                cmd.DispatchCompute(m_VolumeVoxelizationCS, kernel, (w + 7) / 8, (h + 7) / 8, 1);
            }
        }
Пример #27
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);
        }
Пример #28
0
        protected override void OnProcess(RenderContext context)
        {
            var graphicsDevice = GraphicsService.GraphicsDevice;

            if (TextureHelper.IsFloatingPointFormat(context.SourceTexture.Format))
            {
                graphicsDevice.SamplerStates[0] = SamplerState.PointClamp;
            }
            else
            {
                graphicsDevice.SamplerStates[0] = SamplerState.LinearClamp;
            }

            graphicsDevice.SetRenderTarget(context.RenderTarget);
            graphicsDevice.Viewport = context.Viewport;

            _viewportSizeParameter.SetValue(new Vector2(graphicsDevice.Viewport.Width, graphicsDevice.Viewport.Height));
            _sourceTextureParameter.SetValue(context.SourceTexture);
            _strengthParameter.SetValue(new Vector2(Strength, InterpolationParameter));

            if (LookupTextureA == null && LookupTextureB == null)
            {
                if (_defaultLookupTexture == null)
                {
                    _defaultLookupTexture = ConvertLookupTexture(CreateLookupTexture2D(graphicsDevice));
                }

                Debug.Assert(_defaultLookupTexture != null, "Failed to create 3D lookup texture.");

                _lookupTexture0Parameter.SetValue(_defaultLookupTexture);
                _lookupTableSizeParameter.SetValue(_defaultLookupTexture.Width);
                _fullColorLookupPass.Apply();
            }
            else if (LookupTextureA == null)
            {
                ApplyPassWithOneLookupTexture(LookupTextureB);
            }
            else if (LookupTextureB == null)
            {
                ApplyPassWithOneLookupTexture(LookupTextureA);
            }
            else
            {
                if (Numeric.AreEqual(InterpolationParameter, 0))
                {
                    ApplyPassWithOneLookupTexture(LookupTextureA);
                }
                else if (Numeric.AreEqual(InterpolationParameter, 1))
                {
                    ApplyPassWithOneLookupTexture(LookupTextureB);
                }
                else
                {
                    _lookupTexture0Parameter.SetValue(LookupTextureA);
                    _lookupTexture1Parameter.SetValue(LookupTextureB);
                    _lookupTableSizeParameter.SetValue(LookupTextureA.Width);
                    _lerpColorLookupPass.Apply();
                }
            }

            graphicsDevice.DrawFullScreenQuad();

            _sourceTextureParameter.SetValue((Texture2D)null);
            _lookupTexture0Parameter.SetValue((Texture2D)null);
            _lookupTexture1Parameter.SetValue((Texture2D)null);
        }
Пример #29
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;
        }
Пример #30
0
 protected Texture3D CreateTexture3D()
 {
     var texture = new Texture3D(); texture.Storage(Format, dimensions); return(texture);
 }
Пример #31
0
        public ShaderResourceView ToTexture3D(Device graphicsDevice, Format format)
        {
            int sizeInBytes = sizeof(float) * width * height * depth;

            DataStream stream = new DataStream(sizeInBytes, true, true);
            for (int x = 0; x < width; x++)
                for (int y = 0; y < height; y++)
                    for (int z = 0; z < depth; z++)
                        stream.Write(values[x, y, z]);
            stream.Position = 0;

            DataBox dataBox = new DataBox(sizeof(float) * width, sizeof(float) * width * height, stream);
            Texture3DDescription description = new Texture3DDescription()
            {
                BindFlags = BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                Depth = depth,
                Format = format,
                Height = height,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                Usage = ResourceUsage.Default,
                Width = width
            };
            Texture3D texture = new Texture3D(graphicsDevice, description, dataBox);

            stream.Dispose();

            return new ShaderResourceView(graphicsDevice, texture);
        }
Пример #32
0
    /// <summary>
    ///
    /// </summary>
    void LoadNoise3dTexture()
    {
        // basic dds loader for 3d texture - !not very robust!

        TextAsset data = Resources.Load("NoiseVolume") as TextAsset;

        byte[] bytes = data.bytes;

        uint height      = BitConverter.ToUInt32(data.bytes, 12);
        uint width       = BitConverter.ToUInt32(data.bytes, 16);
        uint pitch       = BitConverter.ToUInt32(data.bytes, 20);
        uint depth       = BitConverter.ToUInt32(data.bytes, 24);
        uint formatFlags = BitConverter.ToUInt32(data.bytes, 20 * 4);
        uint fourCC      = BitConverter.ToUInt32(data.bytes, 21 * 4);
        uint bitdepth    = BitConverter.ToUInt32(data.bytes, 22 * 4);

        if (bitdepth == 0)
        {
            bitdepth = pitch / width * 8;
        }


        // doesn't work with TextureFormat.Alpha8 for some reason
        _noiseTexture      = new Texture3D((int)width, (int)height, (int)depth, TextureFormat.RGBA32, false);
        _noiseTexture.name = "3D Noise";

        Color[] c = new Color[width * height * depth];

        uint index = 128;

        if (data.bytes[21 * 4] == 'D' && data.bytes[21 * 4 + 1] == 'X' && data.bytes[21 * 4 + 2] == '1' && data.bytes[21 * 4 + 3] == '0' &&
            (formatFlags & 0x4) != 0)
        {
            uint format = BitConverter.ToUInt32(data.bytes, (int)index);
            if (format >= 60 && format <= 65)
            {
                bitdepth = 8;
            }
            else if (format >= 48 && format <= 52)
            {
                bitdepth = 16;
            }
            else if (format >= 27 && format <= 32)
            {
                bitdepth = 32;
            }

            //Debug.Log("DXGI format: " + format);
            // dx10 format, skip dx10 header
            //Debug.Log("DX10 format");
            index += 20;
        }

        uint byteDepth = bitdepth / 8;

        pitch = (width * bitdepth + 7) / 8;

        for (int d = 0; d < depth; ++d)
        {
            //index = 128;
            for (int h = 0; h < height; ++h)
            {
                for (int w = 0; w < width; ++w)
                {
                    float v = (bytes[index + w * byteDepth] / 255.0f);
                    c[w + h * width + d * width * height] = new Color(v, v, v, v);
                }

                index += pitch;
            }
        }

        _noiseTexture.SetPixels(c);
        _noiseTexture.Apply();
    }
Пример #33
0
 public void SetTexture(TextureResourceType type, Texture texture)
 {
     textureType = type;
     switch (textureType)
     {
         case TextureResourceType.Texture3D:
             texture3D = (Texture3D)texture;
             break;
         case TextureResourceType.TextureCube:
             textureCube = (TextureCube)texture;
             break;
         default:
             texture2D = (Texture2D)texture;
             break;
     }
 }
Пример #34
0
        public override void OnImportAsset(UnityEditor.AssetImporters.AssetImportContext ctx)
        {
            byte[] bytes = File.ReadAllBytes(ctx.assetPath);
            int    width = 1, height = 1, depth = 1;

            try
            {
                int    channels = 0;
                string fourcc   = Encoding.UTF8.GetString(SubArray <byte>(bytes, 0, 4));

                if (fourcc != "VF_F" && fourcc != "VF_V")
                {
                    throw new Exception("Invalid VF File Header. Need VF_F or VF_V, found :" + fourcc);
                }
                else
                {
                    if (fourcc == "VF_F")
                    {
                        channels = 1;
                    }
                    if (fourcc == "VF_V")
                    {
                        channels = 3;
                    }
                }

                TextureFormat outFormat = TextureFormat.Alpha8;
                switch (m_OutputFormat)
                {
                case VectorFieldOutputFormat.Byte: outFormat = channels == 3 ? TextureFormat.RGBA32 : TextureFormat.Alpha8; break;

                case VectorFieldOutputFormat.Half: outFormat = channels == 3 ? TextureFormat.RGBAHalf : TextureFormat.RHalf; break;

                case VectorFieldOutputFormat.Float: outFormat = channels == 3 ? TextureFormat.RGBAFloat : TextureFormat.RFloat; break;
                }

                if (bytes.Length < 10)
                {
                    throw new Exception("Malformed VF File, invalid header (less than 10 bytes)");
                }

                width  = BitConverter.ToUInt16(bytes, 4);
                height = BitConverter.ToUInt16(bytes, 6);
                depth  = BitConverter.ToUInt16(bytes, 8);

                int requiredLength = 10 + (4 * channels * (width * height * depth));

                if (bytes.Length != requiredLength)
                {
                    throw new Exception("Malformed VF File, invalid length (expected :" + requiredLength + ", found :" + bytes.Length + ")");
                }

                Texture3D texture = new Texture3D(width, height, depth, outFormat, m_GenerateMipMaps);
                texture.wrapMode   = m_WrapMode;
                texture.filterMode = m_FilterMode;
                texture.anisoLevel = m_AnisoLevel;

                int count = width * height * depth;

                Color[] colors = new Color[count];

                for (int i = 0; i < count; i++)
                {
                    Color c;
                    if (channels == 1)
                    {
                        float x = BitConverter.ToSingle(bytes, 10 + (i * 4 * channels));
                        c = new Color(x, 0, 0);
                    }
                    else
                    {
                        float x = BitConverter.ToSingle(bytes, 10 + (i * 4 * channels));
                        float y = BitConverter.ToSingle(bytes, 14 + (i * 4 * channels));
                        float z = BitConverter.ToSingle(bytes, 18 + (i * 4 * channels));
                        c = new Color(x, y, z);
                    }
                    colors[i] = c;
                }

                texture.SetPixels(colors);
                texture.Apply(true, true);
                ctx.AddObjectToAsset("VectorField", texture);
                ctx.SetMainObject(texture);
            }
            catch (System.Exception e)
            {
                Debug.LogException(e);
            }
        }
Пример #35
0
        /// <summary>
        /// Save current settings to default settings
        /// </summary>
        public void SaveCurrentToDefault()
        {
            defaultIsProceduralSkybox    = isProceduralSkybox;
            defaultShowSettings          = showSettings;
            defaultSkyboxExposure        = skyboxExposure;
            defaultSkyboxGroundIntensity = skyboxGroundIntensity;
            defaultSkyboxRotation        = skyboxRotation;
            defaultSkyboxPitch           = skyboxPitch;
            defaultSkyboxTint            = skyboxTint;
            defaultCustomSkybox          = customSkybox;
            defaultSunColor                = sunColor;
            defaultShadowDistance          = shadowDistance;
            defaultShadowType              = shadowType;
            defaultFogColor                = fogColor;
            defaultFogDistance             = fogDistance;
            defaultFogDensity              = fogDensity;
            defaultSunIntensity            = sunIntensity;
            defaultLWRPSunIntensity        = LWRPSunIntensity;
            defaultHDRPSunIntensity        = HDRPSunIntensity;
            defaultShadowStrength          = shadowStrength;
            defaultIndirectLightMultiplier = indirectLightMultiplier;
            defaultSunRotation             = sunRotation;
            defaultTemperature             = temperature;
            defaultUseTempature            = useTempature;

            defaultScaleHorizonObjectWithFog = scaleHorizonObjectWithFog;
            defaultHorizonSkyEnabled         = horizonSkyEnabled;
            defaultHorizonBlend      = horizonBlend;
            defaultHorizonFalloff    = horizonFalloff;
            defaultHorizonFogDensity = horizonFogDensity;
            defaultHorizonScattering = horizonScattering;
            defaultNearFogDistance   = nearFogDistance;
            defaultHorizonSize       = horizonSize;
            defaultFollowPlayer      = followPlayer;
            defaultHorizonPosition   = horizonPosition;
            defaultHorizonUpdateTime = horizonUpdateTime;
            defaultAmbientMode       = ambientMode;
            defaultSkyColor          = skyColor;
            defaultEquatorColor      = equatorColor;
            defaultGroundColor       = groundColor;
            defaultLWRPSkyColor      = lwrpSkyColor;
            defaultLWRPEquatorColor  = lwrpEquatorColor;
            defaultLWRPGroundColor   = lwrpGroundColor;
            defaultHDRISkybox        = hDRISkybox;
            defaultShadowQuality     = shadowQuality;
            defaultShadowmaskMode    = shadowmaskMode;
            defaultShadowQuality     = shadowQuality;
            defaultShadowResolution  = shadowResolution;
            defaultShadowProjection  = shadowProjection;
            defaultCascadeCount      = cascadeCount;
            defaultEnableSunDisk     = enableSunDisk;
            defaultSkyMultiplier     = skyMultiplier;

            defaultHDRPFogDistance = hDRPFogDistance;
            defaultIsGlobal        = isGlobal;
            defaultBlendDistance   = blendDistance;
            defaultWeight          = weight;
            defaultPriority        = priority;
            defaultFogType         = fogType;

            defaultHDRIExposure         = hDRIExposure;
            defaultHDRIMultiplier       = hDRIMultiplier;
            defaultHDRIUpdateMode       = hDRIUpdateMode;
            defaultHDRIRotation         = hDRIRotation;
            defaultMaxShadowDistance    = maxShadowDistance;
            defaultCascadeSplit1        = cascadeSplit1;
            defaultCascadeSplit2        = cascadeSplit2;
            defaultCascadeSplit3        = cascadeSplit3;
            defaultUseContactShadows    = useContactShadows;
            defaultContactShadowsLength = contactShadowsLength;
            defaultContactShadowsDistanceScaleFactor = contactShadowsDistanceScaleFactor;
            defaultContactShadowsMaxDistance         = contactShadowsMaxDistance;
            defaultContactShadowsFadeDistance        = contactShadowsFadeDistance;
            defaultContactShadowsSampleCount         = contactShadowsSampleCount;
            defaultContactShadowsOpacity             = contactShadowsOpacity;

            defaultUseMicroShadowing  = useMicroShadowing;
            defaultMicroShadowOpacity = microShadowOpacity;

            defaultVolumetricSingleScatteringAlbedo = volumetricSingleScatteringAlbedo;
            defaultVolumetricBaseFogDistance        = volumetricBaseFogDistance;
            defaultVolumetricBaseFogHeight          = volumetricBaseFogHeight;
            defaultVolumetricMeanHeight             = volumetricMeanHeight;
            defaultVolumetricGlobalAnisotropy       = volumetricGlobalAnisotropy;
            defaultVolumetricGlobalLightProbeDimmer = volumetricGlobalLightProbeDimmer;
            defaultVolumetricMaxFogDistance         = volumetricMaxFogDistance;
            defaultVolumetricEnableDistanceFog      = volumetricEnableDistanceFog;

            defaultVolumetricConstFogColor      = volumetricConstFogColor;
            defaultVolumetricMipFogNear         = volumetricMipFogNear;
            defaultVolumetricMipFogFar          = volumetricMipFogFar;
            defaultVolumetricMipFogMaxMip       = volumetricMipFogMaxMip;
            defaultExponentialFogDensity        = exponentialFogDensity;
            defaultExponentialBaseHeight        = exponentialBaseHeight;
            defaultExponentialHeightAttenuation = exponentialHeightAttenuation;
            defaultExponentialMaxFogDistance    = exponentialMaxFogDistance;
            defaultExponentialMipFogNear        = exponentialMipFogNear;
            defaultExponentialMipFogFar         = exponentialMipFogFar;
            defaultExponentialMipFogMaxMip      = exponentialMipFogMaxMip;
            defaultLinearFogDensity             = linearFogDensity;
            defaultLinearHeightStart            = linearHeightStart;
            defaultLinearHeightEnd         = linearHeightEnd;
            defaultLinearMaxFogDistance    = linearMaxFogDistance;
            defaultLinearMipFogNear        = linearMipFogNear;
            defaultLinearMipFogFar         = linearMipFogFar;
            defaultLinearMipFogMaxMip      = linearMipFogMaxMip;
            defaultVolumetricDistanceRange = volumetricDistanceRange;
            defaultVolumetricSliceDistributionUniformity = volumetricSliceDistributionUniformity;
            defaultIndirectDiffuseIntensity     = indirectDiffuseIntensity;
            defaultIndirectSpecularIntensity    = indirectSpecularIntensity;
            defaultEnableScreenSpaceReflections = enableScreenSpaceReflections;
            defaultScreenEdgeFadeDistance       = screenEdgeFadeDistance;
            defaultMaxNumberOfRaySteps          = maxNumberOfRaySteps;
            defaultObjectThickness              = objectThickness;
            defaultMinSmoothness                = minSmoothness;
            defaultSmoothnessFadeStart          = smoothnessFadeStart;
            defaultReflectSky                   = reflectSky;
            defaultEnableScreenSpaceRefractions = enableScreenSpaceRefractions;
            defaultScreenWeightDistance         = screenWeightDistance;
            defaultUseBakingSky                 = useBakingSky;
            defaultUseFogDensityVolume          = useFogDensityVolume;
            defaultSingleScatteringAlbedo       = singleScatteringAlbedo;
            defaultDensityVolumeFogDistance     = densityVolumeFogDistance;
            defaultFogDensityMaskTexture        = fogDensityMaskTexture;
            defaultDensityMaskTiling            = densityMaskTiling;
            defaultDensityScale                 = densityScale;
#if HDPipeline
#if UNITY_2018_3_OR_NEWER
            defaultVolumeProfile          = volumeProfile;
            defaultFogColorMode           = fogColorMode;
            defaultHDRISkyIntensityMode   = hDRISkyIntensityMode;
            defaultVolumetricFogColorMode = volumetricFogColorMode;
#endif
#endif
        }
Пример #36
0
    public void EnsureSetup()
    {
        if (this.mRenderer == null)
        {
            this.mRenderer = this.GetComponent <MeshRenderer> ();
        }

        if (this.IsSlowerPlatform())
        {
            this.mRenderer.enabled = false;
            return;
        }

        if (this.VolumeTexture != null)
        {
            return;
        }

        var coreSize = DefaultVoxelWidth;         //64; //32 // 16
        var cc       = this.gameObject.GetComponentInParent <ChakraControl>();

        if (cc != null)
        {
            coreSize = cc.VoxelResolution;
        }

        this.VolumeSize = new Cubic <int> (coreSize, coreSize, coreSize);
        Texture3D tex = new Texture3D(
            coreSize, coreSize, coreSize,
            TextureFormat.ARGB32, true);

        this.VolumeTexture = tex;

        var numColors = coreSize * coreSize * coreSize;
        var colors    = new Color[numColors];

        for (int i = 0; i < numColors; i++)
        {
            //var ix = (i % coreSize);
            //var iy = ((i / coreSize) % coreSize);
            //var iz = ((i / (coreSize * coreSize)) % coreSize);

            var c = Color.black;             // (((ix + iz) < iy) ? Color.grey : Color.blue);

            colors[i] = c;
        }
        colors[0] = Color.red;
        colors [(coreSize * coreSize) * 1] = Color.red;
        colors [(coreSize * coreSize) * 2] = Color.red;
        colors [(coreSize * coreSize) * 3] = Color.red;
        colors[numColors - 1] = Color.green;

        tex.SetPixels(colors);
        //tex.filterMode = FilterMode.Point;
        tex.filterMode = FilterMode.Trilinear;
        tex.wrapMode   = TextureWrapMode.Clamp;
        tex.Apply();

        this.mMaterial = this.GetComponent <Renderer> ().material;
        this.mMaterial.SetTexture("_MainVol", tex);


        Texture2D tex2 = new Texture2D(coreSize, coreSize);

        tex2.SetPixels(colors);
        tex2.Apply();


        //this.GetComponent<Renderer> ().material.SetTexture ("_MainTex", tex2);
    }
Пример #37
0
        /// <summary>
        /// Open a dds from file.
        /// (Supported formats : Dxt1,Dxt2,Dxt3,Dxt4,Dxt5,A8R8G8B8/Color,X8R8G8B8,R8G8B8,A4R4G4B4,A1R5G5B5,R5G6B5,A8,
        /// FP32/Single,FP16/HalfSingle,FP32x4/Vector4,FP16x4/HalfVector4,CxV8U8/NormalizedByte2/CxVU,Q8VW8V8U8/NormalizedByte4/8888QWVU
        /// ,HalfVector2/G16R16F/16.16fGR,Vector2/G32R32F,G16R16/RG32/1616GB,B8G8R8,X8B8G8R8,A8B8G8R8/Color,L8,A2B10G10R10/Rgba1010102,A16B16G16R16/Rgba64)
        /// </summary>
        /// <param name="fileName">File containing the data.</param>
        /// <param name="device">Graphic device where you want the texture to be loaded.</param>
        /// <param name="texture">The reference to the loaded texture.</param>
        /// <param name="streamOffset">Offset in the stream to where the DDS is located.</param>
        /// <param name="loadMipMap">If true it will load the mip-map chain for this texture.</param>
        public static void DDSFromFile(string fileName, GraphicsDevice device, bool loadMipMap, out Texture3D texture)
        {
            Stream stream = File.OpenRead(fileName);
            Texture tex;
            InternalDDSFromStream(stream, device, 0, loadMipMap, out tex);
            stream.Close();

            texture = tex as Texture3D;
            if (texture == null)
            {
                throw new Exception("The data in the stream contains a Texture2D not TextureCube");
            }
        }
Пример #38
0
 public Texture3D GetDataTexture()
 {
     dataTexture = CreateTextureInternal();
     return(dataTexture);
 }
Пример #39
0
        //new 3d-map texture
        private static Texture3D GenerateNewTexture3D(LoadSurfaceFormat loadSurfaceFormat, FourCC compressionFormat, GraphicsDevice device, int width, int height, int depth, bool hasMipMaps, uint pixelFlags, int rgbBitCount)
        {
            SurfaceFormat surfaceFormat = SurfaceFormatFromLoadFormat(loadSurfaceFormat, compressionFormat, pixelFlags, rgbBitCount);

            Texture3D tx = new Texture3D(device, width, height, depth, hasMipMaps, surfaceFormat);

            if (tx.Format != surfaceFormat)
            {
                throw new Exception("Can't generate a " + surfaceFormat.ToString() + " surface.");
            }

            return tx;
        }
Пример #40
0
 public Texture3D GetGradientTexture()
 {
     gradientTexture = CreateGradientTextureInternal();
     return(gradientTexture);
 }
Пример #41
0
 public void SetTexture3D(FramebufferAttachment attachment, int miplevel, int zOffset, Texture3D texture)
 {
     GL.BindFramebuffer(FramebufferType.Framebuffer, framebuffer);
     GL.FramebufferTexture3D(FramebufferType.Framebuffer, attachment, TextureTarget.Texture3D, texture == null ? 0 : texture.Handle, miplevel, zOffset);
     SetTextureAttachment(attachment, texture);
 }
        // Basic CUBE lut parser
        // Specs: http://wwwimages.adobe.com/content/dam/Adobe/en/products/speedgrade/cc/pdfs/cube-lut-specification-1.0.pdf
        private static void ImportCubeLut(string path)
        {
            // Remove the 'Assets' part of the path & build absolute path
            var fullpath = path.Substring(7);

            fullpath = Path.Combine(Application.dataPath, fullpath);

            // Read the lut data
            var lines = File.ReadAllLines(fullpath);

            // Start parsing
            var i         = 0;
            var size      = -1;
            var sizeCube  = -1;
            var table     = new List <Color>();
            var domainMin = Color.black;
            var domainMax = Color.white;

            while (true)
            {
                if (i >= lines.Length)
                {
                    if (table.Count != sizeCube)
                    {
                        Debug.LogError("Premature end of file");
                    }

                    break;
                }

                var line = FilterLine(lines[i]);

                if (string.IsNullOrEmpty(line))
                {
                    goto next;
                }

                // Header data
                if (line.StartsWith("TITLE"))
                {
                    goto next; // Skip the title tag, we don't need it
                }
                if (line.StartsWith("LUT_3D_SIZE"))
                {
                    var sizeStr = line.Substring(11).TrimStart();

                    if (!int.TryParse(sizeStr, out size))
                    {
                        Debug.LogError("Invalid data on line " + i);
                        break;
                    }

                    if (size < 2 || size > 256)
                    {
                        Debug.LogError("LUT size out of range");
                        break;
                    }

                    sizeCube = size * size * size;
                    goto next;
                }

                if (line.StartsWith("DOMAIN_MIN"))
                {
                    if (!ParseDomain(i, line, ref domainMin))
                    {
                        break;
                    }
                    goto next;
                }

                if (line.StartsWith("DOMAIN_MAX"))
                {
                    if (!ParseDomain(i, line, ref domainMax))
                    {
                        break;
                    }
                    goto next;
                }

                // Table
                var row = line.Split();

                if (row.Length != 3)
                {
                    Debug.LogError("Invalid data on line " + i);
                    break;
                }

                var color = Color.black;
                for (var j = 0; j < 3; j++)
                {
                    float d;
                    if (!float.TryParse(row[j], out d))
                    {
                        Debug.LogError("Invalid data on line " + i);
                        break;
                    }

                    color[j] = d;
                }

                table.Add(color);

next:
                i++;
            }

            if (sizeCube != table.Count)
            {
                Debug.LogError("Wrong table size - Expected " + sizeCube + " elements, got " + table.Count);
                return;
            }

            // Check if the Texture3D already exists, update it in this case (better workflow for
            // the user)
            var assetPath = Path.ChangeExtension(path, ".asset");
            var tex       = AssetDatabase.LoadAssetAtPath <Texture3D>(assetPath);

            if (tex != null)
            {
                tex.SetPixels(table.ToArray(), 0);
                tex.Apply();
            }
            else
            {
                // Generate a new Texture3D
                tex = new Texture3D(size, size, size, TextureFormat.RGBAHalf, false)
                {
                    anisoLevel = 0,
                    filterMode = FilterMode.Bilinear,
                    wrapMode   = TextureWrapMode.Clamp
                };

                tex.SetPixels(table.ToArray(), 0);
                tex.Apply();

                // Save to disk
                AssetDatabase.CreateAsset(tex, assetPath);
            }

            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }
Пример #43
0
 void DoneUpdatingColormap()
 {
     isUpdatingColormap = false;
     colormap           = calculator.colormap;
     Apply();
 }
    private Texture3D ComputeSDF()
    {
        // Create the voxel texture and get an array of pixels from it.
        Texture3D voxels = new Texture3D(m_resolution, m_resolution, m_resolution, TextureFormat.RGBAHalf, false);

        voxels.anisoLevel = 1;
        voxels.filterMode = FilterMode.Bilinear;
        voxels.wrapMode   = TextureWrapMode.Clamp;
        Color[]       pixelArray  = voxels.GetPixels(0);
        ComputeBuffer pixelBuffer = new ComputeBuffer(pixelArray.Length, sizeof(float) * 4);

        pixelBuffer.SetData(pixelArray);

        // Create the triangle array and buffer from the mesh.
        Vector3[]  meshVertices  = m_mesh.vertices;
        int[]      meshTriangles = m_mesh.GetTriangles(m_submeshIndex);
        Triangle[] triangleArray = new Triangle[meshTriangles.Length / 3];
        for (int t = 0; t < triangleArray.Length; t++)
        {
            triangleArray[t].a = meshVertices[meshTriangles[3 * t + 0]] - m_mesh.bounds.center;
            triangleArray[t].b = meshVertices[meshTriangles[3 * t + 1]] - m_mesh.bounds.center;
            triangleArray[t].c = meshVertices[meshTriangles[3 * t + 2]] - m_mesh.bounds.center;
        }
        ComputeBuffer triangleBuffer = new ComputeBuffer(triangleArray.Length, sizeof(float) * 3 * 3);

        triangleBuffer.SetData(triangleArray);

        // Instantiate the compute shader from resources.
        ComputeShader compute = (ComputeShader)Instantiate(Resources.Load("SDFCompute"));
        int           kernel  = compute.FindKernel("CSMain");

        // Upload the pixel buffer to the GPU.
        compute.SetBuffer(kernel, "pixelBuffer", pixelBuffer);
        compute.SetInt("pixelBufferSize", pixelArray.Length);

        // Upload the triangle buffer to the GPU.
        compute.SetBuffer(kernel, "triangleBuffer", triangleBuffer);
        compute.SetInt("triangleBufferSize", triangleArray.Length);

        // Calculate and upload the other necessary parameters.
        float maxMeshSize         = Mathf.Max(Mathf.Max(m_mesh.bounds.size.x, m_mesh.bounds.size.y), m_mesh.bounds.size.z);
        float totalUnitsInTexture = maxMeshSize + 2.0f * m_padding;

        compute.SetInt("textureSize", m_resolution);
        compute.SetFloat("totalUnitsInTexture", totalUnitsInTexture);
        compute.SetInt("useIntersectionCounter", (m_signComputationMethod == SignComputationMethod.IntersectionCounter) ? 1 : 0);

        // Compute the SDF.
        compute.Dispatch(kernel, pixelArray.Length / 256 + 1, 1, 1);

        // Destroy the compute shader and release the triangle buffer.
        DestroyImmediate(compute);
        triangleBuffer.Release();

        // Retrieve the pixel buffer and reapply it to the voxels texture.
        pixelBuffer.GetData(pixelArray);
        pixelBuffer.Release();
        voxels.SetPixels(pixelArray, 0);
        voxels.Apply();

        // Return the voxels texture.
        return(voxels);
    }
Пример #45
0
 void CopyDensityTextureData(ref byte[] byteField, Texture3D texture)
 {
     //In the lines below, we copy the texture data into the density field buffer
     if (GFX.Inst.ByteSurfaceDataType == GFXTextureDataType.BYTE)
         texture.SetData<byte>(byteField);
     else
     {
         int elementCount = texture.Width * texture.Height * texture.Depth;
         switch (GFX.Inst.ByteSurfaceDataType)
         {
             case GFXTextureDataType.COLOR:
                 Color[] colorData = new Color[elementCount];
                 srcTarget.GetTexture().GetData<Color>(colorData);
                 for (int i = 0; i < colorData.Length; i++)
                 {
                     colorData[i].R = byteField[i];
                     colorData[i].G = byteField[i];
                     colorData[i].B = byteField[i];
                     colorData[i].A = byteField[i];
                 }
                 texture.SetData<Color>(colorData);
                 break;
             case GFXTextureDataType.HALFSINGLE:
                 HalfSingle[] hsingData = new HalfSingle[elementCount];
                 for (int i = 0; i < hsingData.Length; i++)
                     hsingData[i] = new HalfSingle((float)byteField[i] / 255.0f);
                 texture.SetData<HalfSingle>(hsingData);
                 break;
             case GFXTextureDataType.SINGLE:
                 float[] singData = new float[elementCount];
                 for (int i = 0; i < singData.Length; i++)
                     singData[i] = (float)byteField[i] / 255.0f;
                 texture.SetData<float>(singData);
                 break;
         }
     }
 }
Пример #46
0
    void ApplySymmetry(ref Texture3D texture, SymmetryDirection3D direction, SymmetryOutcome3D symmetryOutcome)
    {
        var halfwayPoint = texture.width / 2;
        var lowDominant  = symmetryOutcome.lowerIsDominant;

        for (var x = 0; x < texture.height; x++)
        {
            for (var z = 0; z < texture.depth; z++)
            {
                for (var y = 0; y < texture.width; y++)
                {
                    switch (direction)
                    {
                    //case SymmetryDirection.Horizontal:
                    //    referenceValue = symmetryOutcome.quarterHorizontalSymmetryResult ? columnIndex : rowIndex;
                    //    if ((symmetryOutcome.lowerIsDominant && referenceValue >= halfwayPoint - 1) ||
                    //        (!symmetryOutcome.lowerIsDominant && referenceValue <= halfwayPoint + 1))
                    //        SetSymmetricalVoxel(texture, direction, columnIndex, rowIndex, depthIndex, halfwayPoint);
                    //    break;
                    //case SymmetryDirection.Vertical:
                    //    referenceValue = symmetryOutcome.quarterVerticalSymmetryResult ? rowIndex : columnIndex;
                    //    if ((symmetryOutcome.lowerIsDominant && referenceValue >= halfwayPoint - 1) ||
                    //        (!symmetryOutcome.lowerIsDominant && referenceValue <= halfwayPoint + 1))
                    //        SetSymmetricalVoxel(texture, direction, columnIndex, rowIndex, depthIndex, halfwayPoint);
                    //    break;
                    //case SymmetryDirection.ForwardDiagonal:
                    //    if (symmetryOutcome.quarterForwardDiagonalSymmetryResult) {
                    //        if (symmetryOutcome.lowerIsDominant && columnIndex > rowIndex ||
                    //            !symmetryOutcome.lowerIsDominant && columnIndex < rowIndex)
                    //            texture.SetPixel(columnIndex, rowIndex, depthIndex,
                    //                texture.GetPixel(
                    //                    texture.width - rowIndex,
                    //                    texture.width - columnIndex,
                    //                    texture.depth - depthIndex));
                    //    } else {
                    //        if (symmetryOutcome.lowerIsDominant && rowIndex < texture.width - columnIndex ||
                    //            !symmetryOutcome.lowerIsDominant && rowIndex > texture.width - columnIndex)
                    //            texture.SetPixel(columnIndex, rowIndex, depthIndex,
                    //                texture.GetPixel(
                    //                    texture.width - rowIndex,
                    //                    texture.width - columnIndex,
                    //                    texture.depth - depthIndex));
                    //    }
                    //
                    //    break;
                    //case SymmetryDirection.BackwardDiagonal:
                    //    if (symmetryOutcome.quarterBackwardDiagonalSymmetryResult) {
                    //        if (symmetryOutcome.lowerIsDominant && rowIndex < texture.width - columnIndex ||
                    //            !symmetryOutcome.lowerIsDominant && rowIndex > texture.width - columnIndex)
                    //            texture.SetPixel(columnIndex, rowIndex, depthIndex,
                    //                texture.GetPixel(rowIndex, columnIndex, depthIndex));
                    //    } else if (symmetryOutcome.lowerIsDominant && columnIndex > rowIndex ||
                    //               !symmetryOutcome.lowerIsDominant && columnIndex < rowIndex)
                    //        texture.SetPixel(columnIndex, rowIndex, depthIndex,
                    //            texture.GetPixel(rowIndex, columnIndex, depthIndex));
//
                    //    break;
                    case SymmetryDirection3D.TopLeftToBottomRight:
                        if (x < y)  //(lowDominant && x < y || !lowDominant && x > y)
                        {
                            SetSymmetricalVoxel(texture, direction, y, x, z, halfwayPoint);
                        }
                        break;

                    case SymmetryDirection3D.FrontBottomToTopBack:
                        break;

                    case SymmetryDirection3D.BottomLeftToTopRight:
                        if (lowDominant && x > y || !lowDominant && x < y)
                        {
                            SetSymmetricalVoxel(texture, direction, y, x, z, halfwayPoint);
                        }
                        break;

                    case SymmetryDirection3D.FrontTopToBottomBack:
                        break;

                    case SymmetryDirection3D.FrontRightToBackLeft:
                        break;

                    case SymmetryDirection3D.FrontLeftToBackRight:
                        break;

                    case SymmetryDirection3D.FrontCenterToBackCenterVertical:
                        if (lowDominant && y > halfwayPoint || !lowDominant && y < halfwayPoint)
                        {
                            SetSymmetricalVoxel(texture, direction, y, x, z, halfwayPoint);
                        }
                        break;

                    case SymmetryDirection3D.FrontCenterToBackCenterHorizontal:
                        if (lowDominant && x > halfwayPoint || !lowDominant && x < halfwayPoint)
                        {
                            SetSymmetricalVoxel(texture, direction, y, x, z, halfwayPoint);
                        }
                        break;

                    case SymmetryDirection3D.MiddleTopToMiddleBottomVertical:
                        if (lowDominant && z > halfwayPoint || !lowDominant && z < halfwayPoint)
                        {
                            SetSymmetricalVoxel(texture, direction, y, x, z, halfwayPoint);
                        }
                        break;

                    default:
                        throw new ArgumentOutOfRangeException(nameof(direction), direction, null);
                    }
                }
            }
        }
    }
Пример #47
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);
        }
Пример #48
0
 public void Allocate_Uninitialized_Fail(Device device, Type textureType, int width, int height, int depth)
 {
     using Texture3D <float> texture = device.Get().AllocateTexture3D <float>(textureType, width, height, depth);
 }
Пример #49
0
        public XnaHardwarePixelBuffer( BufferUsage usage )
            : base( 0, 0, 0, PixelFormat.Unknown, usage, false, false )
        {
            device = null;
            surface = null;
            tempSurface = null;
#if !SILVERLIGHT
            volume = null;
            tempVolume = null;
#endif
            doMipmapGen = false;
            HWMipmaps = false;
            mipTex = null;
            sliceTRT = new List<RenderTexture>();
        }
 public DataBox MapSubresource(Texture3D resource, int mipSlice, int arraySlice, MapMode mode, MapFlags flags, out DataStream stream)
 {
     return(deviceContext.MapSubresource(resource, mipSlice, arraySlice, mode, flags, out stream));
 }
Пример #51
0
 public void SetColorGradeTexture(Texture3D colourGradeTexture)
 {
     _ColorGradeTexture = colourGradeTexture;
 }
  public Texture3D Generate() {
    if (mesh == null) {
      throw new System.ArgumentException("Mesh must have been assigned");
    }

    // Create the voxel texture.
    Texture3D voxels = new Texture3D(resolution, resolution, resolution, TextureFormat.RGBAHalf, false);
    voxels.anisoLevel = 1;
    voxels.filterMode = FilterMode.Bilinear;
    voxels.wrapMode = TextureWrapMode.Clamp;

    // Get an array of pixels from the voxel texture, create a buffer to
    // hold them, and upload the pixels to the buffer.
    Color[] pixelArray = voxels.GetPixels(0);
    ComputeBuffer pixelBuffer = new ComputeBuffer(pixelArray.Length, sizeof(float) * 4);
    pixelBuffer.SetData(pixelArray);

    // Get an array of triangles from the mesh.
    Vector3[] meshVertices = mesh.vertices;
    int[] meshTriangles = mesh.GetTriangles(subMeshIndex);
    Triangle[] triangleArray = new Triangle[meshTriangles.Length / 3];
    for (int t = 0; t < triangleArray.Length; t++) {
        triangleArray[t].a = meshVertices[meshTriangles[3 * t + 0]];  // - mesh.bounds.center;
        triangleArray[t].b = meshVertices[meshTriangles[3 * t + 1]];  // - mesh.bounds.center;
        triangleArray[t].c = meshVertices[meshTriangles[3 * t + 2]];  // - mesh.bounds.center;
    }

    // Create a buffer to hold the triangles, and upload them to the buffer.
    ComputeBuffer triangleBuffer = new ComputeBuffer(triangleArray.Length, sizeof(float) * 3 * 3);
    triangleBuffer.SetData(triangleArray);

    // Instantiate the compute shader from resources.
    ComputeShader compute = Instantiate(Resources.Load("GenerateSDF")) as ComputeShader;
    int kernel = compute.FindKernel("CSMain");

    // Upload the pixel buffer to the GPU.
    compute.SetBuffer(kernel, "pixelBuffer", pixelBuffer);
    compute.SetInt("pixelBufferSize", pixelArray.Length);

    // Upload the triangle buffer to the GPU.
    compute.SetBuffer(kernel, "triangleBuffer", triangleBuffer);
    compute.SetInt("triangleBufferSize", triangleArray.Length);

    // Calculate and upload the other necessary parameters.
    compute.SetInt("textureSize", resolution);
    Vector3 minExtents = Vector3.zero;
    Vector3 maxExtents = Vector3.zero;
    foreach (Vector3 v in mesh.vertices) {
      for (int i = 0; i < 3; i++) {
        minExtents[i] = Mathf.Min(minExtents[i], v[i]);
        maxExtents[i] = Mathf.Max(maxExtents[i], v[i]);
      }
    }
    compute.SetVector("minExtents", minExtents - Vector3.one*padding);
    compute.SetVector("maxExtents", maxExtents + Vector3.one*padding);

    // Compute the SDF.
    compute.Dispatch(kernel, pixelArray.Length / 256 + 1, 1, 1);

    // Destroy the compute shader and release the triangle buffer.
    DestroyImmediate(compute);
    triangleBuffer.Release();

    // Retrieve the pixel buffer and reapply it to the voxels texture.
    pixelBuffer.GetData(pixelArray);
    pixelBuffer.Release();
    voxels.SetPixels(pixelArray, 0);
    voxels.Apply();

    // Return the voxel texture.
    return voxels;
  }
Пример #53
0
 private void DestroyColorGrade()
 {
     _ColorGradeTexture = null;
 }
Пример #54
0
    void OnEnable()
    {
        // debug information, check if the stride we set corresponds with actual struct size
        int size = System.Runtime.InteropServices.Marshal.SizeOf(typeof(VolumeData));

        Debug.Log("Struct size check: " + (size == VolumeDataStride ? "Pass" : "Fail"));

        // get all objects that have a SDFBaker component:
        SDFBaker[] bakers = GameObject.FindObjectsOfType <SDFBaker>() as SDFBaker[];

        texCollection     = new List <Texture3D>();
        gameObjCollection = new List <GameObject>();
        gameObjectStatus  = new List <bool>();
        volumeData        = new List <VolumeData>();

        foreach (SDFBaker v in bakers)
        {
            // store reference to game objects that have SDF data
            GameObject obj = v.gameObject;
            // set transformation changed flag as true to trigger texture update
            obj.transform.hasChanged = true;
            gameObjectStatus.Add(obj.activeSelf);
            gameObjCollection.Add(obj);

            // prepare transform data of objects for passing to shaders
            VolumeData vd = new VolumeData();
            vd.WorldToLocal = obj.transform.worldToLocalMatrix;
            vd.Extents      = v.sdfData.bounds.extents;
            vd.Center       = v.sdfData.bounds.center;
            //Debug.Log(obj.name + " " + vd.Center + " " + vd.Extents);
            //Debug.Log(obj.name + "\n" + vd.WorldToLocal);

            // if there are multiple objects sharing the same SDF texture,
            // only save one copy in the texture atlas, and assign the index to per-object data
            Texture3D tex    = v.sdfData.sdfTexture;
            int       tempId = texCollection.FindIndex(x => x.name == tex.name);
            if (tempId < 0)
            {
                vd.TextureIndex = texCollection.Count;
                texCollection.Add(tex);
            }
            else
            {
                vd.TextureIndex = tempId;
            }

            //Debug.Log(obj.name + " texIdx: " + vd.TextureIndex);
            volumeData.Add(vd);
        }

        // copy the listed volume transform data to the computer buffer,
        // Shader.setBuffer() or _material.setBuffer() would copy the buffer to GPU side
        volumeDataBuffer = new ComputeBuffer(volumeData.Count, VolumeDataStride);
        volumeDataBuffer.SetData(volumeData);

        // the texture atlas is of same with & height with local SDF's,
        // while its depth is (#SDF * depth), hence it's not cubed and doesn't support LOD operations
        textureAtlas = new Texture3D(DistanceFieldDepth, DistanceFieldDepth, DistanceFieldDepth * texCollection.Count, TextureFormat.RHalf, false);
        Debug.Log("Atlas Depth: " + textureAtlas.depth);

        if (SystemInfo.copyTextureSupport == CopyTextureSupport.Copy3D)
        {
            Debug.Log("Don't support Copy3d");
        }
        else
        {
            Debug.Log("Support copy 3d");
        }

        // f**k this
        // should be replaced by a computer shader later
        for (int i = 0; i < texCollection.Count; i++)
        {
            for (int d = 0; d < texCollection[i].depth; d++)
            {
                for (int y = 0; y < texCollection[i].height; y++)
                {
                    for (int x = 0; x < texCollection[i].width; x++)
                    {
                        int depth = i * DistanceFieldDepth + d;
                        textureAtlas.SetPixel(x, y, depth, texCollection[i].GetPixel(x, y, d, 0));
                    }
                }
                // doesnot work
                //Graphics.CopyTexture(texCollection[i], d, 0, textureAtlas, i * DistanceFieldDepth + d, 0);
            }
        }
        // Important: This function does the actual CPU->GPU copy
        textureAtlas.Apply();

        // Global shader properties never change through rendering
        Shader.SetGlobalVector("_BlitScaleBiasRt", new Vector4(1f, 1f, 0f, 0f));
        Shader.SetGlobalVector("_BlitScaleBias", new Vector4(1f, 1f, 0f, 0f));
        // in case there isn't new texture genereation at run time
        Shader.SetGlobalTexture("_TextureAtlas", textureAtlas);

        // initialize global SDF texture
        globalDistanceFieldTexture.Initialize();
        Shader.SetGlobalTexture("_GlobalDFTex", globalDistanceFieldTexture);
    }
Пример #55
0
        private void InitializeFromImpl(DataBox[] dataBoxes = null)
        {
            if (ParentTexture != null)
            {
                NativeDeviceChild = ParentTexture.NativeDeviceChild;
            }

            if (NativeDeviceChild == null)
            {
                switch (Dimension)
                {
                    case TextureDimension.Texture1D:
                        NativeDeviceChild = new Texture1D(GraphicsDevice.NativeDevice, ConvertToNativeDescription1D(), ConvertDataBoxes(dataBoxes));
                        break;
                    case TextureDimension.Texture2D:
                    case TextureDimension.TextureCube:
                        NativeDeviceChild = new Texture2D(GraphicsDevice.NativeDevice, ConvertToNativeDescription2D(), ConvertDataBoxes(dataBoxes));
                        break;
                    case TextureDimension.Texture3D:
                        NativeDeviceChild = new Texture3D(GraphicsDevice.NativeDevice, ConvertToNativeDescription3D(), ConvertDataBoxes(dataBoxes));
                        break;
                }
            }

            NativeShaderResourceView = GetShaderResourceView(ViewType, ArraySlice, MipLevel);
            NativeUnorderedAccessView = GetUnorderedAccessView(ViewType, ArraySlice, MipLevel);
            NativeRenderTargetView = GetRenderTargetView(ViewType, ArraySlice, MipLevel);
            NativeDepthStencilView = GetDepthStencilView(out HasStencil);
        }
    public void Convert(Texture2D temp2DTex)
    {
        if (temp2DTex)
        {
            int dim = temp2DTex.width * temp2DTex.height;
            dim = temp2DTex.height;

            if (!ValidDimensions(temp2DTex))
            {
                Debug.LogWarning("The given 2D texture " + temp2DTex.name + " cannot be used as a 3D LUT.");

                return;
            }
            // if (temp2DTex.GetPixel(5, 5) == null) { Debug.Log("bug"); return; }

            #if UNITY_EDITOR
            if (Application.isPlaying != true)
            {
                string path = AssetDatabase.GetAssetPath(LutTexture);
                MemoPath = path;
                TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
                if (!textureImporter.isReadable)
                {
                    /*
                     * bool doImport = textureImporter.isReadable == false;
                     * if (textureImporter.mipmapEnabled == true)
                     * {
                     * doImport = true;
                     * }
                     * if (textureImporter.textureCompression != TextureImporterCompression.Uncompressed)
                     * {
                     * doImport = true;
                     * }*/
                    textureImporter.isReadable         = true;
                    textureImporter.mipmapEnabled      = false;
                    textureImporter.textureCompression = TextureImporterCompression.Uncompressed;
                    AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
                }
            }
            #endif

            var c    = temp2DTex.GetPixels();
            var newC = new Color[c.Length];

            for (int i = 0; i < dim; i++)
            {
                for (int j = 0; j < dim; j++)
                {
                    for (int k = 0; k < dim; k++)
                    {
                        int j_ = dim - j - 1;
                        newC[i + (j * dim) + (k * dim * dim)] = c[k * dim + i + j_ * dim * dim];
                    }
                }
            }


            if (converted3DLut)
            {
                DestroyImmediate(converted3DLut);
            }
            converted3DLut = new Texture3D(dim, dim, dim, TextureFormat.ARGB32, false);
            converted3DLut.SetPixels(newC);
            converted3DLut.Apply();
        }
        else
        {
            SetIdentityLut();
        }
    }
Пример #57
0
 void LoadTextureFromFile(string filename)
 {
     switch (textureType)
     {
         case TextureResourceType.Texture3D:
             texture3D = Texture3D.FromFile(GFX.Device, filename);
             break;
         case TextureResourceType.TextureCube:
             textureCube = TextureCube.FromFile(GFX.Device, filename);
             break;
         default:
             texture2D = Texture2D.FromFile(GFX.Device, filename);
             break;
     }
 }
Пример #58
0
        protected static void GenerateNoiseTexture(int resolution, int period)
        {
            // Set up Texture3D for noise sampling
            noiseTexture = new Texture3D(graphicsDevice,
                resolution, resolution, resolution,
                false, SurfaceFormat.Color);

            // Fill a Resolution^3 array with values generated using smooth noise
            // Uses smooth noise instead of pure random numbers because linear filtering
            // on random values doesn't provide a smooth or consistent enough gradient
            Color[] noise = new Color[(int)Math.Pow(resolution, 3)];
            int index = 0;
            // how many often does the pattern "cycle" over the texture?
            float inverseFrequency = (float)period / resolution;

            for (int i = 0; i < resolution; i++)
                for (int j = 0; j < resolution; j++)
                    for (int k = 0; k < resolution; k++)
                    {
                        float x = i * inverseFrequency;
                        float y = j * inverseFrequency;
                        float z = k * inverseFrequency;

                        // sample different tiling noise domains for each color channel
                        noise[index].R = SampleNoise(x, y, z, period, 0);
                        noise[index].G = SampleNoise(x, y, z, period, 50);

                        index++;
                    }

            noiseTexture.SetData<Color>(noise);
        }
Пример #59
0
 static public VFXValue <Texture> Constant(Texture3D value)
 {
     return(new VFXTexture3DValue(value, Mode.Constant));
 }
Пример #60
0
        /// <summary>
        /// Revert current settings back to default settings
        /// </summary>
        public void RevertToDefault()
        {
            isProceduralSkybox      = defaultIsProceduralSkybox;
            showSettings            = defaultShowSettings;
            fogColor                = defaultFogColor;
            skyboxExposure          = defaultSkyboxExposure;
            skyboxGroundIntensity   = defaultSkyboxGroundIntensity;
            skyboxRotation          = defaultSkyboxRotation;
            skyboxPitch             = defaultSkyboxPitch;
            skyboxTint              = defaultSkyboxTint;
            customSkybox            = defaultCustomSkybox;
            shadowStrength          = defaultShadowStrength;
            indirectLightMultiplier = defaultIndirectLightMultiplier;
            sunColor                = defaultSunColor;
            shadowDistance          = defaultShadowDistance;
            shadowType              = defaultShadowType;
            fogDistance             = defaultFogDistance;
            fogDensity              = defaultFogDensity;
            sunIntensity            = defaultSunIntensity;
            LWRPSunIntensity        = defaultLWRPSunIntensity;
            HDRPSunIntensity        = defaultHDRPSunIntensity;
            sunRotation             = defaultSunRotation;
            temperature             = defaultTemperature;
            useTempature            = defaultUseTempature;

            scaleHorizonObjectWithFog = defaultScaleHorizonObjectWithFog;
            horizonSkyEnabled         = defaultHorizonSkyEnabled;
            horizonBlend      = defaultHorizonBlend;
            horizonFalloff    = defaultHorizonFalloff;
            horizonFogDensity = defaultHorizonFogDensity;
            horizonScattering = defaultHorizonScattering;
            nearFogDistance   = defaultNearFogDistance;
            horizonSize       = defaultHorizonSize;
            followPlayer      = defaultFollowPlayer;
            horizonPosition   = defaultHorizonPosition;
            horizonUpdateTime = defaultHorizonUpdateTime;
            ambientMode       = defaultAmbientMode;
            skyColor          = defaultSkyColor;
            equatorColor      = defaultEquatorColor;
            groundColor       = defaultGroundColor;
            lwrpSkyColor      = defaultLWRPSkyColor;
            lwrpEquatorColor  = defaultLWRPEquatorColor;
            lwrpGroundColor   = defaultLWRPGroundColor;
            hDRISkybox        = defaultHDRISkybox;
            shadowQuality     = defaultShadowQuality;
            shadowmaskMode    = defaultShadowmaskMode;
            shadowResolution  = defaultShadowResolution;
            shadowProjection  = defaultShadowProjection;
            cascadeCount      = defaultCascadeCount;
            enableSunDisk     = defaultEnableSunDisk;
            skyMultiplier     = defaultSkyMultiplier;
            hDRPFogDistance   = defaultHDRPFogDistance;

            isGlobal      = defaultIsGlobal;
            blendDistance = defaultBlendDistance;
            weight        = defaultWeight;
            priority      = defaultPriority;

            hDRIExposure         = defaultHDRIExposure;
            hDRIMultiplier       = defaultHDRIMultiplier;
            hDRIUpdateMode       = defaultHDRIUpdateMode;
            hDRIRotation         = defaultHDRIRotation;
            maxShadowDistance    = defaultMaxShadowDistance;
            cascadeSplit1        = defaultCascadeSplit1;
            cascadeSplit2        = defaultCascadeSplit2;
            cascadeSplit3        = defaultCascadeSplit3;
            useContactShadows    = defaultUseContactShadows;
            contactShadowsLength = defaultContactShadowsLength;
            contactShadowsDistanceScaleFactor = defaultContactShadowsDistanceScaleFactor;
            contactShadowsMaxDistance         = defaultContactShadowsMaxDistance;
            contactShadowsFadeDistance        = defaultContactShadowsFadeDistance;
            contactShadowsSampleCount         = defaultContactShadowsSampleCount;
            contactShadowsOpacity             = defaultContactShadowsOpacity;

            useMicroShadowing  = defaultUseMicroShadowing;
            microShadowOpacity = defaultMicroShadowOpacity;

            volumetricSingleScatteringAlbedo = defaultVolumetricSingleScatteringAlbedo;
            volumetricBaseFogDistance        = defaultVolumetricBaseFogDistance;
            volumetricBaseFogHeight          = defaultVolumetricBaseFogHeight;
            volumetricMeanHeight             = defaultVolumetricMeanHeight;
            volumetricGlobalAnisotropy       = defaultVolumetricGlobalAnisotropy;
            volumetricGlobalLightProbeDimmer = defaultVolumetricGlobalLightProbeDimmer;
            volumetricMaxFogDistance         = defaultVolumetricMaxFogDistance;

            volumetricEnableDistanceFog = defaultVolumetricEnableDistanceFog;

            volumetricConstFogColor = defaultVolumetricConstFogColor;
            volumetricMipFogNear    = defaultVolumetricMipFogNear;
            volumetricMipFogFar     = defaultVolumetricMipFogFar;
            volumetricMipFogMaxMip  = defaultVolumetricMipFogMaxMip;
            volumetricDistanceRange = defaultVolumetricDistanceRange;
            volumetricSliceDistributionUniformity = defaultVolumetricSliceDistributionUniformity;
            exponentialBaseHeight        = defaultExponentialBaseHeight;
            exponentialHeightAttenuation = defaultExponentialHeightAttenuation;
            exponentialMaxFogDistance    = defaultExponentialMaxFogDistance;
            exponentialMipFogNear        = defaultExponentialMipFogNear;
            exponentialMipFogFar         = defaultExponentialMipFogFar;
            exponentialMipFogMaxMip      = defaultExponentialMipFogMaxMip;
            linearHeightStart            = defaultLinearHeightStart;
            linearHeightEnd              = defaultLinearHeightEnd;
            linearMaxFogDistance         = defaultLinearMaxFogDistance;
            linearMipFogNear             = defaultLinearMipFogNear;
            linearMipFogFar              = defaultLinearMipFogFar;
            linearMipFogMaxMip           = defaultLinearMipFogMaxMip;
            indirectDiffuseIntensity     = defaultIndirectDiffuseIntensity;
            indirectSpecularIntensity    = defaultIndirectSpecularIntensity;
            enableScreenSpaceReflections = defaultEnableScreenSpaceReflections;
            screenEdgeFadeDistance       = defaultScreenEdgeFadeDistance;
            maxNumberOfRaySteps          = defaultMaxNumberOfRaySteps;
            objectThickness              = defaultObjectThickness;
            minSmoothness                = defaultMinSmoothness;
            smoothnessFadeStart          = defaultSmoothnessFadeStart;
            reflectSky                   = defaultReflectSky;
            enableScreenSpaceRefractions = defaultEnableScreenSpaceRefractions;
            screenWeightDistance         = defaultScreenWeightDistance;
            useBakingSky                 = defaultUseBakingSky;
            useFogDensityVolume          = defaultUseFogDensityVolume;
            singleScatteringAlbedo       = defaultSingleScatteringAlbedo;
            densityVolumeFogDistance     = defaultDensityVolumeFogDistance;
            fogDensityMaskTexture        = defaultFogDensityMaskTexture;
            densityMaskTiling            = defaultDensityMaskTiling;
            densityScale                 = defaultDensityScale;
            linearFogDensity             = defaultLinearFogDensity;
            exponentialFogDensity        = defaultExponentialFogDensity;
            fogType = defaultFogType;

#if HDPipeline
#if UNITY_2018_3_OR_NEWER
            volumeProfile          = defaultVolumeProfile;
            volumetricFogColorMode = defaultVolumetricFogColorMode;
            fogColorMode           = defaultFogColorMode;
            hDRISkyIntensityMode   = defaultHDRISkyIntensityMode;
#endif
#endif
        }