Warning: This method is less efficient than using a texture array, although it is easier to set up. Use it just for fun.
Hello!
I will tell you how to write a shader that allows you to freely repeat any texture from a texture atlas in 3D.
This is an image of my bark textures atlas:
I applied the first texture of this atlas to this tree with scale values x=1, y=1, z=1:
This looks very blurry because we need values x=3, y=10. However, we can’t achieve this with standard means because we are using a texture atlas.
The first thing you need to do is convert the material into a shader:
Next, open this shader and paste this code into it:
uniform vec2 atlas_size; // The size of the texture atlas, for example 4x3 means that the texture atlas is 4 textures wide and 3 textures tall
void vertex() {
UV = UV * uv1_scale.xy + uv1_offset.xy;
}
void fragment() {
vec2 base_uv = UV;
// Pass UV2 values for repetitions
vec2 repeat_texture = uv2_scale.xy;
// Approve the texture
base_uv = mod(base_uv * (repeat_texture * atlas_size), 1.0);
// Calculate the offset
vec2 tile_offset = vec2(float(int(UV.x * atlas_size.x)) / atlas_size.x, float(int(UV.y * atlas_size.y)) / atlas_size.y);
// Repeat the texture and apply the offset
base_uv = base_uv / atlas_size + tile_offset;
//Texture code
This code is part of the standard shader code, you can just copy and paste it, but you have to know what you are doing.
The code uses Blender’s UV calculations, so I don’t know if this method will work for models from other 3D engines.
Next, you need to go to Shader Parameters and find “Atlas Size”. In x, enter the number of textures in the atlas along the x-axis, for example x=4, and in y, enter the number of textures along the y-axis, for example y=2:
As I said, we need values x=3, y=10 to make the tree bark quality. Let’s do this:
Important: if you need UV2, this method will not work for you. You will have to either manually enter the scale or come up with another solution.
In this frame, you can see two trees that use the same material but have different UVs. If my code didn’t work, it would have affected the second tree, but it didn’t:
Now you can easily repeat any texture from the texture atlas!
But there are always mistakes. With this approach, you will see seams between textures, like in this image:
This is not critical if you know that the player will never focus on this object. But if the texture has transparent edges, then problems will arise:
This problem can be solved by sacrificing the quality of sampling:
Important: Do this before converting the material to a shader.
Actually, I don’t know why these stripes appear, if you have any ideas, then suggest them.
That’s it for now, bye!