comparison semiconginev2/old/core/matrix.nim @ 1218:56781cc0fc7c compiletime-tests

did: renamge main package
author sam <sam@basx.dev>
date Wed, 17 Jul 2024 21:01:37 +0700
parents semicongine/old/core/matrix.nim@a3eb305bcac2
children
comparison
equal deleted inserted replaced
1217:f819a874058f 1218:56781cc0fc7c
1 import std/math
2 import std/macros
3 import std/random
4 import std/strutils
5 import std/strformat
6 import std/typetraits
7
8 import ./vector
9
10 export math
11
12 type
13 # layout is row-first
14 # having an object instead of directly aliasing the array seems a bit ugly at
15 # first, but is necessary to be able to work correctly with distinguished
16 # types (i.e. TMat23 and TMat32 would be an alias for the same type array[6, T]
17 # which prevents the type system from identifying the correct type at times)
18 #
19 # Though, great news is that objects have zero overhead!
20 TMat2*[T: SomeNumber] = object
21 data*: array[4, T]
22 TMat23*[T: SomeNumber] = object
23 data*: array[6, T]
24 TMat32*[T: SomeNumber] = object
25 data*: array[6, T]
26 TMat3*[T: SomeNumber] = object
27 data*: array[9, T]
28 TMat34*[T: SomeNumber] = object
29 data*: array[12, T]
30 TMat43*[T: SomeNumber] = object
31 data*: array[12, T]
32 TMat4*[T: SomeNumber] = object
33 data*: array[16, T]
34 TMat* = TMat2|TMat3|TMat4|TMat23|TMat32|TMat34|TMat43
35 Mat2* = TMat2[float32]
36 Mat23* = TMat23[float32]
37 Mat32* = TMat32[float32]
38 Mat3* = TMat3[float32]
39 Mat34* = TMat34[float32]
40 Mat43* = TMat43[float32]
41 Mat4* = TMat4[float32]
42
43 func MakeUnit2*[T: SomeNumber](): auto {.compiletime.} = TMat2[T](data: [
44 T(1), T(0),
45 T(0), T(1),
46 ])
47 func MakeUnit3*[T: SomeNumber](): auto {.compiletime.} = TMat3[T](data: [
48 T(1), T(0), T(0),
49 T(0), T(1), T(0),
50 T(0), T(0), T(1),
51 ])
52 func MakeUnit4*[T: SomeNumber](): auto {.compiletime.} = TMat4[T](data: [
53 T(1), T(0), T(0), T(0),
54 T(0), T(1), T(0), T(0),
55 T(0), T(0), T(1), T(0),
56 T(0), T(0), T(0), T(1),
57 ])
58
59 # generates constants: Unit
60 # Also for Y, Z, R, G, B
61 # not sure if this is necessary or even a good idea...
62 macro generateAllConsts() =
63 result = newStmtList()
64 for theType in ["int", "int8", "int16", "int32", "int64", "float", "float32", "float64"]:
65 var typename = theType[0 .. 0]
66 if theType[^2].isDigit:
67 typename = typename & theType[^2]
68 if theType[^1].isDigit:
69 typename = typename & theType[^1]
70 result.add(newConstStmt(
71 postfix(ident("Unit2" & typename), "*"),
72 newCall(nnkBracketExpr.newTree(ident("MakeUnit2"), ident(theType)))
73 ))
74 result.add(newConstStmt(
75 postfix(ident("Unit3" & typename), "*"),
76 newCall(nnkBracketExpr.newTree(ident("MakeUnit3"), ident(theType)))
77 ))
78 result.add(newConstStmt(
79 postfix(ident("Unit4" & typename), "*"),
80 newCall(nnkBracketExpr.newTree(ident("MakeUnit4"), ident(theType)))
81 ))
82
83 generateAllConsts()
84
85 const Unit2* = MakeUnit2[float32]()
86 const Unit3* = MakeUnit3[float32]()
87 const Unit4* = MakeUnit4[float32]()
88
89 template RowCount*(m: typedesc): int =
90 when m is TMat2: 2
91 elif m is TMat23: 2
92 elif m is TMat32: 3
93 elif m is TMat3: 3
94 elif m is TMat34: 3
95 elif m is TMat43: 4
96 elif m is TMat4: 4
97 template ColumnCount*(m: typedesc): int =
98 when m is TMat2: 2
99 elif m is TMat23: 3
100 elif m is TMat32: 2
101 elif m is TMat3: 3
102 elif m is TMat34: 4
103 elif m is TMat43: 3
104 elif m is TMat4: 4
105 template matlen(m: typedesc): int =
106 when m is TMat2: 4
107 elif m is TMat23: 6
108 elif m is TMat32: 6
109 elif m is TMat3: 9
110 elif m is TMat34: 12
111 elif m is TMat43: 12
112 elif m is TMat4: 16
113
114
115 func toString[T](value: T): string =
116 var
117 strvalues: seq[string]
118 maxwidth = 0
119
120 for n in value.data:
121 let strval = &"{float(n):.4f}"
122 strvalues.add(strval)
123 if strval.len > maxwidth:
124 maxwidth = strval.len
125
126 for i in 0 ..< strvalues.len:
127 let filler = " ".repeat(maxwidth - strvalues[i].len)
128 if i mod T.ColumnCount == T.ColumnCount - 1:
129 result &= filler & strvalues[i] & "\n"
130 else:
131 if i mod T.ColumnCount == 0:
132 result &= " "
133 result &= filler & strvalues[i] & " "
134
135 func `$`*(v: TMat2[SomeNumber]): string = toString[TMat2[SomeNumber]](v)
136 func `$`*(v: TMat23[SomeNumber]): string = toString[TMat23[SomeNumber]](v)
137 func `$`*(v: TMat32[SomeNumber]): string = toString[TMat32[SomeNumber]](v)
138 func `$`*(v: TMat3[SomeNumber]): string = toString[TMat3[SomeNumber]](v)
139 func `$`*(v: TMat34[SomeNumber]): string = toString[TMat34[SomeNumber]](v)
140 func `$`*(v: TMat43[SomeNumber]): string = toString[TMat43[SomeNumber]](v)
141 func `$`*(v: TMat4[SomeNumber]): string = toString[TMat4[SomeNumber]](v)
142
143 func `[]`*[T: TMat](m: T, row, col: int): auto = m.data[col + row * T.ColumnCount]
144 func `[]=`*[T: TMat, U](m: var T, row, col: int, value: U) = m.data[col + row * T.ColumnCount] = value
145 func `[]`*[T: TMat](m: T, i: int): auto = m.data[i]
146 func `[]=`*[T: TMat, U](m: var T, i: int, value: U) = m.data[i] = value
147
148 func Row*[T: TMat2](m: T, i: 0..1): auto = TVec2([m[i, 0], m[i, 1]])
149 func Row*[T: TMat32](m: T, i: 0..2): auto = TVec2([m[i, 0], m[i, 1]])
150 func Row*[T: TMat23](m: T, i: 0..1): auto = TVec3([m[i, 0], m[i, 1], m[i, 2]])
151 func Row*[T: TMat3](m: T, i: 0..2): auto = TVec3([m[i, 0], m[i, 1], m[i, 2]])
152 func Row*[T: TMat43](m: T, i: 0..3): auto = TVec3([m[i, 0], m[i, 1], m[i, 2]])
153 func Row*[T: TMat34](m: T, i: 0..2): auto = TVec4([m[i, 0], m[i, 1], m[i, 2], m[i, 3]])
154 func Row*[T: TMat4](m: T, i: 0..3): auto = TVec4([m[i, 0], m[i, 1], m[i, 2], m[i, 3]])
155
156 func Col*[T: TMat2](m: T, i: 0..1): auto = TVec2([m[0, i], m[1, i]])
157 func Col*[T: TMat23](m: T, i: 0..2): auto = TVec2([m[0, i], m[1, i]])
158 func Col*[T: TMat32](m: T, i: 0..1): auto = TVec3([m[0, i], m[1, i], m[2, i]])
159 func Col*[T: TMat3](m: T, i: 0..2): auto = TVec3([m[0, i], m[1, i], m[2, i]])
160 func Col*[T: TMat34](m: T, i: 0..3): auto = TVec3([m[0, i], m[1, i], m[2, i]])
161 func Col*[T: TMat43](m: T, i: 0..2): auto = TVec4([m[0, i], m[1, i], m[2, i], m[3, i]])
162 func Col*[T: TMat4](m: T, i: 0..3): auto = TVec4([m[0, i], m[1, i], m[2, i], m[3, i]])
163
164 proc createMatMatMultiplicationOperator(leftType: typedesc, rightType: typedesc, outType: typedesc): NimNode =
165 var data = nnkBracket.newTree()
166 for i in 0 ..< RowCount(leftType):
167 for j in 0 ..< rightType.ColumnCount:
168 data.add(newCall(
169 ident("sum"),
170 infix(
171 newCall(newDotExpr(ident("a"), ident("Row")), newLit(i)),
172 "*",
173 newCall(newDotExpr(ident("b"), ident("Col")), newLit(j))
174 )
175 ))
176
177 return newProc(
178 postfix(nnkAccQuoted.newTree(ident("*")), "*"),
179 params = [
180 ident("auto"),
181 newIdentDefs(ident("a"), ident(leftType.name)),
182 newIdentDefs(ident("b"), ident(rightType.name))
183 ],
184 body = nnkObjConstr.newTree(ident(outType.name), nnkExprColonExpr.newTree(ident("data"), data)),
185 procType = nnkFuncDef,
186 )
187
188 proc createMatMatAdditionOperator(theType: typedesc): NimNode =
189 var data = nnkBracket.newTree()
190 for i in 0 ..< matlen(theType):
191 data.add(
192 infix(
193 nnkBracketExpr.newTree(ident("a"), newLit(i)),
194 "+",
195 nnkBracketExpr.newTree(ident("b"), newLit(i)),
196 ))
197
198 return newProc(
199 postfix(nnkAccQuoted.newTree(ident("+")), "*"),
200 params = [
201 ident("auto"),
202 newIdentDefs(ident("a"), ident(theType.name)),
203 newIdentDefs(ident("b"), ident(theType.name))
204 ],
205 body = nnkObjConstr.newTree(ident(theType.name), nnkExprColonExpr.newTree(ident("data"), data)),
206 procType = nnkFuncDef,
207 )
208
209 proc createVecMatMultiplicationOperator(matType: typedesc, vecType: typedesc): NimNode =
210 var data = nnkBracket.newTree()
211 for i in 0 ..< matType.RowCount:
212 data.add(newCall(
213 ident("sum"),
214 infix(
215 ident("v"),
216 "*",
217 newCall(newDotExpr(ident("m"), ident("Row")), newLit(i))
218 )
219 ))
220
221 let resultVec = newCall(
222 nnkBracketExpr.newTree(ident(vecType.name), ident("T")),
223 data,
224 )
225 let name = postfix(nnkAccQuoted.newTree(ident("*")), "*")
226 let genericParams = nnkGenericParams.newTree(nnkIdentDefs.newTree(ident("T"), ident("SomeNumber"), newEmptyNode()))
227 let formalParams = nnkFormalParams.newTree(
228 ident("auto"),
229 newIdentDefs(ident("m"), nnkBracketExpr.newTree(ident(matType.name), ident("T"))),
230 newIdentDefs(ident("v"), nnkBracketExpr.newTree(ident(vecType.name), ident("T"))),
231 )
232
233 return nnkFuncDef.newTree(
234 name,
235 newEmptyNode(),
236 genericParams,
237 formalParams,
238 newEmptyNode(),
239 newEmptyNode(),
240 resultVec
241 )
242
243
244 proc createMatScalarOperator(matType: typedesc, op: string): NimNode =
245 result = newStmtList()
246
247 var data = nnkBracket.newTree()
248 for i in 0 ..< matType.RowCount * matType.ColumnCount:
249 data.add(infix(nnkBracketExpr.newTree(newDotExpr(ident("a"), ident("data")), newLit(i)), op, ident("b")))
250 result.add(newProc(
251 postfix(nnkAccQuoted.newTree(ident(op)), "*"),
252 params = [
253 ident("auto"),
254 newIdentDefs(ident("a"), ident(matType.name)),
255 newIdentDefs(ident("b"), ident("SomeNumber")),
256 ],
257 body = nnkObjConstr.newTree(ident(matType.name), nnkExprColonExpr.newTree(ident("data"), data)),
258 procType = nnkFuncDef,
259 ))
260 result.add(newProc(
261 postfix(nnkAccQuoted.newTree(ident(op)), "*"),
262 params = [
263 ident("auto"),
264 newIdentDefs(ident("b"), ident("SomeNumber")),
265 newIdentDefs(ident("a"), ident(matType.name)),
266 ],
267 body = nnkObjConstr.newTree(ident(matType.name), nnkExprColonExpr.newTree(ident("data"), data)),
268 procType = nnkFuncDef,
269 ))
270 if op == "-":
271 var data2 = nnkBracket.newTree()
272 for i in 0 ..< matType.RowCount * matType.ColumnCount:
273 data2.add(prefix(nnkBracketExpr.newTree(newDotExpr(ident("a"), ident("data")), newLit(i)), op))
274 result.add(newProc(
275 postfix(nnkAccQuoted.newTree(ident(op)), "*"),
276 params = [
277 ident("auto"),
278 newIdentDefs(ident("a"), ident(matType.name)),
279 ],
280 body = nnkObjConstr.newTree(ident(matType.name), nnkExprColonExpr.newTree(ident("data"), data2)),
281 procType = nnkFuncDef,
282 ))
283
284 macro createAllMultiplicationOperators() =
285 result = newStmtList()
286
287 for op in ["+", "-", "*", "/"]:
288 result.add(createMatScalarOperator(TMat2, op))
289 result.add(createMatScalarOperator(TMat23, op))
290 result.add(createMatScalarOperator(TMat32, op))
291 result.add(createMatScalarOperator(TMat3, op))
292 result.add(createMatScalarOperator(TMat34, op))
293 result.add(createMatScalarOperator(TMat43, op))
294 result.add(createMatScalarOperator(TMat4, op))
295
296 result.add(createMatMatMultiplicationOperator(TMat2, TMat2, TMat2))
297 result.add(createMatMatMultiplicationOperator(TMat2, TMat23, TMat23))
298 result.add(createMatMatMultiplicationOperator(TMat23, TMat32, TMat2))
299 result.add(createMatMatMultiplicationOperator(TMat23, TMat3, TMat23))
300 result.add(createMatMatMultiplicationOperator(TMat32, TMat2, TMat32))
301 result.add(createMatMatMultiplicationOperator(TMat32, TMat23, TMat3))
302 result.add(createMatMatMultiplicationOperator(TMat3, TMat32, TMat32))
303 result.add(createMatMatMultiplicationOperator(TMat3, TMat3, TMat3))
304 result.add(createMatMatMultiplicationOperator(TMat3, TMat34, TMat34))
305 result.add(createMatMatMultiplicationOperator(TMat43, TMat3, TMat43))
306 result.add(createMatMatMultiplicationOperator(TMat43, TMat34, TMat4))
307 result.add(createMatMatMultiplicationOperator(TMat4, TMat43, TMat43))
308 result.add(createMatMatMultiplicationOperator(TMat4, TMat4, TMat4))
309
310 result.add(createMatMatAdditionOperator(TMat2))
311 result.add(createMatMatAdditionOperator(TMat23))
312 result.add(createMatMatAdditionOperator(TMat32))
313 result.add(createMatMatAdditionOperator(TMat3))
314 result.add(createMatMatAdditionOperator(TMat34))
315 result.add(createMatMatAdditionOperator(TMat43))
316 result.add(createMatMatAdditionOperator(TMat4))
317
318 result.add(createVecMatMultiplicationOperator(TMat2, TVec2))
319 result.add(createVecMatMultiplicationOperator(TMat3, TVec3))
320 result.add(createVecMatMultiplicationOperator(TMat4, TVec4))
321
322 createAllMultiplicationOperators()
323
324 func `*`*(mat: Mat4, vec: Vec3f): Vec3f =
325 (mat * vec.ToVec4(1)).ToVec3
326
327 func Transposed*[T](m: TMat2[T]): TMat2[T] = TMat2[T](data: [
328 m[0, 0], m[1, 0],
329 m[0, 1], m[1, 1],
330 ])
331 func Transposed*[T](m: TMat23[T]): TMat32[T] = TMat32[T](data: [
332 m[0, 0], m[1, 0],
333 m[0, 1], m[1, 1],
334 m[0, 2], m[1, 2],
335 ])
336 func Transposed*[T](m: TMat32[T]): TMat23[T] = TMat23[T](data: [
337 m[0, 0], m[1, 0], m[2, 0],
338 m[0, 1], m[1, 1], m[2, 1],
339 ])
340 func Transposed*[T](m: TMat3[T]): TMat3[T] = TMat3[T](data: [
341 m[0, 0], m[1, 0], m[2, 0],
342 m[0, 1], m[1, 1], m[2, 1],
343 m[0, 2], m[1, 2], m[2, 2],
344 ])
345 func Transposed*[T](m: TMat43[T]): TMat34[T] = TMat34[T](data: [
346 m[0, 0], m[1, 0], m[2, 0], m[3, 0],
347 m[0, 1], m[1, 1], m[2, 1], m[3, 1],
348 m[0, 2], m[1, 2], m[2, 2], m[3, 2],
349 ])
350 func Transposed*[T](m: TMat34[T]): TMat43[T] = TMat43[T](data: [
351 m[0, 0], m[1, 0], m[2, 0],
352 m[0, 1], m[1, 1], m[2, 1],
353 m[0, 2], m[1, 2], m[2, 2],
354 m[0, 3], m[1, 3], m[2, 3],
355 ])
356 func Transposed*[T](m: TMat4[T]): TMat4[T] = TMat4[T](data: [
357 m[0, 0], m[1, 0], m[2, 0], m[3, 0],
358 m[0, 1], m[1, 1], m[2, 1], m[3, 1],
359 m[0, 2], m[1, 2], m[2, 2], m[3, 2],
360 m[0, 3], m[1, 3], m[2, 3], m[3, 3],
361 ])
362
363 func Translate2d*[T](x, y: T): TMat3[T] = TMat3[T](data: [
364 T(1), T(0), x,
365 T(0), T(1), y,
366 T(0), T(0), T(1),
367 ])
368 func Scale2d*[T](sx, sy: T): TMat3[T] = TMat3[T](data: [
369 sx, T(0), T(0),
370 T(0), sy, T(0),
371 T(0), T(0), T(1),
372 ])
373 func Rotate2d*[T](angle: T): TMat3[T] = TMat3[T](data: [
374 cos(angle), -sin(angle), T(0),
375 sin(angle), cos(angle), T(0),
376 T(0), T(0), T(1),
377 ])
378 func Translate*(x = 0'f32, y = 0'f32, z = 0'f32): TMat4[float32] = Mat4(data: [
379 1'f32, 0'f32, 0'f32, x,
380 0'f32, 1'f32, 0'f32, y,
381 0'f32, 0'f32, 1'f32, z,
382 0'f32, 0'f32, 0'f32, 1'f32,
383 ])
384 func Translate*[T: TVec3](v: T): TMat4[float32] = Translate(v[0], v[1], v[2])
385 func Scale*(x = 1'f32, y = 1'f32, z = 1'f32): Mat4 = Mat4(data: [
386 x, 0'f32, 0'f32, 0'f32,
387 0'f32, y, 0'f32, 0'f32,
388 0'f32, 0'f32, z, 0'f32,
389 0'f32, 0'f32, 0'f32, 1'f32,
390 ])
391 func Scale*[T: TVec3](v: T): TMat4[float32] = Scale(v[0], v[1], v[2])
392 func Rotate*(angle: float32, a: Vec3f): Mat4 =
393 let
394 cosa = cos(angle)
395 sina = sin(angle)
396 x = a[0]
397 y = a[1]
398 z = a[2]
399 Mat4(data: [
400 x * x * (1 - cosa) + cosa, y * x * (1 - cosa) - z * sina, z * x * (1 - cosa) + y * sina, 0'f32,
401 x * y * (1 - cosa) + z * sina, y * y * (1 - cosa) + cosa, z * y * (1 - cosa) - x * sina, 0'f32,
402 x * z * (1 - cosa) - y * sina, y * z * (1 - cosa) + x * sina, z * z * (1 - cosa) + cosa, 0'f32,
403 0'f32, 0'f32, 0'f32, 1'f32,
404 ])
405
406 func asMat3(m: Mat4): auto =
407 Mat3(data: [
408 m[0, 0], m[0, 1], m[0, 2],
409 m[1, 0], m[1, 1], m[1, 2],
410 m[2, 0], m[2, 1], m[2, 2],
411 ])
412
413
414 func Inversed*(m: Mat4): Mat4 =
415 var m3 = m.asMat3.Transposed
416 m3[0, 0] = 1'f32 / m3[0, 0]
417 m3[1, 1] = 1'f32 / m3[1, 1]
418 m3[2, 2] = 1'f32 / m3[2, 2]
419 let col3 = -(m3 * m.Col(3).xyz)
420 return Mat4(data: [
421 m3[0, 0], m3[0, 1], m3[0, 2], col3.x,
422 m3[1, 0], m3[1, 1], m3[1, 2], col3.y,
423 m3[2, 0], m3[2, 1], m3[2, 2], col3.z,
424 0, 0, 0, 1,
425 ])
426
427
428 # call e.g. TMat32[int]().randomized() to get a random matrix
429 template makeRandomInit(mattype: typedesc) =
430 proc Randomized*[T: SomeInteger](m: mattype[T]): mattype[T] =
431 for i in 0 ..< result.data.len:
432 result.data[i] = rand(low(typeof(m.data[0])) .. high(typeof(m.data[0])))
433 proc Randomized*[T: SomeFloat](m: mattype[T]): mattype[T] =
434 for i in 0 ..< result.data.len:
435 result.data[i] = rand(T(1.0))
436
437 makeRandomInit(TMat2)
438 makeRandomInit(TMat23)
439 makeRandomInit(TMat32)
440 makeRandomInit(TMat3)
441 makeRandomInit(TMat34)
442 makeRandomInit(TMat43)
443 makeRandomInit(TMat4)
444
445 func Perspective*(fovy, aspect, zNear, zFar: float32): Mat4 =
446 let tanHalfFovy = tan(fovy / 2)
447 return Mat4(data: [
448 1 / (aspect * tanHalfFovy), 0, 0, 0,
449 0, 1 / tanHalfFovy, 0, 0,
450 0, 0, zFar / (zFar - zNear), -(zFar * zNear) / (zFar - zNear),
451 0, 0, 1, 1,
452 ])
453
454 func Ortho*(left, right, top, bottom, zNear, zFar: float32): Mat4 =
455 Mat4(data: [
456 2 / (right - left), 0, 0, -(right + left) / (right - left),
457 0, 2 / (bottom - top), 0, -(bottom + top) / (bottom - top),
458 0, 0, 1 / (zFar - zNear), zNear / (zFar - zNear),
459 0, 0, 0, 1,
460 ])
461
462 # create an orthographic perspective that will map from -1 .. 1 on all axis and keep a 1:1 aspect ratio
463 # the smaller dimension (width or height) will always be 1 and the larger dimension will be larger, to keep the ratio
464 func OrthoWindowAspect*(windowAspect: float32): Mat4 =
465 if windowAspect < 1:
466 let space = 2 * (1 / windowAspect - 1) / 2
467 Ortho(-1, 1, -1 - space, 1 + space, 0, 1)
468 else:
469 let space = 2 * (windowAspect - 1) / 2
470 Ortho(-1 - space, 1 + space, -1, 1, 0, 1)
471
472 func Position*(mat: Mat4): Vec3f {.deprecated.} =
473 mat.Col(3).ToVec3
474
475 func Scaling*(mat: Mat4): Vec3f {.deprecated.} =
476 NewVec4f(mat[0, 0], mat[1, 1], mat[2, 2])