## Tidbit - Texture alignment on an arbitrary surface

Tutorials concerning the OpenGL® ES cross-platform API for full-function 2D and 3D graphics on the Google-Android platform.

### Tidbit - Texture alignment on an arbitrary surface

Problem - creating texture coordinates for an arbitrary surface. A surface is defined as a plane and n vertices on the plane that define the triangles of the surface. If you don't have texture coordinates, how can you create some that make sense and don't stretch/warp your texture.

Solution - create two axis vectors, xaxis and yaxis, for your surface. The texture coordinates are simply the dot product of each vertex to these vectors.

Using java Syntax Highlighting
1. Vector3 xaxis = new Vector3();
2.
3. Vector3 yaxis = new Vector3();
4.
5. Vector3 down = new Vector3();
6.
7.
8.
9. // The xaxis is the real x-axis if the plane is parallel to the xy plane, (normal is 0,0,+-1)
10.
11. // Otherwise, the xaxis is the cross product of 'down' and the plane normal
12.
13.
14.
15. if ((Math.abs(plane.normal.z) == 1) && (plane.normal.x == 0) and (plane.normal.y == 0))
16.
17. {
18.
19.    Vector3.set(xaxis,1,0,0);
20.
21. }
22.
23. else
24.
25. {
26.
27.    Vector3.set(down,0,0,-1);
28.
29.    Vector3.cross_product(xaxis, down, plane.normal);
30.
31.    Vector3.normalize(xaxis,xaxis);
32.
33. }
34.
35.
36.
37. // The yaxis is the cross of the xaxis and the plane normal
38.
39. Vector3.cross_product(yaxis,plane.normal,xaxis);
40.
41. Vector3.normalize(yaxis,yaxis);
42.
43.
44.
45. // For each of your vertices, the x and y texture coordinates are the dot products respective to
46.
47. // these newly created x and y axis vectors.
48.
49.
50.
51. for (int i=0; i<number_of_vertices; i++)
52.
53. {
54.
55.    texture_vertex[i].x = Vector3.dot_product(vertex[i],xaxis) * texture_scale;
56.
57.    texture_vertex[i].y = Vector3.dot_product(vertex[i],yaxis) * texture_scale;
58.
59. }
60.
61.
Parsed in 0.015 seconds, using GeSHi 1.0.8.4
Visit Exit 4 Gaming - http://www.exit4games.com/
Home of LavaBall - http://exit4games.com/?page_id=3
Home of Rebound - http://exit4games.com/?page_id=138
Home of Tap Crazy - http://exit4games.com/?page_id=219