Esempio n. 1
0
 public static Vector4F Generate(Vector4F minValue, Vector4F maxValue)
 {
     lock (_static)
         return(new Vector4F(
                    _static.Next(minValue.X, maxValue.X),
                    _static.Next(minValue.Y, maxValue.Y),
                    _static.Next(minValue.Z, maxValue.Z),
                    _static.Next(minValue.W, maxValue.W)));
 }
Esempio n. 2
0
        //

        public OgreMatrix4(float xx, float xy, float xz, float xw,
                           float yx, float yy, float yz, float yw,
                           float zx, float zy, float zz, float zw,
                           float wx, float wy, float wz, float ww)
        {
            mat0 = new Vector4F(xx, xy, xz, xw);
            mat1 = new Vector4F(yx, yy, yz, yw);
            mat2 = new Vector4F(zx, zy, zz, zw);
            mat3 = new Vector4F(wx, wy, wz, ww);
        }
Esempio n. 3
0
        public static Vector4F[] ToVector4FArray(this Vector4[] source)
        {
            var result = new Vector4F[source.Length];

            for (int n = 0; n < source.Length; n++)
            {
                result[n] = source[n].ToVector4F();
            }
            return(result);
        }
Esempio n. 4
0
        /// <summary>
        /// Performs a linear interpolation between two vectors based on the given weighting.
        /// </summary>
        /// <param name="v1">The first vector.</param>
        /// <param name="v2">The second vector.</param>
        /// <param name="amount">A value between 0 and 1 that indicates the weight of <paramref name="v2"/>.</param>
        /// <returns>The interpolated vector.</returns>
        public static Vector4F Lerp(Vector4F v1, Vector4F v2, float amount)
        {
            Vector4F result;

            result.X = v1.X + ((v2.X - v1.X) * amount);
            result.Y = v1.Y + ((v2.Y - v1.Y) * amount);
            result.Z = v1.Z + ((v2.Z - v1.Z) * amount);
            result.W = v1.W + ((v2.W - v1.W) * amount);
            return(result);
        }
Esempio n. 5
0
        ///////////////////////////////////////////

        /// <summary>
        /// The constructor of the vertex.
        /// </summary>
        /// <param name="position">The position of the vertex.</param>
        /// <param name="normal">The normal of the vertex.</param>
        /// <param name="tangent">The tangent vector of the vertex.</param>
        /// <param name="color">The color of the vertex.</param>
        /// <param name="texCoord0">The texture coordinate 0 of the vertex.</param>
        /// <param name="texCoord1">The texture coordinate 1 of the vertex.</param>
        /// <param name="texCoord2">The texture coordinate 2 of the vertex.</param>
        /// <param name="texCoord3">The texture coordinate 3 of the vertex.</param>
        public StandardVertex(Vector3F position, Vector3F normal, Vector4F tangent, ColorValue color, Vector2F texCoord0, Vector2F texCoord1, Vector2F texCoord2, Vector2F texCoord3, Vector4I blendIndices, Vector4F blendWeights)
        {
            this.Position     = position;
            this.Normal       = normal;
            this.Tangent      = Vector4F.Zero;
            this.Color        = color;
            this.TexCoord0    = texCoord0;
            this.TexCoord1    = texCoord1;
            this.TexCoord2    = texCoord2;
            this.TexCoord3    = texCoord3;
            this.BlendIndices = blendIndices;
            this.BlendWeights = blendWeights;
        }
Esempio n. 6
0
 /// <summary>
 /// The constructor of the vertex.
 /// </summary>
 /// <param name="position">The position of the vertex.</param>
 public StandardVertex(Vector3F position)
 {
     this.Position     = position;
     this.Normal       = Vector3F.Zero;
     this.Tangent      = Vector4F.Zero;
     this.Color        = new ColorValue(1, 1, 1, 1);
     this.TexCoord0    = Vector2F.Zero;
     this.TexCoord1    = Vector2F.Zero;
     this.TexCoord2    = Vector2F.Zero;
     this.TexCoord3    = Vector2F.Zero;
     this.BlendIndices = Vector4I.Zero;
     this.BlendWeights = Vector4F.Zero;
 }
Esempio n. 7
0
            public unsafe void SetPixel(Vector2I position, Vector4F value)
            {
                if (position.X < 0 || position.X >= size.X || position.Y < 0 || position.Y >= size.Y)
                {
                    return;

                    fixed(byte *pData = data)
                    {
                        switch (format)
                        {
                        case PixelFormat.Float32RGBA:
                        {
                            var p = (Vector4F *)pData + position.Y * size.X + position.X;
                            p->X = value.X;
                            p->Y = value.Y;
                            p->Z = value.Z;
                            p->W = value.W;
                        }
                        break;

                        case PixelFormat.Float32RGB:
                        {
                            var p = (Vector3F *)pData + position.Y * size.X + position.X;
                            p->X = value.X;
                            p->Y = value.Y;
                            p->Z = value.Z;
                        }
                        break;

                        case PixelFormat.A8R8G8B8:
                        {
                            var p = pData + (position.Y * size.X + position.X) * 4;
                            p[3] = (byte)MathEx.Clamp((int)(value.W * 255.0), 0, 255);
                            p[2] = (byte)MathEx.Clamp((int)(value.X * 255.0), 0, 255);
                            p[1] = (byte)MathEx.Clamp((int)(value.Y * 255.0), 0, 255);
                            p[0] = (byte)MathEx.Clamp((int)(value.Z * 255.0), 0, 255);
                        }
                        break;

                        default:
                            throw new Exception($"ImageUtility: SetPixel: Format \"{format}\" is not supported.");
                            //Log.Fatal( "ImageUtility: SetPixel: Format is not supported." );
                            //break;
                        }
                    }
            }
Esempio n. 8
0
        public unsafe void SetUniform(Uniform uniform, ParameterType type, int arraySize, IntPtr valueData)
        {
            //int1, vec4, mat3, mat4
            var uniformType = GetUniformTypeByParameterType(type);

            //var uniform = GpuProgramManager.RegisterUniform( name, uniformType, arraySize );

            switch (uniformType)
            {
            //case UniformType.Sampler:
            //Log.Fatal( "ViewportRenderingContext: SetUniform: UniformType.Int1 impl." );
            //break;

            case UniformType.Vector4:
            {
                int sizeInBytes = ParameterTypeUtility.GetElementSizeInBytes(type);
                if (sizeInBytes == 16)
                {
                    Bgfx.SetUniform(uniform, valueData, arraySize);
                }
                else if (sizeInBytes < 16)
                {
                    if (arraySize != 1)
                    {
                        Log.Fatal("ViewportRenderingContext: SetUniform: Arrays with type \'{0}\' are not supported. Only Vec4, Mat3, Mat4 arrays are supported.", type);
                    }

                    Vector4F value = Vector4F.Zero;
                    Buffer.MemoryCopy((void *)valueData, &value, sizeInBytes, sizeInBytes);
                    Bgfx.SetUniform(uniform, &value, 1);
                }
                else
                {
                    Log.Fatal("ViewportRenderingContext: SetUniform: The type \'{0}\' is not supported.", type);
                }
            }
            break;

            case UniformType.Matrix3x3:
            case UniformType.Matrix4x4:
                Bgfx.SetUniform(uniform, valueData, arraySize);
                break;
            }
        }
Esempio n. 9
0
        public ColorValuePowered(Vector4F source)
        {
            float p = 1;

            if (source.X > 1 && source.X > p)
            {
                p = source.X;
            }
            if (source.Y > 1 && source.Y > p)
            {
                p = source.Y;
            }
            if (source.Z > 1 && source.Z > p)
            {
                p = source.Z;
            }
            Color = new ColorValue(source.X / p, source.Y / p, source.Z / p, source.W);
            Power = p;
        }
Esempio n. 10
0
 /// <summary>
 /// Determines whether the specified vector is equal to the current instance of <see cref="Vector4F"/> with a given precision.
 /// </summary>
 /// <param name="v">The vector to compare.</param>
 /// <param name="epsilon">The precision value.</param>
 /// <returns>True if the specified vector is equal to the current instance of <see cref="Vector4F"/>; False otherwise.</returns>
 public bool Equals(ref Vector4F v, float epsilon)
 {
     if (Math.Abs(X - v.X) > epsilon)
     {
         return(false);
     }
     if (Math.Abs(Y - v.Y) > epsilon)
     {
         return(false);
     }
     if (Math.Abs(Z - v.Z) > epsilon)
     {
         return(false);
     }
     if (Math.Abs(W - v.W) > epsilon)
     {
         return(false);
     }
     return(true);
 }
Esempio n. 11
0
            //

            public Item(RectangleF uv)
            {
                UV         = uv;
                EngineTime = Time.Current;

                var vertexStructure = StandardVertex.MakeStructure(StandardVertex.Components.StaticOneTexCoord, true, out int vertexSize);

                var positions = new Vector3F[] { new Vector3F(-0.5f, -0.5f, 0), new Vector3F(0.5f, -0.5f, 0), new Vector3F(0.5f, 0.5f, 0), new Vector3F(-0.5f, 0.5f, 0) };
                var texCoords = new Vector2F[] { uv.LeftTop, uv.RightTop, uv.RightBottom, uv.LeftBottom };

                var vertices = new byte[vertexSize * positions.Length];

                unsafe
                {
                    fixed(byte *pVertices = vertices)
                    {
                        StandardVertex.StaticOneTexCoord *pVertex = (StandardVertex.StaticOneTexCoord *)pVertices;

                        for (int n = 0; n < positions.Length; n++)
                        {
                            pVertex->Position  = positions[n];
                            pVertex->Normal    = new Vector3F(0, 0, 1);
                            pVertex->Tangent   = new Vector4F(1, 0, 0, -1);
                            pVertex->Color     = new ColorValue(1, 1, 1, 1);
                            pVertex->TexCoord0 = texCoords[n];

                            pVertex++;
                        }
                    }
                }

                var mesh     = ComponentUtility.CreateComponent <Component_Mesh>(null, true, false);
                var geometry = mesh.CreateComponent <Component_MeshGeometry>();

                geometry.VertexStructure = vertexStructure;
                geometry.Vertices        = vertices;
                geometry.Indices         = new int[] { 0, 1, 2, 2, 3, 0 };
                mesh.Enabled             = true;

                Mesh = mesh;
            }
Esempio n. 12
0
        void Clamp(Vector4F min, Vector4F max)
        {
            if (X < min.X)
            {
                X = min.X;
            }
            else if (X > max.X)
            {
                X = max.X;
            }

            if (Y < min.Y)
            {
                Y = min.Y;
            }
            else if (Y > max.Y)
            {
                Y = max.Y;
            }

            if (Z < min.Z)
            {
                Z = min.Z;
            }
            else if (Z > max.Z)
            {
                Z = max.Z;
            }

            if (W < min.W)
            {
                W = min.W;
            }
            else if (W > max.W)
            {
                W = max.W;
            }
        }
Esempio n. 13
0
        protected override void OnSetShaderParameters(ViewportRenderingContext context, Component_RenderingPipeline.IFrameData frameData, Component_Image actualTexture, CanvasRenderer.ShaderItem shader)
        {
            base.OnSetShaderParameters(context, frameData, actualTexture, shader);

            var noiseTexture = ResourceManager.LoadResource <Component_Image>(noiseTextureDefault);

            if (noiseTexture == null)
            {
                return;
            }

            GpuTexture gpuNoiseTexture = noiseTexture.Result;            // ResourceUtility.GetTextureCompiledData( noiseTexture );

            shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(1 /*"noiseTexture"*/,
                                                                               noiseTexture, TextureAddressingMode.Wrap, FilterOption.Point, FilterOption.Point, FilterOption.Point));
            //shader.Parameters.Set( "1"/*"noiseTexture"*/, new GpuMaterialPass.TextureParameterValue( noiseTexture,
            //	TextureAddressingMode.Wrap, FilterOption.Point, FilterOption.Point, FilterOption.Point ) );

            {
                var size = actualTexture.Result.ResultSize;
                shader.Parameters.Set("viewportSize", new Vector4(size.X, size.Y, 1.0 / (double)size.X, 1.0 / (double)size.Y).ToVector4F());
            }

            {
                var size = gpuNoiseTexture.ResultSize;
                shader.Parameters.Set("noiseTextureSize", new Vector4(size.X, size.Y, 1.0 / (double)size.X, 1.0 / (double)size.Y).ToVector4F());
            }

            bool r = SeedRandom;

            Vector4F seeds = Vector4F.Zero;

            if (r)
            {
                seeds = new Vector4F(random.NextFloat(), random.NextFloat(), random.NextFloat(), random.NextFloat());
            }
            shader.Parameters.Set("seeds", seeds);
        }
Esempio n. 14
0
            public unsafe void SetPixel(Vector2I position, Vector4F value)
            {
                if (position.X < 0 || position.X >= size.X || position.Y < 0 || position.Y >= size.Y)
                {
                    return;

                    fixed(byte *pData = data)
                    {
                        switch (format)
                        {
                        case PixelFormat.Float32RGB:
                            var p = (Vector3F *)pData + position.Y * size.X + position.X;
                            p->X = value.X;
                            p->Y = value.Y;
                            p->Z = value.Z;
                            break;

                        default:
                            throw new Exception($"ImageUtility: SetPixel: Format \"{format}\" is not supported.");
                            //Log.Fatal( "ImageUtility: SetPixel: Format is not supported." );
                            //break;
                        }
                    }
            }
Esempio n. 15
0
            public unsafe Vector4F GetPixel(Vector2I position)
            {
                if (position.X < 0 || position.X >= size.X || position.Y < 0 || position.Y >= size.Y)
                {
                    return(Vector4F.Zero);
                }

                Vector4F value = new Vector4F(1, 1, 1, 1);

                fixed(byte *pData = data)
                {
                    switch (format)
                    {
                    case PixelFormat.Float32RGBA:
                    {
                        var p = (Vector4F *)pData + position.Y * size.X + position.X;
                        value.X = p->X;
                        value.Y = p->Y;
                        value.Z = p->Z;
                        value.W = p->W;
                    }
                    break;

                    case PixelFormat.Float32RGB:
                    {
                        var p = (Vector3F *)pData + position.Y * size.X + position.X;
                        value.X = p->X;
                        value.Y = p->Y;
                        value.Z = p->Z;
                    }
                    break;

                    case PixelFormat.R8G8B8:
                    {
                        var p = pData + (position.Y * size.X + position.X) * 3;
                        value.X = (float)p[2] / 255.0f;
                        value.Y = (float)p[1] / 255.0f;
                        value.Z = (float)p[0] / 255.0f;
                    }
                    break;

                    //!!!!check

                    case PixelFormat.X8R8G8B8:
                    {
                        var p = pData + (position.Y * size.X + position.X) * 4;
                        value.X = (float)p[2] / 255.0f;
                        value.Y = (float)p[1] / 255.0f;
                        value.Z = (float)p[0] / 255.0f;
                    }
                    break;

                    case PixelFormat.A8R8G8B8:
                    {
                        var p = pData + (position.Y * size.X + position.X) * 4;
                        value.W = (float)p[3] / 255.0f;
                        value.X = (float)p[2] / 255.0f;
                        value.Y = (float)p[1] / 255.0f;
                        value.Z = (float)p[0] / 255.0f;
                    }
                    break;

                    case PixelFormat.L8:
                    {
                        var p = pData + (position.Y * size.X + position.X);
                        var v = (float)p[0] / 255.0f;
                        value.X = v;
                        value.Y = v;
                        value.Z = v;
                    }
                    break;

                    //!!!!

                    default:
                        throw new Exception($"ImageUtility: SetPixel: Format \"{format}\" is not supported.");
                        //Log.Fatal( "ImageUtility: SetPixel: Format is not supported." );
                        //break;
                    }
                }

                return(value);
            }
Esempio n. 16
0
 /// <summary>
 /// Returns the vector which contains e raised to the power of n, where n is the corresponding component in the specified vector.
 /// </summary>
 /// <param name="v">The specified vector.</param>
 /// <returns>The vector which contains e raised to the power of n, where n is the corresponding component in the specified vector.</returns>
 public static Vector4F Exp(Vector4F v)
 {
     return(new Vector4F(MathEx.Exp(v.X), MathEx.Exp(v.Y), MathEx.Exp(v.Z), MathEx.Exp(v.W)));
 }
Esempio n. 17
0
 /// <summary>
 /// Calculates the base 10 logarithm of each component of the specified vector.
 /// </summary>
 /// <param name="v">The specified vector.</param>
 /// <returns>The vector which contains the base 10 logarithms of the corresponding components in the specified vector.</returns>
 public static Vector4F Log10(Vector4F v)
 {
     return(new Vector4F(MathEx.Log10(v.X), MathEx.Log10(v.Y), MathEx.Log10(v.Z), MathEx.Log10(v.W)));
 }
Esempio n. 18
0
        unsafe protected override void OnRender(ViewportRenderingContext context, Component_RenderingPipeline.IFrameData frameData, ref Component_Image actualTexture)
        {
            base.OnRender(context, frameData, ref actualTexture);

            //is not supported
            if (!context.RenderingPipeline.GetUseMultiRenderTargets())
            {
                return;
            }

            //downscale for SSAA
            var actualTextureSource = actualTexture;

            if (actualTexture.Result.ResultSize != context.Owner.SizeInPixels)
            {
                actualTexture = context.RenderTarget2D_Alloc(context.Owner.SizeInPixels, actualTextureSource.Result.ResultFormat);

                //copy to scene texture with downscale
                context.SetViewport(actualTexture.Result.GetRenderTarget().Viewports[0]);

                CanvasRenderer.ShaderItem shader = new CanvasRenderer.ShaderItem();
                shader.VertexProgramFileName   = @"Base\Shaders\EffectsCommon_vs.sc";
                shader.FragmentProgramFileName = @"Base\Shaders\Effects\Downscale2_fs.sc";

                shader.Parameters.Set("sourceSizeInv", new Vector2F(1, 1) / actualTextureSource.Result.ResultSize.ToVector2F());

                shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(0 /*"sourceTexture"*/,
                                                                                   actualTextureSource, TextureAddressingMode.Clamp, FilterOption.Linear, FilterOption.Linear, FilterOption.None));

                context.RenderQuadToCurrentViewport(shader);
            }

            // Setup Constants:

            Vector2F viewportPixelSize        = new Vector2F(1.0f / (float)actualTexture.Result.ResultSize.X, 1.0f / (float)actualTexture.Result.ResultSize.Y);
            Vector2F halfViewportPixelSize    = new Vector2F(1.0f / ((float)actualTexture.Result.ResultSize.X * 0.5f), 1.0f / ((float)actualTexture.Result.ResultSize.Y * 0.5f));
            Vector4F quarterViewportPixelSize = new Vector4F(1.0f / ((float)actualTexture.Result.ResultSize.X * 0.25f), 1.0f / ((float)actualTexture.Result.ResultSize.Y * 0.25f), (float)((actualTexture.Result.ResultSize.X / 4) * (actualTexture.Result.ResultSize.Y / 4)), 0.0f);
            Vector2F viewport2xPixelSize      = new Vector2F(viewportPixelSize.X * 2.0f, viewportPixelSize.Y * 2.0f);

            Matrix4F projectionMatrix = context.Owner.CameraSettings.ProjectionMatrix.ToMatrix4F();

            float depthLinearizeMul = -projectionMatrix[3][2];
            float depthLinearizeAdd = projectionMatrix[2][2];

            if (depthLinearizeMul * depthLinearizeAdd < 0.0f)
            {
                depthLinearizeAdd = -depthLinearizeAdd;
            }

            Vector2F depthUnpackConsts = new Vector2F(depthLinearizeMul, depthLinearizeAdd);

            float tanHalfFOVY = 1.0f / projectionMatrix[1][1];
            float tanHalfFOVX = 1.0F / projectionMatrix[0][0];

            Vector2F cameraTanHalfFOV = new Vector2F(tanHalfFOVX, tanHalfFOVY);

            Vector2F NDCToViewMul = new Vector2F(cameraTanHalfFOV.X * 2.0f, cameraTanHalfFOV.Y * -2.0f);
            Vector2F NDCToViewAdd = new Vector2F(cameraTanHalfFOV.X * -1.0f, cameraTanHalfFOV.Y * 1.0f);

            Matrix4F itViewMatrix = (context.Owner.CameraSettings.ViewMatrix.GetInverse().ToMatrix4F()).GetTranspose();

            // Effect Params:

            float effectSamplingRadiusNearLimit = (float)Radius * 1.2f;

            if (Quality.Value == QualityEnum.Low)
            {
                effectSamplingRadiusNearLimit *= 1.50f;
            }

            effectSamplingRadiusNearLimit /= tanHalfFOVY;

            float effectSamplingRadiusNearLimitRec = 1.0f / effectSamplingRadiusNearLimit;

            Vector4F effectRadiusParams = new Vector4F((float)Radius, -1.0f / (float)Radius, effectSamplingRadiusNearLimitRec, 0.0f);

            float effectFadeOutMul = -1.0f / ((float)FadeOutTo - (float)FadeOutFrom);
            float effectFadeOutAdd = (float)FadeOutFrom / ((float)FadeOutTo - (float)FadeOutFrom) + 1.0f;

            float detailAOStrength     = (float)DetailStrength;
            float effectShadowStrength = (float)Multiplier;
            float effectShadowClamp    = 1.0f;
            float effectShadowPow      = (float)Power;

            float invSharpness = 1.0f - (float)Sharpness;

            if (invSharpness < 0.0f)
            {
                invSharpness = 0.0f;
            }
            if (invSharpness > 1.0f)
            {
                invSharpness = 1.0f;
            }

            // First Pass: Prepare 4 Depth half-Buffers:

            Component_Image[] halfDepths = new Component_Image[4];
            for (int i = 0; i < 4; i++)
            {
                halfDepths[i] = context.RenderTarget2D_Alloc(actualTexture.Result.ResultSize / 2, PixelFormat.Float16R);
            }

            var fourDepthsMRT = context.MultiRenderTarget_Create(new[] {
                new MultiRenderTarget.Item(halfDepths[0]),
                new MultiRenderTarget.Item(halfDepths[1]),
                new MultiRenderTarget.Item(halfDepths[2]),
                new MultiRenderTarget.Item(halfDepths[3])
            });

            {
                context.SetViewport(fourDepthsMRT.Viewports[0], Matrix4F.Identity, Matrix4F.Identity, FrameBufferTypes.All, ColorValue.Zero);

                CanvasRenderer.ShaderItem shader = new CanvasRenderer.ShaderItem();
                shader.VertexProgramFileName   = @"Base\Shaders\EffectsCommon_vs.sc";
                shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\PrepareDepths_fs.sc";

                context.objectsDuringUpdate.namedTextures.TryGetValue("depthTexture", out Component_Image depthTexture);

                shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(0, depthTexture,
                                                                                   TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));

                shader.Parameters.Set("depthUnpackConsts", depthUnpackConsts);
                //!!!!use actualTextureSource size?
                shader.Parameters.Set("viewportPixelSize", viewportPixelSize);

                context.RenderQuadToCurrentViewport(shader);
            }

            // Second Pass: prepare 4 Mip-Maps for each Half-Depth-Map:

            Component_Image[,] depthMipMaps = null;

            if (Quality.Value > QualityEnum.Medium)
            {
                Vector2I[] mipMapSizes = new Vector2I[4];                   // Setup Mip-Map sizes:

                mipMapSizes[0] = new Vector2I(actualTexture.Result.ResultSize / 2);
                for (int m = 1; m < 4; m++)
                {
                    mipMapSizes[m] = new Vector2I(mipMapSizes[m - 1] / 2);
                }

                // Prepare MipMaps textures:

                depthMipMaps = new Component_Image[4, 4];

                for (int d = 0; d < 4; d++)
                {
                    depthMipMaps[d, 0] = halfDepths[d];                         // MipMaps 0 is original halfDepthMaps
                    for (int m = 1; m < 4; m++)
                    {
                        depthMipMaps[d, m] = context.RenderTarget2D_Alloc(mipMapSizes[m], PixelFormat.Float16R);
                    }
                }

                for (int m = 1; m < 4; m++)                  // Mip-Maps loop
                {
                    var fourDepthsMipsMRT = context.MultiRenderTarget_Create(new[] {
                        new MultiRenderTarget.Item(depthMipMaps[0, m]),
                        new MultiRenderTarget.Item(depthMipMaps[1, m]),
                        new MultiRenderTarget.Item(depthMipMaps[2, m]),
                        new MultiRenderTarget.Item(depthMipMaps[3, m])
                    });

                    context.SetViewport(fourDepthsMipsMRT.Viewports[0], Matrix4F.Identity, Matrix4F.Identity, FrameBufferTypes.All, ColorValue.Zero);

                    CanvasRenderer.ShaderItem shader = new CanvasRenderer.ShaderItem();
                    shader.VertexProgramFileName   = @"Base\Shaders\EffectsCommon_vs.sc";
                    shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\PrepareDepthMips_fs.sc";

                    // For current Mip-Map generation using previous Mip-Map:

                    float    prevMipLevel  = (float)(m - 1);
                    var      prevMipSize   = mipMapSizes[m - 1];
                    Vector4F prevMipParams = new Vector4F(1.0f / (float)prevMipSize.X, 1.0f / (float)prevMipSize.Y, prevMipLevel, 0.0f);

                    for (int i = 0; i < 4; i++)
                    {
                        // previous MipMap as input:
                        shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(i, depthMipMaps[i, m - 1],
                                                                                           TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));
                    }
                    shader.Parameters.Set("prevMipParams", prevMipParams);
                    shader.Parameters.Set("effectRadiusParams", effectRadiusParams);

                    context.RenderQuadToCurrentViewport(shader);
                }
            }

            Component_Image SSAOTextureArray = new Component_Image();

            Component_Image SSAOBaseTextureArray = null;

            if (Quality.Value == QualityEnum.HighestAdaptive)
            {
                SSAOBaseTextureArray = new Component_Image();
                SSAOBaseTextureArray = context.RenderTarget2D_Alloc(actualTexture.Result.ResultSize / 2, PixelFormat.R8G8_UInt, 0, false, /*0,*/ 4);
            }

            Component_Image importanceMap     = null;
            Component_Image averageImportance = null;

            // Generate Importance Map for Highest/Adaptive Quality mode:
            if (Quality.Value == QualityEnum.HighestAdaptive)
            {
                // 4 SSAO passes:

                for (int pass = 0; pass < 4; pass++)
                {
                    Vector4F[] patternRotScaleMatrices;
                    GeneratePatternRotScaleMatrices(pass, out patternRotScaleMatrices);

                    Vector2F perPassFullResCoordOffset = new Vector2F((float)(pass % 2), (float)(pass / 2));

                    {
                        context.SetViewport(SSAOBaseTextureArray.Result.GetRenderTarget(0, pass).Viewports[0],
                                            Matrix4F.Identity, Matrix4F.Identity, FrameBufferTypes.All, ColorValue.Zero);

                        CanvasRenderer.ShaderItem shader = new CanvasRenderer.ShaderItem();
                        shader.VertexProgramFileName   = @"Base\Shaders\EffectsCommon_vs.sc";
                        shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\GenerateSSAO_AdaptiveBase_fs.sc";

                        context.objectsDuringUpdate.namedTextures.TryGetValue("normalTexture", out Component_Image normalTexture);

                        for (int m = 0; m < 4; m++)
                        {
                            shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(m, depthMipMaps[pass, m],
                                                                                               TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));
                        }

                        shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(4, halfDepths[pass],
                                                                                           TextureAddressingMode.Mirror, FilterOption.Point, FilterOption.Point, FilterOption.None));

                        shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(5, normalTexture,
                                                                                           TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));

                        shader.Parameters.Set("NDCToViewMul", NDCToViewMul);
                        shader.Parameters.Set("NDCToViewAdd", NDCToViewAdd);
                        shader.Parameters.Set("effectRadiusParams", effectRadiusParams);
                        shader.Parameters.Set("viewportPixelSize", viewportPixelSize);
                        shader.Parameters.Set("viewport2xPixelSize", viewport2xPixelSize);
                        shader.Parameters.Set("halfViewportPixelSize", halfViewportPixelSize);
                        shader.Parameters.Set("perPassFullResCoordOffset", perPassFullResCoordOffset);
                        shader.Parameters.Set("patternRotScaleMatrices", patternRotScaleMatrices);
                        shader.Parameters.Set("effectFadeOutMul", effectFadeOutMul);
                        shader.Parameters.Set("effectFadeOutAdd", effectFadeOutAdd);
                        shader.Parameters.Set("effectShadowStrength", effectShadowStrength);
                        shader.Parameters.Set("effectShadowClamp", effectShadowClamp);
                        shader.Parameters.Set("effectShadowPow", effectShadowPow);
                        shader.Parameters.Set("detailAOStrength", detailAOStrength);
                        shader.Parameters.Set("itViewMatrix", itViewMatrix);

                        context.RenderQuadToCurrentViewport(shader);
                    }
                }

                // Importance Map Generation:
                importanceMap = context.RenderTarget2D_Alloc(actualTexture.Result.ResultSize / 4, PixelFormat.L8);
                {
                    context.SetViewport(importanceMap.Result.GetRenderTarget().Viewports[0],
                                        Matrix4F.Identity, Matrix4F.Identity, FrameBufferTypes.All, ColorValue.Zero);

                    CanvasRenderer.ShaderItem shader = new CanvasRenderer.ShaderItem();
                    shader.VertexProgramFileName   = @"Base\Shaders\EffectsCommon_vs.sc";
                    shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\GenerateImportanceMap_fs.sc";

                    shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(0, SSAOBaseTextureArray,
                                                                                       TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));

                    shader.Parameters.Set("halfViewportPixelSize", halfViewportPixelSize);
                    shader.Parameters.Set("effectShadowStrength", effectShadowStrength);
                    shader.Parameters.Set("effectShadowPow", effectShadowPow);

                    context.RenderQuadToCurrentViewport(shader);
                }

                // Importance Map Post-Process A:
                var importanceMapPong = context.RenderTarget2D_Alloc(actualTexture.Result.ResultSize / 4, PixelFormat.L8);
                {
                    context.SetViewport(importanceMapPong.Result.GetRenderTarget().Viewports[0],
                                        Matrix4F.Identity, Matrix4F.Identity, FrameBufferTypes.All, ColorValue.Zero);

                    CanvasRenderer.ShaderItem shader = new CanvasRenderer.ShaderItem();
                    shader.VertexProgramFileName   = @"Base\Shaders\EffectsCommon_vs.sc";
                    shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\PostProcessImportanceMapA_fs.sc";

                    shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(0, importanceMap,
                                                                                       TextureAddressingMode.Clamp, FilterOption.Linear, FilterOption.Linear, FilterOption.None));

                    shader.Parameters.Set("quarterViewportPixelSize", quarterViewportPixelSize);

                    context.RenderQuadToCurrentViewport(shader);
                }

                // Importance Map Post-Process B:
                {
                    context.SetViewport(importanceMap.Result.GetRenderTarget().Viewports[0],
                                        Matrix4F.Identity, Matrix4F.Identity, FrameBufferTypes.All, ColorValue.Zero);

                    CanvasRenderer.ShaderItem shader = new CanvasRenderer.ShaderItem();
                    shader.VertexProgramFileName   = @"Base\Shaders\EffectsCommon_vs.sc";
                    shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\PostProcessImportanceMapB_fs.sc";

                    shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(0, importanceMapPong,
                                                                                       TextureAddressingMode.Clamp, FilterOption.Linear, FilterOption.Linear, FilterOption.None));

                    shader.Parameters.Set("quarterViewportPixelSize", quarterViewportPixelSize);

                    context.RenderQuadToCurrentViewport(shader);
                }

                context.DynamicTexture_Free(importanceMapPong);

                // Get Average Importance Pass:
                averageImportance = context.RenderTarget2D_Alloc(new Vector2I(1, 1), PixelFormat.L8);
                {
                    context.SetViewport(averageImportance.Result.GetRenderTarget().Viewports[0],
                                        Matrix4F.Identity, Matrix4F.Identity, FrameBufferTypes.All, ColorValue.Zero);

                    CanvasRenderer.ShaderItem shader = new CanvasRenderer.ShaderItem();
                    shader.VertexProgramFileName   = @"Base\Shaders\EffectsCommon_vs.sc";
                    shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\GetAverageImportance_fs.sc";

                    shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(0, importanceMap,
                                                                                       TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));

                    shader.Parameters.Set("quarterViewportPixelSize", quarterViewportPixelSize);

                    context.RenderQuadToCurrentViewport(shader);
                }
            }

            // Third Pass: Generate 4 SSAO buffers:

            Component_Image blurPingTexture = null, blurPongTexture = null;

            if (BlurAmount.Value > 0)
            {
                blurPingTexture = context.RenderTarget2D_Alloc(actualTexture.Result.ResultSize / 2, PixelFormat.R8G8_UInt);
                blurPongTexture = context.RenderTarget2D_Alloc(actualTexture.Result.ResultSize / 2, PixelFormat.R8G8_UInt);
            }

            SSAOTextureArray = context.RenderTarget2D_Alloc(actualTexture.Result.ResultSize / 2, PixelFormat.R8G8_UInt, 0, false, /*0,*/ 4);

            for (int pass = 0; pass < 4; pass++)
            {
                Vector4F[] patternRotScaleMatrices;
                GeneratePatternRotScaleMatrices(pass, out patternRotScaleMatrices);

                Vector2F perPassFullResCoordOffset = new Vector2F((float)(pass % 2), (float)(pass / 2));

                {
                    if (BlurAmount.Value == 0)
                    {
                        context.SetViewport(SSAOTextureArray.Result.GetRenderTarget(0, pass).Viewports[0],
                                            Matrix4F.Identity, Matrix4F.Identity, FrameBufferTypes.All, ColorValue.Zero);
                    }
                    else
                    {
                        context.SetViewport(blurPingTexture.Result.GetRenderTarget().Viewports[0],
                                            Matrix4F.Identity, Matrix4F.Identity, FrameBufferTypes.All, ColorValue.Zero);
                    }

                    CanvasRenderer.ShaderItem shader = new CanvasRenderer.ShaderItem();
                    shader.VertexProgramFileName = @"Base\Shaders\EffectsCommon_vs.sc";

                    if (Quality.Value == QualityEnum.Low)
                    {
                        shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\GenerateSSAO_LQ_fs.sc";
                    }
                    else if (Quality.Value == QualityEnum.Medium)
                    {
                        shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\GenerateSSAO_MQ_fs.sc";
                    }
                    else if (Quality.Value == QualityEnum.High)
                    {
                        shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\GenerateSSAO_HQ_fs.sc";
                    }
                    else if (Quality.Value == QualityEnum.HighestAdaptive)
                    {
                        shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\GenerateSSAO_HAQ_fs.sc";
                    }

                    context.objectsDuringUpdate.namedTextures.TryGetValue("normalTexture", out Component_Image normalTexture);

                    if (Quality.Value > QualityEnum.Medium)
                    {
                        for (int m = 0; m < 4; m++)
                        {
                            shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(m, depthMipMaps[pass, m],
                                                                                               TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));
                        }

                        shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(4, halfDepths[pass],
                                                                                           TextureAddressingMode.Mirror, FilterOption.Point, FilterOption.Point, FilterOption.None));

                        shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(5, normalTexture,
                                                                                           TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));

                        if (Quality.Value == QualityEnum.HighestAdaptive)
                        {
                            shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(6, importanceMap,
                                                                                               TextureAddressingMode.Clamp, FilterOption.Linear, FilterOption.Linear, FilterOption.None));
                            shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(7, averageImportance,
                                                                                               TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));
                            shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(8, SSAOBaseTextureArray,
                                                                                               TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));
                        }
                    }
                    else
                    {
                        shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(0, halfDepths[pass],
                                                                                           TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));

                        shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(1, halfDepths[pass],
                                                                                           TextureAddressingMode.Mirror, FilterOption.Point, FilterOption.Point, FilterOption.None));

                        shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(2, normalTexture,
                                                                                           TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));
                    }

                    shader.Parameters.Set("NDCToViewMul", NDCToViewMul);
                    shader.Parameters.Set("NDCToViewAdd", NDCToViewAdd);
                    shader.Parameters.Set("effectRadiusParams", effectRadiusParams);
                    shader.Parameters.Set("viewportPixelSize", viewportPixelSize);
                    shader.Parameters.Set("viewport2xPixelSize", viewport2xPixelSize);
                    shader.Parameters.Set("halfViewportPixelSize", halfViewportPixelSize);
                    shader.Parameters.Set("perPassFullResCoordOffset", perPassFullResCoordOffset);
                    shader.Parameters.Set("patternRotScaleMatrices", patternRotScaleMatrices);
                    shader.Parameters.Set("effectFadeOutMul", effectFadeOutMul);
                    shader.Parameters.Set("effectFadeOutAdd", effectFadeOutAdd);
                    shader.Parameters.Set("effectShadowStrength", effectShadowStrength);
                    shader.Parameters.Set("effectShadowClamp", effectShadowClamp);
                    shader.Parameters.Set("effectShadowPow", effectShadowPow);
                    shader.Parameters.Set("detailAOStrength", detailAOStrength);
                    shader.Parameters.Set("itViewMatrix", itViewMatrix);

                    if (Quality.Value == QualityEnum.HighestAdaptive)
                    {
                        shader.Parameters.Set("adaptiveSampleCountLimit", (float)AdaptiveQualityLimit);
                        shader.Parameters.Set("passNumber", (float)pass);
                    }

                    context.RenderQuadToCurrentViewport(shader);
                }

                if (Quality.Value > QualityEnum.Medium)
                {
                    // Free Mip-Maps Targets for this Pass:
                    for (int m = 0; m < 4; m++)
                    {
                        context.DynamicTexture_Free(depthMipMaps[pass, m]);
                    }
                }
                else
                {
                    context.DynamicTexture_Free(halfDepths[pass]);
                }

                // Blur SSAO Texture:

                if (BlurAmount.Value > 0)
                {
                    int wideBlursRemaining = Math.Max(0, BlurAmount.Value - 2);

                    for (int i = 0; i < BlurAmount.Value; i++)
                    {
                        if (i == (BlurAmount.Value - 1))
                        {
                            context.SetViewport(SSAOTextureArray.Result.GetRenderTarget(0, pass).Viewports[0],
                                                Matrix4F.Identity, Matrix4F.Identity, FrameBufferTypes.All, ColorValue.Zero);
                        }
                        else
                        {
                            context.SetViewport(blurPongTexture.Result.GetRenderTarget().Viewports[0],
                                                Matrix4F.Identity, Matrix4F.Identity, FrameBufferTypes.All, ColorValue.Zero);
                        }

                        CanvasRenderer.ShaderItem shader = new CanvasRenderer.ShaderItem();
                        shader.VertexProgramFileName = @"Base\Shaders\EffectsCommon_vs.sc";

                        if (Quality.Value > QualityEnum.Low)
                        {
                            if (wideBlursRemaining > 0)
                            {
                                shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\SmartBlurWide_fs.sc";
                                wideBlursRemaining--;
                            }
                            else
                            {
                                shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\SmartBlur_fs.sc";
                            }
                        }
                        else
                        {
                            shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\NonSmartBlur_fs.sc";
                        }

                        if (Quality.Value > QualityEnum.Low)
                        {
                            shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(0, blurPingTexture,
                                                                                               TextureAddressingMode.Mirror, FilterOption.Point, FilterOption.Point, FilterOption.None));
                            shader.Parameters.Set("invSharpness", invSharpness);
                        }
                        else
                        {
                            shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(0, blurPingTexture,
                                                                                               TextureAddressingMode.Clamp, FilterOption.Linear, FilterOption.Linear, FilterOption.None));
                        }

                        shader.Parameters.Set("halfViewportPixelSize", halfViewportPixelSize);

                        context.RenderQuadToCurrentViewport(shader);

                        // Swap Ping-Pong Blur textures:
                        var tmp_tex = blurPingTexture;
                        blurPingTexture = blurPongTexture;
                        blurPongTexture = tmp_tex;
                    }
                }
            }

            if (Quality.Value == QualityEnum.HighestAdaptive)
            {
                context.DynamicTexture_Free(SSAOBaseTextureArray);
            }

            if (Quality.Value == QualityEnum.HighestAdaptive)
            {
                context.DynamicTexture_Free(importanceMap);
                context.DynamicTexture_Free(averageImportance);
            }

            if (BlurAmount.Value > 0)
            {
                // Free Blur ping/pong Targets:
                context.DynamicTexture_Free(blurPingTexture);
                context.DynamicTexture_Free(blurPongTexture);
            }

            // 4th Pass: Apply 4 SSAO Textures to Final SSAO Result:

            var FullSSAOTexture = context.RenderTarget2D_Alloc(actualTexture.Result.ResultSize, PixelFormat.R8G8_UInt);

            {
                context.SetViewport(FullSSAOTexture.Result.GetRenderTarget().Viewports[0],
                                    Matrix4F.Identity, Matrix4F.Identity, FrameBufferTypes.All, ColorValue.Zero);

                CanvasRenderer.ShaderItem shader = new CanvasRenderer.ShaderItem();
                shader.VertexProgramFileName = @"Base\Shaders\EffectsCommon_vs.sc";

                if (Quality.Value > QualityEnum.Low)
                {
                    shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\Apply_fs.sc";
                }
                else
                {
                    shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\Apply_noSmart_fs.sc";
                }

                if (Quality.Value > QualityEnum.Low)
                {
                    shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(0, SSAOTextureArray,
                                                                                       TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));

                    shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(1, SSAOTextureArray,
                                                                                       TextureAddressingMode.Clamp, FilterOption.Linear, FilterOption.Linear, FilterOption.None));
                }
                else
                {
                    shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(0, SSAOTextureArray,
                                                                                       TextureAddressingMode.Clamp, FilterOption.Linear, FilterOption.Linear, FilterOption.None));
                }

                if (Quality.Value > QualityEnum.Low)
                {
                    shader.Parameters.Set("invSharpness", invSharpness);
                    shader.Parameters.Set("halfViewportPixelSize", halfViewportPixelSize);
                }

                context.RenderQuadToCurrentViewport(shader);
            }

            // Free SSAO Texture Array Target:
            context.DynamicTexture_Free(SSAOTextureArray);

            // 5th Final Pass:
            var finalTexture = context.RenderTarget2D_Alloc(actualTextureSource.Result.ResultSize, actualTextureSource.Result.ResultFormat);

            {
                context.SetViewport(finalTexture.Result.GetRenderTarget().Viewports[0]);

                CanvasRenderer.ShaderItem shader = new CanvasRenderer.ShaderItem();
                shader.VertexProgramFileName   = @"Base\Shaders\EffectsCommon_vs.sc";
                shader.FragmentProgramFileName = @"Base\Shaders\Effects\ASSAO\Final_fs.sc";

                shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(0, actualTextureSource,
                                                                                   TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));

                shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(1, FullSSAOTexture,
                                                                                   TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.None));

                shader.Parameters.Set("intensity", (float)Intensity);
                shader.Parameters.Set("showAO", ShowAO ? 1.0f : -1.0f);

                context.RenderQuadToCurrentViewport(shader);
            }

            // Free Targets:
            context.DynamicTexture_Free(actualTexture);
            if (actualTextureSource != actualTexture)
            {
                context.DynamicTexture_Free(actualTextureSource);
            }
            context.DynamicTexture_Free(FullSSAOTexture);

            // Update actual Texture:
            actualTexture = finalTexture;
        }
Esempio n. 19
0
 /// <summary>
 /// Calculates the square root of each component of the specified vector.
 /// </summary>
 /// <param name="v">The specified vector.</param>
 /// <returns>The vector which contains the square root of the corresponding components in the specified vector.</returns>
 public static Vector4F Sqrt(Vector4F v)
 {
     return(new Vector4F(MathEx.Sqrt(v.X), MathEx.Sqrt(v.Y), MathEx.Sqrt(v.Z), MathEx.Sqrt(v.W)));
 }
Esempio n. 20
0
        public static void GenerateSegmentedPlane(int axis, Vector2 size, Vector2I segments, Vector2 uvTilesPerUnit, Vector2 uvTilesInTotal, out Vector3[] positions, out Vector3[] normals, out Vector4[] tangents, out Vector2[] texCoords, out int[] indices, out Face[] faces)
        {
            int resX = Math.Max(2, segments.X + 1);               // 2 minimum
            int resY = Math.Max(2, segments.Y + 1);

            positions = new Vector3[resX * resY];
            texCoords = new Vector2[positions.Length];

            Vector2 vt = uvTilesPerUnit * size;

            for (int y = 0; y < resY; y++)
            {
                // [ -height / 2, height / 2 ]
                double yPos = ((double)y / (resY - 1) - .5) * size.Y;
                double ty   = yPos + size.Y / 2; // [0, height]
                ty /= size.Y;                    // [0, 1]

                for (int x = 0; x < resX; x++)
                {
                    // [ -width / 2, width / 2 ]
                    double xPos = ((double)x / (resX - 1) - .5) * size.X;

                    double tx = xPos + size.X / 2;   // [0, width]
                    tx /= size.X;                    // [0, 1]

                    int index = x + y * resX;

                    if (axis == 0)
                    {
                        positions[index] = new Vector3(0, xPos, yPos);
                    }
                    else if (axis == 1)
                    {
                        positions[index] = new Vector3(-xPos, 0, yPos);
                    }
                    else
                    {
                        positions[index] = new Vector3(xPos, yPos, 0);
                    }
                    //texCoords[ index ] = new Vector2( tx, 1.0f - ty );

                    if (uvTilesInTotal != Vector2.Zero)
                    {
                        texCoords[index] = new Vector2(tx * uvTilesInTotal.X, 1.0f - ty * uvTilesInTotal.Y);
                    }
                    else if (uvTilesPerUnit != Vector2.Zero)
                    {
                        texCoords[index] = new Vector2(tx * vt.X, 1.0f - ty * vt.Y);
                    }
                    else
                    {
                        texCoords[index] = new Vector2(tx, 1.0f - ty);
                    }
                }
            }

            normals = new Vector3[positions.Length];
            for (int n = 0; n < normals.Length; n++)
            {
                if (axis == 0)
                {
                    normals[n] = Vector3F.XAxis;
                }
                else if (axis == 1)
                {
                    normals[n] = Vector3F.YAxis;
                }
                else
                {
                    normals[n] = Vector3F.ZAxis;
                }
            }

            tangents = new Vector4[positions.Length];
            for (int n = 0; n < tangents.Length; n++)
            {
                if (axis == 0)
                {
                    tangents[n] = new Vector4F(0, 1, 0, -1);
                }
                else if (axis == 1)
                {
                    tangents[n] = new Vector4F(-1, 0, 0, -1);
                }
                else
                {
                    tangents[n] = new Vector4F(1, 0, 0, -1);
                }
            }

            int nbFaces = (resX - 1) * (resY - 1);

            indices = new int[nbFaces * 6];
            int tIdx = 0;

            for (int fy = 0; fy < (resY - 1); fy++)
            {
                for (int fx = 0; fx < (resX - 1); fx++)
                {
                    indices[tIdx++] = fy * resX + fx;
                    indices[tIdx++] = fy * resX + 1 + fx;
                    indices[tIdx++] = fy * resX + resX + fx;

                    indices[tIdx++] = fy * resX + resX + fx;
                    indices[tIdx++] = fy * resX + 1 + fx;
                    indices[tIdx++] = fy * resX + resX + 1 + fx;
                }
            }

            var faceTriangles = new FaceVertex[indices.Length];

            for (int i = 0; i < indices.Length; i++)
            {
                faceTriangles[i] = new FaceVertex(indices[i], indices[i]);
            }
            faces = new Face[] { new Face(faceTriangles) };
        }
Esempio n. 21
0
 /// <summary>
 /// Returns a vector containing the smallest components of the specified vectors.
 /// </summary>
 /// <param name="v1">The first vector.</param>
 /// <param name="v2">The second vector.</param>
 /// <returns>A vector containing the smallest components of the specified vectors.</returns>
 public static Vector4F Min(Vector4F v1, Vector4F v2)
 {
     return(new Vector4F(Math.Min(v1.X, v2.X), Math.Min(v1.Y, v2.Y), Math.Min(v1.Z, v2.Z), Math.Min(v1.W, v2.W)));
 }
Esempio n. 22
0
        /// <summary>
        /// Converts a vector into a unit vector.
        /// </summary>
        /// <param name="v">The vector to normalize.</param>
        /// <returns>The normalized vector.</returns>
        public static Vector4F Normalize(Vector4F v)
        {
            float invLength = MathEx.InvSqrt(v.X * v.X + v.Y * v.Y + v.Z * v.Z + v.W * v.W);

            return(new Vector4F(v.X * invLength, v.Y * invLength, v.Z * invLength, v.W * invLength));
        }
Esempio n. 23
0
 /// <summary>
 /// Calculates the dot product of two vectors.
 /// </summary>
 /// <param name="v">The second vector.</param>
 /// <returns>The dot product of the two vectors.</returns>
 public float Dot(ref Vector4F v)
 {
     return(X * v.X + Y * v.Y + Z * v.Z + W * v.W);
 }
Esempio n. 24
0
 /// <summary>
 /// Calculates the dot product of two vectors.
 /// </summary>
 /// <param name="v1">The first vector.</param>
 /// <param name="v2">The second vector.</param>
 /// <returns>The dot product of the two vectors.</returns>
 public static float Dot(ref Vector4F v1, ref Vector4F v2)
 {
     return(v1.X * v2.X + v1.Y * v2.Y + v1.Z * v2.Z + v1.W * v2.W);
 }
Esempio n. 25
0
 /// <summary>
 /// Calculates the hyperbolic tangent of each component of the specified vector.
 /// </summary>
 /// <param name="v">The specified vector.</param>
 /// <returns>The vector which contains the hyperbolic tangents of the corresponding components in the specified vector.</returns>
 public static Vector4F Tanh(Vector4F v)
 {
     return(new Vector4F(MathEx.Tanh(v.X), MathEx.Tanh(v.Y), MathEx.Tanh(v.Z), MathEx.Tanh(v.W)));
 }
Esempio n. 26
0
 /// <summary>
 /// Calculates the distance between two vectors.
 /// </summary>
 /// <param name="v1">The first vector.</param>
 /// <param name="v2">The second vector.</param>
 /// <returns>The distance between two vectors.</returns>
 public static float Distance(ref Vector4F v1, ref Vector4F v2)
 {
     Subtract(ref v1, ref v2, out Vector4F result);
     return(result.Length());
 }
Esempio n. 27
0
 public ColorByte(Vector4F color)
     : this((int)(color.X * 255), (int)(color.Y * 255), (int)(color.Z * 255), (int)(color.W * 255))
 {
 }
Esempio n. 28
0
 /// <summary>
 /// Chooses one of two vectors depending on the <paramref name="pick1"/> value.
 /// </summary>
 /// <param name="v1">The first vector to choose.</param>
 /// <param name="v2">The second vector to choose.</param>
 /// <param name="pick1">If this value is true, the method chooses the virst vector, otherwise it chooses the second one.</param>
 /// <returns>The selected vector.</returns>
 public static Vector4F Select(Vector4F v1, Vector4F v2, bool pick1)
 {
     return(pick1 ? v1 : v2);
 }
Esempio n. 29
0
        public static Result Calculate15(Vector2I textureSize, bool horizontal, double blurFactor)
        {
            Vector2F[] sampleOffsets = new Vector2F[15];
            Vector4F[] sampleWeights = new Vector4F[15];

            // calculate gaussian texture offsets & weights
            float texelSize = 1.0f / (float)(horizontal ? textureSize.X : textureSize.Y);

            texelSize *= (float)blurFactor;

            // central sample, no offset
            sampleOffsets[0] = Vector2F.Zero;
            {
                float distribution = (float)GaussianDistribution(0, 0, 3);
                sampleWeights[0] = new Vector4F(distribution, distribution, distribution, 1);
            }

            // 'pre' samples
            for (int n = 1; n < 8; n++)
            {
                float distribution = (float)GaussianDistribution(n, 0, 3);
                sampleWeights[n] = new Vector4F(distribution, distribution, distribution, 0);

                if (horizontal)
                {
                    sampleOffsets[n] = new Vector2F((float)n * texelSize, 0);
                }
                else
                {
                    sampleOffsets[n] = new Vector2F(0, (float)n * texelSize);
                }
            }

            // 'post' samples
            for (int n = 8; n < 15; n++)
            {
                sampleWeights[n] = sampleWeights[n - 7];
                sampleOffsets[n] = -sampleOffsets[n - 7];
            }

            //normalize weights (fix)
            {
                float total = 0;
                foreach (var v in sampleWeights)
                {
                    total += v.X;
                }
                for (int n = 0; n < sampleWeights.Length; n++)
                {
                    sampleWeights[n] = new Vector4F(sampleWeights[n].ToVector3F() * (1.0f / total), sampleWeights[n].W);
                }

                //Log.Info( total.ToString() );

                //Vec4F total2 = Vec4F.Zero;
                //foreach( var v in sampleWeights )
                //{
                //	total2 += v;
                //}
                //Log.Info( total2.ToString() );
            }

            var result = new Result();

            result.SampleOffsets            = sampleOffsets;
            result.SampleOffsetsAsVec4Array = ConvertToVec4F(sampleOffsets);
            result.SampleWeights            = sampleWeights;
            return(result);
        }
Esempio n. 30
0
 /// <summary>
 /// Returns the vector which contains the components of the first specified vector raised to power of the numbers which are equal to the corresponding components of the second specified vector.
 /// </summary>
 /// <param name="x">The first vector.</param>
 /// <param name="y">The second vector.</param>
 /// <returns>The vector which contains the components of the first specified vector raised to power of
 /// the numbers which are equal to the corresponding components of the second specified vector.</returns>
 public static Vector4F Pow(Vector4F x, Vector4F y)
 {
     return(new Vector4F(MathEx.Pow(x.X, y.X), MathEx.Pow(x.Y, y.Y), MathEx.Pow(x.Z, y.Z), MathEx.Pow(x.W, y.W)));
 }