comparison src/matrix.nim @ 16:617c6dcddbe2

add: matrix multiplications, tests
author Sam <sam@basx.dev>
date Fri, 30 Dec 2022 15:56:17 +0700
parents a571db114152
children
comparison
equal deleted inserted replaced
15:dde536a70483 16:617c6dcddbe2
1 import random 1 import std/math
2 import std/macros
3 import std/random
2 import std/strutils 4 import std/strutils
3 import std/typetraits 5 import std/typetraits
4 6
5 import ./vector 7 import ./vector
6 8
30 MatMN* = Mat23|Mat32|Mat34|Mat43 32 MatMN* = Mat23|Mat32|Mat34|Mat43
31 Mat* = MatMM|MatMN 33 Mat* = MatMM|MatMN
32 IntegerMat = Mat22[SomeInteger]|Mat33[SomeInteger]|Mat44[SomeInteger]|Mat23[SomeInteger]|Mat32[SomeInteger]|Mat34[SomeInteger]|Mat43[SomeInteger] 34 IntegerMat = Mat22[SomeInteger]|Mat33[SomeInteger]|Mat44[SomeInteger]|Mat23[SomeInteger]|Mat32[SomeInteger]|Mat34[SomeInteger]|Mat43[SomeInteger]
33 FloatMat = Mat22[SomeFloat]|Mat33[SomeFloat]|Mat44[SomeFloat]|Mat23[SomeFloat]|Mat32[SomeFloat]|Mat34[SomeFloat]|Mat43[SomeFloat] 35 FloatMat = Mat22[SomeFloat]|Mat33[SomeFloat]|Mat44[SomeFloat]|Mat23[SomeFloat]|Mat32[SomeFloat]|Mat34[SomeFloat]|Mat43[SomeFloat]
34 36
35 37 func unit22[T: SomeNumber](): auto {.compiletime.} = Mat22[T](data:[
36 func rowCount*(m: Mat22): int = 2 38 T(1), T(0),
37 func columnCount*(m: Mat22): int = 2 39 T(0), T(1),
38 func rowCount*(m: Mat23): int = 2 40 ])
39 func columnCount*(m: Mat23): int = 3 41 func unit33[T: SomeNumber](): auto {.compiletime.} = Mat33[T](data:[
40 func rowCount*(m: Mat32): int = 3 42 T(1), T(0), T(0),
41 func columnCount*(m: Mat32): int = 2 43 T(0), T(1), T(0),
42 func rowCount*(m: Mat33): int = 3 44 T(0), T(0), T(1),
43 func columnCount*(m: Mat33): int = 3 45 ])
44 func rowCount*(m: Mat34): int = 3 46 func unit44[T: SomeNumber](): auto {.compiletime.} = Mat44[T](data: [
45 func columnCount*(m: Mat34): int = 4 47 T(1), T(0), T(0), T(0),
46 func rowCount*(m: Mat43): int = 4 48 T(0), T(1), T(0), T(0),
47 func columnCount*(m: Mat43): int = 3 49 T(0), T(0), T(1), T(0),
48 func rowCount*(m: Mat44): int = 4 50 T(0), T(0), T(0), T(1),
49 func columnCount*(m: Mat44): int = 4 51 ])
52
53 # generates constants: Unit
54 # Also for Y, Z, R, G, B
55 # not sure if this is necessary or even a good idea...
56 macro generateAllConsts() =
57 result = newStmtList()
58 for theType in ["int", "int8", "int16", "int32", "int64", "float", "float32", "float64"]:
59 var typename = theType[0 .. 0]
60 if theType[^2].isDigit:
61 typename = typename & theType[^2]
62 if theType[^1].isDigit:
63 typename = typename & theType[^1]
64 result.add(newConstStmt(
65 postfix(ident("Unit22" & typename), "*"),
66 newCall(nnkBracketExpr.newTree(ident("unit22"), ident(theType)))
67 ))
68 result.add(newConstStmt(
69 postfix(ident("Unit33" & typename), "*"),
70 newCall(nnkBracketExpr.newTree(ident("unit33"), ident(theType)))
71 ))
72 result.add(newConstStmt(
73 postfix(ident("Unit44" & typename), "*"),
74 newCall(nnkBracketExpr.newTree(ident("unit44"), ident(theType)))
75 ))
76
77 generateAllConsts()
78
79 const Unit22* = unit22[float]()
80 const Unit33* = unit33[float]()
81 const Unit44* = unit44[float]()
82
83 template rowCount*(m: typedesc): int =
84 when m is Mat22: 2
85 elif m is Mat23: 2
86 elif m is Mat32: 3
87 elif m is Mat33: 3
88 elif m is Mat34: 3
89 elif m is Mat43: 4
90 elif m is Mat44: 4
91 template columnCount*(m: typedesc): int =
92 when m is Mat22: 2
93 elif m is Mat23: 3
94 elif m is Mat32: 2
95 elif m is Mat33: 3
96 elif m is Mat34: 4
97 elif m is Mat43: 3
98 elif m is Mat44: 4
50 99
51 100
52 func toString[T](value: T): string = 101 func toString[T](value: T): string =
53 var 102 var
54 strvalues: seq[string] 103 strvalues: seq[string]
60 if strval.len > maxwidth: 109 if strval.len > maxwidth:
61 maxwidth = strval.len 110 maxwidth = strval.len
62 111
63 for i in 0 ..< strvalues.len: 112 for i in 0 ..< strvalues.len:
64 let filler = " ".repeat(maxwidth - strvalues[i].len) 113 let filler = " ".repeat(maxwidth - strvalues[i].len)
65 if i mod value.columnCount == value.columnCount - 1: 114 if i mod T.columnCount == T.columnCount - 1:
66 result &= filler & strvalues[i] & "\n" 115 result &= filler & strvalues[i] & "\n"
67 else: 116 else:
68 if i mod value.columnCount == 0: 117 if i mod T.columnCount == 0:
69 result &= " " 118 result &= " "
70 result &= filler & strvalues[i] & " " 119 result &= filler & strvalues[i] & " "
71 result = $T & "\n" & result 120 result = $T & "\n" & result
72 121
73 func `$`*(v: Mat22[SomeNumber]): string = toString[Mat22[SomeNumber]](v) 122 func `$`*(v: Mat22[SomeNumber]): string = toString[Mat22[SomeNumber]](v)
76 func `$`*(v: Mat33[SomeNumber]): string = toString[Mat33[SomeNumber]](v) 125 func `$`*(v: Mat33[SomeNumber]): string = toString[Mat33[SomeNumber]](v)
77 func `$`*(v: Mat34[SomeNumber]): string = toString[Mat34[SomeNumber]](v) 126 func `$`*(v: Mat34[SomeNumber]): string = toString[Mat34[SomeNumber]](v)
78 func `$`*(v: Mat43[SomeNumber]): string = toString[Mat43[SomeNumber]](v) 127 func `$`*(v: Mat43[SomeNumber]): string = toString[Mat43[SomeNumber]](v)
79 func `$`*(v: Mat44[SomeNumber]): string = toString[Mat44[SomeNumber]](v) 128 func `$`*(v: Mat44[SomeNumber]): string = toString[Mat44[SomeNumber]](v)
80 129
81 func `[]`*[T: Mat](m: T, row, col: int): auto = m.data[col + row * m.columnCount] 130 func `[]`*[T: Mat](m: T, row, col: int): auto = m.data[col + row * T.columnCount]
82 proc `[]=`*[T: Mat, U](m: var T, row, col: int, value: U) = m.data[col + row * m.columnCount] = value 131 proc `[]=`*[T: Mat, U](m: var T, row, col: int, value: U) = m.data[col + row * T.columnCount] = value
83 132
84 func row*[T: Mat22](m: T, i: 0..1): auto = Vec2([m[i, 0], m[i, 1]]) 133 func row*[T: Mat22](m: T, i: 0..1): auto = Vec2([m[i, 0], m[i, 1]])
85 func row*[T: Mat32](m: T, i: 0..2): auto = Vec2([m[i, 0], m[i, 1]]) 134 func row*[T: Mat32](m: T, i: 0..2): auto = Vec2([m[i, 0], m[i, 1]])
86 func row*[T: Mat23](m: T, i: 0..1): auto = Vec3([m[i, 0], m[i, 1], m[i, 2]]) 135 func row*[T: Mat23](m: T, i: 0..1): auto = Vec3([m[i, 0], m[i, 1], m[i, 2]])
87 func row*[T: Mat33](m: T, i: 0..2): auto = Vec3([m[i, 0], m[i, 1], m[i, 2]]) 136 func row*[T: Mat33](m: T, i: 0..2): auto = Vec3([m[i, 0], m[i, 1], m[i, 2]])
95 func col*[T: Mat33](m: T, i: 0..2): auto = Vec3([m[0, i], m[1, i], m[2, i]]) 144 func col*[T: Mat33](m: T, i: 0..2): auto = Vec3([m[0, i], m[1, i], m[2, i]])
96 func col*[T: Mat34](m: T, i: 0..3): auto = Vec3([m[0, i], m[1, i], m[2, i]]) 145 func col*[T: Mat34](m: T, i: 0..3): auto = Vec3([m[0, i], m[1, i], m[2, i]])
97 func col*[T: Mat43](m: T, i: 0..2): auto = Vec4([m[0, i], m[1, i], m[2, i], m[3, i]]) 146 func col*[T: Mat43](m: T, i: 0..2): auto = Vec4([m[0, i], m[1, i], m[2, i], m[3, i]])
98 func col*[T: Mat44](m: T, i: 0..3): auto = Vec4([m[0, i], m[1, i], m[2, i], m[3, i]]) 147 func col*[T: Mat44](m: T, i: 0..3): auto = Vec4([m[0, i], m[1, i], m[2, i], m[3, i]])
99 148
149 proc createMatMatMultiplicationOperator(leftType: typedesc, rightType: typedesc, outType: typedesc): NimNode =
150 var data = nnkBracket.newTree()
151 for i in 0 ..< rowCount(leftType):
152 for j in 0 ..< rightType.columnCount:
153 data.add(newCall(
154 ident("sum"),
155 infix(
156 newCall(newDotExpr(ident("a"), ident("row")), newLit(i)),
157 "*",
158 newCall(newDotExpr(ident("b"), ident("col")), newLit(j))
159 )
160 ))
161
162 return newProc(
163 postfix(nnkAccQuoted.newTree(ident("*")), "*"),
164 params=[
165 ident("auto"),
166 newIdentDefs(ident("a"), ident(leftType.name)),
167 newIdentDefs(ident("b"), ident(rightType.name))
168 ],
169 body=nnkObjConstr.newTree(ident(outType.name), nnkExprColonExpr.newTree(ident("data"), data)),
170 procType=nnkFuncDef,
171 )
172
173 proc createVecMatMultiplicationOperator(matType: typedesc, vecType: typedesc): NimNode =
174 var data = nnkBracket.newTree()
175 for i in 0 ..< matType.rowCount:
176 data.add(newCall(
177 ident("sum"),
178 infix(
179 ident("v"),
180 "*",
181 newCall(newDotExpr(ident("m"), ident("row")), newLit(i))
182 )
183 ))
184
185 let resultVec = newCall(
186 nnkBracketExpr.newTree(ident(vecType.name), ident("T")),
187 data,
188 )
189 let name = postfix(nnkAccQuoted.newTree(ident("*")), "*")
190 let genericParams = nnkGenericParams.newTree(nnkIdentDefs.newTree(ident("T"), ident("SomeNumber"), newEmptyNode()))
191 let formalParams = nnkFormalParams.newTree(
192 ident("auto"),
193 newIdentDefs(ident("m"), nnkBracketExpr.newTree(ident(matType.name), ident("T"))),
194 newIdentDefs(ident("v"), nnkBracketExpr.newTree(ident(vecType.name), ident("T"))),
195 )
196
197 return nnkFuncDef.newTree(
198 name,
199 newEmptyNode(),
200 genericParams,
201 formalParams,
202 newEmptyNode(),
203 newEmptyNode(),
204 resultVec
205 )
206
207 proc createVecMatMultiplicationOperator1(vecType: typedesc, matType: typedesc): NimNode =
208 var data = nnkBracket.newTree()
209 for i in 0 ..< matType.columnCount:
210 data.add(newCall(
211 ident("sum"),
212 infix(
213 ident("v"),
214 "*",
215 newCall(newDotExpr(ident("m"), ident("col")), newLit(i))
216 )
217 ))
218 let resultVec = nnkObjConstr.newTree(
219 nnkBracketExpr.newTree(ident(vecType.name), ident("float")),
220 nnkExprColonExpr.newTree(ident("data"), data)
221 )
222
223 return nnkFuncDef.newTree(
224 ident("test"),
225 newEmptyNode(),
226 newEmptyNode(),
227 newEmptyNode(),
228 newEmptyNode(),
229 newEmptyNode(),
230 resultVec,
231 )
232
233 proc createMatScalarOperator(matType: typedesc, op: string): NimNode =
234 result = newStmtList()
235
236 var data = nnkBracket.newTree()
237 for i in 0 ..< matType.rowCount * matType.columnCount:
238 data.add(infix(nnkBracketExpr.newTree(newDotExpr(ident("a"), ident("data")), newLit(i)), op, ident("b")))
239 result.add(newProc(
240 postfix(nnkAccQuoted.newTree(ident(op)), "*"),
241 params=[
242 ident("auto"),
243 newIdentDefs(ident("a"), ident(matType.name)),
244 newIdentDefs(ident("b"), ident("SomeNumber")),
245 ],
246 body=nnkObjConstr.newTree(ident(matType.name), nnkExprColonExpr.newTree(ident("data"), data)),
247 procType=nnkFuncDef,
248 ))
249 result.add(newProc(
250 postfix(nnkAccQuoted.newTree(ident(op)), "*"),
251 params=[
252 ident("auto"),
253 newIdentDefs(ident("b"), ident("SomeNumber")),
254 newIdentDefs(ident("a"), ident(matType.name)),
255 ],
256 body=nnkObjConstr.newTree(ident(matType.name), nnkExprColonExpr.newTree(ident("data"), data)),
257 procType=nnkFuncDef,
258 ))
259 if op == "-":
260 var data2 = nnkBracket.newTree()
261 for i in 0 ..< matType.rowCount * matType.columnCount:
262 data2.add(prefix(nnkBracketExpr.newTree(newDotExpr(ident("a"), ident("data")), newLit(i)), op))
263 result.add(newProc(
264 postfix(nnkAccQuoted.newTree(ident(op)), "*"),
265 params=[
266 ident("auto"),
267 newIdentDefs(ident("a"), ident(matType.name)),
268 ],
269 body=nnkObjConstr.newTree(ident(matType.name), nnkExprColonExpr.newTree(ident("data"), data2)),
270 procType=nnkFuncDef,
271 ))
272
273 macro createAllMultiplicationOperators() =
274 result = newStmtList()
275
276 for op in ["+", "-", "*", "/"]:
277 result.add(createMatScalarOperator(Mat22, op))
278 result.add(createMatScalarOperator(Mat23, op))
279 result.add(createMatScalarOperator(Mat32, op))
280 result.add(createMatScalarOperator(Mat33, op))
281 result.add(createMatScalarOperator(Mat34, op))
282 result.add(createMatScalarOperator(Mat43, op))
283 result.add(createMatScalarOperator(Mat44, op))
284
285 result.add(createMatMatMultiplicationOperator(Mat22, Mat22, Mat22))
286 result.add(createMatMatMultiplicationOperator(Mat22, Mat23, Mat23))
287 result.add(createMatMatMultiplicationOperator(Mat23, Mat32, Mat22))
288 result.add(createMatMatMultiplicationOperator(Mat23, Mat33, Mat23))
289 result.add(createMatMatMultiplicationOperator(Mat32, Mat22, Mat32))
290 result.add(createMatMatMultiplicationOperator(Mat32, Mat23, Mat33))
291 result.add(createMatMatMultiplicationOperator(Mat33, Mat32, Mat32))
292 result.add(createMatMatMultiplicationOperator(Mat33, Mat33, Mat33))
293 result.add(createMatMatMultiplicationOperator(Mat33, Mat34, Mat34))
294 result.add(createMatMatMultiplicationOperator(Mat43, Mat33, Mat43))
295 result.add(createMatMatMultiplicationOperator(Mat43, Mat34, Mat44))
296 result.add(createMatMatMultiplicationOperator(Mat44, Mat43, Mat43))
297 result.add(createMatMatMultiplicationOperator(Mat44, Mat44, Mat44))
298
299 result.add(createVecMatMultiplicationOperator(Mat22, Vec2))
300 result.add(createVecMatMultiplicationOperator(Mat33, Vec3))
301 result.add(createVecMatMultiplicationOperator(Mat44, Vec4))
302
303 createAllMultiplicationOperators()
304
305
100 func transposed*[T](m: Mat22[T]): Mat22[T] = Mat22[T](data: [ 306 func transposed*[T](m: Mat22[T]): Mat22[T] = Mat22[T](data: [
101 m[0, 0], m[1, 0], 307 m[0, 0], m[1, 0],
102 m[0, 1], m[1, 1], 308 m[0, 1], m[1, 1],
103 ]) 309 ])
104 func transposed*[T](m: Mat23[T]): Mat32[T] = Mat32[T](data: [ 310 func transposed*[T](m: Mat23[T]): Mat32[T] = Mat32[T](data: [
131 m[0, 1], m[1, 1], m[2, 1], m[3, 1], 337 m[0, 1], m[1, 1], m[2, 1], m[3, 1],
132 m[0, 2], m[1, 2], m[2, 2], m[3, 2], 338 m[0, 2], m[1, 2], m[2, 2], m[3, 2],
133 m[0, 3], m[1, 3], m[2, 3], m[3, 3], 339 m[0, 3], m[1, 3], m[2, 3], m[3, 3],
134 ]) 340 ])
135 341
136 # call e.g. Mat32[int]().initRandom() to get a random matrix 342 # call e.g. Mat32[int]().randomized() to get a random matrix
137 template makeRandomInit(mattype: typedesc) = 343 template makeRandomInit(mattype: typedesc) =
138 proc randomized*[T: SomeInteger](m: mattype[T]): mattype[T] = 344 proc randomized*[T: SomeInteger](m: mattype[T]): mattype[T] =
139 for i in 0 ..< result.data.len: 345 for i in 0 ..< result.data.len:
140 result.data[i] = rand(low(typeof(m.data[0])) .. high(typeof(m.data[0]))) 346 result.data[i] = rand(low(typeof(m.data[0])) .. high(typeof(m.data[0])))
141 proc randomized*[T: SomeFloat](m: mattype[T]): mattype[T] = 347 proc randomized*[T: SomeFloat](m: mattype[T]): mattype[T] =