Jump to content

  • Log In with Google      Sign In   
  • Create Account


[XNA] Aligning texels to pixels doesn't work for small textures


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
12 replies to this topic

#1 Spa8nky   Members   -  Reputation: 230

Like
0Likes
Like

Posted 28 January 2012 - 07:15 AM

I'm attempting to draw a texture that is 3 pixels by 3 pixels in size.

If I draw it using SpriteBatch then the texels are correctly aligned to the pixels

If I draw it using Texture Atlas look up then the texels are not correctly aligned and the x coordinate doesn't line up with the SpriteBatch result.

If I draw it straight from the original texture without the Atlas look up then the texels are not correctly aligned either.

Here is a picture demonstrating the results (All 3 quads have an x position of 100 yet they do not line up):

Posted Image

I'm attempting to line up the pixels to texels as follows:

(C#):


            // [DirectX 9 - Align pixels to texels]
            // • Find size of half a pixel for render targets based on their size
            //   In this case render target size is backBufferWidth * backBufferHeight
            // • The reason that it is 1 / width instead of 0.5 / width is because, in clip space, 
            //   the coordinates range from -1 to 1 (width 2), and not from 0 to 1 (width 1) 
            //   like they do in textures, so you need to double the movement to account for that
            Vector4 halfPixelTexel = new Vector4();

            // Half Pixel
            //halfPixelTexel.X = 1f / textureAtlas.Texture.Width;
            //halfPixelTexel.Y = -1f / textureAtlas.Texture.Height;
            halfPixelTexel.X = 1f / GraphicsDevice.Viewport.Width;
            halfPixelTexel.Y = -1f / GraphicsDevice.Viewport.Height;
            //halfPixelTexel.X = 1f / GraphicsDevice.PresentationParameters.BackBufferWidth;
            //halfPixelTexel.Y = -1f / GraphicsDevice.PresentationParameters.BackBufferHeight;

            // Half Texel
            halfPixelTexel.Z = 0.5f / textureAtlas.Texture.Width;
            halfPixelTexel.W = 0.5f / textureAtlas.Texture.Height;
            //halfPixelTexel.Z = 0.5f / backBufferDim.X;
            //halfPixelTexel.W = 0.5f / backBufferDim.Y;

            effects[EffectName.Quadrangle].Parameters["HalfPixelTexel"].SetValue(halfPixelTexel);
            effects[EffectName.QuadrangleBatch].Parameters["HalfPixelTexel"].SetValue(halfPixelTexel);

HLSL:


VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput Output = (VertexShaderOutput)0;

// Set world transform here (don't use a static identity matrix as it is slower)
float4x4 World =
{
// [Rotation, Scale]
input.Column1.x * input.TexCoordDimension.z, // * Scale X
input.Column1.y * input.TexCoordDimension.z,
input.Column1.z * input.TexCoordDimension.z,
input.Column1.w,
input.Column2.x * input.TexCoordDimension.w, // * Scale Y
input.Column2.y * input.TexCoordDimension.w,
input.Column2.z * input.TexCoordDimension.w,
input.Column2.w,
input.Column3.x,
input.Column3.y,
input.Column3.z,
input.Column3.w,

// [Translation]
input.Column4.x,
input.Column4.y,
input.Column4.z,
input.Column4.w
};

// 'input.Position.w' should always equal 1
input.Position.w = 1;

// [Transformation]
// • Multiplying input.Position by World, then the result by ViewProjection is fast
// • Concatenating World and ViewProjection matrices then multiplying input.Position by the result is slower
input.Position = mul(input.Position, World); 
Output.Position = mul(input.Position, ViewProjection);

// [Texel To Pixel Align] 
// • Half pixel offset for correct texel centering)
// • Should be done AFTER transformation?
Output.Position.xy -= HalfPixelTexel.xy;

// [UV Coordinates]
Output.TextureCoordinates.xy = input.TexCoordDimension.xy;

// [Alpha]
Output.TextureCoordinates.w = input.Normal.w;

    return Output;
}

When using textures larger than 8 pixels this problem does not occur.

Can anyone please explain why the texels are not lining up correctly with the pixels with smaller textures?

Sponsor:

#2 mhagain   Crossbones+   -  Reputation: 7594

Like
0Likes
Like

Posted 28 January 2012 - 07:31 AM

The half-pixel thing is relative to your screen, not to the texture size. That means that you would commonly just subtract 0.5 from x and y in your vertex shader, before transforming the input position.

It appears that the gentleman thought C++ was extremely difficult and he was overjoyed that the machine was absorbing it; he understood that good C++ is difficult but the best C++ is well-nigh unintelligible.


#3 Spa8nky   Members   -  Reputation: 230

Like
0Likes
Like

Posted 28 January 2012 - 08:17 AM

I still get the same results with:


VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput Output = (VertexShaderOutput)0;

// Set world transform here (don't use a static identity matrix as it is slower)
float4x4 World =
{
// [Rotation, Scale]
input.Column1.x * input.TexCoordDimension.z, // * Scale X
input.Column1.y * input.TexCoordDimension.z,
input.Column1.z * input.TexCoordDimension.z,
input.Column1.w,
input.Column2.x * input.TexCoordDimension.w, // * Scale Y
input.Column2.y * input.TexCoordDimension.w,
input.Column2.z * input.TexCoordDimension.w,
input.Column2.w,
input.Column3.x,
input.Column3.y,
input.Column3.z,
input.Column3.w,

// [Translation]
input.Column4.x,
input.Column4.y,
input.Column4.z,
input.Column4.w
};

// 'input.Position.w' should always equal 1
input.Position.w = 1;

input.Position.xy -= 0.5;

// [Transformation]
// • Multiplying input.Position by World, then the result by ViewProjection is fast
// • Concatenating World and ViewProjection matrices then multiplying input.Position by the result is slower
input.Position = mul(input.Position, World); 
Output.Position = mul(input.Position, ViewProjection);

// [UV Coordinates]
Output.TextureCoordinates.xy = input.TexCoordDimension.xy;

// [Alpha]
Output.TextureCoordinates.w = input.Normal.w;

// [Source Rectangles]
// • Pass the source rectangles to the pixel shader for processing
Output.SourceRectangle0 = input.SourceRectangle0;
Output.SourceRectangle1 = input.SourceRectangle1;

    return Output;
}

The SpriteBatch shader subtracts the 0.5 after transformation:



    // Apply the matrix transform.
    outputPosition = mul(float4(position, depth, 1), transpose(MatrixTransform));

// Half pixel offset for correct texel centering.
outputPosition.xy -= 0.5;

This method also produces the same incorrect result with my shader. :(

#4 mhagain   Crossbones+   -  Reputation: 7594

Like
0Likes
Like

Posted 28 January 2012 - 01:24 PM

Subtract before transformation, not after.

You could even encode the subtraction into your world matrix, but I'd advise to get it working this way first.

It appears that the gentleman thought C++ was extremely difficult and he was overjoyed that the machine was absorbing it; he understood that good C++ is difficult but the best C++ is well-nigh unintelligible.


#5 Spa8nky   Members   -  Reputation: 230

Like
0Likes
Like

Posted 28 January 2012 - 02:13 PM

Subtract before transformation, not after.

You could even encode the subtraction into your world matrix, but I'd advise to get it working this way first.


Sorry if I didn't make it clear in my last post but I have already tried that.


input.Position.xy -= 0.5;

// [Transformation]
// • Multiplying input.Position by World, then the result by ViewProjection is fast
// • Concatenating World and ViewProjection matrices then multiplying input.Position by the result is slower
input.Position = mul(input.Position, World);
Output.Position = mul(input.Position, ViewProjection);

The lines above in the last post are what I am referring to.

It doesn't work either.

#6 mikiex   Members   -  Reputation: 237

Like
1Likes
Like

Posted 28 January 2012 - 06:20 PM

Just glancing at this, 3x3 texture is an odd size? Some hardware doesnt like non-power of 2 textures (although is this day and age its less of an issue?) I never tend to use anything lower than 8x8. Also are you clamping your textures?

why not use a larger texture and just leave space?

what is your final aim?

#7 Spa8nky   Members   -  Reputation: 230

Like
0Likes
Like

Posted 29 January 2012 - 06:02 AM

Just glancing at this, 3x3 texture is an odd size? Some hardware doesnt like non-power of 2 textures (although is this day and age its less of an issue?) I never tend to use anything lower than 8x8.


Going the reflection of SpriteBatch, and its accompanying shader, I can't see anything that resizes the 3x3 sprite. SpriteBatch draws it correctly too.

why not use a larger texture and just leave space?


I could do but I wanted to get to the bottom of what was causing this problem.

Also are you clamping your textures?



Yes:


sampler TextureSampler = sampler_state   
{   
    Texture = <Texture>;   

    MinFilter = Point;   
    MagFilter = Point;   
    MipFilter = Point; // None

    AddressU = Clamp;  
    AddressV = Clamp;
};


#8 Nikster   Members   -  Reputation: 178

Like
0Likes
Like

Posted 29 January 2012 - 06:08 AM

The uvs you supply you need to pinch them 1/2 texel, not just move them all by the same value.

htw = half texel width, hth = half texel height.

As in, u(0) += htw, v(0) += hth - u(1) -= htw, v(1) -= hth

Other corner can be worked out from these.

#9 Spa8nky   Members   -  Reputation: 230

Like
0Likes
Like

Posted 29 January 2012 - 07:29 AM

The uvs you supply you need to pinch them 1/2 texel, not just move them all by the same value.

As in, u(0) += htw, v(0) += hth - u(1) -= htw, v(1) -= hth


Would you agree that the following clamping method is equivalent to your pinching method?

// Half Pixel Clamp (Pinch)

//input.Position.x = max(input.Position.x, HalfPixelTexel.x);
//input.Position.y = max(input.Position.y, HalfPixelTexel.y);
//input.Position.x = min(input.Position.x, 1.0 - HalfPixelTexel.x);
//input.Position.y = min(input.Position.y, 1.0 - HalfPixelTexel.y);

// Half Texel Clamp (Pinch)
input.Position.x = max(input.Position.x, HalfPixelTexel.z);
input.Position.y = max(input.Position.y, HalfPixelTexel.w);
input.Position.x = min(input.Position.x, 1.0 - HalfPixelTexel.z);
input.Position.y = min(input.Position.y, 1.0 - HalfPixelTexel.w);

Neither the half texel clamp or the half pixel clamp produce the correct result when applied either before or after transformation.

#10 Nikster   Members   -  Reputation: 178

Like
0Likes
Like

Posted 29 January 2012 - 10:16 AM

Would you agree that the following clamping method is equivalent to your pinching method?


Only if you're using Position as the UV coords, if position is what it implies then it won't help, forget about modifying the vertices positions and change the UV input.

EDIT: and pinch regardless rather than use min, max.

#11 Spa8nky   Members   -  Reputation: 230

Like
0Likes
Like

Posted 29 January 2012 - 11:24 AM

Ok I with you now. How can I determine which UV I am pinching without using conditional statements in HLSL?

u(0) += htw, v(0) += hth - u(1) -= htw, v(1) -= hth


Am I right in assuming that the pinching method will only work when passing in the UV coordinates as 4 corners of a quadrangle?

How would pinching work if the uv coordinates are not four corners of a quadrangle?

#12 Nikster   Members   -  Reputation: 178

Like
0Likes
Like

Posted 29 January 2012 - 12:08 PM

Ok I with you now. How can I determine which UV I am pinching without using conditional statements in HLSL?


You should pinch the data before it gets to the shader. The point where you fill in the UV data in the buffer.


Am I right in assuming that the pinching method will only work when passing in the UV coordinates as 4 corners of a quadrangle?

How would pinching work if the uv coordinates are not four corners of a quadrangle?


No idea, I've only tested with quadrangle (using two triangles), as the artefacts you are seeing are normally associated (or are more noticeable) with 2D UI elements. Chances are if you're using triangles as part of 3D meshes rather than sprite type primitives then it may not be noticeable.

However, the quadrangle method is because, on the top left side += relates to the normal texel mapping to primitive (.5 of a texel), the -= however is because we associate 1.0f as a bottom/right edge, but we know 1.0 = 0.0 :) so the right edge is really 1.0f - texel width + half texel width).

#13 Spa8nky   Members   -  Reputation: 230

Like
0Likes
Like

Posted 31 January 2012 - 03:36 PM

So I've been trying to implement your suggestion but it doesn't solve the problem:


				v = quadrangles[i].Vertices;

				halfTexel.X = 0.5f / quadrangles[i].Width;
				halfTexel.Y = 0.5f / quadrangles[i].Height;

				// [0] Lower Left	   [1] -- [3]	 (0,0)--(1,0)
				// [1] Upper Left		|	  |		|	  |
				// [2] Lower Right	   |	  |		|	  |
				// [3] Upper Right	  [0] -- [2]	 (0,1)--(1,1)

				v[0].TexCoordDimension.X = halfTexel.X;						 // Texture Coordinates stored in X,Y Quadrangle Dimensions stored in Z,W
				v[0].TexCoordDimension.Y = 1f - halfTexel.Y;
				v[1].TexCoordDimension.X = halfTexel.X;
				v[1].TexCoordDimension.Y = halfTexel.Y;
				v[2].TexCoordDimension.X = 1f - halfTexel.X;
				v[2].TexCoordDimension.Y = 1f - halfTexel.Y;
				v[3].TexCoordDimension.X = 1f - halfTexel.X;
				v[3].TexCoordDimension.Y = halfTexel.Y;

				// Copy the vertex data to the drawer's large vertices array
				v.CopyTo(vertices, i * 4);

or


                v[0].TexCoordDimension.X += halfTexel.X;
                v[0].TexCoordDimension.Y -= halfTexel.Y;

                v[1].TexCoordDimension.X += halfTexel.X;
                v[1].TexCoordDimension.Y += halfTexel.Y;

                v[2].TexCoordDimension.X -= halfTexel.X;
                v[2].TexCoordDimension.Y -= halfTexel.Y;

                v[3].TexCoordDimension.X -= halfTexel.X;
                v[3].TexCoordDimension.Y += halfTexel.Y;

How do I calculate one texel?

I have tried:


			halfTexel.X = 0.5f / game.GraphicsDevice.PresentationParameters.BackBufferWidth;
			halfTexel.Y = 0.5f / game.GraphicsDevice.PresentationParameters.BackBufferHeight;

and


			halfTexel.X = 0.5f / game.TextureAtlas.Texture.Width;
			halfTexel.Y = 0.5f / game.TextureAtlas.Texture.Height;

None of the above produces the correct result Posted Image




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS