-
Notifications
You must be signed in to change notification settings - Fork 0
Texture wrapping
Jean-Milost Reymond edited this page Nov 21, 2025
·
2 revisions
The final step of this software renderer is to wrap a texture to the model.
The idea here is to use the the provided texture coordinates to pick the correct pixel in the provided texture bitmap, and to write it on the canvas.
To achieve that, the weights calculated during the barycentric coordinates calculation may once again be used.
// calculate perspective-correct texture coordinates
float u = ((texCoord[0].m_X * w0) + (texCoord[1].m_X * w1) + (texCoord[2].m_X * w2)) * z;
float v = ((texCoord[0].m_Y * w0) + (texCoord[1].m_Y * w1) + (texCoord[2].m_Y * w2)) * z;
// wrap coordinates (handle values outside 0-1)
u = u - std::floorf(u);
v = v - std::floorf(v);
// clamp to prevent out-of-bounds access
std::size_t tx = (std::size_t)std::floorf(u * (float)m_TexWidth);
std::size_t ty = (std::size_t)std::floorf(v * (float)m_TexHeight);
// clamp to valid range
if (tx >= m_TexWidth)
tx = m_TexWidth - 1;
if (ty >= m_TexHeight)
ty = m_TexHeight - 1;
// calculate the texture line width
const std::size_t line = m_TexWidth * m_TexBPP;
// calculate the pixel index to get
const std::size_t texIndex = (ty * line) + (tx * m_TexBPP);
// get the pixel color from texture
const BYTE b = m_pTexture[texIndex];
const BYTE g = m_pTexture[texIndex + 1];
const BYTE r = m_pTexture[texIndex + 2];
// write pixel (BGR format for Windows DIB)
m_pPixels[pixelIndex] = (b << 16) | (g << 8) | r;