# How can I render a texture to a polygon in SDL2? A fake 3D problem

I am working on a fake 3D game recently. The game is based on the perspective principle and using angular perspective. Here is a screen shot:

But the problem is that the walls and floor displayed are polygons, not exact rectangles. I draw them preline. Now I want to put some imgs on them. How can I render a texture to a polygon? How do I make texture exactly fill the area? How do I give the plane a more 3D-like feel?

The technique you're looking for is "rasterization."

At the vertices of your triangle, you have parameters like color and texture coordinates. While rasterizing the polygon (e.g. while you determine which pixels are filled) you interpolate these parameters across the polygon. This is also what you do with depth in order to calculate per-pixel depth values, for example.

The interpolated texture coordinates can then be used to sample a source texture, giving you the "correct" texel for each rasterized fragment (pixel) of the output image.

That by itself gives you only a basic result. The texture will be unfiltered, which probably isn't quite what you want, and it also won't be perspective corrected. The result will look a lot like Ps1-era 3D, for what it's worth.

Adding perspective correction isn't the hardest thing. It mostly just involved scaling the interpolations by the inverse of the depth values that you're also interpolating.

Filtering the texture is the harder part. GPUs does this using techniques like mipmaps, among others.

You can find a lot of tutorials online just by Googling "triangle rasterization" though. Many will cover in-depth how to do texturing, including perspective-corrected and filtered texturing.

The first hit I got looks decent, though perhaps a bit math heavy if you're new to the topic: http://www.scratchapixel.com/lessons/3d-basic-rendering/rasterization-practical-implementation/perspective-correct-interpolation-vertex-attributes