MIP-mapping in direct3d

Source: Internet
Author: User
Introduction

For those of you who don't know, MIP-mapping is a form of anti-aliasing that is used in processing 3D rendering engines. it prevents the well-known interference pattern that occurs on detailed textures, known as the 'moir é pattern '. this happens because when the texture is far enough away, there are more texels (texture pixels) then there are pixels to be rendered on the screen. this means that some texels get skipped over, and visual information is lost.


The uugly 'bitty 'Look near the top is the moir é pattern in action.

In a properly anti-aliased rendering, what wocould happen is all of the texels that land within a single pixel on the screen wocould be weighted, summed and a final average value is placed on the screen. this cocould be very processor intensive... just imagine being far away from a small box that has a 256x256 texture on it. if this box only covers an 8x8 pixel area on the screen, that's 1024 texels Per pixel! You wowould have to sum up and average all those texels just to render one pixel on the screen !!! Obviusly this isn' t going to happen in real-time.

The idea of MIP-mapping is simple: if what you are drawing is really big then use a big texture, and if it's small, use a small texture. the great thing about using a smaller texture when needed is that the Texel colours can be averaged from the higher resolution texture. and if you use a texture that has a less or equal number texels for the pixels to be rendered, then there is no moir é pattern.


Same Scene rendered using MIP-mapping.

MIP-Map Factory

Say you have a detailed texture of size 128x128. if you down-sample it by a factor of 2 simply by taking the average of every 2x2 Texel area, you end up with the same texture at 64x64, just with less detail. but you won't need the detail because you will only view it from further away. this becomes our level one MIP-map (the original texture is refered to as level zero ). if you repeat the process on your newly generated texture, then you get level two, and so on. generally you stop at a smallest of a 2x2 texture (after that, you just have a single solid color ).


MIP-maps generated by averaging 2x2 Texel areas.

Below is some sample code for generating the image data for the MIP-maps.


/* example C code for generating mip-maps (recursive function) */
/* NOTE: this is untested (and un-optimal ;) */

void MakeMipMaps( Texture *parentTexture)
{
int width = parentTexture->width / 2;
int height = parentTexture->height / 2;
Texture *newTexture;
int u, v;
int texel;

/* we want to stop recursing after 2 x 2 map */
if (width < 2) return;
if (height < 2) return;

newTexture = CreateTexture( width, height);

/* find the new texture values */
for (u = 0; u < width; u++)
for (v = 0; v < height; v++)
{
/* sum up 2 x 2 texel area */
/* for simplicity of example, this doesn't seperate
the RGB channels like it should */
texel = GetTexel( parentTexture, u * 2 , v * 2 )
+ GetTexel( parentTexture, u * 2 + 1, v * 2 )
+ GetTexel( parentTexture, u * 2 , v * 2 + 1)
+ GetTexel( parentTexture, u * 2 + 1, v * 2 + 1);

/* take the average */
texel /= 4;

PutTexel( newTexture, u, v, texel);
}

/* make a link to the mip map */
parentTexture->mipMap = newTexture;

/* recurse until we are done */
MakeMipMaps( newTexture);
}
The rendering pipeline

Since this article is directed to people using direct3d, I won't be getting into specific rendering algorithms, but it's always good to have a general idea of what's going on in the lower levels.

In order to render a textured polygon, the rendering engine needs to know how to adjust texels it has to advance to get to the pixel beside it, and how to get to the line below it. for it to choose a MIP-map, it checks if either of these values is greater than 1.0, which means there are texels that will potentially be skipped over, so instead, use the next level (lower resolution) MIP-map. repeat t His check until the values are both less than or equal to 1.0, or the lowest resolution MIP-map is reached, and you have the one that will be used. and of course, for each time the next level is selected, the Texel coordinates are divided by two. this process may sound like an expensive operation, but in the rendering pipeline it can be optimized to simple non-iterative instructions. granted thoug H, it generally is slower than regular texture mapping (but the results are worth it !).

There are also other algorithms used to figure out where the MIP-maps go, such as spliting the polygons at boundries Based on the surface angle and distance from the view point, but they all produce basically the same results (though some are faster in certain situations ).


This demonstrates where the different MIP-map levels are used by inverting the texture color at each level.

MIP-maps usually can be bilinear filtered just like any other texture, but most 3D hardware also allows for a third level of linear filtering on MIP-maps. this level will fade smoothly between the MIP-map levels instead of having a sharp break (the break usually isn't very noticable though because you are going between two textures of the same color composition).

Direct3d implementation

I am going to assume that you already know how to initialize direct3d and get textured polygons on the screen. if you don't, there are plenty of good tutorials already written about that, so please refer to those. this will just give you the additional steps required to get your polygons MIP-mapped.

The first step is to allocate your MIP-maps. this is done in the createsurface () call for your texture. by specifying the ddscaps_mipmap and ddscaps_complex capabilities for your surface, the driver will automatically allocate the appropriate MIP-maps and attach them to your surface. you will also need to specify the ddsd_mipmapcount flag and set the number of MIP-map levels that you want (remember that the original texture also counts as a level ).


/* allocates a texture surface with optional mip-maps */
/* NOTES: - texture width and height need to be powers of 2 */
/* - as a general rule, it's good to have width = height for textures */
/* - this is untested (my code is in C++ classes so I re-wrote it here
in C for simplicity, so there may be some subtle differences or
typos that prevent it from compiling) */

LPDIRECTDRAWSURFACE CreateD3DTexture( LPDIRECTDRAW lpDD,
int width, int height,
int mipmap,
DDPIXELFORMAT *pixelFormat)
{
LPDIRECTDRAWSURFACE surface; /* pointer to surface to be created */
DDSURFACEDESC ddsd; /* description of surface to create */
DWORD mipLevels = 1; /* number of mip-map levels to create
(1 = just original texture) */
DWORD flags = DDSD_WIDTH | DDSD_HEIGHT | DDSD_PIXELFORMAT | DDSD_CAPS;
DWORD caps = DDSCAPS_TEXTURE | DDSCAPS_3DDEVICE;
HRESULT result;

/* put texture in video memory if driver allows it */
if (VideoMemoryTexturesAllowed())
caps |= DDSCAPS_VIDEOMEMORY;
else
caps |= DDSCAPS_SYSTEMMEMORY;

if (mipmap)
{
/* count how many mip-map levels we need */
int mipWidth = width;
int mipHeight = height;

/* smallest mip-map we want is 2 x 2 */
while ((mipWidth > 2) && (mipHeight > 2))
{
mipLevels++;
mipWidth /= 2;
mipHeight /= 2;
}

if (mipLevels > 1)
{
/* tell it we want mip-maps */
flags |= DDSD_MIPMAPCOUNT;
caps |= DDSCAPS_MIPMAP | DDSCAPS_COMPLEX;
}
}

/* set up buffer properties */
memset(&ddsd, 0, sizeof(ddsd));
ddsd.dwSize = sizeof(ddsd);
ddsd.dwFlags = flags;
ddsd.dwWidth = width;
ddsd.dwHeight = height;
ddsd.ddpfPixelFormat = *pixelFormat;
ddsd.ddsCaps.dwCaps = caps;
ddsd.dwMipMapCount = mipLevels;

/* create texture surface and associated mip-maps */
result = IDirectDraw_CreateSurface( lpDD, &ddsd, &surface, NULL);

if (result != DD_OK) return NULL;

return surface;
}

The createsurface () call here will create the number of surfaces you specify in ddsd. dwmipmapcount, but it only returns a pointer to one surface. the MIP-map surfaces are accessed by calling getattachedsurface (). there is no need to do anything special in clean-up because all auto-generated surfaces are released with the parent surface.

Now that the MIP-maps have been created, you will need to put in the texture images. using the images generated from the code sample in the 'mip-Map Factory 'section of this article, you can copy the images to the MIP-maps like so:


Texture *textureData;
LPDIRECTDRAWSURFACE surface, mipSurface, nextSurface;
DDSURFACEDESC ddsd;

/* generate the mip-maps from the original image */
MakeMipMaps( originalImage);

/* create the texture surfaces */
surface = CreateD3DTexture( lpDD, originalImage->width,
originalImage->height, TRUE, pixelFormat);

/* iterate through the mip-maps and copy the data */
textureData = originalImage;
mipSurface = surface;

while (textureData != NULL)
{
/* lock surface so we can write to it */
memset(&ddsd, 0, sizeof(ddsd));
ddsd.dwSize = sizeof(ddsd);
IDirectDraw_Lock( mipSurface, NULL, &ddsd, 0, NULL);

/* copy data from from image to the texture surface */
CopyTextureData(
ddsd.lpSurface, /* pointer to destination surface data */
ddsd.lPitch, /* number of bytes per horizontal span in the dest surface */
textureData); /* pointer to source image */

/* done writing surface so unlock the memory */
IDirectDraw_Unlock( mipSurface, NULL);

/* follow the links down to through the mip-map levels of texture data */
textureData = textureData->mipMap;
if (textureData == NULL)
{
/* done the last mip-map, need to release the reference to the surface */
/* don't want to release the first surface or it will free the whole thing! */
if (mipSirface != surface)
IDirectDraw_Release( mipSurface);
break;
}

/* get the surface for the next level mip-map */
IDirectDraw_GetAttachedSurface( mipSurface, &ddsd.ddsCaps, &nextSurface);

/* need to release the reference to the parent surface */
if (mipSirface != surface)
IDirectDraw_Release( mipSurface);

mipSurface = nextSurface;
}

/* now the textures are loaded, we can grab the handle and start referencing it,
just like with a regular texture */
. . .
IDirectDraw_QueryInterface(surface, IID_IDirect3DTexture, (void**)&D3DTexture);
IDirect3DTexture_GetHandle( D3DTexture, lpD3DDevice, &handle);
. . .

Now that the image data for the textures has been loaded, it's pretty much ready to go. the only thing missing is to tell direct3d that you want it to render the MIP-maps. if you were to render it now just like any other texture, it will only use the original full-sized texture. in order to get it to use the MIP-maps, we must set the render state d3drenderstate_texturemin to one of the following values:

  • D3dfilter_mipnearest-use MIP-maps with point sampling
  • D3dfilter_miplinear-use MIP-maps with bilinear filtering (texture interpolation)
  • D3dfilter_linearmipnearest-use MIP-maps with point sampling, and apply a linear filter between each MIP-map level and the next (smooths transitions between the different levels)
  • D3dfilter_linearmiplinear-use MIP-maps with bilinear filtering, and apply a linear filter between each MIP-map level and the next

Throw that into your direct3d code, and just like that, your textures are MIP-mapped. remember though, that just like with the rest of direct3d, you will have to check the capabilities of the driver to make sure it supports these render states before you can use them.

If for some reason you want to render without the MIP-maps, you can always set it back to either d3dfilter_nearest or d3dfilter_linear.

In closing

Hopefully by now you shoshould have been able to seemlessly integrate MIP-mapping into your direct3d graphics engine, so that some day you can display it to thousands of on-lookers who will say "ooohh, aaahh, smooth... "And stare in wonderment at the absence of moir é patterns

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.