private void addPosition(string[] lineParts) { Vec3 position = new Vec3 { x = float.Parse(lineParts[1]), y = float.Parse(lineParts[2]), z = float.Parse(lineParts[3]), }; positions.Add(position); }
private void addNormal(string[] lineParts) { Vec3 normal = new Vec3 { x = float.Parse(lineParts[1]), y = float.Parse(lineParts[2]), z = float.Parse(lineParts[3]), }; normals.Add(normal); }
private void createTangents() { List<Vec3> tan1 = ZeroOut(vertices.Count); List<Vec3> tan2 = ZeroOut(vertices.Count); int numTriangles = indices.Count; //int triangleIndex = 0; for (int i = 0; i < numTriangles; i+= 3) { int i1 = indices[i]; int i2 = indices[i + 1]; int i3 = indices[i + 2]; Vec3 v1 = vertices[i1].position; Vec3 v2 = vertices[i2].position; Vec3 v3 = vertices[i3].position; Vec2 w1 = vertices[i1].textureCoord; Vec2 w2 = vertices[i2].textureCoord; Vec2 w3 = vertices[i3].textureCoord; float x1 = v2.x - v1.x; float x2 = v3.x - v1.x; float y1 = v2.y - v1.y; float y2 = v3.y - v1.y; float z1 = v2.z - v1.z; float z2 = v3.z - v1.z; float s1 = w2.x - w1.x; float s2 = w3.x - w1.x; float t1 = w2.y - w1.y; float t2 = w3.y - w1.y; float r = 1.0f / (s1 * t2 - s2 * t1); Vec3 sdir = new Vec3(); sdir.x = (t2 * x1 - t1 * x2) * r; sdir.y = (t2 * y1 - t1 * y2) * r; sdir.z = (t2 * z1 - t1 * z2) * r; Vec3 tdir = new Vec3(); tdir.x = (s1 * x2 - s2 * x1) * r; tdir.y = (s1 * y2 - s2 * y1) * r; tdir.z = (s1 * z2 - s2 * z1) * r; tan1[i1] += sdir; tan1[i2] += sdir; tan1[i3] += sdir; tan2[i1] += tdir; tan2[i2] += tdir; tan2[i3] += tdir; } for (int i = 0; i < vertices.Count; i++) { Vec3 n = vertices[i].normal; Vec3 t = tan1[i]; vertices[i].tangent = (Vec4)((t - n) * Vec3.Dot(n, t)).normalize(); vertices[i].tangent.w = (Vec3.Dot(Vec3.Cross(n, t), tan2[i]) < 0.0f) ? -1.0f : 1.0f; } }
public Vec3 normalize() { Vec3 normalized = new Vec3(); float length = (float)Math.Abs(Math.Sqrt(((x*x) + (y * y) + (z * z)))); normalized.x = x / length; normalized.y = y / length; normalized.z = z / length; return normalized; }
public static float Dot(Vec3 v1, Vec3 v2) { return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z; }
public static Vec3 Cross(Vec3 v1, Vec3 v2) { Vec3 vc = new Vec3(); vc.x = v1.y * v2.z - v1.z * v2.y; vc.y = v1.z * v2.x - v1.x * v2.z; vc.z = v1.x * v2.y - v1.y * v2.x; return vc; }
private List<Vec3> ZeroOut(int count) { List<Vec3> list = new List<Vec3>(count); for (int i = 0; i < count; i++) { Vec3 v = new Vec3(); list.Add(v); } return list; }