v2 / vlib / v / tests / builtin_arrays / array_fixed_op_overload_test.v
78 lines · 66 sloc · 1.63 KB · e2e5cf8db56f3562c7baa735061690be936bdf3e
Raw
1import math
2import math.vec
3
4type Vector3 = vec.Vec3[f32]
5
6fn vector3(x f32, y f32, z f32) Vector3 {
7 return Vector3{x, y, z}
8}
9
10pub type Matrix4 = [16]f32
11
12pub fn matrix4(x0 f32, x1 f32, x2 f32, x3 f32, x4 f32, x5 f32, x6 f32, x7 f32, x8 f32, x9 f32, x10 f32, x11 f32, x12 f32, x13 f32, x14 f32, x15 f32) Matrix4 {
13 return [
14 x0,
15 x1,
16 x2,
17 x3,
18 x4,
19 x5,
20 x6,
21 x7,
22 x8,
23 x9,
24 x10,
25 x11,
26 x12,
27 x13,
28 x14,
29 x15,
30 ]!
31}
32
33pub fn (x Matrix4) str() string {
34 return '|${x[0]:-6.3},${x[1]:-6.3},${x[2]:-6.3},${x[3]:-6.3}|\n' +
35 '|${x[4]:-6.3},${x[5]:-6.3},${x[6]:-6.3},${x[7]:-6.3}|\n' +
36 '|${x[8]:-6.3},${x[9]:-6.3},${x[10]:-6.3},${x[11]:-6.3}|\n' +
37 '|${x[12]:-6.3},${x[13]:-6.3},${x[14]:-6.3},${x[15]:-6.3}|'
38}
39
40pub fn matrix4_unit() Matrix4 {
41 return matrix4(f32(1), 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)
42}
43
44pub fn (a Matrix4) * (b Matrix4) Matrix4 {
45 mut res := Matrix4{}
46 for i := 0; i < 4; i++ {
47 for j := 0; j < 4; j++ {
48 res[j * 4 + i] = 0
49 for k := 0; k < 4; k++ {
50 res[j * 4 + i] += a[k * 4 + i] * b[j * 4 + k]
51 }
52 }
53 }
54 return res
55}
56
57pub fn rotate(angle f32, w Vector3) Matrix4 {
58 cs := f32(math.cos(angle))
59 sn := f32(math.sin(angle))
60 cv := f32(1.0) - cs
61 axis := w.normalize()
62
63 ax := axis.x
64 ay := axis.y
65 az := axis.z
66
67 return matrix4((ax * ax * cv) + cs, (ax * ay * cv) + az * sn, (ax * az * cv) - ay * sn, 0,
68 (ay * ax * cv) - az * sn, (ay * ay * cv) + cs, (ay * az * cv) + ax * sn, 0,
69
70 (az * ax * cv) + ay * sn, (az * ay * cv) - ax * sn, (az * az * cv) + cs, 0, 0, 0, 0, 1)
71}
72
73fn test_array_fixed_op_overload() {
74 mut rot := matrix4_unit()
75 rot *= rotate(0.5, vector3(0.5, 0.5, 0.5))
76 println(rot)
77 assert true
78}
79