Read this:

http://www.sjbaker.org/steve/omniv/tiling_textures.html